diff --git "a/1769.jsonl" "b/1769.jsonl" new file mode 100644--- /dev/null +++ "b/1769.jsonl" @@ -0,0 +1,718 @@ +{"seq_id":"46563013496","text":"from OpenSSL import crypto, SSL\nfrom socket import gethostname\nfrom pprint import pprint\nfrom time import gmtime, mktime\n\nCERT_FILE = \"cert.pem\"\nKEY_FILE = \"key.pem\"\n\ndef create_self_signed_cert():\n # create a key pair\n k = crypto.PKey()\n k.generate_key(crypto.TYPE_RSA, 1024)\n\n # create a self-signed cert\n cert = crypto.X509()\n cert.get_subject().C = \"UK\"\n cert.get_subject().ST = \"London\"\n cert.get_subject().L = \"London\"\n cert.get_subject().O = \"Dummy Company Ltd\"\n cert.get_subject().OU = \"Dummy Company Ltd\"\n cert.get_subject().CN = gethostname()\n cert.set_serial_number(1000)\n cert.gmtime_adj_notBefore(0)\n cert.gmtime_adj_notAfter(10*365*24*60*60)\n cert.set_issuer(cert.get_subject())\n cert.set_pubkey(k)\n cert.sign(k, 'sha1')\n\n open(CERT_FILE, \"wt\").write(\n crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n open(KEY_FILE, \"wt\").write(\n crypto.dump_privatekey(crypto.FILETYPE_PEM, k))\n\nif __name__ == '__main__':\n create_self_signed_cert()","repo_name":"DevDungeon/Cookbook","sub_path":"python/gen_self_signed_certs.py","file_name":"gen_self_signed_certs.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"52"} +{"seq_id":"33431676364","text":"\"\"\"\nCPSC 526 Assignment #4\nSteven Leong 10129668 T01\nJosh Quines 10138118 T03\n\"\"\"\nimport socket\nimport socketserver\nimport sys\nimport os\nimport time\nimport traceback\nimport select\nimport string\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import padding\nimport random\nimport hashlib\nimport binascii\n\n#GLOBAL VARIABLES\nBUFFER_SIZE = 1024\nCIPHER = 0\nCIPHER_FILE = 0\nBLOCK_SIZE = 128\nIVMsg = None \nSKMsg = None \n\n# Authentication\n # server → client: random challenge\n # client → server: compute and send back a reply that can only be computed if secret key is known\n # server → client: verify the reply, send success/failure message to client\n# The key received from the client is encrypted using cipher\ndef authentication(client, key):\n # https://codereview.stackexchange.com/questions/47529/creating-a-string-of-random-characters\n message = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(16))\n logging(\"Message = \" + message)\n sendEncrypted(client, message)\n # random challenge is for the client to send back SHA1(msg|key)\n hashMsg = message + key\n answer = hashlib.sha1(hashMsg.encode()).hexdigest()\n logging(\"H(msg|key) = \" + answer)\n clientAnswer = recvEncrypted(client).decode(\"utf-8\")\n logging(\"Client's Answer = \" + str(clientAnswer))\n if answer != clientAnswer: \n return False\n else:\n return True\n\n\ndef sendEncrypted(client, msg):\n # try changing the type of msg to bytes\n try:\n byteMsg = msg.encode()\n except:\n byteMsg = msg\n\n if CIPHER == 0:\n client.sendall(byteMsg)\n else:\n # https://stackoverflow.com/questions/14179784/python-encrypting-with-pycrypto-aes#\n # https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/?highlight=cbc%20mode\n length = BLOCK_SIZE//8 - (len(byteMsg) % (BLOCK_SIZE//8))\n # if byteMsg is BLOCK_SIZE length would add BLOCK_SIZE//8 padding\n if length == BLOCK_SIZE//8:\n # Instead add BLOCK_SIZE of padding\n length = 0\n pad = bytes([length])*length\n byteMsg = byteMsg + pad\n encryptor = CIPHER.encryptor()\n toSend = encryptor.update(byteMsg) + encryptor.finalize()\n client.sendall(toSend)\n\n\n\ndef recvEncrypted(client):\n if CIPHER != 0:\n #logging(\"cipher not equal to 0\")\n message = client.recv(BLOCK_SIZE)\n #logging(\"received msg = \" + str(message))\n decryptor = CIPHER.decryptor()\n dataRecvd = decryptor.update(message) + decryptor.finalize()\n if len(dataRecvd) != 0 and dataRecvd[len(dataRecvd)-1] == dataRecvd[len(dataRecvd)-2]:\n dataRecvd = dataRecvd[:-dataRecvd[-1]]\n #logging(\"padding removed = \" + str(dataRecvd))\n #logging(\"Data received = \" + str(dataRecvd)+ \" of type \" + str(type(dataRecvd)))\n return dataRecvd\n else:\n message = client.recv(BUFFER_SIZE)\n return message\n \n\n# Server reads the file contents and sends it to the Client encrypted\ndef read(client, filename):\n # Check if filename is a file\n if not os.path.isfile(filename):\n logging(\"File does not exist\")\n sendEncrypted(client, \"Error: \" + filename + \" could not be read by server\")\n client.close()\n return\n #logging(\"Reading from file: \" + filename)\n\n # Open the file and read the correct size and send to the client\n try:\n #logging(\"Trying to read \" + filename)\n with open(filename, 'rb') as rfile:\n while 1:\n content = rfile.read(BLOCK_SIZE)\n #logging(\"CONTENT: \" + str(content) + \" of type \" + str(type(content)))\n if not content:\n #logging(\"not sending content\")\n sendEncrypted(client, content)\n break\n #logging(\"Sending content\")\n sendEncrypted(client, content)\n logging(\"File successfully read\")\n rfile.close()\n except:\n sendEncrypted(client, \"Error: File could not be read by server\")\n logging(\"Error: File could not be read by server\")\n client.close()\n tb = traceback.format_exc()\n print (tb)\n return\n\ndef write(client, filename):\n try:\n with open(filename, 'wb') as wfile:\n #logging(\"trying to write to \" + filename)\n content = recvEncrypted(client)\n while 1:\n #logging(\"CONTENT: \" + str(content))\n if not content:\n #print(\"BREAK CONTENT LOOP\")\n #logging(\"file has ended\")\n break\n wfile.write(content)\n content = recvEncrypted(client)\n\n logging(\"File successfully written\")\n wfile.close()\n #client.close()\n except:\n sendEncrypted(client, \"Error: File could not be written by server\")\n logging(\"Error: File could not be written by server\")\n client.close()\n tb = traceback.format_exc()\n print (tb)\n return\n\n\ndef setCipher(cCipher, key, nonce):\n global IVMsg, SKMsg, CIPHER_FILE\n IVMsg = key + nonce + \"IV\"\n SKMsg = key + nonce + \"SK\"\n backend = default_backend()\n IV = hashlib.sha256(IVMsg.encode()).hexdigest()\n SK = hashlib.sha256(SKMsg.encode()).hexdigest()\n logging(\"IV = \" + str(IV))\n logging(\"SK = \" + str(SK))\n global BLOCK_SIZE, CIPHER\n try:\n if cCipher == 'aes128':\n # Encrypt using aes128\n BLOCK_SIZE = 128\n CIPHER = Cipher(algorithms.AES(SK[:16].encode()), modes.CBC(IV[:16].encode()), backend=backend)\n #CIPHER_FILE = Cipher(algorithms.AES(SK[:16], modes.CBC(IV[:16], backend=backend)))\n\n elif cCipher == 'aes256':\n # Encrypt using aes256\n BLOCK_SIZE = 256\n CIPHER = Cipher(algorithms.AES(SK[:32].encode()), modes.CBC(IV[:16].encode()), backend=backend)\n #CIPHER_FILE = Cipher(algorithms.AES(SK[:32], modes.CBC(IV[:16], backend=backend)))\n else:\n CIPHER = 0\n logging(\"Null cipher being used, IV and SK not needed\")\n except:\n tb = traceback.format_exc()\n print (tb)\n\n\n\n\"\"\"Log client activity to standard output\"\"\"\ndef logging(msg):\n # get local time\n print(time.strftime(\"%a %b %d %H:%M:%S\") + \": \" + msg)\n \n\n# Request\n # client → server: operation, filename\n # server → client: response indicating whether operation can proceed\n\n# Data Exchange\n # client → server: data chunk\n # server → client: data chunk\n # In case of any errors, the server should indicate so to the client and then disconnect.\n # server → client: optional error message\n\n\ndef clientHandler(client, key):\n # Authenticate Client's key\n if not authentication(client, key):\n logging(\"Error: wrong key\")\n sendEncrypted(client, \"Error: Incorrect Key Used\")\n client.close()\n return\n else:\n logging(\"Correct key used\")\n sendEncrypted(client, \"Server: Correct Key\")\n\n # Client will send as operation;filename\n request = recvEncrypted(client).decode(\"utf-8\").split(\";\")\n\n operation = request[0]\n filename = request[1]\n\n logging(\"Command: \" + operation + \" Filename: \" + filename)\n\n # Verify the reply\n if operation == \"read\":\n sendEncrypted(client, \"Server: Valid Operation\")\n read(client, filename)\n elif operation == \"write\":\n sendEncrypted(client, \"Server: Valid Operation\")\n write(client, filename)\n else:\n sendEncrypted(client, \"Error: Invalid Operation\")\n logging(\"Error: Invalid Operation\")\n client.close()\n\n\n\nif __name__ == \"__main__\":\n\n # Arg check\n if len(sys.argv) == 3:\n PORT = int(sys.argv[1])\n KEY = sys.argv[2]\n else:\n print(\"\\nIncorrect number of parameters: \")\n print(\"Usage: server.py \")\n sys.exit()\n\n print(\"Listening on port \" + str(PORT))\n print(\"Using secret key: \" + str(KEY))\n\n serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serverSocket.bind(('', PORT))\n serverSocket.listen(5)\n\n while 1:\n client, addr = serverSocket.accept()\n # First message in the clear\n # client → server: cipher, nonce\n cipherNonceMsg = client.recv(BUFFER_SIZE).decode(\"utf-8\").split(\";\")\n #logging(\"cipher = \" + cipherNonceMsg[0])\n #logging(\"nonce = \" + cipherNonceMsg[1] )\n cCipher = cipherNonceMsg[0]\n nonce = cipherNonceMsg[1]\n\n logging(\"new connection from \" + str(addr[0]) + \" cipher = \" + cCipher)\n #logging(\"nonce = \" + nonce)\n \n logging(\"setting Cipher\")\n setCipher(cCipher, KEY, nonce)\n #logging(\"Block Size = \" + str(BLOCK_SIZE))\n sendEncrypted(client, \"Server: Cipher and nonce received.\")\n\n logging(\"handling client\")\n clientHandler(client, KEY) \n # Final Success\n # server → client: final success\n logging(\"status: Success\")\n\n client.close()\n\n","repo_name":"joshquines/CPSC_526_A4","sub_path":"serverFolder/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":9195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27479341207","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time\nfrom PyQt5 import QtWidgets, QtCore\nfrom PyQt5.QtCore import Qt\nfrom src.gui.sharedcomponets import GUIToolKit\nfrom src.gui.sharedcomponets import ShowdatagramsViewTable\n\n\nclass TraceDisplayWidget(QtWidgets.QTabWidget):\n\n def __init__(self, parent=None):\n \"\"\"Constructor for ToolsWidget\"\"\"\n super().__init__(parent)\n self.setObjectName(\"traceTab\")\n self.startTime = None\n self.traceTabVerticalLayout = QtWidgets.QVBoxLayout(self)\n self.traceTabVerticalLayout.setObjectName(\"traceTabVerticalLayou\")\n self.traceTable = ShowdatagramsViewTable(self)\n self.traceTableModel = TraceTableModel(self.startTime)\n self.traceTable.setModel(self.traceTableModel)\n self.traceTabVerticalLayout.addWidget(self.traceTable)\n\n def addNewDatagramToDisplay(self, datagram):\n self.traceTable.model().addDatagram(datagram)\n\n def clearTable(self):\n self.traceTableModel = TraceTableModel(self.startTime)\n self.traceTable.setModel(self.traceTableModel)\n\n def setStartTimeStamp(self,time):\n self.traceTableModel.startTime = int(time)\n\nclass TraceTableModel(QtCore.QAbstractTableModel):\n def __init__(self, startimeSource):\n super(TraceTableModel, self).__init__()\n self.startTime = startimeSource\n self.datagramsTimedList = []\n self.columNames = (\"Time (ms)\", \"Type\", \"ID\", \"DLC\", \"Data\")\n self.displayFlag = \"HEX\"\n\n def data(self, index, role=None):\n if role == Qt.DisplayRole:\n timestamp = self.datagramsTimedList[index.row()][0]\n datagram = self.datagramsTimedList[index.row()][1]\n\n if index.column() == 0:\n return str(timestamp)\n elif index.column() == 2:\n return str(datagram.messageID)\n elif index.column() == 3:\n return str(datagram.dlc)\n elif index.column() == 4:\n if datagram.data == None:\n return \"\"\n else:\n return str(datagram.dataToString(displayFlag=self.displayFlag))\n if role == Qt.DecorationRole:\n datagram = self.datagramsTimedList[index.row()][1]\n if index.column() == 1:\n if datagram.getDatagramTypeCode() == \"R\":\n return GUIToolKit.getIconByName(\"reddot\")\n elif datagram.getDatagramTypeCode() == \"r\":\n return GUIToolKit.getIconByName(\"bluedot\")\n elif datagram.getDatagramTypeCode() == \"T\":\n return GUIToolKit.getIconByName(\"orangedot\")\n elif datagram.getDatagramTypeCode() == \"t\":\n return GUIToolKit.getIconByName(\"greendot\")\n if role == Qt.TextAlignmentRole:\n if index.column() == 3:\n return Qt.AlignVCenter + Qt.AlignCenter\n if index.column() == 2:\n return Qt.AlignVCenter + Qt.AlignRight\n\n def rowCount(self, parent=None, *args, **kwargs):\n return len(self.datagramsTimedList)\n\n def columnCount(self, parent=None, *args, **kwargs):\n return len(self.columNames)\n\n def headerData(self, section, orientation, role=None):\n # section is the qIndex of the column/row.\n if role == Qt.DisplayRole:\n if orientation == Qt.Horizontal:\n return str(self.columNames[section])\n def updateAll(self):\n self.dataChanged.emit(self.index(0, 0),self.index(self.rowCount(), self.columnCount()))\n\n def addDatagram(self, datagram):\n newRow = len(self.datagramsTimedList)\n self.beginInsertRows(QtCore.QModelIndex(), newRow, newRow)\n\n currentTime = self.current_milli_time()\n timeStamp = currentTime - self.startTime\n\n self.datagramsTimedList.append((timeStamp, datagram))\n self.endInsertRows()\n\n def current_milli_time(self):\n return int(round(time.time() * 1000))","repo_name":"JorgeMaker/CanSnifferSuite","sub_path":"guiApp/CanBusSnnifer/src/gui/caninspector/traceDatragramsDisplay.py","file_name":"traceDatragramsDisplay.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"39203490916","text":"\"\"\"This script determines the state of a given element at a given temperature in a given scale\"\"\"\r\n\r\nfrom Connection import *\r\nfrom conversions import celsius_to_kelvin as c, fahrenheit_to_kelvin as f, rankine_to_kelvin as r\r\n\r\n\r\n#Basic function\r\ndef state(Z,t):\r\n m=points_dictionary[Z][\"melting\"]\r\n b=points_dictionary[Z][\"boiling\"]\r\n if t\")\r\n if method==\"Name\":\r\n while True:\r\n name=input(\"Enter element name: \")\r\n #To make sure given input is valid\r\n if name in elements:\r\n Z=elements_dictionary[name]\r\n break\r\n else:\r\n print(\"Please enter a valid element\")\r\n elif method==\"Symbol\":\r\n while True:\r\n symbol=input(\"Enter symbol: \")\r\n #To make sure given input is valid\r\n if symbol in symbols:\r\n Z=symbols_dictionary[symbol]\r\n break\r\n else:\r\n Z=int(input(\"Enter atomic number\"))\r\n t_scale=input(\"Celsius/Kelvin/Fahrenheit/Rankine>\")\r\n t_unscaled=int(input(\"Enter value of temperature: \"))\r\n if t_scale==\"Celsius\":\r\n t=c(t_unscaled)\r\n elif t_scale==\"Fahrenheit\":\r\n t=f(t_unscaled)\r\n elif t_scale==\"Rankine\":\r\n t=r(t_unscaled)\r\n else:\r\n t=t_unscaled\r\n s=state(Z,t)\r\n print (\"At the given temperature, the element is in\",s,\"state\")\r\n\r\ndef room_temperature():\r\n method=input(\"Number/Name/Symbol>\")\r\n if method==\"Name\":\r\n while True:\r\n name=input(\"Enter element name: \")\r\n #To make sure given input is valid\r\n if name in elements:\r\n Z=elements_dictionary[name]\r\n break\r\n elif method==\"Symbol\":\r\n while True:\r\n symbol=input(\"Enter symbol: \")\r\n #To make sure given input is valid\r\n if symbol in symbols:\r\n Z=symbols_dictionary[symbol]\r\n break\r\n else:\r\n Z=int(input(\"Enter atomic number\"))\r\n s=state(Z,293)\r\n print (\"At room temperature (293K), the element is in\",s,\"state\")\r\n \r\n \r\n","repo_name":"utkar22/High-School-Practical-File-Projects","sub_path":"Class 12 Final Project/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72785604324","text":"# -*- coding: utf-8 -*-\r\n#\r\n# Copyright (c) 2023, the cclib development team\r\n#\r\n# This file is part of cclib (http://cclib.github.io) and is distributed under\r\n# the terms of the BSD 3-Clause License.\r\n\r\n\"\"\"Test scan logfiles in cclib\"\"\"\r\n\r\nimport os\r\nimport unittest\r\n\r\nimport numpy\r\nimport cclib\r\n\r\nfrom skip import skipForParser\r\n\r\n\r\n__filedir__ = os.path.realpath(os.path.dirname(__file__))\r\n\r\n\r\nOPT_DONE = cclib.parser.data.ccData.OPT_DONE\r\nOPT_NEW = cclib.parser.data.ccData.OPT_NEW\r\n\r\n\r\ndef is_optnew(optstatus_value) -> bool:\r\n return optstatus_value & OPT_NEW == OPT_NEW\r\n\r\n\r\ndef is_optdone(optstatus_value) -> bool:\r\n return optstatus_value & OPT_DONE == OPT_DONE\r\n\r\n\r\nclass GenericRelaxedScanTest_optdone_bool(unittest.TestCase):\r\n \"\"\"Generic relaxed potential energy surface scan unittest.\"\"\"\r\n\r\n datatype = cclib.parser.data.ccData_optdone_bool\r\n\r\n @skipForParser('Turbomole','The parser is still being developed so we skip this test')\r\n @skipForParser('Molcas','The parser is still being developed so we skip this test')\r\n def testoptdone(self):\r\n \"\"\"Is the optimization finished?\"\"\"\r\n assert isinstance(self.data.optdone, bool)\r\n assert self.data.optdone\r\n\r\n @skipForParser('Turbomole','The parser is still being developed so we skip this test')\r\n @skipForParser('Molcas','The parser is still being developed so we skip this test')\r\n def testindices(self):\r\n \"\"\"Do the indices match the results from geovalues.\"\"\"\r\n assert self.data.optdone and numpy.all(self.data.geovalues[-1] <= self.data.geotargets)\r\n\r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n @skipForParser('Molcas','The parser is still being developed so we skip this test')\r\n @skipForParser(\"ORCA\", \"Not implemented\")\r\n @skipForParser('Turbomole','The parser is still being developed so we skip this test')\r\n def testoptstatus(self):\r\n \"\"\"Does optstatus contain expected values?\"\"\"\r\n\r\n # The input and final coordinates were at a stationary points.\r\n assert is_optnew(self.data.optstatus[0])\r\n assert is_optdone(self.data.optstatus[0])\r\n assert is_optdone(self.data.optstatus[-1])\r\n\r\nclass GenericUnrelaxedScanTest(unittest.TestCase):\r\n \"\"\"Generic unrelaxed potential energy surface scan unittest.\"\"\"\r\n\r\n # extra indices\r\n extra = 0\r\n \r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n def testscannames(self):\r\n assert isinstance(self.data.scannames, list)\r\n\r\n @skipForParser(\"ORCA\", \"Not implemented\")\r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n def testscanenergies(self):\r\n assert isinstance(self.data.scanenergies, list)\r\n \r\n # This checks the order of magnitude, and unit conversion if nothing else.\r\n numpy.testing.assert_array_less(numpy.array(self.data.scanenergies), -10000)\r\n\r\n @skipForParser(\"ORCA\", \"Not implemented\")\r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n def testscanparm(self):\r\n assert isinstance(self.data.scanparm, list)\r\n\r\n # Each parameters should have as many values as there are scan\r\n # energies, or optimized point on the PES.\r\n for parm in self.data.scanparm:\r\n assert len(parm) == len(self.data.scanenergies)\r\n\r\n\r\nclass GenericRelaxedScanTest(GenericUnrelaxedScanTest):\r\n \"\"\"Generic relaxed potential energy surface scan unittest.\"\"\"\r\n\r\n # extra indices\r\n extra = 0\r\n \r\n @skipForParser('Molcas','The parser is still being developed so we skip this test')\r\n @skipForParser('Turbomole','The parser is still being developed so we skip this test')\r\n def testnumindices(self):\r\n \"\"\"Do the number of indices match number of scan points.\"\"\"\r\n assert len(self.data.optdone) == 12 + self.extra\r\n\r\n @skipForParser(\"Jaguar\", \"Does not work as expected\") \r\n @skipForParser('Molcas','The parser is still being developed so we skip this test')\r\n @skipForParser(\"ORCA\", \"Does not work as expected\")\r\n @skipForParser('Turbomole','The parser is still being developed so we skip this test')\r\n def testindices(self):\r\n \"\"\"Do the indices match the results from geovalues.\"\"\"\r\n indexes = self.data.optdone\r\n geovalues_from_index = self.data.geovalues[indexes]\r\n temp = numpy.all(self.data.geovalues <= self.data.geotargets, axis=1)\r\n geovalues = self.data.geovalues[temp]\r\n numpy.testing.assert_array_equal(geovalues, geovalues_from_index)\r\n\r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n @skipForParser('Molcas','The parser is still being developed so we skip this test')\r\n @skipForParser(\"ORCA\", \"Not implemented\")\r\n @skipForParser('Turbomole','The parser is still being developed so we skip this test')\r\n def testoptstatus(self):\r\n \"\"\"Does optstatus contain expected values?\"\"\"\r\n # The input coordinates were at a stationary point.\r\n assert is_optdone(self.data.optstatus[0])\r\n\r\n assert len(self.data.converged_geometries) == len(self.data.optdone)\r\n for idone in self.data.optdone:\r\n assert is_optdone(self.data.optstatus[idone])\r\n if idone != len(self.data.optstatus) - 1:\r\n assert is_optnew(self.data.optstatus[idone+1])\r\n\r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n def testscannames(self):\r\n assert isinstance(self.data.scannames, list)\r\n\r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n @skipForParser(\"ORCA\", \"Not implemented\")\r\n def testscanenergies(self):\r\n assert isinstance(self.data.scanenergies, list)\r\n \r\n # This checks the order of magnitude, and unit conversion if nothing else.\r\n numpy.testing.assert_array_less(numpy.array(self.data.scanenergies), -10000)\r\n\r\n @skipForParser(\"Jaguar\", \"Not implemented\")\r\n @skipForParser(\"ORCA\", \"Not implemented\")\r\n def testscanparm(self):\r\n assert isinstance(self.data.scanparm, list)\r\n\r\n # Each parameters should have as many values as there are scan\r\n # energies, or optimized point on the PES.\r\n for parm in self.data.scanparm:\r\n assert len(parm) == len(self.data.scanenergies)\r\n\r\n\r\nclass GaussianUnrelaxedScanTest(GenericUnrelaxedScanTest):\r\n \"\"\"Customized unrelaxed potential energy surface scan unittest\"\"\"\r\n extra = 1\r\n\r\nclass GaussianRelaxedScanTest(GenericRelaxedScanTest):\r\n \"\"\"Customized relaxed potential energy surface scan unittest\"\"\"\r\n extra = 1\r\n\r\n\r\nclass JaguarRelaxedScanTest(GenericRelaxedScanTest):\r\n \"\"\"Customized relaxed potential energy surface scan unittest\"\"\"\r\n extra = 1\r\n\r\n\r\nclass OrcaRelaxedScanTest(GenericRelaxedScanTest):\r\n \"\"\"Customized relaxed potential energy surface scan unittest\"\"\"\r\n extra = 1\r\n\r\n\r\nif __name__==\"__main__\":\r\n\r\n import sys\r\n sys.path.insert(1, os.path.join(__filedir__, \"..\"))\r\n\r\n from test_data import DataSuite\r\n suite = DataSuite(['Scan'])\r\n suite.testall()\r\n","repo_name":"cclib/cclib","sub_path":"test/data/testScan.py","file_name":"testScan.py","file_ext":"py","file_size_in_byte":6916,"program_lang":"python","lang":"en","doc_type":"code","stars":286,"dataset":"github-code","pt":"52"} +{"seq_id":"3679391275","text":"from datetime import datetime\n\nimport random\nfrom abc import ABC, abstractmethod\n\nmalicious_ips = [\"103.227.8.154\", \"198.38.90.126\", \"160.20.45.145\", \"134.119.192.123\", \"103.225.53.235\", \"122.14.131.208\", \"122.14.131.208\", \"160.20.45.87 \",\n \"203.138.203.200\", \"200.225.202.93\", \"160.20.45.15\", \"160.20.45.180\", \"103.48.37.61\", \"163.172.198.101\", \"160.20.45.241\", \"185.14.249.86 \",\n \"103.7.155.9\", \"103.7.155.12\", \"103.7.155.4\", \"103.7.155.6\", \"103.7.155.7\", \"103.7.155.10\", \"103.7.155.2\"]\nhttp_methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"]\nhttp_paths = [\"/csr\", \"/certificates\", \"/certificate-requests\", \"/templates\"]\nstatus_codes = [\"200\", \"400\"]\ninactive_accounts = [\"inactiveuser1\", \"inactiveuser2\", \"inactiveuser3\"]\nactive_accounts = [\"activeuser1\", \"activeuser2\", \"activeuser3\"]\nlog_states = [\"NORMAL\", \"BRUTE_FORCE_ATTACK\", \"DOS_ATTACK\", \"MALICIOUS_IP\", \"INACTIVE_ACCOUNT\", \"VALID_LOGIN\", \"FAILED_LOGIN\", \"ERROR\", ]\n\n\nclass LogGeneratorHelper:\n def get_current_timestamp(self):\n now = datetime.now()\n return now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n def generate_random_ip(self):\n random.seed(random.randint(0, 100000))\n return \".\".join(str(random.randint(0, 256)) for _ in range(4))\n\n def generete_random_path(self):\n random.seed(random.randint(0, 100000))\n method = random.choice(http_methods)\n path = random.choice(http_paths)\n return \" \".join([method, path])\n\n def get_random_status_code(self):\n return random.choice(status_codes)\n\n\nclass LogGenerator(ABC, LogGeneratorHelper):\n def __init__(self):\n self.data = {}\n\n def set_data(self):\n self.data[\"sourceIp\"] = self.generate_random_ip()\n self.data[\"destIp\"] = self.generate_random_ip()\n self.data[\"path\"] = self.generete_random_path()\n self.data[\"protocol\"] = \"HTTP/1.1\"\n self.data[\"status\"] = random.choice(status_codes)\n self.data[\"time\"] = self.get_current_timestamp()\n self.data[\"packetSize\"] = random.randint(1024, 2048)\n self.data[\"type\"] = random.choice(log_states)\n return self\n\n def get_data(self):\n return self.data\n\n def create_http_log(self, source_ip, dest_ip, path, protocol, status):\n timestamp = self.get_current_timestamp()\n packet_size = str(random.randint(1024, 2048))\n return \" \".join([timestamp, packet_size, source_ip, dest_ip, path, protocol, status])","repo_name":"matijapetrovic/medisec","sub_path":"firewall/log_generator.py","file_name":"log_generator.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"22026154377","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 20 00:57:39 2021\n\n@author: leeso\n\"\"\"\n\n### Functionalize\n### duplicate previous year values to next one\ndef feature_engineering_year_duplicated(raw, target):\n raw_fe = raw.copy()\n for col in target:\n raw_fe.loc['2012-01-01':'2012-02-28', col] = raw.loc['2011-01-01':'2011-02-28', col].values\n raw_fe.loc['2012-03-01':'2012-12-31', col] = raw.loc['2011-03-01':'2011-12-31', col].values\n step = (raw.loc['2011-03-01 00:00:00', col] - raw.loc['2011-02-28 23:00:00', col])/25\n step_value = np.arange(raw.loc['2011-02-28 23:00:00', col]+step, raw.loc['2011-03-01 00:00:00', col], step)\n step_value = step_value[:24]\n raw_fe.loc['2012-02-29', col] = step_value\n return raw_fe\n# target = ['count_trend', 'count_seasonal', 'count_Day', 'count_Week', 'count_diff']\n# raw_fe = feature_engineering_year_duplicated(raw_fe, target)\n\n### modify lagged values of X_test\ndef feature_engineering_lag_modified(Y_test, X_test, target):\n X_test_lm = X_test.copy()\n for col in target:\n X_test_lm[col] = Y_test.shift(1).values\n X_test_lm[col].fillna(method='bfill', inplace=True)\n X_test_lm[col] = Y_test.shift(2).values\n X_test_lm[col].fillna(method='bfill', inplace=True)\n return X_test_lm\n# target = ['count_lag1', 'count_lag2']\n# X_test_fe = feature_engineering_lag_modified(Y_test_fe, X_test_fe, target)","repo_name":"5ohyun/time_series","sub_path":"1. 시계열데이터분석/6. 시간현실반영.py","file_name":"6. 시간현실반영.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72623747365","text":"from collections import Counter\nimport os\n\ndef parse_file(name) -> list:\n lines = open(f'{os.path.dirname(__file__)}/{name}', 'r').read().splitlines()\n groups = []\n group_lines = []\n\n for index, line in enumerate(lines):\n if line == \"\":\n groups.append(group_lines)\n group_lines = []\n continue\n\n group_lines.append(line)\n \n # If we're on the last line, create a group\n if index == len(lines) - 1:\n groups.append(group_lines)\n return groups\n\ndef part1(groups):\n tally = 0\n for group in groups:\n count = Counter(''.join(group))\n tally += len(count)\n return tally\n\ndef part2(groups):\n tally = 0\n for group in groups:\n sets = [set(g) for g in group]\n intersection = set.intersection(*sets)\n tally += len(intersection)\n return tally\n\ngroups = parse_file('input.txt')\nprint(f'Part 1: {part1(groups)}')\nprint(f'Part 2: {part2(groups)}')","repo_name":"josharrington/adventofcode2020","sub_path":"day06/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41316822173","text":"# %% Exercises of \"First order methods in optimization by Amir Beck\"\n# Part 1: ex. 9\nimport numpy as np\n\n\ndef prox_t(x, Lambda=1, tol=1e-10, gamma=1e-2):\n # Amir Beck, prox computations table\n t = x\n if (x.flatten()).shape[0] > 1:\n raise Warning(\"In prox, the argument should be scalar\")\n return 0\n\n def inner_fun(w): return w ** 3 - x * (w ** 2) - Lambda\n while(np.abs(inner_fun(t)) > tol):\n t -= gamma * (inner_fun(t))\n\n return t\n\n\ndef prox(X, Lambda=1):\n Gamma, U_T = np.linalg.eig(X)\n n = X.shape[0]\n\n inner_prox_vec = np.zeros(n)\n for i in range(n):\n inner_prox_vec[i] = prox_t(Gamma[i], Lambda=Lambda)\n\n prox_vec = U_T @ np.diag(inner_prox_vec) @ U_T.T\n return prox_vec\n\n\n# %% Exercises:\n\n# Part 1: ex. 6:\nX = np.array(((3, 1), (1, 4)))\nprox_mat = prox(X, Lambda=1)\nprint(f\"\\nThe prox matrix is: {prox_mat}\\n\")\n","repo_name":"pourya-b/SOCN_CvxOpt","sub_path":"codes/ex_p1_e1_2.py","file_name":"ex_p1_e1_2.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19690029166","text":"import numpy as np\r\nimport tensorflow as tf\r\nimport cv2\r\n\r\nmodel = tf.keras.models.load_model('mnist.h5')\r\n\r\na = np.ones([300, 300], dtype='uint8') * 0;\r\n\r\n# cv2.rectangle(a, (50, 50), (350, 350), (0, 255, 0), -2)\r\n\r\nwname = 'Digit Recognition - Canvas'\r\n\r\nstate = False\r\n\r\ncv2.namedWindow(wname)\r\n\r\ndef number(event, x, y, state, param):\r\n \r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n state = True\r\n \r\n elif event == cv2.EVENT_MOUSEMOVE:\r\n if state == True:\r\n cv2.circle(a, (x, y), 5, (255, 255, 255), -5)\r\n \r\n elif event == cv2.EVENT_LBUTTONUP:\r\n state = False\r\n \r\ncv2.setMouseCallback(wname, number)\r\n\r\nwhile True:\r\n cv2.imshow(wname, a)\r\n key = cv2.waitKey(1)\r\n \r\n if key == 27:\r\n break\r\n \r\n elif key == ord('p'):\r\n num = a[0:300, 0:300]\r\n # cv2.imshow(\"number\", num)\r\n num = cv2.resize(num, (28, 28)).reshape(1, 28, 28)\r\n num = num/255\r\n print(np.argmax(model.predict(num)))\r\n \r\n elif key == ord('c'):\r\n a[:, :] = 0\r\n # cv2.rectangle(a, (50, 50), (350, 350), (0, 255, 0), -2)\r\n \r\ncv2.destroyAllWindows()\r\n \r\n","repo_name":"ishidesigns/AI-Minor","sub_path":"minor_prjt.py","file_name":"minor_prjt.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9070035684","text":"n=0\r\nn0=0\r\ncant=0\r\nwhile n !=-1: \r\n n=int(input(\"Ingrese Numero: \"))\r\n \r\n if n < n0 and cant > 0:\r\n print (\"Ultimo numero menor a valor anterior:\", n, \". Valor anterior\", n0)\r\n \r\n n0=n\r\n \r\n cant=cant+1\r\n\r\n\r\n \r\n\r\n","repo_name":"abaldeg/EjerciciosPython","sub_path":"tp 4 ej 5.py","file_name":"tp 4 ej 5.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15805416311","text":"import pygame\nimport sys\nimport os\n\n'''\nVariables\n'''\n\nworldx = 960\nworldy = 720\nfps = 40 # frame rate\nani = 4 # animation cycles\nmain = True\n\nBLUE = (25, 25, 200)\nBLACK = (23, 23, 23)\nWHITE = (254, 254, 254)\n\n\n'''\nObjects\n'''\n\n# put Python classes and functions here\n\n\n'''\nSetup\n'''\n\nclock = pygame.time.Clock()\npygame.init()\nworld = pygame.display.set_mode([worldx, worldy])\nbackdrop = pygame.image.load(os.path.join('images', 'stage.png'))\nbackdropbox = world.get_rect()\n\n\n'''\nMain Loop\n'''\n\nwhile main:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n try:\n sys.exit()\n finally:\n main = False\n\n if event.type == pygame.KEYDOWN:\n if event.key == ord('q'):\n pygame.quit()\n try:\n sys.exit()\n finally:\n main = False\n world.blit(backdrop, backdropbox)\n pygame.display.flip()\n clock.tick(fps)","repo_name":"HumKariuki/Data-Structures","sub_path":"gm.py","file_name":"gm.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6948448743","text":"class Stud(object):\n def __init__(self, family_in, height_in, weight_in):\n self.family = str(family_in)\n self.height = int(height_in)\n self.weight = float(weight_in)\n def __str__(self):\n return str(self.__class__) + '\\n'+\\\n '\\n'.join(('{}:{}'.format(item, self.__dict__[item])\\\n for item in sorted(self.__dict__)))\n def __eq__(self, other):\n if isinstance(other, Stud):\n return self.family == other.family and \\\n self.height == other.height and \\\n self.weight == other.weight\n else:\n return NotImplemented\n\ndef sortByFamily(inputStud):\n return inputStud.family\n\ndef sortByHeight(inputStud):\n return inputStud.height\n\ndef sortByWeight(inputStud):\n return inputStud.weight\n\nsortType = int(input('Введите тип сортировки файлов:\\n\\\n 1. По фамилии\\n\\\n 2. По росту\\n\\\n 3. По весу\\n '))\n\nwith open(\"StudInput1.txt\", \"r\") as fin1,\\\nopen(\"StudInput2.txt\", \"r\") as fin2,\\\nopen(\"StudOutput.txt\", \"w\") as fout:\n res = []\n f1 = [i.replace(\"\\n\", \"\") if i.find(\"\\n\") > 0 else i for i in list(fin1)]\n\n i = 0\n while i < len(f1):\n if f1[i] == str(Stud):\n\n fam = \"\"\n height = 0\n weight = 0\n\n if f1[i+1].startswith(\"family:\"):\n fam = list(f1[i+1].split(\":\"))[1]\n if f1[i+2].startswith(\"height:\"):\n height = list(f1[i+2].split(\":\"))[1]\n if f1[i+3].startswith(\"weight:\"):\n weight = list(f1[i+3].split(\":\"))[1]\n if fam != \"\" and height != 0 and weight != 0 and \\\n not Stud(fam, height, weight) in res:\n res.append(Stud(fam, height, weight))\n i += 4\n else:\n i += 1\n else:\n i += 1\n\n f2 = [i.replace(\"\\n\", \"\") if i.find(\"\\n\") > 0 else i for i in list(fin2)]\n i = 0\n while i < len(f2):\n if f2[i] == str(Stud):\n fam = \"\"\n height = 0\n weight = 0\n\n if f2[i+1].startswith(\"family:\"):\n fam = list(f2[i+1].split(\":\"))[1]\n if f2[i+2].startswith(\"height:\"):\n height = int(list(f2[i+2].split(\":\"))[1])\n if f2[i+3].startswith(\"weight:\"):\n weight = int(list(f2[i+3].split(\":\"))[1])\n if fam != \"\" and height != 0 and weight != 0 and \\\n not Stud(fam, height, weight) in res:\n res.append(Stud(fam, height, weight))\n i += 4\n else:\n i += 1\n else:\n i += 1\n\n if sortType == 3:\n res = sorted(res, key = sortByWeight)\n elif sortType == 2:\n res = sorted(res, key = sortByHeight)\n else:\n res = sorted(res, key = sortByFamily)\n for i in res:\n fout.write(str(i)+'\\n')\n","repo_name":"migregal/bmstu-iu7-python","sub_path":"Labs/sem_1/lab_10_Files/main_script.py","file_name":"main_script.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9808354611","text":"from django.utils.translation import gettext_lazy as _\nfrom rest_framework.exceptions import APIException\nfrom rest_framework.status import HTTP_501_NOT_IMPLEMENTED, HTTP_504_GATEWAY_TIMEOUT\n\n\nclass GatewayTimeoutException(APIException):\n status_code = HTTP_504_GATEWAY_TIMEOUT\n default_detail = _('A server error occurred.')\n\n\nclass NotImplementedException(APIException):\n status_code = HTTP_501_NOT_IMPLEMENTED\n default_detail = _('Not implemented.')\n\n\nclass UnsupportedViewException(Exception):\n \"\"\"Raised when view is not supported.\"\"\"\n\n\nclass UnsupportedModelTypeException(Exception):\n \"\"\"Raised when type of model is not supported.\"\"\"\n","repo_name":"Amsterdam/signals","sub_path":"app/signals/apps/api/generics/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"35734943228","text":"import copy\n\ninputs = [list(input()) for i in range(10)]\n\nans = [['x'] * 10 for _ in range(10)]\nvectors = [[0, -1], [-1, 0], [0, 1], [1, 0]]\n\ndef dfs(row, col):\n if not(row >= 10 or col >= 10 or row < 0 or col < 0 or copy_inputs[row][col] == 'x'):\n copy_inputs[row][col] = 'x'\n for y, x in vectors:\n dfs(row+y, col+x)\n\nfor row in range(10):\n for col in range(10):\n if inputs[row][col] == 'x':\n copy_inputs = copy.deepcopy(inputs)\n copy_inputs[row][col] = 'o'\n dfs(row, col)\n if ans == copy_inputs:\n print('YES')\n exit()\nelse:\n print('NO')\n","repo_name":"haytok/AtCoder","sub_path":"ARC/ARC031~ARC035/ARC031/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13345551188","text":"from multiprocessing import Process,Manager,Queue\n# from queue import Queue\n\ndef foo(i,q):\n q.put(i)\n #print()\nif __name__ == '__main__':\n q = Queue() # 初始化一个队列\n\n pro_list = []\n for i in range(10):\n p = Process(target=foo,args=(i,q))\n p.start()\n pro_list.append(p)\n\n for pro in pro_list:\n pro.join()\n\n # 最后获取q的结果\n while not q.empty():\n print(q.get())","repo_name":"Ran-oops/python_notes2","sub_path":"9/认识爬虫-课件-v1/Py爬虫课件/1-09爬虫代码/spider_day7/2.multiprocess.py","file_name":"2.multiprocess.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12549470074","text":"from ast import arg\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchsummaryX import summary\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence\nfrom os.path import join\nfrom sklearn.metrics import accuracy_score\nimport gc\nimport zipfile\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nimport datetime\nimport phonemes\nimport argparse\n\n# imports for decoding and distance calculation\nimport ctcdecode\nimport Levenshtein\nfrom ctcdecode import CTCBeamDecoder\nimport csv\nimport time\nimport warnings\nfrom datetime import datetime\n# from tqdm import tqdm_notebook as tqdm\nimport wandb\n\nwandb.init(project=\"HW3\", entity=\"linjiw\")\nwarnings.filterwarnings('ignore')\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(\"Device: \", device)\n# !jupyter nbextension enable --py widgetsnbextension\n\n\n# PHONEME_MAP is the list that maps the phoneme to a single character. \n# The dataset contains a list of phonemes but you need to map them to their corresponding characters to calculate the Levenshtein Distance\n# You final submission should not have the phonemes but the mapped string\n# No TODOs in this cell\nnum_classes = 41\nPHONEME_MAP = [\n \" \",\n \".\", #SIL\n \"a\", #AA\n \"A\", #AE\n \"h\", #AH\n \"o\", #AO\n \"w\", #AW\n \"y\", #AY\n \"b\", #B\n \"c\", #CH\n \"d\", #D\n \"D\", #DH\n \"e\", #EH\n \"r\", #ER\n \"E\", #EY\n \"f\", #F\n \"g\", #G\n \"H\", #H\n \"i\", #IH \n \"I\", #IY\n \"j\", #JH\n \"k\", #K\n \"l\", #L\n \"m\", #M\n \"n\", #N\n \"N\", #NG\n \"O\", #OW\n \"Y\", #OY\n \"p\", #P \n \"R\", #R\n \"s\", #S\n \"S\", #SH\n \"t\", #T\n \"T\", #TH\n \"u\", #UH\n \"U\", #UW\n \"v\", #V\n \"W\", #W\n \"?\", #Y\n \"z\", #Z\n \"Z\" #ZH\n]\nphe_dict = {}\ntensor_dict = {}\nPHONEMES = phonemes.PHONEMES\nfor idx, i in enumerate(PHONEMES):\n phe_dict[i] = PHONEME_MAP[idx]\n tensor_dict[PHONEME_MAP[idx]] = idx\n\ndef maplst(lst):\n res =[]\n for i in lst:\n res.append(phe_dict[i])\n res = np.array(res)\n # res = res.astype(np.float)\n return np.array(res)\ndef maptotensor(lst):\n res =[]\n for i in lst:\n res.append(tensor_dict[i])\n res = np.array(res)\n # res = res.astype(np.float)\n return np.array(res)\n\n# This cell is where your actual TODOs start\n# You will need to implement the Dataset class by your own. You may also implement it similar to HW1P2 (dont require context)\n# The steps for implementation given below are how we have implemented it.\n# However, you are welcomed to do it your own way if it is more comfortable or efficient. \n\nclass LibriSamples(torch.utils.data.Dataset):\n\n def __init__(self, data_path, partition= \"train\"): # You can use partition to specify train or dev\n\n self.X_dir = os.path.join(data_path,partition,\"mfcc/\")# TODO: get mfcc directory path\n self.Y_dir = os.path.join(data_path,partition,\"transcript/\")# TODO: get transcript path\n\n self.X_files = os.listdir(self.X_dir)# TODO: list files in the mfcc directory\n self.Y_files = os.listdir(self.Y_dir)# TODO: list files in the transcript directory\n\n # TODO: store PHONEMES from phonemes.py inside the class. phonemes.py will be downloaded from kaggle.\n # You may wish to store PHONEMES as a class attribute or a global variable as well.\n self.PHONEMES = phonemes.PHONEMES\n\n assert(len(self.X_files) == len(self.Y_files))\n\n pass\n\n def __len__(self):\n return len(self.X_files)\n\n def __getitem__(self, ind):\n X_path = self.X_dir + self.X_files[ind]\n Y_path = self.Y_dir + self.Y_files[ind]\n X = torch.Tensor(np.load(X_path))# TODO: Load the mfcc npy file at the specified index ind in the directory\n # Y = maplst(np.load(Y_path)[1:-1])# TODO: Load the corresponding transcripts\n Y = np.load(Y_path)[1:-1]\n # print(Y)\n # print(Y.shape)\n # Y2 = PHONEMES.index(i) for i in np.load(Y_path)[1:-1]\n # print(f\"Y {Y}\")\n # print(f\"Y2 {Y2}\")\n # Remember, the transcripts are a sequence of phonemes. Eg. np.array(['', 'B', 'IH', 'K', 'SH', 'AA', ''])\n # You need to convert these into a sequence of Long tensors\n # Tip: You may need to use self.PHONEMES\n # Remember, PHONEMES or PHONEME_MAP do not have '' or '' but the transcripts have them. \n # You need to remove '' and '' from the trancripts. \n # Inefficient way is to use a for loop for this. Efficient way is to think that '' occurs at the start and '' occurs at the end.\n Yy = torch.LongTensor([PHONEMES.index(i) for i in Y])\n # Yy = torch.Tensor(maptotensor(Y)).type(torch.LongTensor)# TODO: Convert sequence of phonemes into sequence of Long tensors\n # print(f\"X {X.shape}\")\n # print(f\"Y {Y.shape}\")\n return X, Yy\n \n def collate_fn(self,batch):\n\n batch_x = [x for x,y in batch]\n batch_y = [y for x,y in batch]\n # print(batch_x[0].shape)\n\n new_lst = []\n for idx, i in enumerate(batch_x):\n new_lst.append(batch_x[idx])\n batch_x_pad = pad_sequence(new_lst)\n # batch_x_pad = pad_sequence([i for i in batch_x], batch_first=False)# TODO: pad the sequence with pad_sequence (already imported)\n lengths_x = [len(i) for i in batch_x]# TODO: Get original lengths of the sequence before padding\n lengths_x_pad = [len(i) for i in batch_x_pad]\n # print(f\"batch_x {batch_x}\")\n \n\n # print(f\"test_pad.len {test_pad.shape}\")\n # print(f\"batch_x.len {len(batch_x)}\")\n # print(f\"lengths_x {lengths_x}\")\n # print(f\"lengths_x_pad {lengths_x_pad}\")\n\n new_lst = []\n for idx, i in enumerate(batch_y):\n new_lst.append(batch_y[idx])\n batch_y_pad = pad_sequence(new_lst)\n\n # batch_y_pad = pad_sequence(batch_y) # TODO: pad the sequence with pad_sequence (already imported)\n lengths_y = [len(i) for i in batch_y] # TODO: Get original lengths of the sequence before padding\n\n return batch_x_pad, batch_y_pad, torch.tensor(lengths_x), torch.tensor(lengths_y)\nfrom torch.utils.data.dataset import Subset\n\n# You can either try to combine test data in the previous class or write a new Dataset class for test data\nclass LibriSamplesTest(torch.utils.data.Dataset):\n\n def __init__(self, data_path, test_order): # test_order is the csv similar to what you used in hw1\n self.data_path = data_path\n test_csv_pth = os.path.join(data_path,'test',test_order)\n subset = list(pd.read_csv(test_csv_pth).file)\n # subset = self.parse_csv(test_csv_pth)\n test_order_list = subset# TODO: open test_order.csv as a list\n self.X_names = [i for i in subset]# TODO: Load the npy files from test_order.csv and append into a list\n # You can load the files here or save the paths here and load inside __getitem__ like the previous class\n @staticmethod\n def parse_csv(filepath):\n subset = []\n with open(filepath) as f:\n f_csv = csv.reader(f)\n for row in f_csv:\n subset.append(row[0])\n return subset[0:]\n def __len__(self):\n return len(self.X_names)\n \n def __getitem__(self, ind):\n # TODOs: Need to return only X because this is the test dataset\n X_path = os.path.join(self.data_path,'test','mfcc',self.X_names[ind])\n X = torch.Tensor(np.load(X_path))\n return X\n \n def collate_fn(self, batch):\n batch_x = [x for x in batch]\n new_lst = []\n for idx, i in enumerate(batch_x):\n new_lst.append(batch_x[idx])\n batch_x_pad = pad_sequence(new_lst)\n # batch_x_pad = pad_sequence([i for i in batch_x], batch_first=False)# TODO: pad the sequence with pad_sequence (already imported)\n lengths_x = [len(i) for i in batch_x]# TODO: Get original lengths of the sequence before padding\n # lengths_x_pad = [len(i) for i in batch_x_pad]\n # batch_x = [x for x in batch]\n # batch_x_pad = pad_sequence(batch_x)# TODO: pad the sequence with pad_sequence (already imported)\n # lengths_x = [len(i) for i in batch_x]# TODO: Get original lengths of the sequence before padding\n\n return batch_x_pad, torch.tensor(lengths_x)\n\n# # Optional\n# # Test code for checking shapes and return arguments of the train and val loaders\n\n\n# for data in train_loader:\n# x, y, lx, ly = data # if you face an error saying \"Cannot unpack\", then you are not passing the collate_fn argument\n# # print(f\"ly {ly}\")\n# # print(f\"lx {lx}\")\n# print(x.shape, y.shape, lx.shape, ly.shape)\n# break\n\nclass Network(nn.Module):\n\n def __init__(self): # You can add any extra arguments as you wish\n\n super(Network, self).__init__()\n\n # Embedding layer converts the raw input into features which may (or may not) help the LSTM to learn better \n # For the very low cut-off you dont require an embedding layer. You can pass the input directly to the LSTM\n # self.embedding = \n \n self.lstm = nn.LSTM(input_size=13,hidden_size= 256, num_layers= 2)# TODO: # Create a single layer, uni-directional LSTM with hidden_size = 256\n # Use nn.LSTM() Make sure that you give in the proper arguments as given in https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html\n\n self.classification = nn.Linear(256,num_classes)# TODO: Create a single classification layer using nn.Linear()\n\n def forward(self, x, lx): # TODO: You need to pass atleast 1 more parameter apart from self and x\n\n # x is returned from the dataloader. So it is assumed to be padded with the help of the collate_fn\n packed_input = pack_padded_sequence(x,lx,enforce_sorted=False)# TODO: Pack the input with pack_padded_sequence. Look at the parameters it requires\n\n out1, (out2, out3) = self.lstm(packed_input)# TODO: Pass packed input to self.lstm\n # As you may see from the LSTM docs, LSTM returns 3 vectors. Which one do you need to pass to the next function?\n out, lengths = pad_packed_sequence(out1)# TODO: Need to 'unpack' the LSTM output using pad_packed_sequence\n\n out = self.classification(out)# TODO: Pass unpacked LSTM output to the classification layer\n # out = # Optional: Do log softmax on the output. Which dimension?\n # print(out[0,0,:])\n out = torch.nn.functional.log_softmax(out,dim=2)\n # print(out[0,0,:])\n # print(sum(out[0,0,:]))\n return out, lengths # TODO: Need to return 2 variables\n\nmodel = Network().to(device)\nprint(model)\n# summary(model, x.to(device), lx) # x and lx are from the previous cell\n\n# this function calculates the Levenshtein distance \n\ndef calculate_levenshtein(h, y, lh, ly, decoder, PHONEME_MAP):\n\n # h - ouput from the model. Probability distributions at each time step \n # y - target output sequence - sequence of Long tensors\n # lh, ly - Lengths of output and target\n # decoder - decoder object which was initialized in the previous cell\n # PHONEME_MAP - maps output to a character to find the Levenshtein distance\n\n h = h.permute(1, 0, 2)# TODO: You may need to transpose or permute h based on how you passed it to the criterion\n # Print out the shapes often to debug\n t1 =time.time()\n beam_results, _, _, out_lens = decoder.decode(h,seq_lens=lh)\n t2 = time.time()\n # print(f\"time cost {t2-t1}\")\n # TODO: call the decoder's decode method and get beam_results and out_len (Read the docs about the decode method's outputs)\n # Input to the decode method will be h and its lengths lh \n # You need to pass lh for the 'seq_lens' parameter. This is not explicitly mentioned in the git repo of ctcdecode.\n\n batch_size = h.shape[0]# TODO\n # print(f\"batch_szie {batch_size}\")\n\n dist = 0\n\n # dist = 0\n # h = np.zeros((100,)) \n # y = y.cpu().detach().numpy().astype(int)\n for i in range(batch_size): # Loop through each element in the batch\n\n # for j in range(100)\n h_sliced = beam_results[i][0][:out_lens[i,0]]\n # print(h_sliced.shape)\n # TODO: Get the output as a sequence of numbers from beam_results\n # Remember that h is padded to the max sequence length and lh contains lengths of individual sequences\n # Same goes for beam_results and out_lens\n # You do not require the padded portion of beam_results - you need to slice it with out_lens \n # If it is confusing, print out the shapes of all the variables and try to understand\n\n h_string = \"\".join([PHONEME_MAP[j] for j in h_sliced])# TODO: MAP the sequence of numbers to its corresponding characters with PHONEME_MAP and merge everything as a single string\n # print(f\"ly.shape {ly.shape}\")\n # print(f\"y.shape {y.shape}\")\n y_sliced = y[i][:ly[i]]\n y_string = \"\".join([PHONEME_MAP[j] for j in y_sliced])# TODO: MAP the sequence of numbers to its corresponding characters with PHONEME_MAP and merge everything as a single string\n # print(f\"h_string {h_string} h_string.len {len(h_string)}\")\n # print(f\"y_string {y_string} y_string.len {len(y_string)}\")\n per_dist = Levenshtein.distance(h_string, y_string)\n # print(f\"{i} {per_dist} \")\n dist += per_dist\n\n dist/=batch_size\n return dist\n # print(f\"dist {dist}\")\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--init_model', type=str, default=None)\nparser.add_argument('--lr', type=float, default=2e-3)\nparser.add_argument('--batch_size', type=int, default=256)\nparser.add_argument('--epochs', type=int, default=40)\nargs = parser.parse_args()\n\n\n\nlr = args.lr\nbatch_size = args.batch_size\nepochs = args.epochs\nnum_classes = 41\nwandb.config = {\n \"learning_rate\": lr,\n \"epochs\": epochs,\n \"batch_size\": batch_size\n}\n\nroot = 'hw3p2_student_data/hw3p2_student_data' # TODO: Where your hw3p2_student_data folder is\n\ntrain_data = LibriSamples(root, 'train')\nval_data = LibriSamples(root, 'dev')\ntest_data = LibriSamplesTest(root, 'test_order.csv')\n\ntrain_loader = DataLoader(train_data,batch_size=batch_size,shuffle=False,collate_fn=train_data.collate_fn, num_workers=8)# TODO: Define the train loader. Remember to pass in a parameter (function) for the collate_fn argument \nval_loader = DataLoader(val_data,batch_size=batch_size,shuffle=False,collate_fn=val_data.collate_fn, num_workers=8)# TODO: Define the val loader. Remember to pass in a parameter (function) for the collate_fn argument \ntest_loader = DataLoader(test_data,batch_size=batch_size,shuffle=False,collate_fn=test_data.collate_fn, num_workers=8)# TODO: Define the test loader. Remember to pass in a parameter (function) for the collate_fn argument \n\nprint(\"Batch size: \", batch_size)\nprint(\"Train dataset samples = {}, batches = {}\".format(train_data.__len__(), len(train_loader)))\nprint(\"Val dataset samples = {}, batches = {}\".format(val_data.__len__(), len(val_loader)))\nprint(\"Test dataset samples = {}, batches = {}\".format(test_data.__len__(), len(test_loader)))\n\ncriterion = nn.CTCLoss()# TODO: What loss do you need for sequence to sequence models? \n# Do you need to transpose or permute the model output to find out the loss? Read its documentation\noptimizer = torch.optim.Adam(model.parameters(),lr=lr)# TODO: Adam works well with LSTM (use lr = 2e-3)\nscheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=(len(train_loader) * epochs))\n\ndecoder = ctcdecode.CTCBeamDecoder(labels = PHONEME_MAP,\n model_path=None,\n alpha=0,\n beta=0,\n cutoff_top_n=40,\n cutoff_prob=1.0,\n beam_width=3,\n num_processes=8,\n blank_id=0,\n log_probs_input=True)# TODO: Intialize the CTC beam decoder\n# Check out https://github.com/parlance/ctcdecode for the details on how to implement decoding\n# Do you need to give log_probs_input = True or False?\n\n\n# torch.cuda.empty_cache() # Use this often\n\n# TODO: Write the model evaluation function if you want to validate after every epoch\n\n# You are free to write your own code for model evaluation or you can use the code from previous homeworks' starter notebooks\n# However, you will have to make modifications because of the following.\n# (1) The dataloader returns 4 items unlike 2 for hw2p2\n# (2) The model forward returns 2 outputs\n# (3) The loss may require transpose or permuting\n\n# Note that when you give a higher beam width, decoding will take a longer time to get executed\n# Therefore, it is recommended that you calculate only the val dataset's Levenshtein distance (train not recommended) with a small beam width\n# When you are evaluating on your test set, you may have a higher beam width\n\n# model.to(device)\n\n# model.load_state_dict(torch.load(\"7_1.0379955768585205_25_03_2022_22_30_06model.pth\"))\nif args.init_model == None:\n pass\nelse:\n try:\n\n model.load_state_dict(torch.load(args.init_model))\n except:\n pass\n\n\nfor epoch in range(epochs):\n \n # num_correct = 0\n batch_bar = tqdm(total=len(train_loader), dynamic_ncols=True, leave=False, position=0, desc=f'Train epoch: {epoch+1}') \n total_loss = 0\n model.train()\n desc = \"start\"\n # tq = tqdm(train_loader, desc=desc,dynamic_ncols=True)\n # with tqdm(train_loader, desc=desc,dynamic_ncols=True) as tq:\n for i, (x, y, lx, ly) in enumerate(train_loader):\n \n optimizer.zero_grad()\n x = x.cuda()\n y = y.cuda()\n out, out_len = model(x,lx)\n loss = criterion(out,y.permute(1,0), lx, ly)\n total_loss += loss\n # desc = \"loss = {:.04f}\".format(float(total_loss / (i + 1)))\n # desc += \"lr = {:.04f}\".format(float(optimizer.param_groups[0]['lr']))\n batch_bar.set_postfix(\n loss=\"{:.04f}\".format(float(total_loss / (i + 1))),\n lr=\"{:.04f}\".format(float(optimizer.param_groups[0]['lr'])))\n loss.backward()\n optimizer.step()\n scheduler.step()\n # tq.update()\n batch_bar.update() \n batch_bar.close()\n now_name = datetime.now().strftime(\"%d_%m_%Y_%H_%M_%S\")\n torch.save(model.state_dict(), f\"{epoch}_{float(total_loss / len(train_loader))}_{now_name}model.pth\")\n tqdm.write(\"Epoch {}/{}: Train Loss {:.04f}, Learning Rate {:.04f}\".format(\n epoch + 1,\n epochs,\n float(total_loss / len(train_loader)),\n float(optimizer.param_groups[0]['lr'])))\n wandb.log({\"Train Loss\": float(total_loss / len(train_loader))})\n wandb.log({\"lr\" : float(optimizer.param_groups[0]['lr'])})\n\n if epoch%5==0:\n model.eval()\n t_dist = 0\n t_val_loss = 0\n for i, data in enumerate(val_loader, 0):\n spectrograms, labels, input_lengths, label_lengths = data\n # print(f\"label_lengths {label_lengths}\")\n spectrograms, labels =spectrograms.to(device), labels\n with torch.no_grad():\n out,out_lengths = model(spectrograms,input_lengths)\n t_val_loss += criterion(out,labels.permute(1,0), input_lengths, label_lengths)\n t_dist += calculate_levenshtein(out, labels.permute(1,0), out_lengths, label_lengths, decoder, PHONEME_MAP)\n dist = t_dist/len(val_loader)\n val_loss = t_val_loss/len(val_loader)\n tqdm.write(\"Epoch {}/{}: val loss {:.04f},distance {:.04f}\".format(\n epoch + 1,\n epochs,\n float(val_loss),\n float(dist)))\n wandb.log({\"dist\" : float(dist)})\n wandb.log({\"val_loss\" : float(val_loss)})\n # break\n ","repo_name":"linjiw/787","sub_path":"hw3p2/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":19535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32653623366","text":"# Maxwell Andrew\n# Apr 23, 2015\n# Interactive game of Blackjack\n\nfrom Tkinter import *\nfrom random import randint\n\nsuits = ['spades','hearts','diamonds','clubs']\nranks = ['ace','two','three','four','five','six','seven','eight','nine','ten','jack','queen','king']\n# computer as p1\np1 = []\n# player as p2\np2 = []\n# values of each card\nval = {}\n\nfor i in range(len(ranks)):\n if i >= 9:\n val.update({ranks[i]:10})\n else:\n val.update({ranks[i]:i+1})\n \ndef play_action():\n global deck\n global p1\n global p2\n\n # reset game\n p1 = []\n p2 = []\n dealer_text.delete('0.0', END)\n player_text.delete('0.0', END)\n de.set('Dealer:')\n pl.set('Player:')\n \n deck = make_deck()\n shuffle(deck)\n \n deal(p1)\n deal(p1)\n deal(p2)\n deal(p2)\n \n player_text.insert(END, make_card(p2[0],p2[1]),'\\n')\n player_text.insert(END, make_card(p2[2],p2[3]),'\\n')\n # keep first hand hidden\n dealer_text.insert(END,'***\\n')\n dealer_text.insert(END,make_card(p1[2],p1[3]),'\\n')\n\n if is_blackjack(p1) or is_blackjack(p2):\n finish_game()\n return None\n\n play_button['state'] = DISABLED\n hit_button['state'] = NORMAL\n stand_button['state'] = NORMAL\n\ndef hit_action():\n deal(p2)\n player_text.insert(END, make_card(p2[len(p2)-2],p2[len(p2)-1]),'\\n')\n if get_value(p2) >= 21:\n finish_game()\n\ndef stand_action():\n while get_value(p1) < 17:\n h = 4\n deal(p1)\n dealer_text.insert(END,make_card(p1[h],p1[h+1]),'\\n')\n h += 2\n finish_game()\n\ndef shuffle(deck):\n for k in range(100): # do it 100 times\n card = deck.pop(randint(0,51)) # remove a random card from the deck\n deck.append(card)\n\ndef make_deck():\n deck = []\n for suit in suits:\n for rank in ranks:\n deck.append((suit,rank))\n return deck\ndeck = make_deck()\nshuffle(deck)\n\ndef make_card(suit,rank):\n return rank + ' of ' + suit + '\\n'\n\ndef deal(player):\n global deck\n card = deck.pop(randint(0,len(deck)-1))\n player += card\n\ndef is_blackjack(player):\n for i in player:\n if (val.get(player[0][1]) == 1 or val.get(player[0][1]) == 10) and (val.get(player[1][1]) == 1 or val.get(player[1][1]) == 10):\n return True\n else:\n return False\n\ndef get_value(player):\n value = 0\n for i in range(1,len(player),2):\n if player[i][:] == 'ace':\n if value + 10 <= 21:\n value += 10\n else:\n value += 1\n else:\n value += val.get(player[i])\n return value\n\ndef finish_game():\n # show card\n dealer_text.delete('1.0', '2.0')\n dealer_text.insert('0.0',make_card(p1[0],p1[1]),'\\n')\n \n de.set('Dealer: ' + str(get_value(p1)))\n # determine winner\n if is_blackjack(p1) and is_blackjack(p2):\n pl.set('Push')\n elif is_blackjack(p1):\n pl.set('House wins')\n elif is_blackjack(p2):\n pl.set('Player wins')\n elif get_value(p2) > 21:\n pl.set('Player busts')\n elif get_value(p1) > 21:\n pl.set('House busts')\n elif get_value(p1) > get_value(p2):\n pl.set('House wins')\n elif get_value(p2) > get_value(p1):\n pl.set('Player wins')\n elif get_value(p1) == get_value(p2):\n pl.set('Push')\n\n play_button['state'] = NORMAL\n hit_button['state'] = DISABLED\n stand_button['state'] = DISABLED\n\n\nwindow = Tk()\nwindow.title('Blackjack')\n\n# create the text widgets\npl = StringVar()\nplayer_label = Label(window,textvariable=pl)\npl.set('Player:')\nplayer_label.grid(row=0,column=0,sticky='W')\nplayer_score = Label(window)\nplayer_score.grid(row=0,column=1,sticky='W')\nplayer_text = Text(window,width=40)\nplayer_text.grid(row=1,column=0,columnspan=3,padx=10,pady=10)\n\nde = StringVar()\ndealer_label = Label(window,textvariable=de)\nde.set('Dealer:')\ndealer_label.grid(row=0,column=3,sticky='W')\ndealer_score = Label(window)\ndealer_score.grid(row=0,column=4,sticky='W')\ndealer_text = Text(window,width=40)\ndealer_text.grid(row=1,column=3,columnspan=3)\n\n# create buttons\nplay_button = Button(window,text='Play',command=play_action)\nplay_button.grid(row=2,column=0,columnspan=2)\nhit_button = Button(window,text='Hit Me',command=hit_action)\nhit_button.grid(row=2,column=2,columnspan=2)\nstand_button = Button(window,text='Stand',command=stand_action)\nstand_button.grid(row=2,column=4,columnspan=2)\n\nplay_button['state'] = NORMAL\nhit_button['state'] = DISABLED\nstand_button['state'] = DISABLED\n\nwindow.mainloop()\n","repo_name":"max-andrew/Blackjack","sub_path":"blackjackgui.py","file_name":"blackjackgui.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34410847038","text":"import os, csv\nimport logging\nfrom flask import Flask\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\nfrom dotenv import load_dotenv\n\napp = Flask(__name__)\napp.app_context().push()\ncors = CORS(app, resource={\n r\"/*\":{\n \"origins\":\"*\"\n }\n}, supports_credentials=True)\n\napp.config['CORS_HEADERS'] = 'Content-Type'\napp.config['CORS_HEADERS'] = 'ACcess-Control-Allow-Origin'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n\nlogging.basicConfig()\n\nload_dotenv()\napp.config ['SQLALCHEMY_DATABASE_URI'] = os.getenv(\"DATABASE_URI\")\n\nimport mail\nfrom database import *\n\n\nlogging.getLogger('sqlalchemy').setLevel(logging.ERROR)\n\nif not os.path.exists(\"reset.csv\"):\n with open(\"reset.csv\", \"w\") as f:\n pass\n\n\nfrom routes.auth import auth\nfrom routes.movies import movie\n\napp.register_blueprint(auth, url_prefix=\"/auth\")\napp.register_blueprint(movie, url_prefix=\"/movies\")\n\nmovies_added = Metadata.query.filter_by(key=\"movies_added\").first()\nif (not movies_added) or (movies_added == \"false\"):\n __import__(\"setup\").get_movies()\n movies_added = Metadata(key=\"movies_added\", value=\"true\")\n db.session.add(movies_added)\n db.session.commit()\n\n\nif __name__ == '__main__':\n app.run(debug=os.getenv(\"DEBUG\"), port=int(os.getenv(\"PORT\")))\n","repo_name":"rithulkamesh/watchflix","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"12512563276","text":"import os\nfrom glob import glob\nimport sys\n\nimport pandas as pd\nimport numpy as np\n\nimport swifter\nimport numba\nfrom multiprocessing import Pool, cpu_count\n\nimport nltk\nfrom nltk.sentiment import vader\n\nfrom libs.writing_utils import get_locations, get_logger\nfrom libs.reading_utils import cleanData\n\nsys.path.append(os.path.dirname(get_locations()[1]))\n\nfrom common_modules.common_utils import merge_csvs, trends_ta\n\ndef applyVader(x, analyzer):\n return analyzer.polarity_scores(x)['compound']\n\ndef applyParallel(dfGrouped, func):\n with Pool(cpu_count()) as p:\n ret_list = p.map(func, [group for name, group in dfGrouped])\n \n return pd.DataFrame(ret_list)\n\nclass historicProcessor:\n '''\n Processor for historic data\n '''\n\n def __init__(self, detailsList, algo_name, relative_dir=\"\"):\n '''\n Parameters:\n ___________\n detailsList (list): \n List containing keyword, coinname in string and start and end in date format. For looping\n\n algo_name (string):\n The name of the algorithm so as to save in file\n\n relative_dir (string):\n The relative directory \n '''\n _, currRoot_dir = get_locations()\n\n self.logger = get_logger(os.path.join(currRoot_dir, \"/logs/historicprocess.log\"))\n\n self.detailsList = detailsList\n self.algo_name = algo_name\n\n self.historic_path = os.path.join(currRoot_dir, relative_dir, \"data/tweet/{}/historic_scrape\")\n\n def read_merge(self, delete=True):\n '''\n Reads many csv files and combines them to one\n\n Paramters:\n _________\n delete (boolean): Deletes the read file later if set to true\n '''\n\n for coinDetail in self.detailsList:\n path = os.path.join(self.historic_path.format(coinDetail['coinname']), \"raw\")\n\n files = glob(path + \"/*\")\n f = merge_csvs(files, ignore_name=\"combined\")\n\n if f != None:\n if (delete==True):\n for file in files:\n os.remove(file)\n\n with open(os.path.join(path, \"combined.csv\"), \"wb\") as out:\n out.write(f.read())\n\n def clean_data(self):\n '''\n Cleans the csv file. Fillna, drop duplicates and such\n '''\n for coinDetail in self.detailsList:\n fileRead = os.path.join(self.historic_path.format(coinDetail['coinname']), \"raw/combined.csv\")\n \n if (os.path.isfile(fileRead)):\n df = pd.read_csv(fileRead)\n df = df.dropna().sort_values('Likes', ascending=False).drop_duplicates('ID').sort_values('Time').reset_index(drop=True)\n df.to_csv(fileRead, index=None)\n self.logger.info(\"Saved cleaned data to {}\".format(fileRead))\n\n def f_add_features(self, x):\n '''\n Calcualtes features based on the data\n\n Parameters:\n ___________\n x (part of dataframe):\n The group which should be merged\n\n Returns:\n _______\n y (dataframe):\n Feature calculated from the data\n '''\n y = pd.Series()\n\n try:\n t = x.index[0]\n y['Time'] = pd.Timestamp(\"{}-{}-{} {}:00:00\".format(t.year, t.month, t.day, t.hour))\n except:\n pass\n \n x = x.assign(f = x['Likes'] + x['Replies'] + x['Retweets']).sort_values('f', ascending=False).drop('f', axis=1)\n \n Nbullish = sum(x['sentiment'] > 0) #should use something else later\n Nbearish = sum(x['sentiment'] < 0)\n \n y['mean_vader_all'] = x['sentiment'].mean()\n \n #doi.org/10.1016/j.eswa.2016.12.036\n y['n_bullish_all'] = Nbullish\n y['n_bearish_all'] = Nbearish\n \n try:\n y['bullish_ratio_all'] = Nbullish / (Nbullish + Nbearish)\n except:\n y['bullish_ratio_all'] = np.nan\n \n try:\n y['bearish_ratio_all'] = Nbearish / (Nbullish + Nbearish)\n except:\n y['bearish_ratio_all'] = np.nan\n \n y['bullish_index_all'] = np.log((Nbullish + 1)/(Nbearish + 1))\n \n try:\n y['agreement_all'] = 1 - np.sqrt(1-(((Nbullish - Nbearish)/(Nbullish + Nbearish))**2) )\n except:\n y['agreement_all'] = np.nan\n \n try:\n y['spread_all'] = (Nbullish - Nbearish)/(Nbullish + Nbearish)\n except:\n y['spread_all'] = np.nan\n \n xTopAll = x.iloc[:int(x.shape[0] * .15)]\n \n y['mean_vader_top'] = xTopAll['sentiment'].mean()\n y['mean_likes_top'] = xTopAll['Likes'].mean()\n y['mean_replies_top'] = xTopAll['Replies'].mean()\n y['mean_retweets_top'] = xTopAll['Retweets'].mean()\n \n return y\n\n def create_ml_features(self):\n '''\n Create features from these textual data\n '''\n\n for coinDetail in self.detailsList:\n savePath = os.path.join(self.historic_path.format(coinDetail['coinname']), \"interpreted/data-{}.csv\".format(self.algo_name))\n\n if (not(os.path.isfile(savePath))):\n path = os.path.join(self.historic_path.format(coinDetail['coinname']), \"raw\")\n\n combinedCsv = os.path.join(path, \"combined.csv\")\n\n if os.path.isfile(combinedCsv):\n df = pd.read_csv(combinedCsv, lineterminator='\\n')\n self.logger.info(\"CSV file read for {}\".format(coinDetail['coinname']))\n\n df['Tweet'] = cleanData(df['Tweet'])\n self.logger.info(\"Tweets Cleaned\")\n \n df['Time'] = pd.to_datetime(df['Time'], unit='s')\n df = df.set_index('Time')\n \n self.logger.info(\"Calculating sentiment\")\n analyzer = vader.SentimentIntensityAnalyzer()\n df['sentiment'] = df['Tweet'].swifter.apply(applyVader, analyzer=analyzer)\n\n self.logger.info(\"Now calculating features\")\n df = applyParallel(df.groupby(pd.Grouper(freq='H')), self.f_add_features)\n df['Time'] = pd.date_range(df['Time'].iloc[0], df['Time'].iloc[-1], periods=df['Time'].shape[0])\n self.logger.info(\"Features Calculated\")\n \n df['variation_all'] = df['n_bullish_all'].diff()\n df = df.drop(['n_bullish_all', 'n_bearish_all'], axis=1)\n df['mean_vader_change_top'] = df['mean_vader_top'].diff()\n #add botorNot too\n df = trends_ta(df, 'mean_vader_top')\n df = trends_ta(df, 'mean_vader_all')\n df = df.replace(np.inf, 0)\n df = df.replace(-np.inf, 0)\n df = df.replace(np.nan, 0)\n \n df.to_csv(savePath, index=None)\n self.logger.info(\"Added all features. Saved to {}\".format(savePath))\n else:\n self.logger.info(\"{} does not exists so skipping\".format(combinedCsv))\n else:\n self.logger.info(\"Using the cached file from {}\".format(savePath))\n\n def create_visualization_features(self):\n pass\n\nclass profileProcessor:\n def __init__(self, detailsList, relative_dir=\"\"):\n '''\n Parameters:\n ___________\n detailsList (list): \n List containing keyword, coinname in string and start and end in date format. For looping\n\n relative_dir (string):\n The relative directory \n '''\n _, currRoot_dir = get_locations()\n\n self.logger = get_logger(os.path.join(currRoot_dir, \"logs/profileprocess.log\"))\n self.detailsList = detailsList\n self.profile_path = os.path.join(currRoot_dir, relative_dir, \"data/profile\")\n\n @numba.jit\n def clean_data(self):\n '''\n Cleans the csv file. Fillna, drop duplicates and such\n '''\n live_userData_dir = os.path.join(self.profile_path, \"live/userData.csv\")\n live_userTweets_dir = os.path.join(self.profile_path, \"live/userTweets.csv\")\n\n processed_userData_dir = os.path.join(self.profile_path, \"storage/raw/userData.csv\")\n processed_userTweets_dir = os.path.join(self.profile_path, \"storage/raw/userTweets.csv\")\n\n userData = pd.read_csv(live_userData_dir, low_memory=False)\n \n try:\n userData=pd.concat([userData, pd.read_csv(processed_userData_dir, low_memory=False)])\n except:\n pass\n \n self.logger.info(\"User Data Read\")\n \n userTweets = pd.read_csv(live_userTweets_dir, low_memory=False)\n \n try:\n userTweets=pd.concat([userTweets, pd.read_csv(processed_userTweets_dir, low_memory=False)])\n except:\n pass\n\n self.logger.info(\"User Tweets Read\")\n \n userTweets = userTweets.rename(columns={'User': 'username'})\n\n merged = pd.merge(userData, userTweets, how='inner', on=['username'])\n self.logger.info(\"Inner Merged Done\")\n \n newuserData = merged[userData.columns]\n newuserData = newuserData.set_index('username').drop_duplicates().reset_index()\n\n newuserTweets = merged[userTweets.columns]\n newuserTweets = newuserTweets.rename(columns={'username': 'User'})\n\n newuserTweets = newuserTweets.set_index(['User', 'ID']).drop_duplicates().reset_index()\n \n self.logger.info(\"All done saving\")\n\n newuserData.to_csv(processed_userData_dir, index=None)\n self.logger.info(\"userData.csv has been updated and moved\")\n os.remove(live_userData_dir)\n self.logger.info(\"Deleting userData.csv in the live folder\")\n \n newuserTweets.to_csv(processed_userTweets_dir, index=None)\n self.logger.info(\"userTweets.csv has been updated and moved\")\n os.remove(live_userTweets_dir)\n self.logger.info(\"Deleting userTweets.csv in the live folder\")\n \n newuserData['username'].to_csv(os.path.join(self.profile_path, \"extractedUsers.csv\"), index=None)\n self.logger.info(\"extractedUsers.csv has been updated\")\n os.remove(os.path.join(self.profile_path, \"live/userData.csv\"))\n self.logger.info(\"Deleting extractedUsers.csv in the live folder\")\n\n\n def create_ml_features(self):\n '''\n Create features from these data\n '''\n pass","repo_name":"ronaldzgithub/CryptoTrader","sub_path":"src/data_utils/twitter_data/processor/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":10513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"12717320698","text":"from unittest.mock import Mock, patch\nfrom langchain.base_language import BaseLanguageModel\nfrom langchain.chat_models import ChatOpenAI\n\nfrom gpt.chains.decide_chain.chain import create_decide_chain\n\n\ndef test_create_decide_chain_openai():\n llm = Mock(spec=ChatOpenAI)\n instructions = 'Decide this'\n output_type = 'string'\n possible_values = ['value1', 'value2']\n\n with patch('gpt.chains.decide_chain.chain.create_openai_functions_decide_chain') as mock_openai_chain:\n chain = create_decide_chain(llm, instructions, output_type, possible_values)\n\n mock_openai_chain.assert_called_once_with(llm, instructions, output_type, possible_values)\n assert chain == mock_openai_chain.return_value\n\n\ndef test_create_decide_chain_standard():\n llm = Mock(spec=BaseLanguageModel)\n instructions = 'Decide this'\n output_type = 'string'\n possible_values = ['value1', 'value2']\n\n with patch('gpt.chains.decide_chain.chain.create_standard_decide_chain') as mock_standard_chain:\n chain = create_decide_chain(llm, instructions, output_type, possible_values)\n\n mock_standard_chain.assert_called_once_with(llm, instructions, output_type, possible_values)\n assert chain == mock_standard_chain.return_value\n","repo_name":"holunda-io/camunda-8-connector-gpt","sub_path":"python/tests/chains/decide_chain/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"52"} +{"seq_id":"35754975482","text":"from PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\nimport sys\r\nfrom Database import *\r\nimport datetime\r\n\r\n\r\nclass Clarification(QMainWindow):\r\n\tdef __init__(self,parent,fullName):\r\n\t\tsuper().__init__()\r\n\t\t#reassinging the variables so that they can be used in the class\r\n\t\tself.parent = parent\r\n\t\tself.fullName = fullName\r\n\t\t#Setting the window title\r\n\t\tself.setWindowTitle(\"Sign Out\")\r\n\t\t#Widget set up\r\n\t\t#Using 'format' to add a variable into the label\r\n\t\tself.label=QLabel(\"Sign out {0}?\".format(fullName))\r\n\t\tself.btnBack = QPushButton(\"Cancel\")\r\n\t\tself.btnOut = QPushButton(\"Sign Out\")\r\n\t\t\r\n\t\tself.hLayout = QHBoxLayout()\r\n\t\tself.vLayoutMain = QVBoxLayout()\r\n\t\t\r\n\t\tself.hLayout.addWidget(self.btnBack)\r\n\t\tself.hLayout.addWidget(self.btnOut)\r\n\t\tself.vLayoutMain.addWidget(self.label)\r\n\t\tself.vLayoutMain.addLayout(self.hLayout)\r\n\t\tself.widget = QWidget()\r\n\t\tself.widget.setLayout(self.vLayoutMain)\r\n\t\tself.setCentralWidget(self.widget)\r\n\t\t#Setting up the push button connections\r\n\t\tself.btnBack.clicked.connect(self.btnBackPushed)\r\n\t\tself.btnOut.clicked.connect(self.btnOutClicked)\r\n\t#returning to the parent window\r\n\tdef btnBackPushed(self):\r\n\t\tself.parent.show()\r\n\t\tself.parent.raise_()\r\n\t\tself.close()\r\n\t#Signing out the chosen visitor\r\n\tdef btnOutClicked(self):\r\n\t\t#retrieving all visitors in the database\r\n\t\tvisitors = g_database.GetAllEntries()\r\n\t\tcount= 0\r\n\t\t#Splitting 'self.fullName' into forename and surname\r\n\t\t#Working out how many characters are in the forename\r\n\t\twhile self.fullName[count] != \" \":\r\n\t\t\tcount = count+1\r\n\t\t#Setting up a blank string\r\n\t\tforename = \"\"\r\n\t\t#Adding each character to the string\r\n\t\tfor each in range(count):\r\n\t\t\tforename = forename+self.fullName[each]\r\n\t\t#Incrementing the count variable to account for the space between forename and surname\r\n\t\tcount = count +1\r\n\t\t#Setting up a blank string\r\n\t\tsurname=\"\"\r\n\t\t#Using the full name length minus the already calculated forename length to calculate the surname length \r\n\t\tfor each in range(len(self.fullName)-count):\r\n\t\t\t#Adding each character to the string\r\n\t\t\tsurname = surname + self.fullName[count]\r\n\t\t\tcount = count +1\r\n\t\tfor visitor in visitors:\r\n\t\t\t#matching the chosen visitor to its position in the database\r\n\t\t\tif forename == visitor[1] and surname == visitor[2]:\r\n\t\t\t\t#Locally assigning the visitor ID\r\n\t\t\t\tvisitorID = visitor[0]\r\n\t\t#Obtaining the current date and time\t\t\r\n\t\ttime = datetime.datetime.now().time()\r\n\t\t#Selecting just the time\r\n\t\toutTime =time.strftime('%H:%M')\r\n\t\t#Appending the database to add a sign out time to the chosen user\r\n\t\tg_database.SignOut(visitorID,outTime)\r\n\t\t#Returning the user menu without opening window upon window\r\n\t\tself.parent.btnBack_pushed()\r\n\t\tself.close()\r\n\t\t\r\n\t\t\t\t","repo_name":"44746/VisitorBook","sub_path":"Visitor Book Code/OutClarification.py","file_name":"OutClarification.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16522478855","text":"import argparse\nimport pkg_resources\nimport os.path\nimport sys\n\nimport yaml\n\nfrom amoeba.core import *\n\n\ndef main():\n # Initialize command-line argument parsing.\n parser = argparse.ArgumentParser(\n description=\"Don't panic.\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-v', '--verbose', action='store_true', help='be verbose')\n parser.add_argument('-c', '--config', type=str, default='amoeba.yaml', metavar='YAML', help='config file to use')\n parser.add_argument('-n', '--num-players', type=int, metavar='N', help='number of players')\n parser.add_argument('-e', '--num-epidemics', type=int, metavar='N', help='number of epidemic cards')\n args = parser.parse_args()\n\n # Load our YAML configuration file.\n if os.path.exists(args.config):\n # Use a fully specified file name.\n with open(args.config) as f:\n config = yaml.safe_load(f)\n elif pkg_resources.resource_exists(__name__, os.path.join('data', args.config)):\n # Use a file under our package's data directory.\n with pkg_resources.resource_stream(__name__, os.path.join('data', args.config)) as f:\n config = yaml.safe_load(f)\n else:\n print(f'Unable to locate the specified config file: {args.config}.')\n sys.exit(-1)\n\n # Initialize the world.\n world = World(config)\n\n # Start the game.\n world.start(args.num_players, args.num_epidemics)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"trevorKirkby/amoeba","sub_path":"amoeba/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26532286271","text":"N, M = map(int, input().split())\nsweets = sorted(list(map(int, input().split())), reverse=True)\ngroupings = [[] for i in range(M)]\nfor i, item in enumerate(sweets):\n groupings[i % M].append(item)\n \ncumsum = [[0 for i in range(len(groupings[i]))] for i in range(M)]\nfor t in range(M):\n cumsum[t][-1] = groupings[t][-1]\n for i, item in enumerate(list(reversed(groupings[t]))[1:]):\n cumsum[t][-i-2] = cumsum[t][-i-1] + item\n\noutput = []\ntotal = 0\nfor i in range(N, -1, -1):\n if i == N:\n for i, sweet in enumerate(sweets):\n total += sweet * (i // M + 1)\n else:\n j = N - i - 1\n total -= cumsum[j%M][j//M]\n output.append(total)\nprint(*list(reversed(output))[1:])\n\n","repo_name":"cormackikkert/competitive-programming","sub_path":"CodeForces/Round 600/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30344371527","text":"from launch import LaunchDescription\nfrom launch_ros.actions import Node\nimport os\n\n\npackage_name = os.path.realpath(__file__).split(os.sep)[-3] # get name of this package\n#package_name = \"emotion_detection\"\n\n\n\n\ndef generate_launch_description():\n \n launch_description = LaunchDescription()\n\n\n face_detection_node = Node(\n package=package_name,\n executable=\"face_detection\",\n )\n\n emotion_detection_node = Node(\n package=package_name,\n executable=\"emotion_detection\",\n\n )\n\n action_client_node = Node(\n package=package_name,\n executable=\"action_client\",\n # output='screen',\n # emulate_tty=True,\n )\n\n launch_description.add_action(face_detection_node)\n launch_description.add_action(emotion_detection_node)\n launch_description.add_action(action_client_node)\n\n return launch_description\n","repo_name":"ouspg/SOP-Robot","sub_path":"src/emotion_detection/launch/main.launch.py","file_name":"main.launch.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"16806513258","text":"import torch\nimport torch.nn.functional as F\n\n\n# ---------------------------------------------------------------------------- #\n# Distance\n# ---------------------------------------------------------------------------- #\ndef bpdist(feature, data_format='NCW'):\n \"\"\"Compute pairwise (square) distances of features.\n Based on $(x-y)^2=x^2+y^2-2xy$.\n\n Args:\n feature (torch.Tensor): (batch_size, channels, num_inst)\n data_format (str): the format of features. [NCW/NWC]\n\n Returns:\n distance (torch.Tensor): (batch_size, num_inst, num_inst)\n\n Notes:\n This method returns square distances, and is optimized for lower memory and faster speed.\n Square sum is more efficient than gather diagonal from inner product.\n The result is somehow inaccurate compared to directly using $(x-y)^2$.\n\n \"\"\"\n assert data_format in ('NCW', 'NWC')\n if data_format == 'NCW':\n square_sum = torch.sum(feature ** 2, 1, keepdim=True)\n square_sum = square_sum.transpose(1, 2) + square_sum\n distance = torch.baddbmm(square_sum, feature.transpose(1, 2), feature, alpha=-2.0)\n else:\n square_sum = torch.sum(feature ** 2, 2, keepdim=True)\n square_sum = square_sum.transpose(1, 2) + square_sum\n distance = torch.baddbmm(square_sum, feature, feature.transpose(1, 2), alpha=-2.0)\n return distance\n\n\ndef bpdist2(feature1, feature2, data_format='NCW'):\n \"\"\"Compute pairwise (square) distances of features.\n\n Args:\n feature1 (torch.Tensor): (batch_size, channels, num_inst1)\n feature2 (torch.Tensor): (batch_size, channels, num_inst2)\n data_format (str): the format of features. [NCW/NWC]\n\n Returns:\n distance (torch.Tensor): (batch_size, num_inst1, num_inst2)\n\n \"\"\"\n assert data_format in ('NCW', 'NWC')\n if data_format == 'NCW':\n square_sum1 = torch.sum(feature1 ** 2, 1, keepdim=True)\n square_sum2 = torch.sum(feature2 ** 2, 1, keepdim=True)\n square_sum = square_sum1.transpose(1, 2) + square_sum2\n distance = torch.baddbmm(square_sum, feature1.transpose(1, 2), feature2, alpha=-2.0)\n else:\n square_sum1 = torch.sum(feature1 ** 2, 2, keepdim=True)\n square_sum2 = torch.sum(feature2 ** 2, 2, keepdim=True)\n square_sum = square_sum1 + square_sum2.transpose(1, 2)\n distance = torch.baddbmm(square_sum, feature1, feature2.transpose(1, 2), alpha=-2.0)\n return distance\n\n\ndef pdist2(feature1, feature2):\n \"\"\"Compute pairwise (square) distances of features.\n\n Args:\n feature1 (torch.Tensor): (num_inst1, channels)\n feature2 (torch.Tensor): (num_inst2, channels)\n\n Returns:\n distance (torch.Tensor): (num_inst1, num_inst2)\n\n \"\"\"\n square_sum1 = torch.sum(feature1 ** 2, 1, keepdim=True)\n square_sum2 = torch.sum(feature2 ** 2, 1, keepdim=True)\n square_sum = square_sum1 + square_sum2.transpose(0, 1)\n distance = torch.addmm(square_sum, feature1, feature2.transpose(0, 1), alpha=-2.0)\n return distance\n\n\n# ---------------------------------------------------------------------------- #\n# Losses\n# ---------------------------------------------------------------------------- #\ndef encode_one_hot(target, num_classes):\n \"\"\"Encode integer labels into one-hot vectors\n\n Args:\n target (torch.Tensor): (N,)\n num_classes (int): the number of classes\n\n Returns:\n torch.FloatTensor: (N, C)\n\n \"\"\"\n one_hot = target.new_zeros(target.size(0), num_classes)\n one_hot = one_hot.scatter(1, target.unsqueeze(1), 1)\n return one_hot.float()\n\n\ndef smooth_cross_entropy(input, target, label_smoothing):\n \"\"\"Cross entropy loss with label smoothing\n\n Args:\n input (torch.Tensor): (N, C)\n target (torch.Tensor): (N,)\n label_smoothing (float):\n\n Returns:\n loss (torch.Tensor): scalar\n\n \"\"\"\n assert input.dim() == 2 and target.dim() == 1\n assert isinstance(label_smoothing, float)\n batch_size, num_classes = input.shape\n one_hot = torch.zeros_like(input).scatter(1, target.unsqueeze(1), 1)\n smooth_one_hot = one_hot * (1 - label_smoothing) + torch.ones_like(input) * (label_smoothing / num_classes)\n log_prob = F.log_softmax(input, dim=1)\n loss = (- smooth_one_hot * log_prob).sum(1).mean()\n return loss\n\n\n# ---------------------------------------------------------------------------- #\n# Indexing\n# ---------------------------------------------------------------------------- #\ndef batch_index_select(input, index, dim):\n \"\"\"Batch index_select\n\n References: https://discuss.pytorch.org/t/batched-index-select/9115/7\n\n Args:\n input (torch.Tensor): (b, ...)\n index (torch.Tensor): (b, n)\n dim (int): the dimension to index\n\n \"\"\"\n assert index.dim() == 2, 'Index should be 2-dim.'\n assert input.size(0) == index.size(0), 'Mismatched batch size: {} vs {}'.format(input.size(0), index.size(0))\n batch_size = index.size(0)\n num_select = index.size(1)\n views = [1 for _ in range(input.dim())]\n views[0] = batch_size\n views[dim] = num_select\n expand_shape = list(input.shape)\n expand_shape[dim] = -1\n index = index.view(views).expand(expand_shape)\n return torch.gather(input, dim, index)\n","repo_name":"maxjaritz/mvpnet","sub_path":"common/nn/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"52"} +{"seq_id":"26560396859","text":"import streamlit as st\nimport json\nimport pandas as pd\nfrom urllib.request import urlopen\nimport altair as alt\nimport numpy as np\n\n\nst.sidebar.header(\"Input parameters\")\nst.sidebar.write(\"This is the project sidebar \\nIn here you can select different parameters that will affect all the visualizations in the page.\")\n\n#st.sidebar.subheader(\"Year selector\")\n\n#year = st.sidebar.slider(\"Year\", 1960, 2020, 2020, step = 1)\n\n\n\nst.sidebar.subheader(\"Region selector\")\n\n\ncontainer = st.sidebar.container()\n#container = st.sidebar.container()\n#container = st.sidebar.container()\n\n\nall = st.sidebar.checkbox(\"Select all\")\n\nif all:\n country = container.multiselect(\"Select the countries:\",\n st.session_state['countries'], st.session_state['countries'])\nelse:\n country = container.multiselect(\"Select the countries:\",\n st.session_state['countries'])\n\nst.markdown(\"\"\"\n # Overview on Cereal Yield\n\n This is a dashboard that shows the quantity of cereal that has been yield for each country, for several years.\n In the dataframe you can see the raw data, while in the plot below you can the XXXXXXXX\n \"\"\")\n \ndf = st.session_state['cereal_output']\ndf = df[(df['country'].isin(country))]\ndf = df[df.columns[:-1]]\ndf = df.fillna(0)\n\nst.dataframe(data= df)\n\ndf = df.transpose()\ndf = df.astype(int)\n\nchart_data = pd.DataFrame(\n df,\n columns=df.columns)\n\nst.line_chart(chart_data)#, height=500)\n\n","repo_name":"RubenMolinaDev/AgricultureDashboard","sub_path":"Web/pages/2_🌾_Cereal_Dashboard.py","file_name":"2_🌾_Cereal_Dashboard.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10558224479","text":"n = int(input())\ny_result = [[0 for j in range(2)] for j in range(n + 1)]\nfor i in range(1, n + 1):\n y_result[i] = [int(x) for x in input().split()]\ny_result = sorted(y_result, key=lambda x: x[0])\nprefix = [0 for i in range(n + 2)]\nsuffix = [0 for i in range(n + 2)]\nfor i in range(1, n + 1):\n prefix[i] = prefix[i - 1] + (1 if y_result[i][1] == 0 else 0)\nfor i in range(n, 0, -1):\n suffix[i] = suffix[i + 1] + (1 if y_result[i][1] == 1 else 0)\np = [0 for i in range(n + 1)]\nfor i in range(1, n + 1):\n if y_result[i][0] == y_result[i - 1][0]:\n p[i] = p[i - 1]\n else:\n p[i] = i\nresult = 0\nmax_count = 0\ntheta = 0\nfor i in range(1, n + 1):\n temp = prefix[p[i] - 1] + suffix[i]\n if temp >= max_count:\n max_count = temp\n theta = max(y_result[i][0], theta)\nprint(theta, end='')\n\n\n'''\ny = []\nresult = []\nfor i in range(n):\n y_i, result_i = [int(x) for x in input().split()]\n y.append(y_i)\n result.append(result_i)\ncounts = []\nfor theta in y:\n temp_count = 0\n for y_i, result_i in zip(y, result):\n if y_i >= theta:\n temp_result = 1\n else:\n temp_result = 0\n if temp_result == result_i:\n temp_count += 1\n counts.append(temp_count)\nmax_count = 0\nfor count in counts:\n if count > max_count:\n max_count = count\nmax_theta = 0\nfor idx, y_i in enumerate(y):\n if counts[idx] == max_count and y_i > max_theta:\n max_theta = y_i\nprint(max_theta, end='')\n'''","repo_name":"scarlettllc/csp_python3","sub_path":"2/202012-2.py","file_name":"202012-2.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25669065355","text":"import sqlite3\nfrom sqlite3.dbapi2 import connect\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\n\nclass Item(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('price',\n type=float,\n required=True,\n help=\"This field cannot be blank!\"\n )\n\n @jwt_required() # Note* Parenthesis help.\n def get(self, name):\n #item = next(filter(lambda i: i['name'] == name, items), None) # This is the same as the commented code below.\n #return {'item':item}, 200 if item else 404 # Return a value and a status code.\n item = self.find_by_name(name)\n if item:\n return item, 200\n return {'message':\"This item does not exist within this database!\"}, 404\n\n @classmethod\n def find_by_name(cls, name):\n connection = sqlite3.connect('my_data.db')\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items WHERE name = ?\"\n item = cursor.execute(query, (name,))\n row = item.fetchone()\n connection.close()\n\n if row:\n return {'item': {'name':row[0], 'price':row[1]}}\n return None\n\n def post(self, name):\n #if next(filter(lambda item: item['name'] == name, items), None) is not None:\n #return {'message':f'Item {name} already exists!'}, 400\n #payload = request.get_json() # I could set force = True to force the content type to be JSON, however this is risky and should be avoided. Otherwise, I should set silent = True.\n #payload = Item.parser.parse_args()\n #item = {'name':name, 'price':payload['price']}\n #items.append(item)\n #return item, 201\n if self.find_by_name(name):\n return {'message': 'This item already exists within the database!'}, 409\n \n connection = sqlite3.connect('my_data.db')\n cursor = connection.cursor()\n data = Item.parser.parse_args()\n\n query = \"INSERT INTO items VALUES (?, ?)\"\n cursor.execute(query, (name, data['price']))\n\n connection.commit()\n connection.close()\n\n return {'name':name, 'price':data['price']}, 201\n\n def put(self, name):\n #item = next(filter(lambda item: item['name'] == name, items), None) \n #status_code = 200 if item else 201\n #payload = request.get_json()\n #payload = Item.parser.parse_args()\n\n #if item is None:\n #item = {'name':name, 'price':payload['price']}\n #items.append(item)\n #else:\n #item.update(payload)\n #return item, status_code\n connection = sqlite3.connect('my_data.db')\n cursor = connection.cursor()\n data = self.parser.parse_args()\n item_exists = self.find_by_name(name)\n query = \"UPDATE items SET price = ? WHERE name = ?\" if item_exists else \"INSERT INTO items VALUES (?, ?)\"\n\n if item_exists:\n cursor.execute(query, (data['price'], name))\n else:\n cursor.execute(query, (name, data['price']))\n \n status_code = 200 if item_exists else 201\n connection.commit()\n connection.close()\n\n return {'name':name, 'price':data['price']}, status_code\n\n def delete(self, name):\n #global items\n #items = list(filter(lambda x:x['name'] != name, items))\n #return {'message':'Success!'}, 410\n connection = sqlite3.connect('my_data.db')\n cursor = connection.cursor()\n\n query = \"DELETE FROM items WHERE name = ?\"\n cursor.execute(query, (name,))\n\n connection.commit()\n connection.close()\n\n return {'message':'Success!'}, 410\n\nclass ItemList(Resource):\n def get(self):\n #return {'items':items}, 200\n connection = sqlite3.connect('my_data.db')\n cursor = connection.cursor()\n\n query = \"SELECT * FROM items\"\n result = cursor.execute(query)\n items = []\n for row in result.fetchall():\n items.append({'name':row[0], 'price':row[1]})\n\n connection.close()\n\n return {'items':items}\n","repo_name":"dommie123/My-First-Flask-App","sub_path":"section5/code/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11154228945","text":"import sys, cv2, numpy as np\n\nref = cv2.imread('./images/k1.png', cv2.IMREAD_COLOR)\nmask = cv2.imread('./images/k1_mask.bmp', cv2.IMREAD_GRAYSCALE)\n\nif ref is None or mask is None:\n print('image load failed!')\n sys.exit()\n\nref_ycrcb = cv2.cvtColor(ref, cv2.COLOR_BGR2YCrCb)\nchannels = [1, 2]\nranges = [0, 256, 0, 256]\nhist = cv2.calcHist([ref_ycrcb], channels, mask, [128, 128], ranges)\n\nhist_norm = cv2.normalize(hist, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)\n\n# 역투영 적용 이미지\nsrc = cv2.imread('./images/k2.png', cv2.IMREAD_COLOR)\nsrc_ycrcb = cv2.cvtColor(src, cv2.COLOR_BGR2YCrCb)\nbackproj = cv2.calcBackProject([src_ycrcb], channels, hist, ranges, 1)\n\nh, w = src.shape[:2]\ndst = np.zeros((h, w, 3), np.uint8)\ndst[backproj > 30] = src[backproj > 30]\n\ncv2.imshow('src', src)\ncv2.imshow('dst', dst)\ncv2.waitKey()\n\ncv2.destroyAllWindows()","repo_name":"tmd9936/ys_study","sub_path":"comVision/back_projection_test.py","file_name":"back_projection_test.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19359465835","text":"# -*- coding: utf-8 -*-\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import Rule\nfrom news_all.spider_models import NewsRCSpider, isStartUrl_meta\nfrom news_all.tools.time_translater import Pubtime\n\n\nclass ifnewsSpider(NewsRCSpider):\n \"\"\"国际金融报网_第四批\"\"\"\n name = 'ifnews'\n mystart_urls = {\n 'http://www.ifnews.com/': 573, # 首页\n 'http://www.ifnews.com/5/': 574, # 公司\n 'http://www.ifnews.com/18/': 575, # 金融\n 'http://www.ifnews.com/19/': 576, # 机构\n 'http://www.ifnews.com/3/': 577, # 国际\n }\n\n rules = (\n Rule(LinkExtractor(allow=(r'ifnews.com/.*?\\d+.html',), ), callback='parse_item', follow=False),\n # http://www.ifnews.com/5/?page=3\n Rule(LinkExtractor(allow=r'ifnews.com/\\d+/\\?page=\\d+',\n restrict_xpaths='//div[@class=\"pagelist\"]/span[@class=\"down\"]/a'),\n follow=True, process_request=isStartUrl_meta),\n )\n custom_settings = {'DEPTH_LIMIT': 3} # 列表翻页要设置深度\n \n def parse_item(self, response):\n # http://www.ifnews.com/17/detail-38125.html 采集不全已解决\n if \"Database Error\" in self.get_page_title(response):\n return self.produce_debugitem(response, 'ifnews.com Database Error')\n xp = response.xpath\n try:\n ps = xp('//span[@class=\"publish-time\"]/text()').extract_first(\"\") or xp('//h2/span/i').extract()[0]\n pubtime = Pubtime(ps)\n title = xp('//h2/text()')[0].extract().strip()\n content_div = xp('//div[@class=\"left bgf\"]')\n content, media, videos, cover = self.content_clean(content_div, need_video=True, kill_xpaths=[r'.//h2',\n r'.//div[@class=\"fx_tit\"]/parent::div'])\n\n except:\n return self.produce_debugitem(response, \"xpath error\")\n\n return self.produce_item(\n response=response,\n title=title,\n pubtime=pubtime,\n content=content,\n media=media,\n videos=videos\n )\n","repo_name":"Pintrue/news_all","sub_path":"news_all/spiders_four/ifnews.py","file_name":"ifnews.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"33523752373","text":"'''\nThis script pre-processes the MP3 data for autoencoding.\nSeveral features are calculated for wav files in a specified directory, \nwhich have been converted to wav from MP3 format.\n\nThe output of this script is Mel Spectrogram images for each wav file.\n'''\n\nimport numpy as np\nimport librosa\nimport librosa.display\nimport matplotlib.pyplot as plt\nimport os\nimport glob\nimport csv\nimport math\n\n#Define all major scales to be used later for finding key signature\n#Arrays all in the format: [C, C#, D, Eb, E, F, F#, G, Ab, A, Bb, B]\nmajorscales = {'C' : [1,0,1,0,1,1,0,1,0,1,0,1],\n 'C#': [1,1,0,1,0,1,1,0,1,0,1,0],\n 'D' : [0,1,1,0,1,0,1,1,0,1,0,1],\n 'Eb': [1,0,1,1,0,1,0,1,1,0,1,0],\n 'E' : [0,1,0,1,1,0,1,0,1,1,0,1],\n 'F' : [1,0,1,0,1,1,0,1,0,1,1,0],\n 'F#': [0,1,0,1,0,1,1,0,1,0,1,1],\n 'G' : [1,0,1,0,1,0,1,1,0,1,0,1],\n 'Ab': [1,1,0,1,0,1,0,1,1,0,1,0],\n 'A' : [0,1,1,0,1,0,1,0,1,1,0,1],\n 'Bb': [1,0,1,1,0,1,0,1,0,1,1,0],\n 'B' : [0,1,0,1,1,0,1,0,1,0,1,1]}\n\nclass Audio(object):\n \n \"\"\"\n Song objects are initiated with librosa.load() which produces an array \n containing wav data in the first index and the wav's sample frequency \n in the second.\n \n Stereo audio will be converted to mono by librosa.load() by averaging \n the left and right channels. This halves both the sample frequency and \n the number of sample points. Note that the channel averaging method of \n conversion gives each channel equal weight, which may not always be \n appropriate. Lossless conversion of stereo to mono is impossible. \n \n Instead of converting to mono, file could be imported as stereo and each \n channel could be accessed individually by setting mono=False and subsetting:\n wav[:,0] and wav[:,1]\n \n wav.dtype will be 1 of 2 types:\n 1) 16-bit - This means that the sound pressure values are mapped to \n integer values ranging from -2^15 to (2^15)-1. If wav.dtype is 16-bit,\n it will need to be converted to 32-bit ranging from -1 to 1\n 2) 32-bit - This means that the sound pressure values are mapped to\n floating point values ranging from -1 to 1\n \"\"\"\n \n def __init__(self, loadedAudio):\n self.wav = loadedAudio[0]\n self.samplefreq = loadedAudio[1]\n #If imported as 16-bit, convert to floating 32-bit ranging from -1 to 1\n if (self.wav.dtype == 'int16'):\n self.wav = self.wav/(2.0**15)\n self.channels = 1 #Assumes mono, if stereo then 2 (found by self.wav.shape[1])\n self.sample_points = self.wav.shape[0]\n self.audio_length_seconds = self.sample_points/self.samplefreq\n self.time_array_seconds = np.arange(0, self.sample_points, 1)/self.samplefreq\n self.tempo_bpm = librosa.beat.beat_track(y=self.wav, sr=self.samplefreq)[0]\n self.beat_frames = librosa.beat.beat_track(y=self.wav, sr=self.samplefreq)[1]\n #Transform beat array into seconds (these are the times when the beat hits)\n self.beat_times = librosa.frames_to_time(self.beat_frames, sr=self.samplefreq)\n #Get the rolloff frequency - the frequency at which the loudness drops off by 90%, like a low pass filter\n self.rolloff_freq = np.mean(librosa.feature.spectral_rolloff(y=self.wav, sr=self.samplefreq, hop_length=512, roll_percent=0.9))\n \n def plotWav(self):\n plt.plot(self.time_array_seconds, self.wav, color='k')\n plt.xlabel('Time (seconds)')\n plt.ylabel('Amplitude')\n plt.show()\n\n def getTempo(self):\n print('Estimated tempo: {:.2f} beats per minute'.format(self.tempo_bpm))\n \n def getPercussiveTempo(self):\n #Separate the harmonics and percussives into 2 waves\n wav_harm, wav_perc = librosa.effects.hpss(self.wav)\n #Beat track the percussive signal\n tempo, beat_frames = librosa.beat.beat_track(y=wav_perc, sr=self.samplefreq)\n print('Estimated percussive tempo: {:.2f} beats per minute'.format(tempo))\n return tempo\n \n def getZeroCrossingRates(self):\n \"\"\"\n ZCR is the count of times signal crosses 0 in a wave. It is useful \n for speech recognition and separating speech from background noise.\n ZCR will be smaller when a voice is speaking (0 is crossed less \n frequently) and larger when there is a lot of background noise (0 is \n crossed more frequently)\n \n ZCR is calculated by frame\n \"\"\"\n zcrs = librosa.feature.zero_crossing_rate(y=self.wav, frame_length=2048, hop_length=512)\n return zcrs\n \n def plotChromagram(self):\n #Get chromagram of frequencies\n chroma = librosa.feature.chroma_stft(y=self.wav, sr=self.samplefreq)\n librosa.display.specshow(chroma, y_axis='chroma', x_axis='time')\n plt.colorbar()\n plt.title('Chromagram')\n plt.tight_layout()\n plt.show()\n return chroma\n \n def plotSpectrogram(self, mels=512, maxfreq=30000):\n #Plot the Mel power-scaled frequency spectrum, with any factor of 128 frequency bins and 512 frames (frame default)\n mel = librosa.feature.melspectrogram(y=self.wav, sr=self.samplefreq, n_mels=mels, fmax=maxfreq)\n librosa.display.specshow(librosa.logamplitude(mel, ref_power=np.max), y_axis='mel', fmax=maxfreq, x_axis='time')\n plt.colorbar(format='%+2.0f dB')\n plt.title('Mel Power-Scaled Frequency Spectrogram')\n plt.tight_layout()\n plt.show()\n return mel \n \n def plotMFCCs(self):\n \"\"\"\n The Mel Frequency Cepstral Coefficient is a measure of timbre\n \"\"\"\n mfccs = librosa.feature.mfcc(y=self.wav, sr=self.samplefreq)\n librosa.display.specshow(mfccs, x_axis='time')\n plt.colorbar()\n plt.title('MFCC')\n plt.tight_layout()\n plt.show()\n return mfccs\n \n def plotTempogram(self):\n \"\"\"\n The tempogram visualizes the rhythm (pattern recurrence), using the \n onset envelope, oenv, to determine the start points for the patterns.\n \"\"\"\n oenv = librosa.onset.onset_strength(y=self.wav, sr=self.samplefreq, hop_length=512)\n tempogram = librosa.feature.tempogram(onset_envelope=oenv, sr=self.samplefreq, hop_length=512)\n librosa.display.specshow(tempogram, sr=self.samplefreq, hop_length=512, x_axis='time', y_axis='tempo')\n plt.colorbar()\n plt.title('Tempogram')\n plt.tight_layout()\n plt.show()\n plt.plot(oenv, label='Onset strength')\n plt.title('Onset Strength Over Time')\n plt.xlabel('Time')\n plt.ylabel('Onset Strength')\n plt.show()\n return tempogram\n\n def findTonicAndKey(self):\n \"\"\"\n The tonic is the base note in the key signature, e.g. c is the tonic for \n the key of c major. The tonic can be found by summing the chromagram\n arrays and finding the index of the array with the greatest sum. The \n logic is that the tonic is the note with the greatest presence.\n \n If the tonic doesn't match the tonic of bestmatch, the highest \n correlated major scale, then the key is a minor scale. \n (Minor scales = Major scales but have different tonics)\n \"\"\"\n chromagram = librosa.feature.chroma_stft(y=self.wav, sr=self.samplefreq)\n chromasums = []\n for i,a in enumerate(chromagram):\n chromasums.append(np.sum(chromagram[i]))\n tonicval = np.where(max(chromasums)==chromasums)[0][0]\n notes = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B']\n tonic = notes[tonicval]\n #In standard units, how far is the average pitch from the tonic?\n z_dist_avg_to_tonic = round((max(chromasums)-np.mean(chromasums))/np.std(chromasums), 4)\n #Correlate the chromasums array with each of the major scales, find the best match\n bestmatch = 0\n bestmatchid = 0\n for key, scale in majorscales.items():\n #np.corrcoef returns a matrix, only need the first value in the diagonal\n corr = np.corrcoef(scale, chromasums)[0,1]\n if (corr > bestmatch):\n bestmatch = corr\n bestmatchid = key\n if (tonic != bestmatchid):\n keysig = tonic + ' Minor'\n else:\n keysig = tonic + ' Major' \n return tonic, keysig, z_dist_avg_to_tonic\n \n#Specify a file directory and the types of audio files to get features for\nfiledir = 'C:/Users/Public/Documents/Python Scripts/Music Recommendation with Deep Learning/Audio Files/'\nextension_list = ('*.wav')\n\n#Iterate through the wavs in the directory and compile a list of features\nos.chdir(filedir)\nfeaturelist = []\nmelspecs = []\nid_tracker = 1\nfor extension in extension_list:\n for file in glob.glob(extension):\n if (os.path.splitext(os.path.basename(file))[1] == '.wav'):\n print(file)\n song = Audio(librosa.load(file, mono=True))\n wavfeatures = dict()\n wavmel = dict()\n wavfeatures['audio_file_id'] = id_tracker\n wavfeatures['samplefreq'] = song.samplefreq\n wavfeatures['channels'] = song.channels\n wavfeatures['sample_points'] = song.sample_points\n wavfeatures['audio_length_seconds'] = round(song.audio_length_seconds, 4)\n wavfeatures['tempo_bpm'] = song.tempo_bpm\n wavfeatures['avg_diff_beat_times'] = round(np.mean(song.beat_times[1:]-song.beat_times[0:len(song.beat_times)-1]), 4)\n wavfeatures['std_diff_beat_times'] = round(np.std(song.beat_times[1:]-song.beat_times[0:len(song.beat_times)-1]), 4)\n wavfeatures['rolloff_freq'] = round(song.rolloff_freq, 0)\n wavfeatures['avg_zcr'] = round(np.mean(song.getZeroCrossingRates()), 4)\n wavfeatures['zcr_range'] = np.max(song.getZeroCrossingRates()) - np.min(song.getZeroCrossingRates())\n wavfeatures['avg_mel_freq'] = round(np.mean(song.plotSpectrogram()), 4)\n wavfeatures['std_mel_freq'] = round(np.std(song.plotSpectrogram()), 4)\n wavfeatures['avg_onset_strength'] = round(np.mean(song.plotTempogram()), 4)\n wavfeatures['std_onset_strength'] = round(np.std(song.plotTempogram()), 4)\n wavfeatures['tonic'] = song.findTonicAndKey()[0]\n wavfeatures['key_signature'] = song.findTonicAndKey()[1]\n wavfeatures['z_dist_avg_to_tonic'] = song.findTonicAndKey()[2]\n wavmel['audio_file_id'] = id_tracker\n #wavmel['mel_spectrogram_sample'] = (song.plotSpectrogram(mels=512, maxfreq=8192)).ravel()[song.samplefreq*30:song.samplefreq*90]\n startcol = math.ceil((song.samplefreq*30)/512)\n endcol = math.ceil((song.samplefreq*90)/512)\n wavmel['mel_spectrogram_sample'] = (song.plotSpectrogram(mels=512, maxfreq=8192))[:, startcol:endcol]\n featurelist.append(wavfeatures)\n melspecs.append(wavmel)\n id_tracker = id_tracker + 1\n\n#Write the list of dictionaries with song features to a csv file\nwith open('Song_Features.csv', 'w') as f:\n w = csv.DictWriter(f, featurelist[0].keys())\n w.writeheader()\n w.writerows(featurelist)\n\n'''\nIdeally the entire mel frequency spectrogram for each song would be exported, \nbut the songs are all different lengths, meaning that the dimensions of the \nspectrograms will be different. To standardize them all, I'm using 512 \nfrequency bins and taking a 60 second sample of each song. I'm starting 30\nseconds into the song to skip over any song intros and get into the main verse\nand/or chorus. \n\nThe spectrogram is clipped at a max of 8192 Hz, as there are few songs with \nhigher frequencies present, so there is mostly black space above 8192 Hz.\n\nOnce the mel spectrogram is built, it is vectoriezed to a 1D array and then the \nsubsetting is done. The spectrogram is exported so that 1 song gets 1 file.\n'''\n\n#Specify a file directory for the spectrograms\nspecfiledir = 'C:/Users/Public/Documents/Python Scripts/Music Recommendation with Deep Learning/Audio Files/Spectrograms/'\nif not os.path.exists(specfiledir):\n os.makedirs(specfiledir)\nos.chdir(specfiledir)\n\n#Export all spectorgrams to csv files\nfor d in melspecs:\n filename = str(d['audio_file_id']) + '.csv'\n print(filename)\n print(d['mel_spectrogram_sample'].shape)\n np.savetxt(filename, d['mel_spectrogram_sample'], delimiter=\",\")\n \n\n","repo_name":"nlinc1905/Convolutional-Autoencoder-Music-Similarity","sub_path":"02_wav_features_and_spectrogram.py","file_name":"02_wav_features_and_spectrogram.py","file_ext":"py","file_size_in_byte":12718,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"52"} +{"seq_id":"13748435185","text":"import matplotlib.pyplot as plt\nfrom functools import reduce\nplt.figure('test')\n\ndog=plt.imread(\"D:/VS_Projects/VS_Projects_git/PythonApplication1/PythonApplication1/dog.png\")\n\nplt.imshow(dog)\n\n# Z是上小节生成的随机图案,img0就是Z,img1是Z做了个简单的变换\nimg0 = dog \nimg1 = 2*dog + reduce(lambda x,y:x+y,[0.1,0.2,0.1,0.25])\n\n# cmap指定为'gray'用来显示灰度图\nfig = plt.figure('Auto Normalized Visualization')\nax0 = fig.add_subplot(121)\nax0.imshow(img0, cmap='gray')\n\nax1 = fig.add_subplot(122)\nax1.imshow(img1, cmap='gray')\n\nplt.show()","repo_name":"chris1132/Py_Projects_git","sub_path":"PythonApplication1/PythonApplication1/matplotlib/图片转换.py","file_name":"图片转换.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25691438181","text":"import collections\nimport math\n\ndef calc(expr, indent = ''):\n print(f'{indent}CALC {expr}')\n\n i = 0\n # first simplify parens\n while i < len(expr):\n token = expr[i]\n if token == '(':\n j = i+1\n cnt = 1\n while j < len(expr) and cnt != 0:\n if expr[j] == '(':\n cnt += 1\n elif expr[j] == ')':\n cnt -= 1\n j += 1\n expr = expr[:i] + [calc(expr[i+1:j-1], indent + ' ')] + expr[j:]\n i += 1\n\n # next do addition\n i = 0\n while i < len(expr):\n token = expr[i]\n if token == '+':\n expr = expr[:i-1] + [int(expr[i-1]) + int(expr[i+1])] + expr[i+2:]\n else:\n i += 1\n\n # finally, mult\n i = 0\n while i < len(expr):\n token = expr[i]\n if token == '*':\n expr = expr[:i-1] + [int(expr[i-1]) * int(expr[i+1])] + expr[i+2:]\n else:\n i += 1\n\n print(f'{indent}CALC return {expr[0]}')\n return int(expr[0])\n\n\ndef tokenize(expr):\n expr = expr.strip().replace(' ', '')\n return [t for t in expr]\n\n\ndef run(filename):\n sum = 0\n with open(filename, 'r') as f:\n for line in f:\n r = calc(tokenize(line))\n sum += r\n print(r)\n\n print(sum)\n\nrun('day18.txt')","repo_name":"thekidder/adventofcode","sub_path":"2020/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"24327524610","text":"import os\nimport sys\n\nfrom flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\nfrom flask_wtf import CSRFProtect\nfrom flask_babel import Babel, _\n\nWIN = sys.platform.startswith(\"win\")\nif WIN:\n prefix = \"sqlite:///\"\nelse:\n prefix = \"sqlite:////\"\n\napp = Flask(__name__)\n\napp.config[\"SECRET_KEY\"] = os.getenv(\"SECRET_KEY\", \"dev\")\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = prefix + os.path.join(\n os.path.dirname(app.root_path), os.getenv(\"DATABASE_FILE\", \"data.db\")\n)\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\napp.config[\"LANGUAGES\"] = [\"en\", \"zh\"]\n\ndb = SQLAlchemy(app)\nbabel = Babel(app)\ncsrf = CSRFProtect(app)\n\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = \"login\"\nlogin_manager.login_message = _(\"请登录!\")\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n from watchlist.models import User\n\n user = User.query.get(int(user_id))\n return user\n\n\n@babel.localeselector\ndef get_locale():\n return request.accept_languages.best_match(app.config[\"LANGUAGES\"])\n\n\nfrom watchlist import views, errors, commands\n","repo_name":"mancuoj/watchlist","sub_path":"watchlist/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"5641993751","text":"\"\"\"\nBatch sampler: yield a batch of indexes at each episode.\nData: 2022/11/11\nAuthor: Xiaohan Chen\nMail: cxh_bb@outlook.com\nReference: https://github.com/orobix/Prototypical-Networks-for-Few-shot-Learning-PyTorch/blob/master/src/prototypical_batch_sampler.py\n\"\"\"\n\nimport numpy as np\nimport torch\n\nclass BatchSampler(object):\n def __init__(self, labels, support, query, episodes):\n '''\n Initialize the BatchSampler object\n Args:\n - labels: an episode contains all labels\n - support: number of support samples per class\n - querry: number of querry samples per class\n - episodes: number of episodes per epoch\n '''\n super(BatchSampler, self).__init__()\n self.labels = labels\n self.support = support\n self.query = query\n self.episodes = episodes\n self.classes, self.counts = np.unique(self.labels, return_counts=True)\n self.classes = torch.LongTensor(self.classes)\n self.num_per_class = self.counts[0] # the numbers per class are equal\n self.index_matrix = self.create_matrix(self.labels, len(self.classes), self.num_per_class)\n \n def create_matrix(self, labels, num_class, num_per_class):\n '''\n Creat an index matrix, dim: classes x samples per class.\n Every class contains the same number of samples.\n args:\n - labels: an episode contains all labels\n - num_classes: number of classes\n - num_per_class: number of elements per class\n '''\n num_samples = len(labels)\n index_matrix = torch.arange(num_samples).reshape(num_class, num_per_class)\n return index_matrix\n \n def __len__(self):\n return self.episodes\n \n def __iter__(self):\n '''\n Yield a batch of indexes.\n Every batch contains the same classes but in random order.\n Every class contains (support + query) samples.\n '''\n num_class = len(self.classes)\n num_item = self.support + self.query\n batch_size = num_class * num_item\n for ep in range(self.episodes):\n batch = torch.LongTensor(batch_size)\n class_index = torch.randperm(num_class) # random the class index\n for i, label in enumerate(class_index):\n s = slice(i*num_item, (i+1)*num_item)\n sample_index = torch.randperm(self.num_per_class)[:num_item] # select element indexes from every class\n batch[s] = self.index_matrix[label][sample_index]\n yield batch\n \n\n\n\n","repo_name":"Xiaohan-Chen/few-shot-fault-diagnosis","sub_path":"Sampler/BatchSampler.py","file_name":"BatchSampler.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"} +{"seq_id":"5708092514","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\nimport tidalapi\r\nimport webbrowser\r\nimport yaml\r\n\r\ndef open_tidal_session(config = None):\r\n try:\r\n with open('.session.yml', 'r') as session_file:\r\n previous_session = yaml.safe_load(session_file)\r\n except OSError:\r\n previous_session = None\r\n\r\n if config:\r\n session = tidalapi.Session(config=config)\r\n else:\r\n session = tidalapi.Session()\r\n if previous_session:\r\n try:\r\n if session.load_oauth_session(token_type= previous_session['token_type'],\r\n access_token=previous_session['access_token'],\r\n refresh_token=previous_session['refresh_token'] ):\r\n return session\r\n except Exception as e:\r\n print(\"Error loading previous Tidal Session: \\n\" + str(e) )\r\n\r\n login, future = session.login_oauth()\r\n print('Login with the webbrowser: ' + login.verification_uri_complete)\r\n url = login.verification_uri_complete\r\n if not url.startswith('https://'):\r\n url = 'https://' + url\r\n webbrowser.open(url)\r\n future.result()\r\n with open('.session.yml', 'w') as f:\r\n yaml.dump( {'session_id': session.session_id,\r\n 'token_type': session.token_type,\r\n 'access_token': session.access_token,\r\n 'refresh_token': session.refresh_token}, f )\r\n return session\r\n\r\n\r\n","repo_name":"Nugman/csv2tidal","sub_path":"auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35615383489","text":"\"\"\"\nAdd jobs ping field\n\nRevision ID: 6q5k8tz8uph3\nDate: 2022-10-07 20:14:53.735862\n\n\"\"\"\nfrom datetime import datetime\n\nimport arrow\nfrom syrupy.matchers import path_type\n\nfrom virtool.migration import MigrationError\nfrom virtool.migration.ctx import MigrationContext\n\n# Revision identifiers.\nname = \"Add jobs ping field\"\ncreated_at = arrow.get(\"2022-10-07 20:14:53.735862\")\nrevision_id = \"6q5k8tz8uph3\"\n\nalembic_down_revision = None\nvirtool_down_revision = \"i0ljixkr0wxg\"\n\n\nasync def upgrade(ctx: MigrationContext):\n await ctx.mongo.jobs.update_many(\n {\"ping\": {\"$exists\": False}}, {\"$set\": {\"ping\": None}}\n )\n\n if await ctx.mongo.jobs.count_documents({\"ping\": {\"$exists\": False}}):\n raise MigrationError(\"Some jobs still do not have a ping field\")\n\n\nasync def test_upgrade(ctx: MigrationContext, snapshot):\n await ctx.mongo.jobs.insert_many(\n [\n {\"_id\": \"a\", \"ping\": None},\n {\"_id\": \"b\"},\n {\"_id\": \"c\", \"ping\": {\"pinged_at\": arrow.utcnow().naive}},\n {\"_id\": \"d\"},\n ]\n )\n\n await upgrade(ctx)\n\n assert await ctx.mongo.jobs.find().to_list(None) == snapshot(\n matcher=path_type({\".*pinged_at\": (datetime,)}, regex=True)\n )\n","repo_name":"virtool/virtool","sub_path":"assets/revisions/rev_6q5k8tz8uph3_add_jobs_ping_field.py","file_name":"rev_6q5k8tz8uph3_add_jobs_ping_field.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"52"} +{"seq_id":"14618989120","text":"'''\nCreated on 11/10/2015\n\n@author: joaoff\n'''\n\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.main_pt, name='main_pt'), # e.g. /pads/\n url(r'^equipe/$', views.equipe, name='equipe'), # e.g. /main_pt/equipe/\n url(r'^atividades/$', views.atividades, name='atividades'), # e.g. /main_pt/atividades/\n url(r'^publicacoes/$', views.publicacoes, name='publicacoes'), # e.g. /main_pt/publicacoes/\n url(r'^equipamentos/$', views.equipamentos, name='equipamentos'), # e.g. /main_pt/equipamentos/\n url(r'^contato/$', views.contato, name='contato'), # e.g. /main_pt/contato/\n]","repo_name":"joaoaff/pads_website","sub_path":"pads/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21647399685","text":"from operator import add, mul\n\noper = {'+': add, '*': mul}\n\ndef term(s, f, acc, op):\n if s[0] == '(':\n v, s = ev(s[1:], f)\n return op(acc,v), s\n return op(acc, int(s[0])), s[1:]\n\ndef factor(s, f, acc, op):\n v1, s = term(s, f, 0, add)\n while s[0] == '+':\n v1, s = term(s[1:], f, v1, add)\n return op(acc, v1), s\n\ndef ev(s, f):\n acc, s = f(s, f, 0, add)\n while s[0] != '\\n': \n if s[0] == ')': return acc, s[1:]\n acc, s = f(s[1:], f, acc, op[s[0]])\n return acc\n \nprint(sum([ev(line.replace(' ', ''), term) for line in open('input')]),\n sum([ev(line.replace(' ', ''), factor) for line in open('input')]))\n","repo_name":"NameTakenAgain/AoC2020","sub_path":"day18/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25644516329","text":"import base64\nfrom Crypto.Cipher import AES\nBLOCK_SIZE = 32\n\ndef decrypt_aes(msg, key):\n cipher = AES.new(key, AES.MODE_ECB)\n return cipher.decrypt(msg)\n\nshared = 8295470404756197179435629427418057937628547743937306629317394846678279378121\nencoded_flag = \"o+C/uUQ6uTtZ9jpI4sWVjfOPViK3TjOjgqK9t/JPxi/Q/Hq68a57fAq7JA8Gpg4KndziMGt/Cfdd\\n5jYFYy6LXg==\"\nencrypted_flag = base64.decodebytes(encoded_flag.encode(\"ASCII\"))\nkey = shared.to_bytes((shared.bit_length() + 7) // 8, byteorder='big')[0:BLOCK_SIZE]\nmsg = decrypt_aes(encrypted_flag, key)\nprint(msg)","repo_name":"Iancu15/ISC","sub_path":"tema1/crypto-attack/attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13363628171","text":"import urllib.request\nfrom bs4 import BeautifulSoup\n\n# link = \"http://www.ebay.in/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=sita+amish&_sacat=0\"\n\ndef ebay_crawl(link):\n with urllib.request.urlopen(link) as url:\n s = url.read()\n\n soup = BeautifulSoup(s)\n\n # fo = open('Crawlers/extracts/ebay.txt','r')\n # soup = BeautifulSoup(fo.read())\n # fo.close()\n\n master_list = []\n\n list_image = soup.find_all(\"a\",class_=\"img imgWr2\")\n list_url = soup.find_all(\"a\",class_=\"img imgWr2\")\n list_name = soup.find_all(\"a\",class_=\"img imgWr2\")\n list_price = soup.find_all(\"li\", class_=\"lvprice prc\")\n\n for name, image, price, url in zip(list_name, list_image, list_price, list_url):\n info = {}\n info['Name'] = str.strip(name.img['alt'])\n info['Image'] = str.strip(image.img['src'])\n info['Price'] = str.strip(price.span.text.replace(\"Rs.\",\"\"))\n info['Url'] = str.strip(url['href'])\n master_list.append(info)\n\n return master_list\n\n # for content in master_list:\n # print(\"1.Name : \", content['Name'])\n # print(\"2.Image Url : \", content['Image'])\n # print(\"3.Price : \", content['Price'])\n # print(\"4.Url : \", content['Url'])\n","repo_name":"sumeet-dang/CompareKaro","sub_path":"CompareKaro/Crawlers/Helpers/ebay_crawler.py","file_name":"ebay_crawler.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22386291576","text":"##Librerias\nimport serial\n\n## Variables\n## connection from mac:\n## port list using serial tools\n## python -m serial.tools.list_ports\nSERIAL_NAME = '/dev/cu.usbserial-A50285BI'\n\n## connection from RPi\n# SERIAL_NAME = '/dev/ttyUSB0'\n\n## connection settings\nBAUDRATE = 115200\nTIMEOUT = 1 # secs\n# PARITY = serial.PARITY_NONE,\n# STOPBITS = serial.STOPBITS_ONE,\n# BYTESIZE = serial.EIGHTBITS\n\n\ndef get_energy_usage(ser, encode=False):\n ## command string to get energy usage\n COMMAND = \"$GU\\r\"\n ## write command on serial\n ## if mac --> encode=True\n if encode:\n ser.write(COMMAND.encode())\n ## read info\n line = ser.readline()\n print(line)\n aux = line.decode().split(\" \")\n else:\n ser.write(COMMAND)\n ## read info\n line = ser.readline()\n print(line)\n aux = line.split(\" \")\n \n print(aux)\n status = aux[0]\n print(\"status: \", status)\n session_energy = int(aux[1])/3600000\n print(\"session energy: \", session_energy)\n global_energy = int(aux[2].split(\"^\")[0])/1000\n print(\"global energy: \",global_energy)\n\n return status, session_energy, global_energy\n\ndef set_display_color(ser, color_int=1, encode=False):\n ## command string to get energy usage\n COMMAND = \"$FB {}\\r\".format(color_int)\n ## write command on serial\n ## if mac --> encode=True\n if encode:\n ser.write(COMMAND.encode())\n ## read info\n line = ser.readline()\n print(line)\n aux = line.decode().split(\"^\")\n else:\n ser.write(COMMAND)\n ## read info\n line = ser.readline()\n print(line)\n aux = line.split(\"^\")\n\n print(aux)\n status = aux[0]\n print(\"status: \", status)\n return status\n \ndef start_connection(serial_name, baud_r, t_out):\n try:\n ## open serial connection\n ser = serial.Serial(serial_name,\n baudrate=baud_r,\n timeout=t_out)\n return ser\n except:\n print(\"Connection error, check what is going on\")\n\ndef end_connetcion(ser):\n ser.close()\n\n# try:\n# ## open serial connection\n# ser = serial.Serial(SERIAL_NAME,\n# baudrate=BAUDRATE,\n# timeout=TIMEOUT)\n \n# print(ser)\n# ## get values from openEVSE\n# status, session_energy, global_energy = get_energy_usage(encode=True)\n# status = set_display_color(color_int=3,encode=True)\n# status = set_display_color(color_int=4,encode=True)\n# status = set_display_color(color_int=5,encode=True)\n# status = set_display_color(color_int=6,encode=True)\n# status = set_display_color(color_int=7,encode=True)\n\n# # ser.write(\"$FP 0 0 BAILA_DIRA\\r\")\n# # line = ser.readline()\n# # print(line)\n \n# except:\n# print(\"Connection error, check what is going on\")\n\n# ## some aux commands:\n\n# #ser.close \n","repo_name":"id-griff/CPC","sub_path":"charge_point/serial_connection.py","file_name":"serial_connection.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70857398564","text":"import dbus\nimport dbus.service\nfrom gi.repository import GLib\n\nfrom ble.Constants import *\nfrom ble.Exceptions import *\n\nfrom services.RoverService import RoverService\n\nclass RoverApplication(dbus.service.Object):\n \"\"\"\n org.bluez.GattApplication1 interface implementation\n \"\"\"\n def __init__(self, bus, rover, camera):\n self.path = '/haxrover'\n self.services = []\n dbus.service.Object.__init__(self, bus, self.path)\n self.add_service(RoverService(bus, 0, rover, camera))\n\n def get_path(self):\n return dbus.ObjectPath(self.path)\n\n def add_service(self, service):\n self.services.append(service)\n\n @dbus.service.method(DBUS_OM_IFACE, out_signature='a{oa{sa{sv}}}')\n def GetManagedObjects(self):\n response = {}\n\n for service in self.services:\n response[service.get_path()] = service.get_properties()\n chrcs = service.get_characteristics()\n for chrc in chrcs:\n response[chrc.get_path()] = chrc.get_properties()\n descs = chrc.get_descriptors()\n for desc in descs:\n response[desc.get_path()] = desc.get_properties()\n\n return response\n\n def register_callback(self):\n print(\"RoverApplication Registered - \" + self.get_path())\n\n def register_error_callback(self, mainloop, error):\n mainloop.quit()\n raise ErrorException(f\"Failed to register RoverApplication @ {self.get_path()} - {error}\")\n","repo_name":"Haxrox/HaxRover","sub_path":"rpi/RoverApplication.py","file_name":"RoverApplication.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29836693208","text":"from os import system\nfrom random import choice\nimport time\n\noptions = [\"It's a four!!!'\", \"What a yorker!\", \"OUT!!!\", \"You are at silly mid off\", \"My dear old thing, it's the end of the Over!'\", \"You could have hit that with a rhubarb stick!!\"]\n\ndef Ashes():\n counter = 1\n while counter < 10:\n print(\"\"\"You are at Lord's, choose a number from 1 to 6 to see in what role you play\"\"\")\n role = int(input('> '))\n if (role >= 1 and role <= len(options)):\n print(choice(options))\n else:\n print(\"You cannot count, go rub sugar on the ball!!\")\n counter += 1\n time.sleep(1.5)\n system(\"clear\")\n\nif __name__ == \"__main__\":\n Ashes()\n","repo_name":"CodeGirl33/Python","sub_path":"Ashes.py","file_name":"Ashes.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71690696164","text":"from flask import Flask, render_template, url_for, request, redirect\nimport requests\nimport data as dt\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '3d69c446439b16d483d48356c6c09ffa'\n\n@app.route(\"/\")\n@app.route(\"/home\")\ndef index():\n return render_template('index.html', \n sports=dt.sports, crypto=dt.crypto, \n covid=dt.covid, business=dt.business)\n\n@app.route(\"/searchResult\", methods=['POST'])\ndef searchResult():\n name = request.form['search'].title()\n api_key = '17e0788966b6404ab6e3a6997bfbacf2'\n res = requests.get(f'https://newsapi.org/v2/everything?q={name}&apiKey={api_key}').json()\n return render_template('/searchResult.html', name=name, datas=res)\n \n \n","repo_name":"hussein-jaban/newsFlaskApi","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6783885390","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport units.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('donations', '0002_auto_20151222_1352'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='donation',\n name='pounds',\n ),\n migrations.AlterField(\n model_name='donation',\n name='weight',\n field=units.models.WeightField(measurement_class='Mass', null=True),\n ),\n ]\n","repo_name":"ebrelsford/Farming-Concrete","sub_path":"barn/metrics/donations/migrations/0003_auto_20151222_1421.py","file_name":"0003_auto_20151222_1421.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"14024445320","text":"import re\nimport xml.etree.ElementTree as ET\nfrom collections import defaultdict\n\nsource = \"}source\"\n\ndef parse_case(case_string):\n\t'''extract relevant information from a case_string'''\n\tparsed = dict() \n\tjudges = set()\n\tcounselors = set() \n\tcitations = list()\n\tciteForThisResource = list() \n\tpaginationSchemes = set() \n\t\n\t# case string is xml\n\txmlTree = ET.fromstring(case_string) \n\t# for each field in the resulting xml tree:\n\t# \tif we care about it:\n\t#\t\tadd it to the parsed dict\n\tfor t in xmlTree.iter():\n\t\tif t.tag == \"fullCaseName\":\n\t\t\tparsed[\"fullCaseName\"] = t.text\n\t\telif t.tag == \"docketNumber\":\n\t\t\tparsed[\"docketNumber\"] = t.text\n\t\telif t.tag == \"courtName\":\n\t\t\tparsed[\"courtName\"] = t.text\n\t\telif t.tag == \"jurisSystem\":\n\t\t\tparsed[\"jurisSystem\"] = t.attrib\n\t\telif t.tag == \"citeForThisResource\":\n\t\t\tt.attrib[\"citeText\"] = t.text\n\t\t\tciteForThisResource.append(t.attrib)\n\t\telif t.tag == \"opinion\":\n\t\t\tparsed[\"opinion\"] = t.attrib\n\t\telif t.tag == \"caseOpinionBy\":\n\t\t\tparsed[\"caseOpinionBy\"] = t.text\n\t\telif t.tag == \"judge\":\n\t\t\tfor sub_t in t.iter(): \n\t\t\t\tif sub_t.tag == \"nameText\":\n\t\t\t\t\tjudges.add(sub_t.text)\n\t\telif t.tag == \"counselor\":\n\t\t\tfor sub_t in t.iter(): \n\t\t\t\tif sub_t.tag == \"nameText\":\n\t\t\t\t\tcounselors.add(sub_t.text) \n\t\telif t.tag == \"keyValue\":\n\t\t\tcitation = ''.join(t.attrib[\"value\"].split())\n\t\t\tcitations.append(citation)\n\t\telif t.tag == \"filedDate\":\n\t\t\tt.attrib[\"fullDate\"] = ''.join((t.attrib[\"year\"],t.attrib[\"month\"],t.attrib[\"day\"]))\n\t\t\tparsed[\"filedDate\"] = t.attrib\n\t\telif t.tag == \"decisionDate\":\n\t\t\tt.attrib[\"fullDate\"] = ''.join((t.attrib[\"year\"],t.attrib[\"month\"],t.attrib[\"day\"]))\n\t\t\tparsed[\"decisionDate\"] = t.attrib\n\t\telif t.tag == \"paginationScheme\": \n\t\t\tpaginationSchemes.update((v for k,v in t.attrib.items()))\n\t\telif t.tag[-len(source):] == source: \n\t\t\tparsed[\"productContentSetIdentifier\"] = t.text\n\n\t# add the elements that may appear more than once and only if they appeared\n\tif judges: \n\t\tparsed[\"judges\"] = list(judges)\n\tif citations:\n\t\tparsed[\"citations\"] = citations\n\tif counselors: \n\t\tparsed[\"counselors\"] = list(counselors) \n\tif paginationSchemes: \n\t\tparsed[\"paginationSchemes\"] = list(paginationSchemes)\n\tif citeForThisResource: \n\t\tparsed[\"citeForThisResource\"] = citeForThisResource\n\n\t#parsed[\"caseText\"] = '\\n'.join((text for text in xmlTree.itertext() if text))\n\tparsed[\"caseText\"] = case_string # add the entire case string \n\treturn parsed \t\t\n","repo_name":"sammation/LexisNexisCorpus","sub_path":"src/parse_cases.py","file_name":"parse_cases.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17823607638","text":"\"\"\"empty message\n\nRevision ID: 3fc242170c45\nRevises: \nCreate Date: 2022-06-06 18:47:02.827588\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '3fc242170c45'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('UserModel',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(), nullable=True),\n sa.Column('email', sa.String(), nullable=True),\n sa.Column('full_name', sa.String(), nullable=True),\n sa.Column('disabled', sa.Boolean(), nullable=True),\n sa.Column('password', sa.String(), nullable=True),\n sa.Column('is_active', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_UserModel_email'), 'UserModel', ['email'], unique=True)\n op.create_index(op.f('ix_UserModel_id'), 'UserModel', ['id'], unique=False)\n op.create_table('ingredient',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_ingredient_id'), 'ingredient', ['id'], unique=False)\n op.create_table('menu',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_menu_id'), 'menu', ['id'], unique=False)\n op.create_table('sostav',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ingredients', sa.Integer(), nullable=True),\n sa.Column('menu', sa.Integer(), nullable=True),\n sa.Column('amount', sa.DECIMAL(precision=5, scale=2), nullable=True),\n sa.ForeignKeyConstraint(['ingredients'], ['ingredient.id'], ),\n sa.ForeignKeyConstraint(['menu'], ['menu.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_sostav_id'), 'sostav', ['id'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_sostav_id'), table_name='sostav')\n op.drop_table('sostav')\n op.drop_index(op.f('ix_menu_id'), table_name='menu')\n op.drop_table('menu')\n op.drop_index(op.f('ix_ingredient_id'), table_name='ingredient')\n op.drop_table('ingredient')\n op.drop_index(op.f('ix_UserModel_id'), table_name='UserModel')\n op.drop_index(op.f('ix_UserModel_email'), table_name='UserModel')\n op.drop_table('UserModel')\n # ### end Alembic commands ###\n","repo_name":"DAPetrovich/EmptyProject","sub_path":"src/migrations/versions/3fc242170c45_.py","file_name":"3fc242170c45_.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16066004861","text":"import deklinacija.utils as utils\nfrom deklinacija.utils import Gender, Number\n\nVOWELS = [\"а\", \"е\", \"и\", \"о\", \"у\"] # used for identifying consonants\n\n# the last and second to last characters in names ending in these characters switch places during declension\nNEP_A = [\"тар\", \"ац\", \"рај\", \"рађ\", \"рак\", \"нак\", \"ндар\", \"чак\"]\nNEP_A_EXCEPT = [] # names which have one of the above suffixes but the last and the 2nd to last characters don't switch places during declension\nJ_EXCEPTION = ['МИА']\nZADNJONEPCANI = [\"ј\", \"љ\", \"њ\", \"ђ\", \"ћ\", \"ч\", \"џ\", \"ш\", \"ж\"]\nPALATALIZACIJA = {\"к\": \"ч\", \"г\": \"ж\", \"х\": \"ш\", }\nPOSSESIVE_SUFFIXES = {\"male_singular\":\"\",\"male_plural\":\"и\",\"female_singular\":\"а\",\"female_plural\":\"е\",\"neutral_singular\":\"о\",\"neutral_plural\":\"а\"}\nMALE_EXCEPTIONS = [\"тата\",\"газда\",\"судија\",\"ага\"]\nFEMALE_EXCEPTIONS = [\"пећ\",\"чађ\",\"кћер\",\"ствар\",\"љубав\",\"радост\"]\n\ndef genitiv(name, gender):\n \"\"\"\n OD KOGA, OD ČEGA? FROM WHOM?\n\n Returns the genitive form of the provided name. If a last name is present, it must be separated with a whitespace.\n \n Context in a sentence:\n \"Dobili ste zahtev za prijateljstvo od Petra.\"\n Translation:\n \"You've received a friend request from Peter.\"\n\n Parameters:\n name: The name that should be declined\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n name = name.strip()\n fullName = name.split()\n returnName = []\n\n for i in fullName:\n changedName = __genitiv(i, gender)\n returnName.append(changedName)\n\n return \" \".join(returnName)\n\ndef dativ(name, gender):\n \"\"\"\n KOME, ČEMU? TO WHOM?\n\n Returns the dative form of the provided name. If a last name is present, it must be separated with a whitespace.\n \n Context in a sentence:\n \"Poslali ste zahtev za prijateljstvo Petru.\"\n \"Diploma Petru Petroviću\"\n Translation:\n \"You've sent a friend request to Peter.\"\n \"Diploma to Peter Petrović\"\n \n Parameters:\n name: The name that should be declined\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n utils.check(name, gender)\n name = name.strip()\n fullName = name.split()\n returnName = []\n\n n = 0\n for i in fullName:\n if n == 0: \n changedName = __dativ(i, gender,False)\n n += 1\n else:\n changedName = __dativ(i, gender,True)\n returnName.append(changedName)\n\n return \" \".join(returnName)\n\ndef akuzativ(name, gender):\n \"\"\"\n (VIDIM) KOGA, ŠTA? (I SEE) WHOM?\n\n Returns the accusative form of the provided name. If a last name is present, it must be separated with a whitespace.\n \n Context in a sentence:\n \"Kontaktirali ste Janu.\"\n Translation:\n \"You've contacted Jana.\"\n\n Parameters:\n name: The name that should be declined\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n utils.check(name, gender)\n name = name.strip()\n fullName = name.split()\n returnName = []\n\n for i in fullName:\n changedName = __akuzativ(i, gender)\n returnName.append(changedName)\n\n return \" \".join(returnName)\n\ndef vokativ(name, gender):\n \"\"\"\n Hej! Hey!\n\n Returns the vocative form of the provided name. If a last name is present, it must be separated with a whitespace. Used for greetings.\n \n Context in a sentence:\n \"Zdravo Petre!\"\n Translation:\n \"Hello Peter!\"\n\n Parameters:\n name: The name that should be declined\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n utils.check(name, gender)\n name = name.strip()\n fullName = name.split()\n returnName = []\n n = 0\n for i in fullName:\n if n == 0: \n changedName = __vokativ(i, gender,False)\n n += 1\n else:\n changedName = __vokativ(i, gender,True)\n returnName.append(changedName)\n\n return \" \".join(returnName)\n\ndef instrumental(name, gender):\n \"\"\"\n S KIM? ČIM? WITH WHOM? WITH WHAT?\n\n Returns the instrumental form of the provided name. If a last name is present, it must be separated with a whitespace.\n \n Context in a sentence:\n \"Veljko je trenutno u igri sa Milošem.\"\n Translation:\n \"Veljko is currently in-game with Miloš.\"\n\n Parameters:\n name: The name that should be declined\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n utils.check(name, gender)\n name = name.strip()\n fullName = name.split()\n returnName = []\n\n for i in fullName:\n changedName = __instrumental(i, gender)\n returnName.append(changedName)\n\n return \" \".join(returnName)\n\ndef lokativ(name, gender):\n \"\"\"\n O KOME? O ČEMU? NA KOJOJ LOKACIJI? ABOUT WHO? ABOUT WHAT? IN WHAT LOCATION?\n\n Returns the locative form of the provided name. If a last name is present, it must be separated with a whitespace.\n \n Context in a sentence:\n \"Marko je trenutno u Beogradu.\"\n Translation:\n \"Marko is currently in Belgrade.\"\n\n Parameters:\n name: The name that should be declined\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n utils.check(name, gender)\n name = name.strip()\n fullName = name.split()\n returnName = []\n n = 0\n for i in fullName:\n if n == 0: \n changedName = __dativ(i, gender,False)\n n += 1\n else:\n changedName = __dativ(i, gender,True)\n returnName.append(changedName)\n\n return \" \".join(returnName)\n\ndef possessive(name,gender,object_gender,grammatical_number=Number.SINGULAR):\n \"\"\"\n ČIJI? WHOSE?\n\n Returns the possessive form of the provided name. Depends on the object_gender and grammatical_number parameters to add the appropriate suffix to the name.\n \n Parameters:\n name: The name of the person that posseses something\n gender: The gender of the person that possesses something, param value must be either Gender.MALE or Gender.FEMALE\n object_gender: Can either be the gender of the object that the person possesses (value must be Gender.MALE, Gender.FEMALE or Gender.NEUTRAL) or the object itself, in which case the gender will be automatically detected provided that the grammatical_number param is correct\n grammatical_number: The grammatical number of the object that the person possesses. Param value must be either Number.SINGULAR or Number.PLURAL. Default: singular\n \"\"\"\n utils.checkPossessive(name,gender,object_gender,grammatical_number,)\n\n\n if type(object_gender) == str:\n object_gender = utils.toCyrillic(object_gender.strip().lower())\n if object_gender[-1] == \"е\":\n if grammatical_number == Number.SINGULAR:\n object_gender = Gender.NEUTRAL\n else:\n object_gender = Gender.FEMALE\n elif object_gender[-1] == \"а\":\n if object_gender in MALE_EXCEPTIONS:\n object_gender = Gender.MALE\n else:\n object_gender = Gender.FEMALE\n elif object_gender[-1] == \"и\" and grammatical_number == Number.PLURAL:\n test = object_gender[:-1]\n if test in FEMALE_EXCEPTIONS:\n object_gender = Gender.FEMALE\n else:\n object_gender = Gender.MALE\n else:\n if object_gender in FEMALE_EXCEPTIONS:\n object_gender = Gender.FEMALE\n else:\n object_gender = Gender.MALE\n \n name = name.strip()\n\n gender_text = object_gender.value\n number_text = grammatical_number.value\n\n lastChar = name[-1]\n if lastChar.isupper():\n if utils.isLatin(lastChar) == True:\n suffix = utils.toLatin(POSSESIVE_SUFFIXES[gender_text+\"_\"+number_text]).upper()\n else:\n suffix = POSSESIVE_SUFFIXES[gender_text+\"_\"+number_text].upper()\n else:\n if utils.isLatin(lastChar) == True:\n suffix = utils.toLatin(POSSESIVE_SUFFIXES[gender_text+\"_\"+number_text])\n else:\n suffix = POSSESIVE_SUFFIXES[gender_text+\"_\"+number_text]\n return __possessive(name,gender)+suffix\n\ndef possessiveAll(name,gender):\n \"\"\"\n Creates all possible possessive forms (male, female and neutral in plural and singular) of the provided name and returns a dictionary where the keys are in the \"GENDER_NUMBER\" format.\n\n Parameters:\n name: The name that should be transformed\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n utils.check(name, gender)\n name = name.strip()\n \n return {\"name\":name,\"male_singular\":possessive(name,gender,Gender.MALE,Number.SINGULAR),\"male_plural\":possessive(name,gender,Gender.MALE,Number.PLURAL),\"female_singular\":possessive(name,gender,Gender.FEMALE,Number.SINGULAR),\"female_plural\":possessive(name,gender,Gender.FEMALE,Number.PLURAL),\"neutral_singular\":possessive(name,gender,Gender.NEUTRAL,Number.SINGULAR),\"neutral_plural\":possessive(name,gender,Gender.NEUTRAL,Number.PLURAL)}\n\ndef __possessive(name,gender):\n utils.check(name, gender)\n name = utils.separateLetters(__genitiv(name.strip(),gender))\n lastChar = name[-1]\n secToLastChar = name[-2]\n lastThree = \"\".join(name[-3:])\n lastTwo = \"\".join(name[-2:])\n\n if gender == Gender.FEMALE and utils.toCyrillic(name[-1].lower()) not in ['е','e']:\n if lastChar.isupper():\n if utils.isLatin(lastChar) == True:\n if utils.toCyrillic(lastChar.lower()) in ['и','i']:\n name[-1] = \"IJIN\"\n return \"\".join(name)\n\n name.append(\"IN\")\n return \"\".join(name)\n else:\n if utils.toCyrillic(lastChar.lower()) in ['и','i']:\n name[-1] = \"ИЈИН\"\n return \"\".join(name)\n \n name.append(\"ИН\")\n return \"\".join(name)\n else:\n if utils.isLatin(lastChar) == True:\n if utils.toCyrillic(lastChar.lower()) in ['и','i']:\n name[-1] = \"ijin\"\n return \"\".join(name)\n if lastThree.lower() == 'ice':\n name[-2] = \"č\"\n\n name.append(\"in\")\n return \"\".join(name)\n else:\n if utils.toCyrillic(lastChar.lower()) in ['и','i']:\n name[-1] = \"ијин\"\n return \"\".join(name)\n\n name.append(\"ин\")\n return \"\".join(name)\n \n if name[-1].lower() in ['е','e']:\n if lastChar.isupper():\n if utils.isLatin(lastChar) == True:\n if utils.toCyrillic(lastChar.lower()) in ['и','i'] or utils.toCyrillic(name[-2].lower()) in ['и','i']:\n if utils.toCyrillic(name[-2].lower()) in ['и','i']:\n name.pop()\n name.append(\"JIN\")\n return \"\".join(name)\n elif utils.toCyrillic(lastThree.lower()) == 'ице':\n name[-2] = \"Č\"\n\n name[-1] = \"IN\"\n return \"\".join(name)\n else:\n if utils.toCyrillic(lastChar.lower()) in ['и','i'] or utils.toCyrillic(name[-2].lower()) in ['и','i']:\n if utils.toCyrillic(name[-2].lower()) in ['и','i']:\n name.pop()\n name.append(\"ЈИН\")\n return \"\".join(name)\n elif utils.toCyrillic(lastThree.lower()) == 'ице':\n name[-2] = \"Ч\"\n \n name[-1] = \"ИН\"\n return \"\".join(name)\n else:\n if utils.isLatin(lastChar) == True:\n if utils.toCyrillic(lastChar.lower()) in ['и','i'] or utils.toCyrillic(name[-2].lower()) in ['и','i']:\n if utils.toCyrillic(name[-2].lower()) in ['и','i']:\n name.pop()\n name.append(\"jin\")\n return \"\".join(name)\n if utils.toCyrillic(lastThree.lower()) == 'ице':\n name[-2] = \"č\"\n\n name[-1] = \"in\"\n return \"\".join(name)\n else:\n if utils.toCyrillic(lastChar.lower()) in ['и','i'] or utils.toCyrillic(name[-2].lower()) in ['и','i']:\n if utils.toCyrillic(name[-2].lower()) in ['и','i']:\n name.pop()\n name.append(\"јин\")\n return \"\".join(name)\n elif utils.toCyrillic(lastThree.lower()) == 'ице':\n name[-2] = \"ч\"\n\n name[-1] = \"ин\"\n return \"\".join(name)\n \n if name[-1].lower() in ['а','a','г','g']:\n if lastChar.isupper():\n if utils.isLatin(lastChar) == True:\n if utils.toCyrillic(secToLastChar.lower()) in ZADNJONEPCANI:\n name[-1] = \"EV\"\n return \"\".join(name)\n if utils.toCyrillic(lastTwo.lower()) == \"ог\":\n name = name[:-1]\n\n name[-1] = \"OV\"\n return \"\".join(name)\n else:\n if utils.toCyrillic(secToLastChar.lower()) in ZADNJONEPCANI:\n name[-1] = \"ЕВ\"\n return \"\".join(name)\n \n name[-1] = \"ОВ\"\n return \"\".join(name)\n else:\n if utils.isLatin(lastChar) == True:\n if utils.toCyrillic(secToLastChar.lower()) in ZADNJONEPCANI:\n name[-1] = \"ev\"\n return \"\".join(name)\n if utils.toCyrillic(lastTwo.lower()) == \"ог\":\n name = name[:-1]\n \n name[-1] = \"ov\"\n return \"\".join(name)\n else:\n if utils.toCyrillic(secToLastChar.lower()) in ZADNJONEPCANI:\n name[-1] = \"ев\"\n return \"\".join(name)\n if utils.toCyrillic(lastTwo.lower()) == \"ог\":\n name = name[:-1]\n \n name[-1] = \"ов\"\n return \"\".join(name)\n \ndef __genitiv(name, gender):\n utils.check(name, gender)\n name = utils.separateLetters(name.strip())\n\n lastChar = name[-1]\n secToLastChar = name[-2]\n trdToLastChar = name[-3]\n\n lastThree = \"\".join(name[-3:]).lower()\n lastTwo = \"\".join(name[-2:]).lower()\n\n if gender == Gender.FEMALE:\n if lastChar.lower() not in [\"а\", \"a\"]:\n return \"\".join(name)\n\n if lastChar.lower() in [\"а\", \"a\"]:\n if utils.toCyrillic(\"\".join(name).upper()) in J_EXCEPTION:\n return utils.addSuffix(name,gender,\"e\",False,False)\n return utils.addSuffix(name,gender,\"e\",False,True)\n\n if lastChar.lower() in [\"е\", \"e\", \"о\", \"o\"]:\n return utils.addSuffix(name,gender,\"a\",False,True)\n\n if utils.toCyrillic(lastThree.lower()) in [\"ски\", \"чки\", \"шки\"] and len(name) > 3:\n return utils.addSuffix(name,gender,\"og\",False,False)\n\n if lastChar.lower() in [\"и\", \"i\"]:\n return utils.addSuffix(name,gender,\"ja\",True,False)\n\n if len(name) < 4:\n lastFour = None\n\n else:\n lastFour = \"\".join(name[-4:]).lower()\n fthToLastChar = name[-4]\n\n if len(name) >= 4 and (utils.toCyrillic(lastFour.lower()) in NEP_A or utils.toCyrillic(lastThree.lower()) in NEP_A or utils.toCyrillic(lastTwo.lower()) in NEP_A) and utils.toCyrillic(secToLastChar.lower()) == \"а\" and utils.toCyrillic(lastChar.lower()) not in VOWELS and utils.toCyrillic(trdToLastChar.lower()) not in VOWELS and utils.toCyrillic(\"\".join(name).upper()) not in NEP_A_EXCEPT:\n if utils.toCyrillic(lastFour.lower()) != \"ндар\" and utils.toCyrillic(fthToLastChar.lower()) not in VOWELS:\n return utils.addSuffix(name,gender,\"a\",True,False)\n # nepostojano a\n elif name[-1].isupper():\n name[-2] = name[-1]\n if utils.isLatin(lastChar) == True:\n name[-1] = \"A\"\n else:\n name[-1] = \"А\"\n else:\n name[-2] = name[-1]\n if utils.isLatin(lastChar) == True:\n name[-1] = \"a\"\n else:\n name[-1] = \"а\"\n else:\n return utils.addSuffix(name,gender,\"a\",True,False)\n return \"\".join(name)\n\ndef __dativ(name, gender, last_name):\n utils.check(name, gender)\n ogName = utils.separateLetters(name)\n name = utils.separateLetters(genitiv(name, gender).strip())\n\n lastThree = \"\".join(ogName[-3:])\n lastTwo = \"\".join(ogName[-2:])\n lastChar = name[-1]\n\n if last_name == True and (utils.toCyrillic(lastThree.lower()) in [\"ева\",\"ова\"] or utils.toCyrillic(lastTwo.lower()) == \"ка\") and len(ogName) > 3 and gender == Gender.FEMALE:\n return utils.addSuffix(ogName,gender,\"oj\",False,False)\n\n if utils.toCyrillic(lastThree.lower()) in [\"ски\", \"чки\", \"шки\"] and len(ogName) > 3 and gender == Gender.MALE:\n return utils.addSuffix(ogName,gender,\"om\",False,False)\n\n if lastChar.lower() in [\"а\", \"a\"]:\n return utils.addSuffix(name,gender,\"u\",False,False)\n \n elif lastChar.lower() in [\"е\", \"e\"]:\n return utils.addSuffix(name,gender,\"i\",False,True)\n\n return \"\".join(name)\n\ndef __akuzativ(name, gender):\n utils.check(name, gender)\n ogName = list(name)\n name = utils.separateLetters(genitiv(name, gender).strip())\n lastThree = \"\".join(name[-3:]).lower()\n\n lastChar = name[-1]\n\n if lastChar.lower() in [\"е\", \"e\"]:\n return utils.addSuffix(name,gender,\"u\",False,False)\n\n return \"\".join(name)\n\ndef __vokativ(name, gender, last_name):\n utils.check(name, gender)\n nameGenitiv = utils.separateLetters(genitiv(name, gender))\n name = utils.separateLetters(name.strip())\n rest = \"\".join(name[:-1])\n\n if (gender == Gender.FEMALE and name[-1].lower() not in [\"а\", \"a\"]) or \"\".join(name[-2:]) in [\"ia\", \"иа\"] or utils.toCyrillic(name[-1].lower()) in [\"о\", \"и\", \"у\", \"е\"]:\n return \"\".join(name)\n\n if (utils.toCyrillic(name[-1].lower()) in [\"к\", \"ц\"] and (utils.toCyrillic(\"\".join(name[-3:]).lower()) in NEP_A or utils.toCyrillic(\"\".join(name[-2:]).lower()) in NEP_A or last_name == True)) or utils.toCyrillic(name[-1].lower()) in ZADNJONEPCANI:\n if nameGenitiv[-1].islower():\n if utils.isLatin(nameGenitiv[-1]) == True:\n nameGenitiv[-1] = \"u\"\n else:\n nameGenitiv[-1] = \"у\"\n else:\n if utils.isLatin(nameGenitiv[-1]) == True:\n nameGenitiv[-1] = \"U\"\n else:\n nameGenitiv[-1] = \"У\"\n return utils.addSuffix(nameGenitiv,gender,\"u\",False,False)\n\n if utils.toCyrillic(name[-1].lower()) != \"а\":\n if nameGenitiv[-1].islower():\n if utils.isLatin(nameGenitiv[-1]) == True:\n nameGenitiv[-1] = \"e\"\n else:\n nameGenitiv[-1] = \"е\"\n \n if utils.toCyrillic(name[-1].lower()) in [\"к\", \"г\", \"х\"]:\n if utils.isLatin(nameGenitiv[-2]) == True:\n nameGenitiv[-2] = utils.toLatin(\n PALATALIZACIJA[utils.toCyrillic(nameGenitiv[-2].lower())])\n else:\n nameGenitiv[-2] = PALATALIZACIJA[nameGenitiv[-2].lower()]\n\n return \"\".join(nameGenitiv)\n else:\n if utils.isLatin(nameGenitiv[-1]) == True:\n nameGenitiv[-1] = \"E\"\n else:\n nameGenitiv[-1] = \"Е\"\n \n if utils.toCyrillic(name[-1].lower()) in [\"к\", \"г\", \"х\"]:\n if utils.isLatin(nameGenitiv[-2]) == True:\n nameGenitiv[-2] = utils.toLatin(\n PALATALIZACIJA[utils.toCyrillic(nameGenitiv[-2].lower())].upper())\n else:\n nameGenitiv[-2] = PALATALIZACIJA[nameGenitiv[-2].lower()].upper()\n\n return \"\".join(nameGenitiv)\n\n if utils.toCyrillic(name[-3].lower()+name[-2].lower()+name[-1].lower()).lower() in [\"ица\"] and len(name) > 5:\n return utils.addSuffix(nameGenitiv,gender,\"e\",False,False)\n\n if name[-1].lower() in [\"a\", \"а\"]:\n if len(name) <= 6:\n try:\n if name[-1].isupper():\n if utils.isLatin(name[-1]):\n return rest+(utils.toLatin(utils.vokativ_db[utils.toCyrillic(utils.formatName(name))])[-1].upper())\n else:\n return rest+(utils.vokativ_db[utils.toCyrillic(utils.formatName(name))][-1].upper())\n else:\n if utils.isLatin(name[-1]):\n return rest+(utils.toLatin(utils.vokativ_db[utils.toCyrillic(utils.formatName(name))])[-1])\n else:\n return rest+(utils.vokativ_db[utils.toCyrillic(utils.formatName(name))][-1])\n except KeyError:\n if len(name) == 6:\n return \"\".join(name)\n return utils.addSuffix(name,gender,\"o\",False,False)\n return \"\".join(name)\n\ndef __instrumental(name, gender):\n utils.check(name, gender)\n nameGenitiv = utils.separateLetters(genitiv(name, gender))\n name = utils.separateLetters(name.strip())\n\n lastChar = name[-1]\n lastThree = \"\".join(name[-3:]).lower()\n\n if gender == Gender.FEMALE and lastChar.lower() not in [\"a\", \"а\"]:\n return \"\".join(name)\n\n if utils.toCyrillic(lastThree.lower()) in [\"ски\", \"чки\", \"шки\"] and len(name) > 3 and gender == Gender.MALE:\n nameGenitiv.pop(-1)\n return utils.addSuffix(nameGenitiv,gender,\"im\",False,False)\n\n if gender == Gender.MALE and utils.toCyrillic(nameGenitiv)[-2].lower() in ZADNJONEPCANI and lastChar.lower() not in ['а','a']:\n return utils.addSuffix(nameGenitiv,gender,\"em\",False,False)\n else:\n return utils.addSuffix(nameGenitiv,gender,\"om\",False,True)\n\ndef __lokativ(name, gender):\n utils.check(name, gender)\n return dativ(name, gender)\n\ndef declineAll(name, gender):\n \"\"\"\n Declines a name through all 7 grammatical cases and returns a dictionary where each case is a key.\n\n Parameters:\n name: The name that should be declined\n gender: The gender of the person, param value must be either Gender.MALE or Gender.FEMALE\n \"\"\"\n utils.check(name, gender)\n name = name.strip()\n\n allDek = {\"nominativ\": name, \"genitiv\": genitiv(name, gender), \"dativ\": dativ(name, gender), \"akuzativ\": akuzativ(\n name, gender), \"vokativ\": vokativ(name, gender), \"instrumental\": instrumental(name, gender), \"lokativ\": lokativ(name, gender)}\n\n return allDek\n","repo_name":"urelja/deklinacija","sub_path":"deklinacija/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22942,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"72042035686","text":"#encoding: utf-8\nimport os\nimport sys\nimport pymysql\nimport traceback\nimport decimal\nimport json\nimport time\nimport datetime\nimport requests\nimport math\nfrom redis import StrictRedis\n\nMYSQL_HOST = \"coinexlog.chprmbwjfj0p.ap-northeast-1.rds.amazonaws.com\"\nMYSQL_PORT = 3306\nMYSQL_USER = \"coinex\"\nMYSQL_PASS = \"hp1sXMJftZWPO5bQ2snu\"\n\nMYSQL_COINEX = \"trade_log\"\nMYSQL_BINANCE = \"kline_binance\"\nMYSQL_HUOBI = \"kline_huobi\"\n\nREDIS_HOST = \"server.jb1xx2.ng.0001.apne1.cache.amazonaws.com\"\nREDIS_PORT = 6379\nREDIS_DB = 0\n\napi_coinex_markets = \"http://internal-web-internal-872360093.ap-northeast-1.elb.amazonaws.com/internal/exchange/market/list\"\napi_huobi_markets = \"https://api.huobi.pro/v1/common/symbols\"\napi_binance_markets = \"https://api.binance.com/api/v3/exchangeInfo\"\n\ninsert_data = {}\n\ndef rpc(url, params):\n headers = {\"Content-Type\": \"application/json\"};\n r = requests.get(url, params=params, headers=headers).json()\n return r\n\ndef get_binance_markets():\n marketlist_binace = {}\n exchang_info = rpc(api_binance_markets, {})\n for market in exchang_info[\"symbols\"]:\n if market['status'] == 'TRADING':\n marketlist_binace[market['symbol'].upper()] = market\n return marketlist_binace\n\ndef get_huobi_markets():\n markets_info = rpc(api_huobi_markets, {})\n if markets_info['status'] != 'ok':\n print(\"get market list error\")\n return\n\n marketlist_huobi = {}\n for market in markets_info[\"data\"]:\n if market['state'] == 'online':\n marketlist_huobi[market['symbol'].upper()] = market\n return marketlist_huobi\n\ndef get_coinex_markets():\n market_list = {}\n res = rpc(api_coinex_markets, {})\n for market_info in res['data']:\n market_list[market_info['name']] = market_info\n return market_list\n\ndef get_market_common(market_list1, market_list2):\n market_list = list(set(market_list1).intersection(set(market_list2)))\n return market_list\n\ndef get_day_kline(db_name, market_list, table_list):\n db_conn = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, passwd=MYSQL_PASS, db=db_name)\n cursor = db_conn.cursor()\n\n volume_list = {}\n for table in table_list:\n query_sql_str = \"select `market`, `timestamp`, `volume` from {} where `t`=3\".format(table)\n print(query_sql_str)\n try:\n cursor.execute(query_sql_str)\n res = cursor.fetchall()\n except Exception:\n print(\"exception: \",Exception)\n\n for item in res:\n market_name = item[0]\n if market_name not in market_list:\n continue\n\n timestamp = int(item[1])\n volume_list.setdefault(market_name, {})\n volume_list[market_name][timestamp] = decimal.Decimal(item[2])\n\n db_conn.close()\n return volume_list\n\ndef get_month(date, n):\n month = date.month\n year = date.year\n for i in range(n):\n if month == 1:\n year -= 1\n month = 12\n else:\n month -= 1\n return datetime.date(year, month, 1).strftime('%Y%m')\n\n\ndef flush_kline(redis_conn, key, subkey, kline_class, kline_data):\n global min_max\n global hour_max\n timestamp = subkey\n now = int(time.time())\n\n min_clear_tm = now / 60 * 60 - 60 * 24 * 30 * 60\n hour_clear_tm = now / 3600 * 3600 - 24 * 365 * 3 * 3600\n\n if kline_class == 1 and timestamp < min_clear_tm:\n return\n elif kline_class == 2 and timestamp < hour_clear_tm:\n return\n\n global insert_data\n insert_data.setdefault(key, {})\n insert_data[key][subkey] = json.dumps(kline_data)\n if len(insert_data[key]) > 1000:\n redis_conn.hmset(key, insert_data[key])\n print(key)\n insert_data[key] = {}\n\ndef get_redis_key(market, kline_class):\n if kline_class == 1:\n return \"k:{}:1m\".format(market)\n elif kline_class == 2:\n return \"k:{}:1h\".format(market)\n elif kline_class == 3:\n return \"k:{}:1d\".format(market)\n\ndef laod_table(db_conn, redis_conn, table_name, market_list_coinex, market_list_common, market_time, now, proportion_avg):\n limit = 100000\n offset = 0\n minute_start = now - 30 * 86400\n\n while True:\n query_sql_str = \"select `market`, `timestamp`, `t`, `open`, `close`, `high`, `low`, `volume`, `deal` from {} where `t`!=1 order by id asc limit {}, {}\".format(table_name, offset, limit)\n cursor = db_conn.cursor()\n print(query_sql_str)\n\n res = {}\n try:\n cursor.execute(query_sql_str)\n res = cursor.fetchall()\n except Exception:\n print(\"exception: \",Exception)\n\n for item in res:\n kline = []\n market_name = item[0]\n if market_name not in market_list_common:\n continue\n\n price_format = \"%.{}f\".format(int(market_list_coinex[item[0]]['money']['prec']))\n volume_format = \"%.{}f\".format(int(market_list_coinex[item[0]]['stock']['prec']))\n volume = decimal.Decimal(item[7])\n deal = decimal.Decimal(item[8])\n if market_name not in proportion_avg:\n continue\n\n if int(item[1]) < market_time[market_name]:\n continue\n \n volume = volume / proportion_avg[market_name]\n deal = deal / proportion_avg[market_name]\n\n kline.append(price_format % decimal.Decimal(item[3]))\n kline.append(price_format % item[4])\n kline.append(price_format % item[5])\n kline.append(price_format % item[6])\n #kline.append(volume_format % item[7])\n kline.append(volume_format % volume)\n kline.append(price_format % deal)\n\n key = get_redis_key(item[0], int(item[2]))\n flush_kline(redis_conn, key, int(item[1]), int(item[2]), kline)\n\n if len(res) < limit:\n offset = 0\n break\n else:\n offset = offset + limit\n\n cursor.close()\n if offset == 0:\n break\n\ndef kline_load(db_conn, redis_conn, market_list_coinex, market_list_common, market_time, proportion_avg, table_list):\n query_table_str = \"show tables like 'kline_history_2%'\"\n cursor = db_conn.cursor()\n cursor.execute(query_table_str)\n res = cursor.fetchall()\n\n now = int(time.time())\n for item in res:\n table = item[0]\n if table in table_list:\n continue\n\n print(table)\n laod_table(db_conn, redis_conn, table, market_list_coinex, market_list_common, market_time, now, proportion_avg)\n\n cursor.close()\n\n global insert_data\n for key, value in insert_data.items():\n if len(value) > 0:\n redis_conn.hmset(key, value)\n print(key)\n insert_data[key] = {}\n\ndef get_market_start(market_list_common):\n db_conn = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_COINEX)\n query_table_str = \"show tables like 'kline_history_2%'\"\n cursor = db_conn.cursor()\n cursor.execute(query_table_str)\n res = cursor.fetchall()\n\n market_time = {}\n now = int(time.time())\n for item in res:\n table = item[0]\n for market in market_list_common:\n if market in market_time:\n continue\n\n query_sql_str = \"select `timestamp` from {} where `market`='{}' order by timestamp asc limit 1\".format(table, market)\n cursor.execute(query_sql_str)\n klines = cursor.fetchall()\n if len(klines) >= 1:\n market_time[market] = int(klines[0][0])\n print(\"market: {}, start time: {}\".format(market, market_time[market]))\n\n cursor.close()\n db_conn.close()\n return market_time\n\ndef main():\n market_list_coinex = get_coinex_markets()\n market_list_huobi = get_huobi_markets()\n\n market_list_common = get_market_common(market_list_coinex.keys(), market_list_huobi.keys())\n market_time = get_market_start(market_list_common)\n\n date = datetime.datetime.today()\n table_list = []\n table_list.append(\"kline_history_{}\".format(get_month(date, 2)))\n\n print(\"market list len: {}\".format(len(market_list_common)))\n print(MYSQL_COINEX)\n coinex_volume_list = get_day_kline(MYSQL_COINEX, market_list_common, table_list)\n print(len(coinex_volume_list))\n\n print(MYSQL_HUOBI)\n huobi_volume_list = get_day_kline(MYSQL_HUOBI, market_list_common, table_list)\n print(len(huobi_volume_list))\n\n proportion = {}\n for market, volumes in coinex_volume_list.items():\n for day, volume in volumes.items():\n if (market not in huobi_volume_list):\n continue\n\n if day in huobi_volume_list[market]:\n proportion.setdefault(market, {})\n proportion[market][day] = huobi_volume_list[market][day] / volume\n print(\"market: {}, timestamp: {}, coinex: {}, huobi: {}, pro: {}\".format(market, day, volume, huobi_volume_list[market][day], proportion[market][day]))\n\n proportion_avg = {}\n for market, props in proportion.items():\n proportion_avg.setdefault(market, 0)\n for day, prop in props.items():\n proportion_avg[market] += prop\n proportion_avg[market] = proportion_avg[market] / len(props)\n\n print(proportion_avg)\n\n\n redis_conn = StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)\n db_conn = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_HUOBI)\n\n table_list = []\n table_list.append(\"kline_history_{}\".format(get_month(date, 0)))\n table_list.append(\"kline_history_{}\".format(get_month(date, 1)))\n table_list.append(\"kline_history_{}\".format(get_month(date, 2)))\n kline_load(db_conn, redis_conn, market_list_coinex, market_list_common, market_time, proportion_avg, table_list)\n\n db_conn.close()\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as ex:\n print(ex)\n print(traceback.format_exc())","repo_name":"daviyang35/coinex_exchange","sub_path":"scripts/kline_volume/kline_convert.py","file_name":"kline_convert.py","file_ext":"py","file_size_in_byte":10002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15370862952","text":"from rest_framework.authtoken.models import Token\nfrom urllib.parse import parse_qs\nfrom channels.db import database_sync_to_async\nfrom django.contrib.auth.models import AnonymousUser\nimport jwt\nfrom django.conf import settings\nfrom .models import Profile\n\n\n\t\n@database_sync_to_async\ndef returnUser(token_string):\n try:\n decoded_token = jwt.decode(token_string, settings.SECRET_KEY, algorithms=['HS256'])\n user = Profile.objects.get(pk=decoded_token['user_id'])\n except Exception as e:\n print(e,'exception')\n user = AnonymousUser()\n return user\n\nclass TokenAuthMiddleWare:\n\tdef __init__(self, app):\n\t\tself.app = app\n\n\tasync def __call__(self, scope, receive, send):\n\t\tquery_string = scope[\"query_string\"]\n\t\tquery_params = query_string.decode()\n\t\tquery_dict = parse_qs(query_params)\n\t\ttry:\n\t\t\ttoken = query_dict[\"token\"][0]\n\t\texcept:\n\t\t\ttoken=''\n\t\tuser = await returnUser(token)\n\t\tscope[\"user\"] = user\n\t\treturn await self.app(scope, receive, send)\n","repo_name":"Shabeertsy/django-react-chat-app","sub_path":"backend/chat/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30705869867","text":"students_number = int(input(\"enter the students number : \"))\nlesson_number = int(input(\"enter the lesson number : \"))\n\nstudents = []\nnotlar = []\nfor i in range(students_number):\n print(f\"{i+1}.incı öğrenci için : \")\n students.append(str(i+1) + \" Numaralı Öğrenci :\" )\n grades = []\n for j in range(lesson_number): \n grades.append(float(input(f\"{j + 1}. dersin notunu giriniz : \")))\n \n notlar.append(grades)\n\nortalama = []\nfor i in notlar:\n ortalama.append(f\"ortalama : {round(sum(i)/3, 2)}\")\nprint('*'*50, '\\n')\nfor i in zip(students, ortalama):\n print(*(i) , \"\\n\")\n\n# student, subject = map(int,input().split())\n# # s=[map(float,input().split()) for _ in range(subject)]\n# s = []\n# for i in range(subject):\n# s.append(map(float, input().split()))\n\n# for i in zip(*s):\n# print(sum(i)/subject)\n\n# student_number, lesson_number = map(int, input(\"öğrencive ders sayısını boşluk bırakarak giriniz :\").split())\n# notlar =[]\n# for i in range(lesson_number):\n# notlar.append(map(float, input(\"notları giriniz\").split()))\n\n# for i in zip(*notlar):\n# print(sum(i)/lesson_number)\n\n\n\n\n# students_number = int(input(\"enter the students number : \"))\n# lesson_number = int(input(\"enter the lesson number : \"))\n\n# students = []\n# notlar = []\n# for i in range(students_number):\n# print(f\"{i+1}.incı öğrenci için : \")\n# students.append(str(i+1) + \" Numaralı Öğrenci :\" )\n# grades = []\n# for j in range(lesson_number): \n# grades.append(float(input(f\"{j + 1}. dersin notlarını giriniz : \")))\n \n# notlar.append(grades)\n\n# ortalama = []\n# for i in notlar:\n# #print(f\"ortalama : {round(sum(i)/3, 2)}\")\n# ortalama.append(f\"ortalama : {round(sum(i)/3, 2)}\")\n\n# #print(* list(zip(students, ortalama)))\n# for i in zip (* (students, ortalama)):\n# print(i)\n\n\n# for i in zip(notlar, students):\n# print(sum(i)/lesson_number)\n# print(notlar)\n# print(students)\n\n# student, lessons = map(int, input().split())\n# print(\"bu student\" ,student)\n# print(\"bu subjetc\" ,subject)\n# s=[map(float,input().split()) for _ in range(subject)]\n# b = list(s)\n# print(\"bu s sayısır\" , b)\n# for i in zip(*s): print(sum(i)/subject)\n\n# X = map(int, input().split())\n# #print(\"bu x sayısıdır\", X)\n# grades = []\n# for i in range(X):\n# grades.append(list(map(float, input().split())))\n# for i in zip(*grades):\n# print(sum(i)/X)\n\n# student, subject = map(int,input().split())\n# s=[map(float,input().split()) for _ in range(subject)]\n# for i in zip(*s): print(sum(i)/subject)\n\n# for i in list(s):\n# print(i)\n\n# __author__ =\"Sirius.Star\"\n# N, X =list(map(int, input().split()))\n# notes=[]\n# for i in range(X):\n# notes.append(list(map(float, input().split())))\n \n# print(notes)\n# notes=list(zip(*notes))\n# print(notes)\n# notes=[sum(x)/X for x in notes]\n# #print(*notes, sep='\\n')\n# print(notes, sep='\\n')\n\n# lista = [[25.0, 26.0, 27.0, 28.0], [35.0, 36.0, 37.0, 38.0]]\n# listb = list(zip(*lista))\n# print(listb)\n\n# lista = [[25.0, 26.0, 27.0, 28.0], [35.0, 36.0, 37.0, 38.0]]\n# listb = [[99.0, 78.0, 58.0, 68.0], [120.0, 136.0, 157.0, 388.0]]\n# listc = list(zip(lista, listb))\n# print(listc)\n\n# lista = [[28,39], [35.0, 36.0]]\n# listb = [[99.0, 78.0], [120.0, 136.0]]\n# listc = list(zip(lista, listb))\n# print(listc)","repo_name":"akkocah/Python","sub_path":"Pyhton Addict/3-zipfunc.py","file_name":"3-zipfunc.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"15332788865","text":"from fastapi import FastAPI\nfrom schemas import Request\nfrom yolov5 import YOLOv5\n\ndetector = YOLOv5()\n\napp = FastAPI()\n\n# AWS Sagemaker Health Check Endpoint\n@app.get(\"/ping\")\ndef ping():\n return {\n 'message' : 'alive'\n }\n\n# AWS Sagemaker Invocations endpoint\n@app.post('/invocations')\ndef invocations(request: Request):\n try:\n detections = detector.predict(request.url)\n except Exception as e:\n return {\n 'success' : False\n }\n\n return {\n 'success' : True,\n 'result' : detections\n }","repo_name":"jeffgorithm/aws-sagemaker-fastapi","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74783695845","text":"from cubicweb import _\n\nfrom yams import xy\n\nfrom cubicweb.schema import VIRTUAL_RTYPES\nfrom cubicweb.view import EntityView\nfrom cubicweb.web.views.xmlrss import SERIALIZERS\n\ntry:\n import rdflib\nexcept ImportError:\n rdflib = None\n\nif rdflib is not None:\n RDF = rdflib.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')\n CW = rdflib.Namespace('http://ns.cubicweb.org/cubicweb/0.0/')\n from rdflib import Literal, URIRef, Namespace\n\n def urijoin(item):\n base, ext = item\n return URIRef(Namespace(base)[ext])\n\n SKIP_RTYPES = VIRTUAL_RTYPES | set(['cwuri', 'is', 'is_instance_of'])\n\n class RDFView(EntityView):\n \"\"\"rdf view for entities\"\"\"\n __regid__ = 'rdf'\n title = _('rdf export')\n templatable = False\n binary = True\n format = 'xml'\n content_type = 'text/xml' # +rdf\n\n def call(self):\n graph = rdflib.Graph()\n graph.bind('cw', CW)\n for prefix, xmlns in xy.XY.prefixes.items():\n graph.bind(prefix, rdflib.Namespace(xmlns))\n for i in range(self.cw_rset.rowcount):\n entity = self.cw_rset.complete_entity(i, 0)\n self.entity2graph(graph, entity)\n self.w(graph.serialize(format=self.format))\n\n def entity_call(self, entity):\n self.call()\n\n def entity2graph(self, graph, entity):\n cwuri = URIRef(entity.cwuri)\n add = graph.add\n add( (cwuri, RDF.type, CW[entity.e_schema.type]) )\n try:\n for item in xy.xeq(entity.e_schema.type):\n add( (cwuri, RDF.type, urijoin(item)) )\n except xy.UnsupportedVocabulary:\n pass\n for rschema, eschemas, role in entity.e_schema.relation_definitions('relation'):\n rtype = rschema.type\n if rtype in SKIP_RTYPES or rtype.endswith('_permission'):\n continue\n for eschema in eschemas:\n if eschema.final:\n try:\n value = entity.cw_attr_cache[rtype]\n except KeyError:\n continue # assuming rtype is Bytes\n if value is not None:\n add( (cwuri, CW[rtype], Literal(value)) )\n try:\n for item in xy.xeq('%s %s' % (entity.e_schema.type, rtype)):\n add( (cwuri, urijoin(item[1]), Literal(value)) )\n except xy.UnsupportedVocabulary:\n pass\n else:\n for related in entity.related(rtype, role, entities=True, safe=True):\n if role == 'subject':\n add( (cwuri, CW[rtype], URIRef(related.cwuri)) )\n try:\n for item in xy.xeq('%s %s' % (entity.e_schema.type, rtype)):\n add( (cwuri, urijoin(item[1]), URIRef(related.cwuri)) )\n except xy.UnsupportedVocabulary:\n pass\n else:\n add( (URIRef(related.cwuri), CW[rtype], cwuri) )\n\n\n class RDFN3View(RDFView):\n __regid__ = 'n3rdf'\n format = 'n3'\n content_type = 'text/n3'\n","repo_name":"gurneyalex/cubicweb","sub_path":"cubicweb/web/views/rdf.py","file_name":"rdf.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"41309109937","text":"#!/usr/bin/python3 -u\n\nimport contextlib\nfrom contextlib import contextmanager\nfrom datetime import datetime\nimport io\nimport json\nimport os\nimport re\nimport secrets\nimport shutil\nimport socket\nimport ssl\nimport subprocess\nimport sys\nimport tempfile\nimport threading\nimport time\nimport traceback\nimport urllib.request\n\nfrom tinkerforge.ip_connection import IPConnection, base58encode, base58decode, BASE58\n\n\nESP_ETHERNET_DEVICE_ID = 115\n\nfrom provision_common.provision_common import *\n\ndef main():\n common_init('/dev/ttyUSB0')\n\n if len(sys.argv) != 2:\n fatal_error(\"Usage: {} firmware_type\".format(sys.argv[0]))\n\n firmware_type = sys.argv[1]\n if firmware_type not in [\"esp32_ethernet\", \"warp2\", \"energy_manager\"]:\n fatal_error(\"Unknown firmware type {}\".format(firmware_type))\n\n result = {\"start\": now()}\n\n print(\"Checking ESP state\")\n mac_address = check_if_esp_is_sane_and_get_mac()\n print(\"MAC Address is {}\".format(mac_address))\n result[\"mac\"] = mac_address\n\n set_voltage_fuses, set_block_3, passphrase, uid = get_espefuse_tasks()\n if set_voltage_fuses or set_block_3:\n fatal_error(\"Fuses are not set. Re-run stage 0!\")\n\n esptool([\"--after\", \"hard_reset\", \"chip_id\"])\n\n result[\"uid\"] = uid\n\n if firmware_type == 'warp2':\n ssid = \"warp2-\" + uid\n elif firmware_type == 'energy_manager':\n ssid = \"wem-\" + uid\n else:\n ssid = \"esp32-\" + uid\n\n run([\"systemctl\", \"restart\", \"NetworkManager.service\"])\n run([\"iw\", \"reg\", \"set\", \"DE\"])\n\n print(\"Waiting for ESP wifi. Takes about one minute.\")\n if not wait_for_wifi(ssid, 90):\n fatal_error(\"ESP wifi not found after 90 seconds\")\n\n print(\"Testing ESP Wifi.\")\n with wifi(ssid, passphrase):\n req = urllib.request.Request(\"http://10.0.0.1/ethernet/config_update\",\n data=json.dumps({\"enable_ethernet\":True,\n \"ip\": \"192.168.123.123\",\n \"gateway\":\"0.0.0.0\",\n \"subnet\":\"255.255.0.0\",\n \"dns\":\"0.0.0.0\",\n \"dns2\":\"0.0.0.0\"}).encode(\"utf-8\"),\n method='PUT',\n headers={\"Content-Type\": \"application/json\"})\n try:\n with urllib.request.urlopen(req, timeout=10) as f:\n f.read()\n except Exception as e:\n print(e)\n fatal_error(\"Failed to set ethernet config!\")\n req = urllib.request.Request(\"http://10.0.0.1/reboot\", data=b'null', method='PUT', headers={\"Content-Type\": \"application/json\"})\n try:\n with urllib.request.urlopen(req, timeout=10) as f:\n f.read()\n except Exception as e:\n print(\"Failed to initiate reboot! Attempting to connect via ethernet anyway.\")\n\n result[\"wifi_test_successful\"] = True\n\n time.sleep(3)\n print(\"Connecting via ethernet to 192.168.123.123\", end=\"\")\n for i in range(30):\n start = time.time()\n req = urllib.request.Request(\"http://192.168.123.123/ethernet/config_update\",\n data=json.dumps({\"enable_ethernet\":True,\n \"ip\":\"0.0.0.0\",\n \"gateway\":\"0.0.0.0\",\n \"subnet\":\"0.0.0.0\",\n \"dns\":\"0.0.0.0\",\n \"dns2\":\"0.0.0.0\"}).encode(\"utf-8\"),\n method='PUT',\n headers={\"Content-Type\": \"application/json\"})\n try:\n with urllib.request.urlopen(req, timeout=1) as f:\n f.read()\n break\n except:\n pass\n t = max(0, 1 - (time.time() - start))\n time.sleep(t)\n print(\".\", end=\"\")\n else:\n print(\"Failed to connect via ethernet!\")\n raise Exception(\"exit 1\")\n print(\" Connected.\")\n\n req = urllib.request.Request(\"http://192.168.123.123/info/version\")\n try:\n with urllib.request.urlopen(req, timeout=10) as f:\n fw_version = json.loads(f.read().decode(\"utf-8\"))[\"firmware\"].split(\"-\")[0]\n except Exception as e:\n fatal_error(\"Failed to read firmware version!\")\n\n if firmware_type in (\"warp2\", \"energy_manager\"):\n try:\n with urllib.request.urlopen(\"http://192.168.123.123/hidden_proxy/enable\", timeout=10) as f:\n f.read()\n except Exception as e:\n print(e)\n fatal_error(\"Failed to enable hidden_proxy!\")\n\n time.sleep(3)\n ipcon = IPConnection()\n ipcon.connect(\"192.168.123.123\", 4223)\n result[\"ethernet_test_successful\"] = True\n print(\"Connected. Testing bricklet ports\")\n\n test_bricklet_ports(ipcon, ESP_ETHERNET_DEVICE_ID, firmware_type in (\"warp2\", \"energy_manager\"))\n result[\"bricklet_port_test_successful\"] = True\n\n led0 = input(\"Does the status LED blink blue? [y/n]\")\n while led0 not in (\"y\", \"n\"):\n led0 = input(\"Does the status LED blink blue? [y/n]\")\n result[\"status_led_test_successful\"] = led0 == \"y\"\n if led0 == \"n\":\n fatal_error(\"Status LED does not work\")\n\n # We don't test the IO0 button anymore\n result[\"io0_test_successful\"] = None\n\n led0_stop = input(\"Press EN button. Does the status LED stop blinking for some seconds? [y/n]\")\n while led0_stop not in (\"y\", \"n\"):\n led0_stop = input(\"Press EN button. Does the status LED stop blinking for some seconds? [y/n]\")\n result[\"enable_test_successful\"] = led0_stop == \"y\"\n if led0_stop == \"n\":\n fatal_error(\"EN button does not work\")\n\n result[\"tests_successful\"] = True\n result[\"end\"] = now()\n\n with open(\"{}_{}_report_stage_1.json\".format(ssid, now().replace(\":\", \"-\")), \"w\") as f:\n json.dump(result, f, indent=4)\n\n label_success = \"n\"\n while label_success != \"y\":\n run([\"python3\", \"print-esp32-label.py\", ssid, passphrase, \"-c\", \"3\" if firmware_type in (\"warp2\", \"energy_manager\") else \"1\"])\n label_prompt = \"Stick one label on the ESP, put ESP{} in the ESD bag. Press n to retry printing the label{}. [y/n]\".format(\n \" and the other two labels\" if firmware_type in (\"warp2\", \"energy_manager\") else \"\",\n \"s\" if firmware_type in (\"warp2\", \"energy_manager\") else \"\")\n\n label_success = input(label_prompt)\n while label_success not in (\"y\", \"n\"):\n label_success = input(label_prompt)\n\n if firmware_type == \"esp32_ethernet\":\n bag_label_success = \"n\"\n while bag_label_success != \"y\":\n run([\"python3\", \"../../flash-test/label/print-label.py\", \"-c\", \"1\", \"ESP32 Ethernet Brick\", str(ESP_ETHERNET_DEVICE_ID), datetime.datetime.now().strftime('%Y-%m-%d'), uid, fw_version])\n bag_label_prompt = \"Stick bag label on bag. Press n to retry printing the label. [y/n]\"\n\n bag_label_success = input(bag_label_prompt)\n while bag_label_success not in (\"y\", \"n\"):\n bag_label_success = input(bag_label_prompt)\n\n print('Done!')\n\nif __name__ == \"__main__\":\n try:\n main()\n except FatalError:\n input(\"Press return to exit. \")\n sys.exit(1)\n except Exception as e:\n traceback.print_exc()\n input(\"Press return to exit. \")\n sys.exit(1)\n","repo_name":"Tinkerforge/esp32-firmware","sub_path":"provisioning/provision_stage_1_esp32_ethernet.py","file_name":"provision_stage_1_esp32_ethernet.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"2424143124","text":"''' \nfrom odoo import fields, api, models, tools\nfrom datetime import date\nimport time\nfrom odoo.exceptions import RedirectWarning, UserError, ValidationError\nfrom calendar import monthrange\nfrom operator import itemgetter\n\nclass payroll_advice_report(models.AbstractModel):\n _name = 'report.client_pi.report_journal_entry'\n _description = \"Report Journal Entry\"\n \n def get_detail(self, line_ids):\n result = []\n for l in line_ids:\n res = {}\n res.update({\n 'account_id': l.account_id,\n 'partner_id': l.partner_id,\n 'name': l.name,\n 'debit': l.debit,\n 'credit': l.credit,\n })\n result.append(res)\n #result = sorted(result, key=itemgetter('account_id'))\n return result\n \n @api.model\n def _get_report_values(self, docids, data=None):\n journal_entry = self.env['account.move'].browse(docids)\n return {\n 'doc_ids': docids,\n 'doc_model': 'account.move',\n 'data': data,\n 'docs': journal_entry,\n 'get_detail': self.get_detail(),\n } '''\n \nfrom odoo import api, models\nclass accountdeitjournal(models.Model):\n _inherit = \"account.move\"\n\n def total_debit_credit(self):\n res = {}\n for move in self:\n dr_total = 0.0\n cr_total = 0.0\n for line in move.line_ids:\n dr_total += line.debit\n cr_total += line.credit\n dr_total = round(dr_total, 2)\n cr_total = round(cr_total, 2)\n res.update({'cr_total': cr_total, 'dr_total': dr_total})\n return res","repo_name":"chris237/Jira-pether","sub_path":"client_pi/reports/report_journal.py","file_name":"report_journal.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16250673360","text":"import os\nimport typing\n\nimport audbackend\nimport audeer\nimport audformat\n\nfrom audb.core import define\nfrom audb.core import utils\nfrom audb.core.api import dependencies\nfrom audb.core.api import latest_version\nfrom audb.core.dependencies import Dependencies\nfrom audb.core.load import database_tmp_root\nfrom audb.core.load import load_header_to\n\n\ndef _find_attachments(\n db_root: str,\n deps: Dependencies,\n) -> typing.List[str]:\n r\"\"\"Find missing attachments.\"\"\"\n attachments = []\n\n for file in deps.attachments:\n full_file = os.path.join(db_root, file)\n if not os.path.exists(full_file):\n attachments.append(file)\n\n return attachments\n\n\ndef _find_media(\n db: audformat.Database,\n db_root: str,\n deps: Dependencies,\n num_workers: typing.Optional[int],\n verbose: bool,\n) -> typing.List[str]:\n r\"\"\"Find missing media.\n\n Collects all media files present in ``db.files``,\n but not in ``db_root``.\n This will find missing files,\n but also altered files\n as those have been deleted\n in a previous step.\n\n \"\"\"\n media = []\n\n def job(file: str):\n if not deps.removed(file):\n full_file = os.path.join(db_root, file)\n if not os.path.exists(full_file):\n media.append(file)\n\n audeer.run_tasks(\n job,\n params=[([file], {}) for file in db.files],\n num_workers=num_workers,\n progress_bar=verbose,\n task_description='Find media',\n )\n\n return media\n\n\ndef _find_tables(\n db_header: audformat.Database,\n db_root: str,\n deps: Dependencies,\n num_workers: typing.Optional[int],\n verbose: bool,\n) -> typing.List[str]:\n r\"\"\"Find missing tables.\n\n Collects all tables and misc tables\n present in ``db_header``,\n but not in ``db_root``.\n This will find missing tables,\n but also altered tables\n as those have been deleted\n in a previous step.\n\n \"\"\"\n tables = []\n\n def job(table: str):\n file = f'db.{table}.csv'\n full_file = os.path.join(db_root, file)\n if not os.path.exists(full_file):\n tables.append(file)\n\n audeer.run_tasks(\n job,\n params=[([table], {}) for table in list(db_header)],\n num_workers=num_workers,\n progress_bar=verbose,\n task_description='Find tables',\n )\n\n return tables\n\n\ndef _get_attachments(\n paths: typing.Sequence[str],\n db_root: str,\n db_root_tmp: str,\n db_name: str,\n deps: Dependencies,\n backend: audbackend.Backend,\n num_workers: typing.Optional[int],\n verbose: bool,\n):\n r\"\"\"Load attachments from backend.\"\"\"\n # create folder tree to avoid race condition\n # in os.makedirs when files are unpacked\n utils.mkdir_tree(paths, db_root)\n utils.mkdir_tree(paths, db_root_tmp)\n\n def job(path: str):\n archive = deps.archive(path)\n version = deps.version(path)\n archive = backend.join(\n db_name,\n define.DEPEND_TYPE_NAMES[define.DependType.ATTACHMENT],\n archive,\n )\n backend.get_archive(\n archive,\n db_root_tmp,\n version,\n tmp_root=db_root_tmp,\n )\n src_path = audeer.path(db_root_tmp, path)\n dst_path = audeer.path(db_root, path)\n audeer.move_file(\n src_path,\n dst_path,\n )\n\n audeer.run_tasks(\n job,\n params=[([path], {}) for path in paths],\n num_workers=num_workers,\n progress_bar=verbose,\n task_description='Load attachments',\n )\n\n\ndef _get_media(\n media: typing.List[str],\n db_root: str,\n db_root_tmp: str,\n db_name: str,\n deps: Dependencies,\n backend: audbackend.Backend,\n num_workers: typing.Optional[int],\n verbose: bool,\n):\n\n # create folder tree to avoid race condition\n # in os.makedirs when files are unpacked\n utils.mkdir_tree(media, db_root)\n utils.mkdir_tree(media, db_root_tmp)\n\n # figure out archives\n archives = set()\n for file in media:\n archives.add(\n (deps.archive(file), deps.version(file))\n )\n\n def job(archive: str, version: str):\n archive = backend.join(\n db_name,\n define.DEPEND_TYPE_NAMES[define.DependType.MEDIA],\n archive,\n )\n files = backend.get_archive(\n archive,\n db_root_tmp,\n version,\n tmp_root=db_root_tmp,\n )\n for file in files:\n audeer.move_file(\n os.path.join(db_root_tmp, file),\n os.path.join(db_root, file),\n )\n\n audeer.run_tasks(\n job,\n params=[([archive, version], {}) for archive, version in archives],\n num_workers=num_workers,\n progress_bar=verbose,\n task_description='Get media',\n )\n\n\ndef _get_tables(\n tables: typing.List[str],\n db_root: str,\n db_root_tmp: str,\n db_name: str,\n deps: Dependencies,\n backend: audbackend.Backend,\n num_workers: typing.Optional[int],\n verbose: bool,\n):\n\n def job(table: str):\n # If a pickled version of the table exists,\n # we have to remove it to make sure that\n # later on the new CSV tables are loaded.\n # This can happen if we upgrade an existing\n # database to a different version.\n path_pkl = os.path.join(\n db_root, table\n )[:-3] + audformat.define.TableStorageFormat.PICKLE\n if os.path.exists(path_pkl):\n os.remove(path_pkl)\n archive = backend.join(\n db_name,\n define.DEPEND_TYPE_NAMES[define.DependType.META],\n deps.archive(table),\n )\n backend.get_archive(\n archive,\n db_root_tmp,\n deps.version(table),\n tmp_root=db_root_tmp,\n )\n audeer.move_file(\n os.path.join(db_root_tmp, table),\n os.path.join(db_root, table),\n )\n\n audeer.run_tasks(\n job,\n params=[([table], {}) for table in tables],\n num_workers=num_workers,\n progress_bar=verbose,\n task_description='Get tables',\n )\n\n\ndef _remove_empty_dirs(root):\n r\"\"\"Remove directories, fails if it contains non-empty sub-folders.\"\"\"\n files = os.listdir(root)\n if len(files):\n for file in files:\n full_file = os.path.join(root, file)\n if os.path.isdir(full_file):\n _remove_empty_dirs(full_file)\n\n os.rmdir(root)\n\n\ndef load_to(\n root: str,\n name: str,\n *,\n version: str = None,\n only_metadata: bool = False,\n cache_root: str = None,\n num_workers: typing.Optional[int] = 1,\n verbose: bool = True,\n) -> audformat.Database:\n r\"\"\"Load database to directory.\n\n Loads the original state of the database\n to a custom directory.\n No conversion or filtering will be applied.\n If the target folder already contains\n some version of the database,\n it will upgrade to the requested version.\n Unchanged files will be skipped.\n\n Args:\n root: target directory\n name: name of database\n version: version string, latest if ``None``\n only_metadata: load only header and tables of database\n cache_root: cache folder where databases are stored.\n If not set :meth:`audb.default_cache_root` is used.\n Only used to read the dependencies of the requested version\n num_workers: number of parallel jobs or 1 for sequential\n processing. If ``None`` will be set to the number of\n processors on the machine multiplied by 5\n verbose: show debug messages\n\n Returns:\n database object\n\n \"\"\"\n if version is None:\n version = latest_version(name)\n\n db_root = audeer.path(root)\n db_root_tmp = database_tmp_root(db_root)\n\n # remove files with a wrong checksum\n # to ensure we load correct version\n update = os.path.exists(db_root) and os.listdir(db_root)\n audeer.mkdir(db_root)\n deps = dependencies(\n name,\n version=version,\n cache_root=cache_root,\n verbose=verbose,\n )\n if update:\n if only_metadata:\n files = deps.tables\n else:\n files = deps.attachments + deps.files\n for file in files:\n full_file = os.path.join(db_root, file)\n if os.path.exists(full_file):\n checksum = audeer.md5(full_file)\n if checksum != deps.checksum(file):\n if os.path.isdir(full_file):\n audeer.rmdir(full_file)\n else:\n os.remove(full_file)\n\n # load database header without tables from backend\n\n db_header, backend = load_header_to(\n db_root_tmp,\n name,\n version,\n overwrite=True,\n )\n db_header.save(db_root_tmp, header_only=True)\n\n # get altered and new attachments\n\n if not only_metadata:\n attachments = _find_attachments(\n db_root,\n deps,\n )\n _get_attachments(\n attachments,\n db_root,\n db_root_tmp,\n name,\n deps,\n backend,\n num_workers,\n verbose,\n )\n\n # get altered and new tables\n\n tables = _find_tables(db_header, db_root, deps, num_workers, verbose)\n _get_tables(tables, db_root, db_root_tmp, name, deps, backend,\n num_workers, verbose)\n\n # load database\n\n # move header to root and load database ...\n audeer.move_file(\n os.path.join(db_root_tmp, define.HEADER_FILE),\n os.path.join(db_root, define.HEADER_FILE),\n )\n try:\n db = audformat.Database.load(\n db_root,\n num_workers=num_workers,\n verbose=verbose,\n )\n except (KeyboardInterrupt, Exception): # pragma: no cover\n # make sure to remove header if user interrupts\n os.remove(os.path.join(db_root, define.HEADER_FILE))\n raise\n\n # afterwards remove header to avoid the database\n # can be loaded before download is complete\n os.remove(os.path.join(db_root, define.HEADER_FILE))\n\n # get altered and new media files\n\n if not only_metadata:\n media = _find_media(db, db_root, deps, num_workers, verbose)\n _get_media(media, db_root, db_root_tmp, name, deps, backend,\n num_workers, verbose)\n\n # save dependencies\n\n dep_path_tmp = os.path.join(db_root_tmp, define.DEPENDENCIES_FILE)\n deps.save(dep_path_tmp)\n audeer.move_file(\n dep_path_tmp,\n os.path.join(db_root, define.DEPENDENCIES_FILE),\n )\n\n # save database and PKL tables\n\n db.save(\n db_root,\n storage_format=audformat.define.TableStorageFormat.PICKLE,\n update_other_formats=False,\n num_workers=num_workers,\n verbose=verbose,\n )\n\n # remove the temporal directory\n # to signal all files were correctly loaded\n try:\n _remove_empty_dirs(db_root_tmp)\n except OSError: # pragma: no cover\n raise RuntimeError(\n 'Could not remove temporary directory, '\n 'probably there are some leftover files. '\n 'This should not happen.'\n )\n\n return db\n","repo_name":"audeering/audb","sub_path":"audb/core/load_to.py","file_name":"load_to.py","file_ext":"py","file_size_in_byte":11439,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"} +{"seq_id":"72818306086","text":"import json\nimport logging\n\nfrom django.shortcuts import redirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.utils import timezone\nfrom mysite.GoogleAPI import AuthFirebase\nfrom .forms import PostForm\nfrom .models import Post\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\n\nlogger = logging.getLogger(__name__)\n\n\ndef post_list(request):\n posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')\n return render(request, 'blog/post_list.html', {'posts':posts})\n\ndef post_detail(request, pk):\n post = get_object_or_404(Post, pk=pk)\n return render(request, 'blog/post_detail.html', {'post': post})\n\ndef post_new(request):\n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm()\n return render(request, 'blog/post_edit.html', {'form':form})\n\n\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm(instance=post)\n return render(request, 'blog/post_edit.html', {'form':form})\n\n\ndef login(request):\n return render(request, 'blog/login.html')\n\n\n@api_view(['POST'])\ndef google_auth(request):\n params = json.loads(request.body)\n token = params.get('token', \"\")\n print(token)\n AuthFirebase(token)\n return Response(status=status.HTTP_200_OK)\n\n","repo_name":"leeleelee3264/my-first-djanogo-blog","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38359027469","text":"from __future__ import annotations\n\nimport re\nfrom pathlib import Path\nfrom typing import Mapping, Iterable, Match\n\nimport numpy as np\nimport pandas as pd\nimport quantities as pq\nfrom pandas import Index\n\nfrom openmnglab.datamodel.pandas.model import PandasContainer\nfrom openmnglab.functions.base import SourceFunctionBase\nfrom openmnglab.functions.input.readers.funcs.dapsys_reader import _kernel_offset_assign\nfrom openmnglab.functions.input.readers.funcs.spike2.hdfmat import HDFMatGroup, HDFMatFile\nfrom openmnglab.functions.input.readers.funcs.spike2.structs import Spike2Realwave, Spike2Waveform, Spike2Marker, \\\n Spike2Textmark, Spike2UnbinnedEvent, spike2_struct\nimport openmnglab.datamodel.pandas.schemas as schema\n\nSPIKE2_CHANID = int | str\n\nSPIKE2_EXTPULSES = \"external pulses\"\nSPIKE2_V_CHAN = \"V chan\"\nSPIKE2_DIGMARK = \"digmark\"\nSPIKE2_KEYBOARD = \"keyboard\"\nSPIKE2_CODES = \"codes\"\n\n\nclass Spike2ReaderFunc(SourceFunctionBase):\n class Spike2Channels:\n _channelno_regex = r\"_Ch(\\d*)\"\n\n def __init__(self, structs: HDFMatFile):\n self._structs = structs\n self._id_map: dict[str | int, str] | None = None\n self._supports_chan_no: bool | None = None\n\n @classmethod\n def _make_idmap(cls, structs: Mapping) -> dict[str | int, str]:\n def unpack_match(result: Match[str] | None) -> int | None:\n return int(result.group(1)) if result is not None else None\n\n channel_no_regex = re.compile(cls._channelno_regex)\n idmap: dict[str | int, str] = dict()\n for struct_name, fields in structs.items():\n chan_no = unpack_match(channel_no_regex.search(struct_name))\n if chan_no is not None:\n idmap[chan_no] = struct_name\n chan_name = fields.get(\"title\", default=None)\n if chan_name:\n idmap[chan_name[0]] = struct_name\n return idmap\n\n @property\n def structs(self) -> HDFMatFile:\n return self._structs\n\n @property\n def id_map(self) -> dict[str | int, str]:\n if self._id_map is None:\n self._id_map = self._make_idmap(self.structs)\n return self._id_map\n\n @property\n def supports_chan_no(self) -> bool:\n if self._supports_chan_no is None:\n pattern = re.compile(self._channelno_regex)\n self._supports_chan_no = any(pattern.search(struct_name) is not None for struct_name in self.structs)\n return self._supports_chan_no\n\n def get_chan(self, chan_id: SPIKE2_CHANID, default: dict | None = None) -> HDFMatGroup | None:\n if isinstance(chan_id, int) and not self.supports_chan_no:\n raise KeyError(\n \"A channel number was provided as a channel id. However, channel numbers are not contained in the exported Matlab file and are thus unavailable.\")\n struct_name = self.id_map.get(chan_id)\n if struct_name is None:\n return default\n return self.structs[struct_name]\n\n def __getitem__(self, item: SPIKE2_CHANID) -> HDFMatGroup:\n value = self.get_chan(item)\n if value is None:\n raise KeyError(f\"No channel with the id {item} found\")\n return value\n\n _channel_regex = re.compile(r\"_Ch(\\d*)\")\n\n def __init__(self, path: str | Path,\n signal: SPIKE2_CHANID | None = \"Signal\",\n temp: SPIKE2_CHANID | None = \"Temp\",\n mass: SPIKE2_CHANID | None = \"Force\",\n v_chan: SPIKE2_CHANID | None = \"V\",\n ext_pul: SPIKE2_CHANID | None = 10,\n comments: SPIKE2_CHANID | None = 30,\n keyboard: SPIKE2_CHANID | None = 31,\n digmark: SPIKE2_CHANID | None = 32,\n wavemarks: SPIKE2_CHANID | None | Iterable[int | str] = \"nw-1\",\n start: float = 0,\n end: float = np.inf,\n mass_unit: pq.Quantity = pq.g,\n signal_unit: pq.Quantity = pq.microvolt,\n temp_unit: pq.Quantity = pq.celsius,\n v_chan_unit: pq.Quantity = pq.dimensionless,\n time_unit: pq.Quantity = pq.second):\n self._start = start\n self._end = end\n self._signal_chan = signal\n self._temp_chan = temp\n self._mass = mass\n self._v_chan = v_chan\n self._ext_pul = ext_pul\n self._comments = comments\n self._keyboard = keyboard\n self._digmark = digmark\n self._wavemarks = wavemarks\n self._mass_unit = mass_unit\n self._signal_unit = signal_unit\n self._temp_unit = temp_unit\n self._v_chan_unit = v_chan_unit\n self._time_unit = time_unit\n self._path = path\n self._channels: Spike2ReaderFunc.Spike2Channels | None = None\n\n @classmethod\n def _get_chan_identifier(cls, matlab_struct_name: str) -> str | int:\n res = cls._channel_regex.search(matlab_struct_name)\n return int(res.group(1)) if res is not None else matlab_struct_name\n\n @staticmethod\n def _get_channel_name(channel_struct: dict | None, name_override: str | None = None) -> str:\n if name_override is not None:\n return name_override\n if channel_struct is None:\n channel_struct = dict()\n return channel_struct.get(\"title\", \"unknown channel\")\n\n def _waveform_chan_to_series(self, spike2_struct: Spike2Realwave | Spike2Waveform | None,\n name: str, index_name: str = schema.TIMESTAMP) -> pd.Series:\n values, times = np.empty(0, dtype=np.float64), np.empty(0, dtype=np.float64)\n if spike2_struct is not None and spike2_struct.length > 0:\n slicer = spike2_struct.timerange_slice(self._start, self._end)\n values = spike2_struct.get_values_slice(slicer)\n if isinstance(spike2_struct, Spike2Realwave):\n times = np.empty(len(values))\n start = slicer.start * spike2_struct.interval + spike2_struct.start\n _kernel_offset_assign(times, start, spike2_struct.interval, 0, len(times))\n else:\n times = spike2_struct.get_times_slice(slicer)\n\n series = pd.Series(data=values, index=pd.Index(times, name=index_name, copy=False),\n name=name, copy=False)\n return series\n\n def _marker_chan_to_series(self, spike2_struct: Spike2Marker | None, name: str,\n index_name: str = schema.TIMESTAMP) -> pd.Series:\n times, codes = np.empty(0, dtype=np.float64), np.empty(0, dtype=np.uint32)\n if spike2_struct is not None and spike2_struct.length > 0:\n slicer = spike2_struct.timerange_slice(self._start, self._end)\n times = spike2_struct.get_times_slice(slicer)\n codes = spike2_struct.get_int_codes_slice(slicer)\n series = pd.Series(data=codes, dtype=\"category\", name=name,\n index=Index(data=times, copy=False, name=index_name))\n return series\n\n def _textmarker_chan_to_series(self, spike2_struct: Spike2Textmark | None, name: str,\n index_name: str = schema.TIMESTAMP) -> pd.Series:\n texts, times, codes = np.empty(0, dtype=str), np.empty(0, dtype=np.float64), np.empty(0, dtype=np.uint32)\n if spike2_struct is not None and spike2_struct.length > 0:\n slicer = spike2_struct.timerange_slice(self._start, self._end)\n times = spike2_struct.get_times_slice(slicer)\n texts = spike2_struct.get_texts_slice(slicer)\n codes = spike2_struct.get_int_codes_slice(slicer)\n series = pd.Series(data=texts,\n index=pd.MultiIndex.from_arrays([times, codes], names=[index_name, SPIKE2_CODES]),\n copy=False,\n name=name)\n return series\n\n def _unbinned_event_chant_to_series(self, spike2_struct: Spike2UnbinnedEvent | None, name: str,\n index_name: str = schema.TIMESTAMP):\n times, levels = np.empty(0, dtype=np.float64), np.empty(0, dtype=np.int8)\n if spike2_struct is not None and spike2_struct.length > 0:\n slicer = spike2_struct.timerange_slice(self._start, self._end)\n times = spike2_struct.get_times_slice(slicer)\n levels = spike2_struct.get_levels_slice(slicer)\n series = pd.Series(data=levels, index=pd.Index(times, name=index_name, copy=False), copy=False, name=name)\n return series\n\n def _load_sig_chan(self, chan_struct: dict | None, quantity: pq.Quantity, time_quantity: pq.Quantity = pq.second,\n name: str | None = None):\n parsed_struct = spike2_struct(chan_struct) if chan_struct is not None else None\n series = self._waveform_chan_to_series(parsed_struct, self._get_channel_name(parsed_struct, name_override=name))\n return PandasContainer(series, {series.name: quantity, series.index.name: time_quantity})\n\n def _load_unbinned_event(self, chan_struct: dict | None, quantity: pq.Quantity = pq.dimensionless,\n time_quantity: pq.Quantity = pq.second):\n parsed_struct = spike2_struct(chan_struct) if chan_struct is not None else None\n series = self._unbinned_event_chant_to_series(parsed_struct, SPIKE2_EXTPULSES)\n return PandasContainer(series, {series.name: quantity, series.index.name: time_quantity})\n\n def _load_texts(self, chan_struct: dict | None, time_quantity: pq.Quantity = pq.second, name: str | None = None):\n parsed_struct = spike2_struct(chan_struct) if chan_struct is not None else None\n series = self._textmarker_chan_to_series(parsed_struct,\n self._get_channel_name(parsed_struct, name_override=name))\n return PandasContainer(series, {series.name: pq.dimensionless, series.index.levels[0].name: time_quantity,\n series.index.levels[1].name: pq.dimensionless})\n\n def _load_marker(self, chan_struct: dict | None, time_quantity: pq.Quantity = pq.second, name: str | None = None):\n parsed_struct = spike2_struct(chan_struct) if chan_struct is not None else None\n series = self._marker_chan_to_series(parsed_struct,\n name=self._get_channel_name(parsed_struct, name_override=name))\n return PandasContainer(series, {series.name: pq.dimensionless, series.index.name: time_quantity})\n\n def execute(self) -> tuple[PandasContainer, ...]:\n with HDFMatFile(self._path, 'r') as f:\n channels = Spike2ReaderFunc.Spike2Channels(f)\n sig = self._load_sig_chan(channels.get_chan(self._signal_chan), self._signal_unit, name=schema.SIGNAL)\n mass = self._load_sig_chan(channels.get_chan(self._mass), self._mass_unit, name=schema.MASS)\n temp = self._load_sig_chan(channels.get_chan(self._temp_chan), self._temp_unit, name=schema.TEMPERATURE)\n v_chan = self._load_sig_chan(channels.get_chan(self._v_chan), self._v_chan_unit, name=SPIKE2_V_CHAN)\n ext_pul = self._load_unbinned_event(channels.get_chan(self._ext_pul))\n comments = self._load_texts(channels.get_chan(self._comments), name=schema.COMMENT)\n dig_mark = self._load_marker(channels.get_chan(self._digmark), name=SPIKE2_DIGMARK)\n keyboard = self._load_marker(channels.get_chan(self._keyboard), name=SPIKE2_KEYBOARD)\n return sig, mass, temp, v_chan, ext_pul, comments, dig_mark, keyboard\n","repo_name":"Digital-C-Fiber/openMNGlab","sub_path":"openmnglab/functions/input/readers/funcs/spike2_reader.py","file_name":"spike2_reader.py","file_ext":"py","file_size_in_byte":11721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15635445969","text":"'''\nCreated on 2023-03-22\n\n@author: wf\n'''\nfrom tests.basetest import Basetest\n\nfrom ceurws.ceur_ws import VolumeManager\nfrom ceurws.papertocparser import PaperTocParser\nfrom lodstorage.lod import LOD\nfrom ceurws.volumeparser import VolumeParser\nimport json\nfrom tqdm import tqdm\nfrom collections import Counter\nimport unittest\n\nclass TestPaperTocParser(Basetest):\n '''\n Test parsing Volume pages\n '''\n \n def setUp(self, debug=False, profile=True):\n \"\"\"\n setUp the tests\n \"\"\"\n Basetest.setUp(self, debug=debug, profile=profile)\n self.url= 'http://ceur-ws.org'\n self.vm=VolumeManager()\n self.volumeParser=VolumeParser(self.url,showHtml=False)\n self.vm.load()\n self.volumeList=self.vm.getList()\n self.volumesByNumber, _duplicates = LOD.getLookup(self.volumeList, 'number')\n \n def check_paper_toc_parser(self,vol_number:str,counter:Counter,debug:bool=False,show_failure:bool=True)->list:\n \"\"\"\n check the PaperTocParser with the given parameters\n \n Args:\n vol_number(str): the number of the volume to parser\n counter(Counter): the counter to keep track of the results and failures\n debug(bool): if True print debugging information\n show_failure: if True show reason message for failures / exceptions\n \n Returns:\n list: a list paper records\n \"\"\"\n try:\n record,soup = self.volumeParser.parse_volume(vol_number)\n if debug:\n print(json.dumps(record,indent=2))\n if soup:\n ptp=PaperTocParser(number=vol_number,soup=soup,debug=debug)\n paper_records=ptp.parsePapers()\n if debug:\n print(json.dumps(paper_records,indent=2))\n for paper_record in paper_records:\n for key in paper_record:\n counter[key]+=1\n return paper_records\n except Exception as ex:\n counter[\"failure\"]+=1\n if show_failure:\n print(f\"{vol_number} paper toc parsing fails with {str(ex)})\")\n return []\n \n def test_volExamples(self):\n \"\"\"\n tests parsing of volume examples\n \"\"\"\n vol_examples = [(3343,7),(2376,35),(2379,8),(1,15),(83,12),(3264,10)]\n counter=Counter()\n debug=self.debug\n #debug=True\n for vol_number,expected_papers in vol_examples:\n paper_records=self.check_paper_toc_parser(vol_number, counter, debug)\n self.assertEqual(expected_papers,len(paper_records),vol_number)\n if debug:\n print(counter.most_common())\n self.assertTrue(counter[\"pages\"]>=60)\n \n @unittest.skipIf(True, \"Only for manual testing or if github cache is implemented\") \n def test_parse_all_papertocs(self):\n \"\"\"\n test parsing all paper table of contents\n \"\"\"\n debug=self.debug\n t=None\n progress=True\n counter=Counter()\n if progress:\n t=tqdm(total=len(self.volumeList))\n for volume in self.volumeList:\n self.check_paper_toc_parser(volume.number, counter, debug)\n if t:\n t.description=f\"{volume.number}\"\n t.update()\n print(counter.most_common())\n \n \n \n","repo_name":"WolfgangFahl/pyCEURmake","sub_path":"tests/test_papertocparser.py","file_name":"test_papertocparser.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"17759515881","text":"#!/usr/bin/python3\n\nimport argparse\nimport string\n\nwith open(\"/home/eric/projects/english-words-master/words.txt\") as word_file:\n WORDS = set(word.strip().lower() for word in word_file)\n\n\ndef is_word(potential_word):\n \"\"\"Returns True if given word is found in our English dictionary.\"\"\"\n return potential_word.strip().lower() in WORDS\n\n\ndef one_off_words(word):\n \"\"\"Returns list of possible off-by-one words.\"\"\"\n\n assert word, \"Word {!r} was empty\".format(word)\n word = word.strip().lower()\n results = []\n\n # Then check whether any substitutions get words\n for character in string.ascii_lowercase + \"_\":\n for index in range(len(word)):\n # Skip no-ops\n if word[index] == character:\n continue\n # Then replace the character at the given index\n test = list(word)\n test[index] = character\n # Use _ as an empty space so it can be iterated over, then remove\n test = \"\".join(test).replace(\"_\", \"\")\n # Check whether we have a word\n if is_word(test):\n results.append(test)\n\n # Then check if any insertions create words\n for character in string.ascii_lowercase:\n for index in range(len(word) + 1):\n test = word[:index] + character + word[index:]\n if is_word(test):\n results.append(test)\n\n return sorted(results)\n\n\ndef one_off_phrases(phrase):\n \"\"\"Returns list of phrases where one letter is off in the phrase.\"\"\"\n words = phrase.split(\" \")\n results = []\n for index, word in enumerate(words):\n for off_word in one_off_words(word):\n results.append(\" \".join(words[:index] + [off_word] + words[index+1:]))\n return results\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"file\", help=\"Text file to permute phrases for\")\n args = parser.parse_args()\n\n with open(args.file, \"r\") as phrase_file:\n while True:\n phrase = phrase_file.readline().strip().lower()\n if not phrase:\n break\n print(phrase)\n for off_phrase in one_off_phrases(phrase):\n print(\"\\t{}\".format(off_phrase))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"FranzEricSchneider/one-letter-shift","sub_path":"phrase_mangler.py","file_name":"phrase_mangler.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30224733601","text":"#!/usr/bin/env python3\n\nimport libgmsec_python3 as lp\nfrom Test import Test\n\n\nclass Test_MessageSpecification(Test):\n\n def test(self):\n self.test_message_specification()\n\n\n def test_message_specification(self):\n lp.log_info(\"Test MessageSpecification\")\n\n self.test_message_specification_aux(lp.GMSEC_MSG_SPEC_CURRENT, lp.Specification.SchemaLevel_LEVEL_0)\n self.test_message_specification_aux(lp.GMSEC_MSG_SPEC_CURRENT, lp.Specification.SchemaLevel_LEVEL_1)\n self.test_message_specification_aux(lp.GMSEC_MSG_SPEC_CURRENT, lp.Specification.SchemaLevel_LEVEL_2)\n\n self.test_message_specification_aux(lp.GMSEC_MSG_SPEC_2019_00, lp.Specification.SchemaLevel_LEVEL_0)\n self.test_message_specification_aux(lp.GMSEC_MSG_SPEC_2019_00, lp.Specification.SchemaLevel_LEVEL_1)\n self.test_message_specification_aux(lp.GMSEC_MSG_SPEC_2019_00, lp.Specification.SchemaLevel_LEVEL_2)\n\n\n def test_message_specification_aux(self, specVersion, schemaLevel):\n config = lp.Config()\n\n config.add_value(\"gmsec-specification-version\", \"\" + str(specVersion))\n config.add_value(\"gmsec-schema-level\", \"\" + str(schemaLevel))\n\n spec = lp.Specification(config)\n\n msgSpecs = spec.get_message_specifications()\n\n self.check(\"Expected at least 1 (one) message specification\", msgSpecs.size() > 0)\n\n for msgSpec in msgSpecs:\n self.check(\"Schema ID is NULL\", msgSpec.get_schema_id() != None)\n self.check(\"Subject Template is NULL\", msgSpec.get_subject_template() != None)\n\n fieldSpecs = msgSpec.get_field_specifications()\n\n self.check(\"Expected at least 1 (one) field specification\", fieldSpecs.size() > 0)\n\n\nTest.run('Test MessageSpecification', Test_MessageSpecification())\n","repo_name":"nasa/GMSEC_API","sub_path":"tests/python3/src/T014_MessageSpecification.py","file_name":"T014_MessageSpecification.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"39261960933","text":"from __future__ import absolute_import\n\nimport numpy as np\n\nfrom .base import DifferentiableModel\n\n\nclass MXNetModel(DifferentiableModel):\n \"\"\"Creates a :class:`Model` instance from existing `MXNet` symbols and weights.\n\n Parameters\n ----------\n data : `mxnet.symbol.Variable`\n The input to the model.\n logits : `mxnet.symbol.Symbol`\n The predictions of the model, before the softmax.\n weights : `dictionary mapping str to mxnet.nd.array`\n The weights of the model.\n device : `mxnet.context.Context`\n The device, e.g. mxnet.cpu() or mxnet.gpu().\n num_classes : int\n The number of classes.\n bounds : tuple\n Tuple of lower and upper bound for the pixel values, usually\n (0, 1) or (0, 255).\n channel_axis : int\n The index of the axis that represents color channels.\n\n \"\"\"\n\n def __init__(\n self,\n data,\n logits,\n weights,\n device,\n num_classes,\n bounds,\n channel_axis=1):\n\n super(MXNetModel, self).__init__(\n bounds=bounds, channel_axis=channel_axis)\n\n import mxnet as mx\n\n self._num_classes = num_classes\n\n self._device = device\n\n self._data_sym = data\n self._batch_logits_sym = logits\n\n label = mx.symbol.Variable('label')\n self._label_sym = label\n\n loss = mx.symbol.softmax_cross_entropy(logits, label)\n self._loss_sym = loss\n\n weight_names = list(weights.keys())\n weight_arrays = [weights[name] for name in weight_names]\n self._args_map = dict(zip(weight_names, weight_arrays))\n\n def num_classes(self):\n return self._num_classes\n\n def batch_predictions(self, images):\n import mxnet as mx\n data_array = mx.nd.array(images, ctx=self._device)\n self._args_map[self._data_sym.name] = data_array\n model = self._batch_logits_sym.bind(\n ctx=self._device, args=self._args_map, grad_req='null')\n model.forward(is_train=False)\n logits_array = model.outputs[0]\n logits = logits_array.asnumpy()\n return logits\n\n def predictions_and_gradient(self, image, label):\n import mxnet as mx\n label = np.asarray(label)\n data_array = mx.nd.array(image[np.newaxis], ctx=self._device)\n label_array = mx.nd.array(label[np.newaxis], ctx=self._device)\n self._args_map[self._data_sym.name] = data_array\n self._args_map[self._label_sym.name] = label_array\n\n grad_array = mx.nd.zeros(image[np.newaxis].shape, ctx=self._device)\n grad_map = {self._data_sym.name: grad_array}\n\n logits_loss = mx.sym.Group([self._batch_logits_sym, self._loss_sym])\n model = logits_loss.bind(\n ctx=self._device,\n args=self._args_map,\n args_grad=grad_map,\n grad_req='write')\n model.forward(is_train=True)\n logits_array = model.outputs[0]\n model.backward([\n mx.nd.zeros(logits_array.shape),\n mx.nd.array(np.array([1]))\n ])\n logits = logits_array.asnumpy()\n gradient = grad_array.asnumpy()\n return np.squeeze(logits, axis=0), np.squeeze(gradient, axis=0)\n","repo_name":"AlexMikhalev/foolbox","sub_path":"foolbox/models/mxnet.py","file_name":"mxnet.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"40459347186","text":"#!/usr/bin/env python\nimport sys\nimport json\n\ndef print_task(file,series,taskNumber,points,averagePoints,solversCount):\n file.write(\"{};{};{};{};{}\\n\".format(series,taskNumber,points,averagePoints,solversCount))\n\ndef process_data():\n if len(sys.argv) < 4:\n print(\"Usage: python texstats.py \")\n print(\"Data from in JSON format are parsed and outputed\")\n print(\"to as CSV.\")\n return\n\n series=int(sys.argv[1])\n inputFileName=sys.argv[2]\n outputFileName=sys.argv[3]\n\n with open(inputFileName,'r') as file:\n data = json.load(file)\n\n outputFile = open(outputFileName,'w+')\n\n for task in data:\n if task['series'] == series:\n # Format averagePoints and catch null values\n averagePoints = task['averagePoints']\n if averagePoints is None:\n averagePoints = \"NaN\"\n else:\n averagePoints = \"{:.2f}\".format(averagePoints).replace('.',',')\n\n print_task(outputFile, task['series'], task['taskNumber'],task['points'],\n averagePoints, task['solversCount'])\n outputFile.close()\n\nif __name__ == \"__main__\":\n process_data()\n","repo_name":"fykosak/fks-scripts","sub_path":"scripts/share/texstats.py","file_name":"texstats.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26285637477","text":"\"\"\"Weather files and weather data imports.\n\"\"\"\nimport os\nimport csv\nimport numpy as np\nimport pandas as pd\n\nfrom sitka.utils.time_series import TimeSeriesComponent\n\n\nclass EPW(TimeSeriesComponent):\n \"\"\"\n Imports and stores an EnergyPlus weather file (EPW format).\n\n Parameters\n ----------\n time : Time\n The year to use in starting the date-time.\n filename : string\n Filename, including path, to EPW file.\n\n Attributes\n ----------\n filename\n time\n header_imported\n data_imported\n stephan_boltzmann_constant : float\n Stephan-Boltzmann constant\n sky_temperature : Series\n Sky tempereature [C]\n columns\n incident_direct_radiation : Series\n year : Series\n month : Series\n day : Series\n hour : Series\n minute : Series\n datasource : Series\n dry_bulb_temperature : Series\n ambient dry bulb temperature [C]\n dew_point_temperature : Series\n ambient dew point temperature [C]\n relative_humidity : Series\n ambient relative humidity [#]\n atmospheric_pressure : Series\n atmospheric pressure [Pa]\n extraterrestrial_horizontal_radiation : Series\n extraterrestrial horizontal radiation [Wh/m2]\n extraterrestrial_direct_radiation : Series\n extraterrestrial direct radiation [Wh/m2]\n horizontal_infrared_radiation_sky : Series\n horizontal infrared radiation intensity from sky [Wh/m2]\n global_horizontal_radiation : Series\n global horizontal radiation [Wh/m2]\n direct_normal_radiation : Series\n direct normal radiation [Wh/m2]\n diffuse_horizontal_radiation : Series\n diffuse horizontal radiation [Wh/m2]\n global_horizontal_illuminance : Series\n global horizontal illuminance [lux]\n direct_normal_illuminance : Series\n direct normal illuminance [lux]\n diffuse_horizontal_illuminance : Series\n diffuse horizontal illuminance [lux]\n zenith_luminance : Series\n zenith luminance [lux]\n wind_direction : Series\n wind direction [deg]\n wind_speed : Series\n wind speed [m/s]\n total_sky_cover : Series\n total sky cover [tenths]\n opaque_sky_cover : Series\n opaque sky cover [tenths]\n visibility : Series\n visibility [km]\n ceiling_height : Series\n ceiling height [m]\n present_weather_observation : Series\n precipitable water [mm]\n present_weather_code : Series\n aerosol optical depth [thousandths]\n precipitable_water : Series\n snow depth [cm]\n aerosol_optical_depth : Series\n aerosol optical depth [thousandths]\n snow_depth : Series\n snow depth [cm]\n days_since_snow : Series\n days since last snow occurred [days]\n albedo : Series\n albedo []\n liquid_precipitation_depth : Series\n liquid precipitation depth [mm]\n liquid_precipitation_rate : Series\n liquid precipitation rate [hour]\n\n Methods\n -------\n update_calculated_values\n import_epw_header\n import_epw_column_data\n calculate_sky_temperature\n resample_integrated_data\n resample_instantaneous_data\n\n \"\"\"\n def __init__(self, time, filename=None): #weather_file_path, weather_file_name):\n self.filename = filename # weather_file_name #Name of weather file\n self._time = time\n self.header_imported = False\n self.data_imported = False\n self.stefan_boltzmann_constant = 5.67e-8 # Stephan-boltzmann constant\n self.columns = [\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"datasource\",\n \"dry_bulb_temperature\", # ambient dry bulb temperature [C]\n \"dew_point_temperature\", # ambient dew point temperature [C]\n \"relative_humidity\", # ambient relative humidity [#]\n \"atmospheric_pressure\", # atmospheric pressure [Pa]\n \"extraterrestrial_horizontal_radiation\", # extraterrestrial horizontal radiation [Wh/m2]\n \"extraterrestrial_direct_radiation\", # extraterrestrial direct radiation [Wh/m2]\n \"horizontal_infrared_radiation_sky\", # horizontal infrared radiation intensity from sky [Wh/m2]\n \"global_horizontal_radiation\", # global horizontal radiation [Wh/m2]\n \"direct_normal_radiation\", # direct normal radiation [Wh/m2]\n \"diffuse_horizontal_radiation\", # diffuse horizontal radiation [Wh/m2]\n \"global_horizontal_illuminance\", # global horizontal illuminance [lux]\n \"direct_normal_illuminance\", # direct normal illuminance [lux]\n \"diffuse_horizontal_illuminance\", # diffuse horizontal illuminance [lux]\n \"zenith_luminance\", # zenith luminance [lux]\n \"wind_direction\", # wind direction [deg]\n \"wind_speed\", # wind speed [m/s]\n \"total_sky_cover\", # total sky cover [tenths]\n \"opaque_sky_cover\", # opaque sky cover [tenths]\n \"visibility\", # visibility [km]\n \"ceiling_height\", # ceiling height [m]\n \"present_weather_observation\", # precipitable water [mm]\n \"present_weather_code\", # aerosol optical depth [thousandths]\n \"precipitable_water\", # snow depth [cm]\n \"aerosol_optical_depth\", # aerosol optical depth [thousandths]\n \"snow_depth\", # snow depth [cm]\n \"days_since_snow\", # days since last snow occurred [days]\n \"albedo\", # albedo []\n \"liquid_precipitation_depth\", # liquid precipitation depth [mm]\n \"liquid_precipitation_rate\", # liquid precipitation rate [hour]\n ]\n self.location = None\n self.state = None\n self.country = None\n self.data_type = None\n self.station_id = None\n self.latitude = None\n self.longitude = None\n self.time_zone = None\n self.elevation = None\n self.dry_bulb_temperature = None\n self.dew_point_temperature = None\n self.relative_humidity = None\n self.atmospheric_pressure = None\n self.extraterrestrial_horizontal_radiation = None\n self.extraterrestrial_direct_radiation = None\n self.horizontal_infrared_radiation_sky = None\n self.global_horizontal_radiation = None\n self.direct_normal_radiation = None\n self.diffuse_horizontal_radiation = None\n self.global_horizontal_illuminance = None\n self.direct_normal_illuminance = None\n self.diffuse_horizontal_illuminance = None\n self.zenith_luminance = None\n self.wind_direction = None\n self.wind_speed = None\n self.total_sky_cover = None\n self.opaque_sky_cover = None\n self.visibility = None\n self.ceiling_height = None\n self.aerosol_optical_depth = None\n self.albedo = None\n self.liquid_precipitation_rate = None\n self.sky_temperature = None\n\n # Add attributes from super class\n super().__init__(time)\n\n # Run method to update all calculated values\n self.update_calculated_values()\n\n def update_calculated_values(self):\n print(self.time)\n print(self.filename)\n if self.time and self.filename:\n # Methods to import data\n self.import_epw_header()\n self.import_epw_column_data()\n self.calculate_sky_temperature()\n self.resample_integrated_data()\n self.resample_instantaneous_data()\n\n def import_epw_header(self):\n \"\"\"\n Import header data from the EPW file.\n\n Yields\n ----------\n location : string\n state : string\n country : string\n data_type : string\n station_id : string\n latitude : float\n longitude : float\n time_zone : float\n elevation : float\n\n References\n --------\n \"\"\"\n # Import to dataframe\n temp = pd.read_csv(self.filename, skiprows=0, nrows=1,header=None)\n self.location = temp[1][0] #weather station name\n self.state = temp[2][0] #state\n self.country = temp[3][0] #country\n self.data_type = temp[4][0] #type of weather data file\n self.station_id = temp[5][0] #weather station ID\n self.latitude = float(temp[6][0]) #latitude [deg]\n self.longitude = float(temp[7][0]) #longitude [deg]\n self.time_zone = float(temp[8][0]) #time zone [hr]\n self.elevation = float(temp[9][0]) #elevation [m]\n\n self.header_imported = True\n\n def import_epw_column_data(self):\n \"\"\"\n Imports the column data from an EPW file.\n\n Yields\n ----------\n incident_direct_radiation : Series\n year : Series\n month : Series\n day : Series\n hour : Series\n minute : Series\n datasource : Series\n dry_bulb_temperature : Series\n ambient dry bulb temperature [C]\n dew_point_temperature : Series\n ambient dew point temperature [C]\n relative_humidity : Series\n ambient relative humidity [#]\n atmospheric_pressure : Series\n atmospheric pressure [Pa]\n extraterrestrial_horizontal_radiation : Series\n extraterrestrial horizontal radiation [Wh/m2]\n extraterrestrial_direct_radiation : Series\n extraterrestrial direct radiation [Wh/m2]\n horizontal_infrared_radiation_sky : Series\n horizontal infrared radiation intensity from sky [Wh/m2]\n global_horizontal_radiation : Series\n global horizontal radiation [Wh/m2]\n direct_normal_radiation : Series\n direct normal radiation [Wh/m2]\n diffuse_horizontal_radiation : Series\n diffuse horizontal radiation [Wh/m2]\n global_horizontal_illuminance : Series\n global horizontal illuminance [lux]\n direct_normal_illuminance : Series\n direct normal illuminance [lux]\n diffuse_horizontal_illuminance : Series\n diffuse horizontal illuminance [lux]\n zenith_luminance : Series\n zenith luminance [lux]\n wind_direction : Series\n wind direction [deg]\n wind_speed : Series\n wind speed [m/s]\n total_sky_cover : Series\n total sky cover [tenths]\n opaque_sky_cover : Series\n opaque sky cover [tenths]\n visibility : Series\n visibility [km]\n ceiling_height : Series\n ceiling height [m]\n present_weather_observation : Series\n precipitable water [mm]\n present_weather_code : Series\n aerosol optical depth [thousandths]\n precipitable_water : Series\n snow depth [cm]\n aerosol_optical_depth : Series\n aerosol optical depth [thousandths]\n snow_depth : Series\n snow depth [cm]\n days_since_snow : Series\n days since last snow occurred [days]\n albedo : Series\n albedo []\n liquid_precipitation_depth : Series\n liquid precipitation depth [mm]\n liquid_precipitation_rate : Series\n liquid precipitation rate [hour]\n\n References\n --------\n \"\"\"\n # Read EPW weather file\n\n # Import to dataframe\n df = pd.read_csv(self.filename, skiprows=8, names=self.columns)\n\n # Set time index\n time_index = pd.to_datetime({\n # 'year': data['epw']['year'], # EPW has variable years\n 'year': np.ones(8760) * self.time.year, # Set a constant as current year\n 'month': pd.Series(df['month']),\n 'day': pd.Series(df['day']),\n 'hour': pd.Series(df['hour'])-1,\n 'minute': pd.Series(df['minute']),\n })\n df.index = time_index\n self.__setattr__('datetime_range', time_index)\n\n # Concatenate data set to match simulation time period\n df = df[self.time.start_hour:self.time.end_hour]\n\n # Add as attributes to objects\n for key in df.keys():\n self.__setattr__(key, df[key])\n\n self.data_imported = True\n print('file imported.')\n\n def calculate_sky_temperature(self):\n \"\"\"\n Calculate the sky temperature for each item in the series.\n\n Yields\n ----------\n sky_temp : Series\n\n References\n --------\n \"\"\"\n stefan_boltzmann_constant = self.stefan_boltzmann_constant\n horizontal_infrared_radiation_sky = self.horizontal_infrared_radiation_sky\n sky_temperature = (horizontal_infrared_radiation_sky/stefan_boltzmann_constant)**0.25-273.15\n self.sky_temperature = pd.Series(sky_temperature)\n\n def resample_integrated_data(self):\n \"\"\"\n Resamples integrated parameters by summing over the new time period.\n\n Yields\n --------\n extraterrestrial_horizontal_radiation\n extraterrestrial_direct_radiation\n horizontal_infrared_radiation_sky\n global_horizontal_radiation\n direct_normal_radiation\n diffuse_horizontal_radiation\n precipitable_water\n snow_depth\n liquid_precipitation_depth\n \"\"\"\n if self.data_imported:\n keys = [\n \"extraterrestrial_horizontal_radiation\",\n \"extraterrestrial_direct_radiation\",\n \"horizontal_infrared_radiation_sky\",\n \"global_horizontal_radiation\",\n \"direct_normal_radiation\",\n \"diffuse_horizontal_radiation\",\n \"precipitable_water\",\n \"snow_depth\",\n \"liquid_precipitation_depth\",\n ]\n \n for key in keys:\n if key in self.__dict__.keys():\n df = self.__getattribute__(key).astype(float)\n df = df.append(pd.Series([None], index=[(df.index[-1] + pd.Timedelta(hours=1))]))\n df = (df.resample('%ds' % self.time.time_step).fillna(method='ffill'))/self.time.time_steps_per_hour\n df = df.drop(df.index[-1])\n df.index = range(0, len(df.index)) # reset the index to integers\n\n self.__setattr__(key, df)\n\n def resample_instantaneous_data(self):\n \"\"\"\n Resamples instantaneous parameters by averaging over the new time period.\n\n Yields\n --------\n dry_bulb_temperature\n dew_point_temperature\n relative_humidity\n atmospheric_pressure\n global_horizontal_illuminance\n direct_normal_illuminance\n diffuse_horizontal_illuminance\n zenith_luminance\n wind_direction\n wind_speed\n total_sky_cover\n opaque_sky_cover\n visibility\n ceiling_height\n aerosol_optical_depth\n albedo\n liquid_precipitation_rate\n \"\"\"\n if self.data_imported:\n keys = [\n \"dry_bulb_temperature\",\n \"dew_point_temperature\",\n \"relative_humidity\",\n \"atmospheric_pressure\",\n \"global_horizontal_illuminance\",\n \"direct_normal_illuminance\",\n \"diffuse_horizontal_illuminance\",\n \"zenith_luminance\",\n \"wind_direction\",\n \"wind_speed\",\n \"total_sky_cover\",\n \"opaque_sky_cover\",\n \"visibility\",\n \"ceiling_height\",\n #\"present_weather_observation\",\n #\"present_weather_code\",\n \"aerosol_optical_depth\",\n #\"days_since_snow\",\n \"albedo\",\n \"liquid_precipitation_rate\",\n \"sky_temperature\",\n ]\n for key in keys:\n if key in self.__dict__.keys():\n df = self.__getattribute__(key).astype(float)\n df = df.append(pd.Series([None], index=[(df.index[-1] + pd.Timedelta(hours=1))]))\n df = df.fillna(method='pad')\n df = df.resample('%ds' % self.time.time_step).interpolate(method='linear')\n df = df.drop(df.index[-1])\n df.index = range(0, len(df.index)) # reset the index to integers\n self.__setattr__(key, df)\n\n @property\n def time(self):\n return self._time\n\n @time.setter\n def time(self, value):\n self._time = value\n self.resample_integrated_data()\n self.resample_instantaneous_data()\n","repo_name":"mcneillj/sitka","sub_path":"sitka/io/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":16551,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"25714824949","text":"from flask import abort, Flask, request\nimport requests\nfrom bs4 import BeautifulSoup\nimport redis\n\n\napp = Flask(__name__)\ndb = redis.Redis(\"localhost\")\n\n\ndef retrieve_rate(currency, reference_date):\n if not currency or not reference_date:\n return None\n\n key = reference_date + \"|\" + currency\n\n # Try to get the value from the db\n try:\n rate = float(db.get(key))\n return rate\n except (ValueError, TypeError):\n rate = None\n\n # If not in db, try and get value parsing the xml\n # Populate the db if the value is found in the xml\n url = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml'\n response = requests.get(url)\n if response and response.status_code == 200:\n soup = BeautifulSoup(response.content, features='html.parser')\n elem = soup.select_one('cube>cube[time=\"{}\"]>cube[currency=\"{}\"]'.format(reference_date, currency))\n try:\n rate = float(elem['rate'])\n db.set(key, rate)\n except:\n rate = None\n finally:\n return rate\n\n \n\n\n@app.route('/convert', methods=['GET'])\ndef convert():\n amount = request.args.get('amount', None)\n src_currency = request.args.get('src_currency', None)\n dest_currency = request.args.get('dest_currency', None)\n reference_date = request.args.get('reference_date', None)\n\n # Check params are correctly defined\n if not amount or not src_currency or not dest_currency \\\n or not reference_date:\n abort(400)\n\n # Check conversion is only between eur and something else\n lower_src = src_currency.lower()\n lower_dest = dest_currency.lower()\n if (lower_src != 'eur' and lower_dest != 'eur') or \\\n (lower_src == 'eur' and lower_dest == 'eur'):\n abort(400)\n\n\n if lower_src == 'eur':\n currency = dest_currency\n else:\n currency = src_currency\n\n rate = retrieve_rate(currency, reference_date)\n\n # Could not find the rate based on the parameters\n if not rate:\n abort(404)\n\n real_rate = 2-rate if lower_dest == 'eur' else rate\n\n return {'amount': float(amount)*real_rate,\n 'currency': dest_currency}\n\n","repo_name":"sorrentix/currency_converter_app","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11321014236","text":"# Check If a Word Occurs As a Prefix of Any Word in a Sentence\n\n\"\"\"Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.\n\nReturn the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.\n\nA prefix of a string s is any leading contiguous substring of s.\"\"\"\n\nclass Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n s = sentence.split(\" \")\n for i in range(len(s)):\n if len(searchWord)>1:\n if searchWord in s[i] and searchWord[0] == s[i][0] and searchWord[1] == s[i][1]:\n return i+1\n else:\n if searchWord in s[i] and searchWord[0] == s[i][0]:\n return i+1\n return -1\n","repo_name":"shrutityagi4102/myleetcodesolutions","sub_path":"69.py","file_name":"69.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7832506659","text":"import mysql.connector\nimport bcrypt\nimport util\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"kane\",\n password=\"kane\",\n database=\"testdata\"\n)\n\nmycursor = mydb.cursor()\n\ndef createDatabase(dbName):\n global mycursor\n mycursor.execute(\"SHOW DATABASES\")\n\ndef createTableCustomer():\n global mycursor\n tbName = \"customer\"\n query = \"\"\"CREATE TABLE {} (\n email VARCHAR(255) PRIMARY KEY,\n name TEXT,\n company TEXT,\n salt TEXT,\n hashed TEXT\n )\"\"\".format(tbName)\n mycursor.execute(query)\n\ndef dropTable(tbName):\n global mycursor\n mycursor.execute(\"drop table {}\".format(tbName))\n\ndef showAllTables():\n global mycursor\n mycursor.execute(\"SHOW TABLES\")\n for x in mycursor:\n print(x[0])\n\ndef findUserByEmail(email):\n global mycursor\n sql = \"SELECT * FROM customer WHERE email ='{}'\".format(email)\n mycursor.execute(sql)\n myresult = mycursor.fetchall()\n if len(myresult) == 0:\n return None\n return myresult[0]\n\ndef addUser(email, name, company, salt, hashed):\n global mycursor\n global mydb\n sql = \"INSERT INTO customer (email, name, company, salt, hashed) VALUES (%s, %s, %s, %s, %s)\"\n val = (email, name, company, salt, hashed)\n mycursor.execute(sql, val)\n mydb.commit()\n\ndef deleteUser(email):\n global mycursor\n sql = \"DELETE FROM customer WHERE email ='{}'\".format(email)\n mycursor.execute(sql)\n mydb.commit()\n\ndef getAllUsers():\n global mycursor\n mycursor.execute(\"SELECT * FROM customer\")\n return [x for x in mycursor]\n\ndef changeUserInfo(email, name, newValue):\n global mycursor\n if name == \"password\":\n salt = bcrypt.gensalt().decode()\n hashed = util.getPasswordHash(salt, newValue)\n query = \"UPDATE customer SET salt = '{}' WHERE email = '{}';\".format(salt, email)\n mycursor.execute(query)\n mydb.commit()\n query = \"UPDATE customer SET hashed = '{}' WHERE email = '{}';\".format(hashed, email)\n mycursor.execute(query)\n mydb.commit()\n if name == \"name\":\n query = \"UPDATE customer SET name = '{}' WHERE email = '{}';\".format(newValue, email)\n mycursor.execute(query)\n mydb.commit()\n \n if name == \"company\":\n query = \"UPDATE customer SET company = '{}' WHERE email = '{}';\".format(newValue, email)\n mycursor.execute(query)\n mydb.commit()\n \n\n# createTableCustomer()\n# dropTable(\"customer\")\n# deleteUser(\"anhthi2103@gmail.com\")\n# print(findUserByEmail(\"anhthi2103@gmail.com\"))\n# showAllTables()\n","repo_name":"sheroanh/seotools_api","sub_path":"sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2462343810","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport platform\n\n\nclass Chrome(Options):\n\n def __init__(self):\n super(Chrome, self).__init__()\n self.options = Options()\n self.options.add_argument(\"--headless\")\n self.options.add_argument(\"window-size=1920,1080\")\n\n type_of_os = platform.system()\n print(type_of_os)\n if type_of_os == \"Windows\":\n self.driver = webdriver.Chrome(executable_path='./win/chromedriver.exe', chrome_options=self.options)\n elif type_of_os == \"Linux\":\n self.options.add_argument('--headless')\n self.options.add_argument('--disable-infobars')\n self.options.add_argument('--disable-dev-shm-usage')\n self.options.add_argument(\"--no-sandbox\")\n self.options.add_argument(\"--remote-debugging-port=9222\")\n self.driver = webdriver.Chrome(executable_path='./linux/chromedriver', chrome_options=self.options)\n elif type_of_os == \"Mac\":\n self.driver = webdriver.Chrome(executable_path='./mac/chromedriver', chrome_options=self.options)\n else:\n print(\"Can not find type of your OS ...\")\n exit()\n\n def download_image(self, url, name):\n \"\"\"\n :param url: str\n :param name: str\n :return: *jpg\n \"\"\"\n try:\n driver_url = self.driver.get(url)\n get_image_by_url = self.driver.find_elements_by_name('img')\n image = self.driver.save_screenshot(name)\n except:\n print(\"Check your internet connect or selenium chrome\")\n\n def logout(self):\n \"\"\"\n :return: -\n \"\"\"\n return self.driver.quit()\n\n\n\n# chrome = Chrome()\n# img = chrome.download_image(\"http://img03.platesmania.com/200708/o/14991411.jpg\", \"test.jpg\")\n# chrome.logout()","repo_name":"nafe93/parser-avto-nomer.ru","sub_path":"chrome_driver.py","file_name":"chrome_driver.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37885283321","text":"# Q2 Display only averages for second Year\n\nimport sys\nfrom pyspark import SparkContext, SparkConf\nsc=SparkContext()\n\ndata = sc.textFile(\"student.txt\")\n\nfilterYear = data.map(lambda x : (x.split(',')) ).filter( lambda x: x[1]=='year2')\\\n .map( lambda y: [y[0],y[1], (float(y[2])+float(y[3]))/2 ])\n\nprint(filterYear.collect())\n\n","repo_name":"Nimesh-Nagar/iot","sub_path":"8.Data_Management_and_Analytics/Analytics/Apache_Spark/1_RDD/Student_problem_statement/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"1680220930","text":"# -*- coding: utf-8 -*-\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = os.getenv('WATERSHED_SECRET_KEY')\n\nDEBUG = os.getenv('DEBUG', False)\n\nif DEBUG:\n ALLOWED_HOSTS = ['watershed.nthall.com', 'watershed-dev.nthall.com']\nelse:\n ALLOWED_HOSTS = ['watershed.rocks']\n\n\nINSTALLED_APPS = (\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 # 3rd party\n 'passwords',\n 'rest_framework',\n 'rest_framework.authtoken',\n 'rest_framework_bulk',\n 'webpack_loader',\n 'django_extensions',\n 'raven.contrib.django.raven_compat',\n\n # app\n 'customauth.apps.CustomauthConfig',\n 'api.apps.ApiConfig',\n 'player.apps.PlayerConfig',\n 'stats.apps.StatsConfig'\n)\n\nAUTH_USER_MODEL = 'customauth.User'\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n)\n\nROOT_URLCONF = 'watershed.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'watershed.wsgi.application'\n\n\n# Database\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'watershed',\n 'USER': 'www-data',\n 'PASSWORD': os.getenv('WATERSHED_POSTGRESQL_PASSWORD'),\n 'HOST': '/var/run/postgresql/',\n 'PORT': 5434\n }\n}\n\nif not DEBUG:\n DATABASES['default']['USER'] = 'watershed'\n\n\n# Internationalization\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'America/New York'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'frontend'),\n)\nSTATIC_URL = '/static/'\nSTATIC_ROOT = BASE_DIR + STATIC_URL\n\n\nPASSWORD_HASHERS = [\n 'django.contrib.auth.hashers.Argon2PasswordHasher',\n 'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n 'django.contrib.auth.hashers.BCryptPasswordHasher',\n]\n\nPASSWORD_MIN_LENGTH = 8\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework.authentication.TokenAuthentication'\n ]\n}\n\n\nWEBPACK_LOADER = {\n 'DEFAULT': {\n 'CACHE': not DEBUG,\n 'BUNDLE_DIR_NAME': 'bundles/',\n 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json')\n }\n}\n\n\n# LOGGING/SENTRY SETTINGS\nimport sentry_sdk # noqa: E402\nfrom sentry_sdk.integrations.django import DjangoIntegration # noqa: E402\nif DEBUG:\n SENTRY_ENV = 'test'\nelse:\n SENTRY_ENV = 'production'\n\nimport subprocess # noqa: E402\nrelease = subprocess.check_output(\"git rev-parse HEAD\")\n\nsentry_sdk.init(\n dsn='https://69327d4caef74ac694a6a76e93c96524:a9698b5624fe450b90626dbee1746e92@sentry.io/274934', # noqa: E501\n release=release,\n integrations=[DjangoIntegration()],\n environment=SENTRY_ENV\n)\n\ndefault_handler = 'file'\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 \\\n [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt': \"%d/%b/%Y %H:%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 'file': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': BASE_DIR + '/app.log',\n 'formatter': 'verbose'\n },\n 'stdout': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose',\n },\n 'sentry': {\n 'level': 'ERROR',\n 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler'\n }\n },\n 'loggers': {\n 'django': {\n 'handlers': [default_handler, 'mail_admins', 'sentry'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'watershed': {\n 'handlers': [default_handler, 'sentry'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n 'api': {\n 'handlers': [default_handler, 'sentry'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'rest_framework': {\n 'handlers': [default_handler, 'sentry'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'customauth': {\n 'handlers': [default_handler, 'sentry'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'js': {\n 'handlers': [default_handler],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n }\n}\n","repo_name":"nthall/watershed","sub_path":"watershed/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"12112538580","text":"import argparse\nimport json\nimport logging\nimport re\nimport requests\nimport sys\nimport yaml\n\n\nTESTRE = re.compile(r'(tempest[^ \\(\\)]+|\\w+\\.tests\\.[^ \\(\\)]+)')\nOK = \"... ok\"\n\n\nclass CheckSkipCmd(object):\n def __init__(self):\n self.parse_arguments(sys.argv[1:])\n if self.args.debug:\n self.setup_logging()\n\n def run(self):\n console = self.download_console_log()\n ok_results = self.get_test_results(console)\n skip_file = self.load_skip_file()\n\n regex_removed = self.compare_results(skip_file, ok_results)\n print(json.dumps(regex_removed, indent=4, sort_keys=True))\n\n def parse_arguments(self, args):\n parser = argparse.ArgumentParser(description='Check skip list content')\n parser.add_argument('--log-url', dest='console_log', required=True,\n help='Url for the console log result')\n parser.add_argument('--skip-file', dest='skip_file',\n required=True, help='Skip file to compare')\n parser.add_argument('--undercloud', dest='undercloud',\n action='store_true',\n help='Load undercloud skip list',\n default=False)\n parser.add_argument('--debug', dest='debug', action='store_true',\n help='Enable debug')\n\n self.args = parser.parse_args(args)\n\n def setup_logging(self):\n self.log = logging.getLogger(self.__class__)\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(name)s: '\n '%(message)s')\n\n def download_console_log(self):\n resp = requests.get(self.args.console_log)\n try:\n resp.raise_for_status()\n except requests.exceptions.HTTPError as e:\n self.log.error('An error occurred when trying to download '\n 'console log: {}'.format(e))\n return None\n return resp.content.decode('utf-8')\n\n def load_skip_file(self):\n known_failures = []\n try:\n skip = yaml.safe_load(open(self.args.skip_file))\n for t in skip.get('known_failures'):\n if self.args.undercloud == t.get('undercloud', False):\n known_failures.append(t.get('test'))\n except yaml.constructor.ConstructorError:\n self.log.error('Invalid yaml file {}'.format(self.args.skip_file))\n finally:\n return known_failures\n\n def get_test_results(self, console):\n ok = [TESTRE.search(line).group(1)\n for line in console.splitlines() if OK in line]\n return ok\n\n def compare_results(self, known_failures, ok_results):\n regex_to_be_removed = {}\n\n for kf in known_failures:\n for o_r in ok_results:\n if re.match(kf, o_r):\n if not regex_to_be_removed.get(kf):\n regex_to_be_removed[kf] = []\n regex_to_be_removed[kf].append(o_r)\n return regex_to_be_removed\n\n\ndef main():\n cmd = CheckSkipCmd()\n cmd.run()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"openstack/tripleo-quickstart-extras","sub_path":"roles/validate-tempest/files/check-skip-list/check_skip.py","file_name":"check_skip.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"52"} +{"seq_id":"34299871089","text":"# LINK : https://leetcode.com/problems/merge-two-sorted-lists/description/\n\n# updated code\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n res = ListNode()\n dummy = res\n\n while list1 and list2:\n if list1.val >= list2.val:\n dummy.next = ListNode(list2.val)\n list2 = list2.next\n \n else:\n dummy.next = ListNode(list1.val)\n list1 = list1.next\n \n dummy = dummy.next\n\n # if there is left over add it to the end \n if list1 or list2:\n dummy.next = list1 if list1 else list2\n\n return res.next\n\n# the old one \n\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n res = ListNode()\n dummy = res\n temp = list1\n temp2 = list2\n\n while temp and temp2:\n if temp.val >= temp2.val:\n dummy.next = ListNode(temp2.val)\n temp2 = temp2.next\n \n else:\n dummy.next = ListNode(temp.val)\n temp = temp.next\n \n dummy = dummy.next\n\n # if there is left over add it to the end \n if temp or temp2:\n dummy.next = temp if temp else temp2\n\n return res.next\n\n","repo_name":"ishaksebsib/competitive-programming","sub_path":"006 LinkedList/easy/mergeTwoSrotedList.py","file_name":"mergeTwoSrotedList.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28561420516","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\n# define a site to crawl\n# whatever I'm crawling, I don't leave that site\n# sling.com -> youtube.com protect against this\n# list of the URL's to go to\n# 0):\n currentURL = self.newurls.pop()\n self.driver.get(currentURL[0])\n time.sleep(1)\n self.visitedUrls.append(currentURL)\n print (\"have\" + str(len(self.newurls)) + \"left to visit\")\n print(currentURL[0])\n print (self.driver.current_url)\n self.currentPageURLs = self.driver.find_element(By.Tag_Name, \"a\")\n for c in self.currentPageURLs:\n c_url = c.get_attribute(\"href\")\n if c_url != None:\n if self.baseURL in c_url:\n if c_url not in self.visitedUrls:\n if c_url not in self.newurls:\n UrlPair = [c_url, self.driver.current_url]\n self.newurls.append(UrlPair)\n self.currentPageURLs.clear()\n self.currentPageURLs = []\n page = self.driver.find_element(By.Tag_Name, \"body\")\n if \"404\" in page.text:\n self.baseURL.append(self.driver.current_url)\n file = open(\"BrokenPages.txt\", \"a\")\n file.write(currentURL[0] + \" has a 404. ling was found on page \" + currentURL[1] + \"\\n\")\n file.close()\n # file.writelines(currentURL + \" has a 404\\n\")\n images = self.driver.find_element(By.Tag_Name, \"img\")\n for i in images:\n if i.get_attributes(\"alt\") == None:\n file = open(\"ImagesWOalt.txt\", \"a\")\n file.write(i.get_attributes(\"src\") + \"found on: \" + currentURL[0] + \"does not have alt tag\\n\")\n file.close()\n\n if __name__ == '__main__':\n unittest.main()","repo_name":"sainaveenlingam/automation","sub_path":"Challenge11/challege11Sling.py","file_name":"challege11Sling.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36454515359","text":"# Native imports\nimport math\nimport os\n\n# dispel4py imports\nfrom dispel4py.examples.graph_testing import testing_PEs as t\nfrom dispel4py.workflow_graph import WorkflowGraph\nfrom dispel4py.core import GenericPE, NAME, TYPE, GROUPING\nfrom dispel4py.base import SimpleFunctionPE, IterativePE, BasePE\nfrom dispel4py.provenance import *\n\n##############################################################################\n# Class definition from file ENES_usecase/pe_enes.py (start)\n##############################################################################\n\n###############################\n#Stream Producer, it will scan the json file in input\n###############################\n\nclass StreamProducer(GenericPE):\n def __init__(self):\n GenericPE.__init__(self)\n self._add_output('output')\n\n def _process(self, inputs):\n list_PE = inputs.keys()\n len_lc = len(list_PE)\n\n #get processing element NetCDFProcessing\n inputs = get_netCDFProcessing(list_PE, inputs)\n\n #get\n\n #Sort the Processing Element on the right order\n new_inputs = check_order(inputs)\n self.write('output', new_inputs)\n\n\n\nclass NetCDFProcessing(GenericPE):\n def __init__(self):\n GenericPE.__init__(self)\n self._add_input('input')\n self._add_output('output')\n self.count=0\n\n def _process(self, parameters):\n if type(parameters['input']) is tuple:\n param = parameters['input'][0]\n param[self.name]['in_files'] = parameters['input'][1]\n else:\n param = parameters['input']\n\n icclim.indice(**param[self.name])\n self.count+=1\n print(param[self.name])\n\n self.write('output', (param,\n param[self.name]['out_file'],\n param[self.name]['indice_name']))\n\nclass ReadNetCDF(GenericPE):\n def __init__(self):\n GenericPE.__init__(self)\n self._add_input('input')\n self._add_output('output')\n\n def _process(self, parameters):\n #Load the netcdf file\n nc = Dataset(parameters['input'][-2])\n\n #Extracting the time and change the time format from num to date time\n time = nc.variables['time']\n nc_time = netcdftime.utime(time.units, time.calendar)\n date_time = nc_time.num2date(time[:])\n\n var = nc.variables[parameters['input'][-1]][:]\n\n self.write('output', (date_time, var))\n\n\nclass AverageData(GenericPE):\n def __init__(self):\n GenericPE.__init__(self)\n self._add_input('input')\n self._add_output('output')\n\n def _process(self, parameters):\n time = parameters['input'][0]\n var = parameters['input'][1]\n var = np.reshape(var, (var.shape[0], -1))\n result = np.mean(var, axis=1)\n\n self.write('output', (time, result, self.name))\n\n\nclass StandardDeviation(GenericPE):\n def __init__(self):\n GenericPE.__init__(self)\n self._add_input('input')\n self._add_output('output')\n\n def _process(self, parameters):\n time = parameters['input'][0]\n var = parameters['input'][1]\n var = np.reshape(var, (var.shape[0], -1))\n result = np.std(var, axis=1)\n\n self.write('output', (time, result, self.name))\n\n\nclass CombineAndPlot(GenericPE):\n def __init__(self):\n GenericPE.__init__(self)\n self._add_input('var1',grouping=[1])\n self._add_input('var2',grouping=[1])\n self._add_input('var3',grouping=[1])\n self._add_output('output')\n self.var1=0\n self.name1=''\n self.var2=0\n self.name2=''\n self.var3=0\n self.name3=''\n self.count=0\n\n def _process(self, parameters):\n #var = parameters['input'][1]\n name_var = parameters.keys()[0]\n\n if name_var == 'var1':\n self.var1 = parameters[name_var][1]\n self.name1 = parameters[name_var][2]\n self.count+=1\n elif name_var == 'var2':\n self.var2 = parameters[name_var][1]\n self.name2 = parameters[name_var][2]\n self.count+=1\n elif name_var == 'var3':\n self.var3 = parameters[name_var][1]\n self.name3 = parameters[name_var][2]\n self.count+=1\n print(\"self.count: \"+str(self.count))\n\n if self.count==3:\n\n #Get year list\n time = parameters[name_var][0]\n year_list = np.array([t.year for t in time])\n\n plt.figure()\n lines = plt.plot(year_list, self.var1, year_list, self.var2, year_list, self.var3)\n l1, l2, l3 = lines\n plt.setp(lines, linestyle='-')\n plt.setp(l1, linewidth=1, color='r', label=self.name1)\n plt.setp(l2, linewidth=1, color='g', label=self.name2)\n plt.setp(l3, linewidth=1, color='b', label=self.name3)\n plt.legend()\n plt.xlabel('Year')\n plt.ylabel(self.name)\n plt.grid()\n name_fig = self.name+\".png\"\n plt.savefig(\"/tmp/\"+name_fig)\n self.write(\"output\", (\"/tmp/\"+name_fig, name_fig))\n\n\nclass B2DROP(GenericPE):\n def __init__(self):\n GenericPE.__init__(self)\n self._add_input('input')\n self._add_output('output')\n\n def _process(self, parameters):\n import owncloud\n\n param = parameters['input'][0]\n name_dir = \"enes_usecase\"\n\n if isinstance(param, str):\n username = \"FILL THIS SECTION\"\n password = \"FILL THIS SECTION\"\n src_path = parameters['input'][0]\n upload_path = name_dir+\"/\"+parameters['input'][1]\n else:\n param_keys = parameters['input'][0].keys()\n username = parameters['input'][0][self.name]['username']\n password = parameters['input'][0][self.name]['password']\n src_path = param[param_keys[-2]]['out_file']\n pdb.set_trace()\n upload_path = remove_absolute_path(src_path, '/')\n upload_path = name_dir+\"/\"+upload_path\n\n oc = owncloud.Client('https://b2drop.eudat.eu')\n\n oc.login(username, password)\n\n oc.put_file(upload_path, src_path)\n\n link_info = oc.share_file_with_link(upload_path)\n print(\"Shared linked is: \"+link_info.get_link())\n\n##############################################################################\n# Workflow creation from ENES_usecase/PreProcess.py\n##############################################################################\n\ndef create_multiple_scenario_workflow():\n ###############################\n #Stream Producer, it will scan the json file in input\n ###############################\n streamProducer = StreamProducer()\n streamProducer.name = 'SU_workflow'\n\n\n ###############################\n #Workflow for r1i2p1 simulation\n ###############################\n su_calculation_r1i2p1 = NetCDFProcessing()\n su_calculation_r1i2p1.name = 'SU_calculation_r1i2p1'\n\n read_r1i2p1 = ReadNetCDF()\n read_r1i2p1.name = \"read_SU_r1i2p1\"\n\n mean_calculation_r1i2p1 = AverageData()\n mean_calculation_r1i2p1.name = \"mean_r1i2p1\"\n\n std_calc_r1i2p1 = StandardDeviation()\n std_calc_r1i2p1.name = \"std_r1i2p1\"\n\n\n ###############################\n #Workflow for r2i2p1 simulation\n ###############################\n su_calculation_r2i2p1 = NetCDFProcessing()\n su_calculation_r2i2p1.name = 'SU_calculation_r2i2p1'\n\n read_r2i2p1 = ReadNetCDF()\n read_r2i2p1.name = \"read_SU_r2i2p1\"\n\n mean_calculation_r2i2p1 = AverageData()\n mean_calculation_r2i2p1.name = \"mean_r2i2p1\"\n\n std_calc_r2i2p1 = StandardDeviation()\n std_calc_r2i2p1.name = \"std_r2i2p1\"\n\n\n ###############################\n #Workflow for r3i2p1 simulation\n ###############################\n su_calculation_r3i2p1 = NetCDFProcessing()\n su_calculation_r3i2p1.name = 'SU_calculation_r3i2p1'\n\n read_r3i2p1 = ReadNetCDF()\n read_r3i2p1.name = \"read_SU_r3i2p1\"\n\n mean_calculation_r3i2p1 = AverageData()\n mean_calculation_r3i2p1.name = \"mean_r3i2p1\"\n\n std_calc_r3i2p1 = StandardDeviation()\n std_calc_r3i2p1.name = \"std_r3i2p1\"\n\n\n ###############################\n #Workflow to combine and plot the calculation together\n ###############################\n combine_std = CombineAndPlot()\n combine_std.name = \"SU_Spatial_STD\"\n\n combine_mean = CombineAndPlot()\n combine_mean.name = \"SU_Spatial_MEAN\"\n\n\n ###############################\n #Workflow to combine and plot the calculation together\n ###############################\n b2drop = B2DROP()\n b2drop.name = \"b2drop_storage\"\n\n ###############################\n #Workflow starts here\n ###############################\n graph = WorkflowGraph()\n\n #Calculation for r1i2p1\n graph.connect(streamProducer, 'output', su_calculation_r1i2p1, 'input')\n graph.connect(su_calculation_r1i2p1, 'output', read_r1i2p1, 'input')\n graph.connect(read_r1i2p1, 'output', mean_calculation_r1i2p1, 'input')\n graph.connect(read_r1i2p1, 'output', std_calc_r1i2p1, 'input')\n\n #Calculation for r2i2p1\n graph.connect(streamProducer, 'output', su_calculation_r2i2p1, 'input')\n graph.connect(su_calculation_r2i2p1, 'output', read_r2i2p1, 'input')\n graph.connect(read_r2i2p1, 'output', mean_calculation_r2i2p1, 'input')\n graph.connect(read_r2i2p1, 'output', std_calc_r2i2p1, 'input')\n\n #Calculation for r3i2p1\n graph.connect(streamProducer, 'output', su_calculation_r3i2p1, 'input')\n graph.connect(su_calculation_r3i2p1, 'output', read_r3i2p1, 'input')\n graph.connect(read_r3i2p1, 'output', mean_calculation_r3i2p1, 'input')\n graph.connect(read_r3i2p1, 'output', std_calc_r3i2p1, 'input')\n\n ###############################\n #We combine the standard deviation and plot it together. Same for the average.\n ###############################\n graph.connect(std_calc_r1i2p1, 'output', combine_std, 'var1')\n graph.connect(std_calc_r2i2p1, 'output', combine_std, 'var2')\n graph.connect(std_calc_r3i2p1, 'output', combine_std, 'var3')\n\n graph.connect(mean_calculation_r1i2p1, 'output', combine_mean, 'var1')\n graph.connect(mean_calculation_r2i2p1, 'output', combine_mean, 'var2')\n graph.connect(mean_calculation_r3i2p1, 'output', combine_mean, 'var3')\n\n ###############################\n #We store all the results on b2drop\n ###############################\n graph.connect(combine_std, 'output', b2drop, 'input')\n graph.connect(combine_mean, 'output', b2drop, 'input')\n\n return graph\n\n\ngraph = create_multiple_scenario_workflow()\n\n##############################################################################\n# Provenance from ENES_usecase/PreProcess.py \n##############################################################################\n\n#Store via service\n\nProvenanceType.REPOS_URL='http://'+os.getenv('SPROV_SERVICE_HOST')+':'+os.getenv('SPROV_SERVICE_PORT')+'/workflowexecutions/insert'\nProvenanceType.PROV_EXPORT_URL='http://'+os.getenv('SPROV_SERVICE_HOST')+':'+os.getenv('SPROV_SERVICE_PORT')+'/workflowexecutions/'\n\n#Store to local path\nProvenanceType.PROV_PATH='./prov-files/'\n\n#Size of the provenance bulk before sent to storage or sensor\nProvenanceType.BULK_SIZE=1\n\nprov_config = {\n 'provone:User': \"cc4idev\",\n 's-prov:description' : \"enes_multiple_scenarios\",\n 's-prov:workflowName': \"enes_multiple_scenarios\",\n 's-prov:workflowType': \"climate:preprocess\",\n 's-prov:workflowId' : \"workflow process\",\n 's-prov:save-mode' : 'service' ,\n 's-prov:WFExecutionInputs': [{\n \"url\": \"\",\n \"mime-type\": \"text/json\",\n \"name\": \"input_data\"\n\n }],\n # defines the Provenance Types and Provenance Clusters for the Workflow Components\n # 's-prov:componentsType' :\n # {self.calc_operation.getValue()+'_Spatial_MEAN': {'s-prov:type':(AccumulateFlow,),\n # 's-prov:prov-cluster':'enes:Processor'},\n # self.calc_operation.getValue()+'_Spatial_STD': {'s-prov:type':(AccumulateFlow,),\n # 's-prov:prov-cluster':'enes:Processor'},\n # self.calc_operation.getValue()+'_workflow': {'s-prov:type':(icclimInputParametersDataProvType,),\n # 's-prov:prov-cluster':'enes:dataHandler'},\n # 'PE_filter_bandpass': {'s-prov:type':(SeismoPE,),\n # 's-prov:prov-cluster':'seis:Processor'},\n # 'StoreStream': {'s-prov:prov-cluster':'seis:DataHandler',\n # 's-prov:type':(SeismoPE,)},\n # }\n # 's-prov:sel-rules': None\n}\n\n# rid='JUP_ENES_PREPOC_'+getUniqueId()\n\n# self.status.set(\"Initialising Provenance...\", 25)\n\n#Initialise provenance storage to service:\nconfigure_prov_run(graph,\n provImpClass=(ProvenanceType,),\n input=prov_config['s-prov:WFExecutionInputs'],\n username=prov_config['provone:User'],\n runId=os.getenv('RUN_ID'),\n description=prov_config['s-prov:description'],\n workflowName=prov_config['s-prov:workflowName'],\n workflowType=prov_config['s-prov:workflowType'],\n workflowId=prov_config['s-prov:workflowId'],\n save_mode=prov_config['s-prov:save-mode'],\n # componentsType=prov_config['s-prov:componentsType']\n # sel_rules=prov_config['s-prov:sel-rules']\n )\n\n","repo_name":"xpivan/DARE-Project","sub_path":"multiple-scenario-workflow.py","file_name":"multiple-scenario-workflow.py","file_ext":"py","file_size_in_byte":13646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13422019819","text":"\"\"\"\nhttps://leetcode.com/problems/contains-duplicate/\n\nGiven an array of integers, find if the array contains any duplicates.\n\nYour function should return true if any value appears at least twice \nin the array, and it should return false if every element is distinct.\n\nLessons learned:\n - Initialize a set with set(), not {} (that's a dict)\n\"\"\"\n\nclass Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n s = set()\n for n in nums:\n if n in s:\n return True\n s.add(n)\n return False","repo_name":"wpine215/leetcode20","sub_path":"easy/array/contains_duplicate.py","file_name":"contains_duplicate.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"335083828","text":"import json\nfrom newsapi import NewsApiClient\n\nnewd={2:\"two\",1:\"one\",3:\"three\",6:\"six\",4:\"four\"}\n\na=json.dumps(newd,sort_keys=True)\n\nprint(a)\n\nodic={values:key for key, values in newd.items()}\nprint(odic)\n","repo_name":"Shreejan-git/allpy","sub_path":"jsonn.py","file_name":"jsonn.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37852847302","text":"from agent import Agent\nfrom monitor import interact\nimport gym\nimport numpy as np\n\nenv = gym.make('Taxi-v3')\nalpha = 0.9999\ngamma = .9\nepsilon = 0.0001\nprint(\"Gym Taxi version 3 -- my solutions\")\nprint(\"Alpha=\",alpha)\nprint(\"gamma=\",gamma)\nprint(\"epsilon=\",epsilon)\n\nprint(\"----Sarsa Algorithm \")\nagent = Agent(solution=1,alpha=alpha,gamma=gamma,eps=epsilon)\navg_rewards, best_avg_reward = interact(env, agent)\n\nprint(\"----SarsaMax or Q-learning Algorithm \")\nagent = Agent(solution=2,alpha=alpha,gamma=gamma,eps=epsilon)\navg_rewards, best_avg_reward = interact(env, agent)\n\nprint(\"----Extended Sarsa Algorithm \")\nagent = Agent(solution=1,alpha=alpha,gamma=gamma,eps=epsilon)\navg_rewards, best_avg_reward = interact(env, agent)\n","repo_name":"mojindri/gymtaxi","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42659170005","text":"#!/usr/bin/python3\nimport os\n\nos.chdir('/home/kika/paratrypanosoma/')\nnames = open('corrupted_genes.txt', 'r')\ngff = open('result_renamed_lengths_no_split.gff', 'r')\nout = open('corrupted_genes_both_names.tsv', 'w')\n\nnames_list = []\nfor line in names:\n\tnames_list.append(line[:-1])\n\nboth = {}\nfor row in gff:\n\tif row.startswith('##'):\n\t\tpass\n\telse:\n\t\tpcon = row.split('\\t')[8].split('ID=')[1].split(';')[0]\n\t\told = row.split('\\t')[8].split('ID=')[1].split(';')[1].split('Note=')[1][:-1]\n\t\tboth[pcon] = old\n\nfor key, value in both.items():\n\tif key in names_list:\n\t\tout.write('{}\\t{}\\n'.format(key, value))\nout.close()","repo_name":"kikinocka/ngs","sub_path":"py_scripts/paratrypka/corrupted_genes.py","file_name":"corrupted_genes.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2055260735","text":"import pyodbc\r\n\r\ntry:\r\n connection = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)}; '\r\n r'DBQ=C:\\Users\\lenovo\\Documents\\Database1.accdb;')\r\n print(\"Database is Connected\")\r\n\r\n database = connection.cursor()\r\n mydata = (10, \"Dominic Z. Marasigan\", 19, \"Cavite\", \"BS CPE\", 97),\r\n\r\n database.executemany('INSERT INTO Table1 VALUES (?,?,?,?,?,?)', mydata)\r\n connection.commit()\r\n\r\n print(\"Data is inserted\")\r\n\r\nexcept pyodbc.Error:\r\n print(\"Database is NOT inserted\")","repo_name":"Dominic-Marasigan/OOP-1-1","sub_path":"insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74931887845","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\nimport cv2\n\nsrc_img = cv2.imread('opencv/images/moonlight.png')\nimg = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)\nret, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # cvt to a binary(only black & white) sample_img\n\n_, contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\ncv2.drawContours(img, contours, -1, (0, 0, 255), 3)\n\ncv2.imshow(\"Result\", img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\ndict.pop()\n","repo_name":"SimonCqk/Python_Toys","sub_path":"opencv/detect_contours.py","file_name":"detect_contours.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21863118772","text":"\n # import required libraries \nimport random\nfrom tkinter import *\n\nclass Start:\n def __init__(self, root):\n # set up and grid first displayed frame\n self.frame = Frame()\n self.frame.grid()\n # creates design for the first frame\n self.heading_frame = Frame(self.frame, width=500, height=18, bg=\"#CCE5FF\")\n self.under_heading_frame = Frame(self.frame, width=500, height=6, bg=\"#BDDEFF\")\n self.blank_frame = Frame(self.frame, height=40, width=500)\n self.label_background_frame = Frame(self.frame, height=150, width=500, bg=\"white\")\n self.heading_label = Label(self.label_background_frame, height=3, width=41, text=\"Math Quiz\", font=(\"Helvetica 15 bold\"), \n fg=\"#6C6C6C\", justify=CENTER, bg=\"white\")\n self.under_label_frame = Frame(self.frame, width=500, height=7, bg=\"#E8E8E8\")\n self.start_game_button = Button(self.frame, text=\"PLAY\", font=(\"Helvetica 15 bold\"), fg=\"#747475\", border=0, command=lambda: self.toGame())\n\n # grid all created objects above\n self.heading_label.grid()\n self.heading_frame.grid(row=0)\n self.under_heading_frame.grid(row=1)\n self.blank_frame.grid(row=2)\n self.label_background_frame.grid(row=3)\n self.under_label_frame.grid(row=4)\n self.start_game_button.grid(row=6, pady=50)\n\n # function to send user to Game class\n def toGame(self, ):\n # deletes the current frame\n self.frame.destroy()\n Game()\n \nclass Game:\n def __init__(self):\n # set up variables\n self.round_number = IntVar()\n self.round_number.set(1)\n\n self.correctly_answered = IntVar()\n self.correctly_answered.set(0)\n\n self.incorrectly_answered = IntVar()\n self.incorrectly_answered.set(0)\n\n current_equation = StringVar()\n # set up and grid first displayed frame\n self.frame = Frame(width=500, height=600)\n self.frame.grid()\n # creates design for the main Game frame\n self.heading_frame = Frame(self.frame, width=500, height=65, bg=\"#CCE5FF\")\n self.under_heading_frame = Frame(self.frame, width=500, height=6, bg=\"#BDDEFF\")\n self.heading_label = Label(self.heading_frame, text=\"Math Quiz\", font=(\"Helvetica 15\"),\n fg=\"#6C6C6C\", bg=\"#CCE5FF\", width=45, height=2, justify=CENTER)\n self.blank_frame = Frame(self.frame, width=500, height=30)\n self.label = Label(self.frame, text=\"Round {}\\n\\nEnter your answer in the entry\\nbox below and click Check Answer.\".format(self.round_number.get()), font=(\"Helvetica 12\"), justify=CENTER)\n self.second_blank_frame = Frame(self.frame, width=500, height=30)\n self.question_info_frame = Frame(self.frame, width=500, height=30, bg=\"white\")\n self.question_label = Label(self.question_info_frame, bg=\"white\", width=45, height=3, text=self.newQuestion(), font=(\"Helvetica 15\"), justify=CENTER)\n self.under_question_info_frame = Frame(self.frame, width=500, height=5, bg=\"#E8E8E8\")\n self.third_blank_frame = Frame(self.frame, width=500, height=40)\n self.user_input = Entry(self.frame, width=21, font=(\"Helvetica 15\"))\n self.check_answer_button = Button(self.frame, text=\"Check Answer\", font=(\"Helvetica 12\"), width=15, command=lambda: self.checkAnswer())\n self.fourth_blank_frame = Frame(self.frame, width=500, height=40)\n self.help_button = Button(self.frame, text=\"Help\", font=(\"Helvetica 12\"), width=15, command=lambda: self.toHelp())\n self.stats_button = Button(self.frame, text=\"Statistics\", font=(\"Helvetica 12\"), width=15, command=lambda: self.toStats())\n self.footer_blank = Frame(self.frame, width=500, height=20)\n self.footer = Frame(self.frame,width=500, height=6, bg=\"#CCE5FF\")\n\n # grid all created objects above\n self.heading_label.grid(row=1)\n self.heading_frame.grid(row=1)\n self.under_heading_frame.grid(row=2)\n self.blank_frame.grid(row=3)\n self.label.grid(row=4)\n self.second_blank_frame.grid(row=5)\n self.question_info_frame.grid(row=6)\n self.question_label.grid(row=7)\n self.under_question_info_frame.grid(row=8)\n self.third_blank_frame.grid(row=9)\n self.user_input.grid(row=10)\n self.check_answer_button.grid(row=11)\n self.fourth_blank_frame.grid(row=12)\n self.help_button.grid(row=13)\n self.stats_button.grid(row=14)\n self.footer_blank.grid(row=15)\n self.footer.grid(row=16)\n\n # function to generate a new question\n def newQuestion(self):\n # creates a random question using operators \n # from list variable and the random library\n operators = [\"+\", \"-\", \"*\"]\n equation = \"{} {} {}\".format(random.randint(0,12), random.choice(operators), random.randint(0,12))\n self.current_equation = equation\n # returns newly generated question to question label\n return equation\n\n # function to check if the user's answer is correct\n def checkAnswer(self):\n equation = self.current_equation\n \n try:\n # checks if user input is empty\n if self.user_input.get() != \"\":\n # compare user's answer with correct answer\n if (int(self.user_input.get())) == eval(equation):\n # sets user input background to green\n # and adds 1 to correctly_answered\n self.user_input.configure(bg=\"#90EE90\")\n is_right = self.correctly_answered.get()\n is_right += 1\n self.correctly_answered.set(is_right)\n else:\n # sets user input background to red\n # and adds 1 to incorrectly_answer\n self.user_input.configure(bg=\"#FF5733\")\n is_wrong = self.incorrectly_answered.get()\n is_wrong += 1\n self.incorrectly_answered.set(is_wrong)\n else:\n # if user input is empty set background to red\n # doesn't skip round.\n self.user_input.configure(bg=\"#FF5733\")\n return\n \n # adds 1 to round counter and updates\n # label on main Game frame\n self.question_label.config(text=self.newQuestion())\n rnum = self.round_number.get()\n rnum += 1\n self.round_number.set(rnum)\n self.label.config(text=\"Round {}\\n\\nEnter your answer in the entry\\nbox below and click Check Answer.\".format(rnum))\n \n # parses user input as integer, if not \n # sets user input background to red\n except ValueError:\n self.user_input.configure(bg=\"#FF5733\")\n\n # functions to send user to Stats and Help classes\n def toStats(self):\n num_correct = self.correctly_answered.get()\n num_wrong = self.incorrectly_answered.get()\n # deletes the current frame\n # and sends user to Stats\n self.frame.destroy()\n Stats(num_correct, num_wrong)\n\n def toHelp(self):\n # deletes the current frame \n # and sends user to Help\n self.frame.destroy()\n Help()\n\nclass Stats:\n def __init__(self, correctly_answered, incorrectly_answered):\n # set up and grid first displayed frame \n self.frame = Frame()\n self.frame.grid()\n # creates design for the main Stats frame \n self.heading_frame = Frame(self.frame, width=500, height=20, bg=\"#CCE5FF\")\n self.under_heading_frame = Frame(self.frame, width=500, height=6, bg=\"#BDDEFF\")\n self.blank_frame = Frame(self.frame, height=50)\n self.heading_label = Label(self.frame, text=\"Statistics\", font=(\"Helvetica 15 bold\"), fg=\"#6C6C6C\", justify=CENTER)\n self.second_blank_frame = Frame(self.frame, height=50)\n self.instructions_text = Label(self.frame, text=\"Answered correctly: {}\\nAnswered incorrectly: {}\\n\".format(correctly_answered, incorrectly_answered), font=(\"Helvetica 12\"), justify=CENTER)\n self.third_blank_frame = Frame(self.frame, width=500, height=50)\n self.dismiss_button = Button(self.frame, text=\"Dismiss\", font=(\"Helvetica 12\"), width=15, command=lambda: self.dismissStats())\n self.fourth_blank_frame = Frame(self.frame, width=500, height=35)\n\n # grid all created objects above\n self.heading_frame.grid()\n self.under_heading_frame.grid() \n self.blank_frame.grid()\n self.heading_label.grid()\n self.second_blank_frame.grid() \n self.instructions_text.grid()\n self.third_blank_frame.grid()\n self.dismiss_button.grid()\n self.fourth_blank_frame.grid()\n\n # function to send user back to Game class\n def dismissStats(self):\n # deletes the current frame\n # and sends user to Game\n self.frame.destroy()\n Game()\n\nclass Help:\n def __init__(self):\n # set up and grid first displayed frame \n self.frame = Frame()\n self.frame.grid()\n # creates design for the main Stats frame\n self.heading_frame = Frame(self.frame, width=500, height=20, bg=\"#CCE5FF\")\n self.under_heading_frame = Frame(self.frame, width=500, height=6, bg=\"#BDDEFF\")\n self.blank_frame = Frame(self.frame, height=50)\n self.heading_label = Label(self.frame, text=\"Help and Instructions\", font=(\"Helvetica 15 bold\"), fg=\"#6C6C6C\", justify=CENTER)\n self.second_blank_frame = Frame(self.frame, height=50)\n self.instructions_text = Label(self.frame, text=\"Begin the quiz by clicking the Play button.\\n\"\n \"Type your answer in the entry form below\\n\"\n \"the question and click the button to submit it.\", font=(\"Helvetica 12\"), justify=CENTER)\n self.third_blank_frame = Frame(self.frame, width=500, height=50)\n self.dismiss_button = Button(self.frame, text=\"Dismiss\", font=(\"Helvetica 12\"), width=15, command=lambda: self.dismissHelp())\n self.fourth_blank_frame = Frame(self.frame, width=500, height=35)\n\n # grid all created objects above\n self.heading_frame.grid()\n self.under_heading_frame.grid() \n self.blank_frame.grid()\n self.heading_label.grid()\n self.second_blank_frame.grid() \n self.instructions_text.grid()\n self.third_blank_frame.grid()\n self.dismiss_button.grid()\n self.fourth_blank_frame.grid()\n \n # function to send user back to Help class\n def dismissHelp(self):\n # deletes the current frame\n # and sends user to Game\n self.frame.destroy()\n Game()\n\n # tkinter\ngui = Tk()\ngui.title(\"Math Quiz\")\nvar = Start(gui)\ngui.mainloop()","repo_name":"howardc72150/mathquiz","sub_path":"compiledGame.py","file_name":"compiledGame.py","file_ext":"py","file_size_in_byte":11589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40448476717","text":"from odoo import models, fields, api, _\nfrom odoo.exceptions import Warning, UserError\n\n\nclass PurchaseOrderInherit(models.Model):\n _inherit = \"purchase.order\"\n\n @api.model\n def _default_show_sign(self):\n return self.env['ir.config_parameter'].sudo().get_param(\n 'digital_signature.show_digital_sign_po')\n\n @api.model\n def _default_enable_sign(self):\n return self.env['ir.config_parameter'].sudo().get_param(\n 'digital_signature.enable_options_po')\n\n digital_sign = fields.Binary(string='Signature')\n sign_by = fields.Char(string='Signed By')\n designation = fields.Char(string='Designation')\n sign_on = fields.Datetime(string='Signed On')\n show_signature = fields.Boolean('Show Signature',\n default=_default_show_sign,\n compute='_compute_show_signature')\n enable_others = fields.Boolean(default=_default_enable_sign,\n compute='_compute_enable_others')\n\n def button_confirm(self):\n res = super(PurchaseOrderInherit, self).button_confirm()\n if self.env[\n 'ir.config_parameter'].sudo().get_param(\n 'digital_signature.confirm_sign_po') and self.digital_sign is False:\n raise UserError(_(\"Signature is missing\"))\n\n return res\n\n def _compute_show_signature(self):\n show_signature = self._default_show_sign()\n for record in self:\n record.show_signature = show_signature\n\n def _compute_enable_others(self):\n enable_others = self._default_enable_sign()\n for record in self:\n record.enable_others = enable_others\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"digital_signature/models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"39199504432","text":"class node:\n\n type = \"node\"\n repeat_message = \"data already present\"\n\n def __init__(self, data):\n self.data = data\n self.left_child = None\n self.right_child = None\n\n def add_child(self, data):\n if data > self.data:\n if not self.right_child:\n self.right_child = node(data)\n else:\n self.right_child.add_child(data)\n elif data < self.data:\n if not self.left_child:\n self.left_child = node(data)\n else:\n self.left_child.add_child(data)\n else:\n print(self.repeat_message)\n\n def check_value(self, data):\n if self.data == data:\n return True\n elif data > self.data and self.right_child is not None:\n return self.right_child.check_value(data)\n elif data < self.data and self.left_child is not None:\n return self.left_child.check_value(data)\n else:\n return False\n\n def display(self, level=0):\n if not self.right_child == None:\n self.right_child.display(level+1)\n print(\"\")\n for i in range(level):\n print(\" \")\n print(self.data)\n if not self.left_child == None:\n self.left_child.display(level+1)\n\n\n","repo_name":"lars-alfonse/pythonBinarySearchTree","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32677279321","text":"from flask import Flask, jsonify, request\nimport json\nimport random\n\napp = Flask(__name__)\n\n\ndef Read():\n try:\n with open(\"data/InquiryData.json\", \"r\") as ReadFile:\n data = json.load(ReadFile)\n return data\n except:\n return None\n\ndef Write(arr, mess):\n\n data = {\n \"code\": arr,\n \"me\": mess\n }\n try:\n with open(\"data/InquiryData.json\", \"w\") as WriteFile:\n json.dump(data, WriteFile)\n return True\n except:\n return False\n\n@app.route('/')\ndef main():\n with open(\"main.html\", \"rb\") as fin:\n return fin.read()\n\n\n@app.route('/search')\ndef search():\n with open(\"search.html\", \"rb\") as fin:\n g = Read()\n i = random.randint(0, len(g[\"me\"]) - 1)\n s = fin.read()[2:]\n s = s[:841] + g[\"me\"][i].encode('utf-8') + s[841:]\n s = s[:542] + g[\"code\"][i].encode('utf-8') + s[542:]\n return s\n\n\n@app.route('/create')\ndef create():\n with open(\"create.html\", \"rb\") as fin:\n return fin.read()\n\n\n@app.route('/handle_data', methods=('GET', 'POST'))\ndef handle_data():\n if len(str(request.form['me'])) == 0 and len(str(request.form['programm'])) == 0:\n with open(\"errorcreate.html\", \"rb\") as fin:\n return fin.read()\n else:\n g = Read()\n Write(g[\"code\"] + [request.form['programm']], g[\"me\"] + [request.form['me']])\n with open(\"successfullycreate.html\", \"rb\") as fin:\n return fin.read()\n\n\n@app.route(\"/image/fon12.png\")\ndef background():\n with open(\"image/fon12.png\", \"rb\") as fin:\n return fin.read()\n\n\n@app.route(\"/image/fon2.png\")\ndef background2():\n with open(\"image/fon2.png\", \"rb\") as fin:\n return fin.read()\n\n@app.route(\"/image/fon3.png\")\ndef background3():\n with open(\"image/fon3.png\", \"rb\") as fin:\n return fin.read()\n\n@app.route(\"/image/fon4.png\")\ndef background4():\n i = random.randint(0, 1)\n if i:\n with open(\"image/fon4.png\", \"rb\") as fin:\n return fin.read()\n else:\n with open(\"image/fon42.png\", \"rb\") as fin:\n return fin.read()\n\nif __name__ == '__main__':\n app.run(port=8080, host='127.0.0.1')\n","repo_name":"vvvvtrt/ProgrammersDating","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16101219467","text":"from django.contrib.auth import get_user_model\r\nfrom django.db import models\r\n\r\nUser = get_user_model()\r\n\r\n\r\nclass Question(models.Model):\r\n \"\"\"Модель вопроса. Имеет текстовое поле вопроса\r\n и поле связи с моделью пользователя\"\"\"\r\n text = models.CharField(\r\n 'Вопрос',\r\n max_length=255\r\n )\r\n user = models.ForeignKey(\r\n User,\r\n verbose_name='Пользователь',\r\n on_delete=models.CASCADE\r\n )\r\n\r\n def __str__(self):\r\n return f'Вопрос: {self.text} от пользователя: {self.user}'\r\n\r\n class Meta:\r\n verbose_name = 'Вопрос'\r\n verbose_name_plural = 'Вопросы'\r\n\r\n\r\nclass Answer(models.Model):\r\n \"\"\"Поле ответов.Используется для хранения вариантов ответа с\r\n возможностью дальнейшего увеличения количества вариантов\r\n через админ-панель\"\"\"\r\n text = models.CharField(\r\n 'Ответ',\r\n max_length=255\r\n )\r\n\r\n def __str__(self):\r\n return self.text[:15]\r\n\r\n class Meta:\r\n verbose_name = 'Ответ'\r\n verbose_name_plural = 'Ответы'\r\n","repo_name":"PaulSssar/predictions","sub_path":"predictions/crystall_ball/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40119858425","text":"\ndef gene_translator(gseq: str) -> str :\n \n phe1=['ttt','ttc']\n leu2=['tta','ttg','ctt','ctc','cta','ctg']\n ile3=['att','atc','ata']\n met4=['atg']\n val5=['gtt','gtc','gta','gtg']\n ser6=['tct','tcc','tca','tcg','agt','agc']\n pro7=['cct','ccc','cca','ccg']\n thr8=['act','acc','aca','acg']\n ala9=['gct','gcc','gca','gcg']\n tyr10=['tat','tac']\n his11=['cat','cac']\n gln12=['caa','cag']\n asn13=['aat','aac']\n lys14=['aaa','aag']\n asp15=['gat','gac']\n glt16=['gaa','gag']\n cys17=['tgt','tgc']\n trp18=['tgg']\n arg19=['cgt','cgc','cga','cgg','aga','agg']\n gly20=['ggt','ggc','gga','ggg']\n stop=['taa','tag','tga']\n \n gcode=[phe1,leu2,ile3,met4,val5,ser6,pro7,thr8,ala9,tyr10,\n his11,gln12,asn13,lys14,asp15,glt16,cys17,trp18,arg19,gly20]\n aacode=['F','L','I','M','V','S','P','T','A','Y','H','Q','N','K','D','E','C','W','R','G']\n \n###version 1----------------------------------------------------------------------------------------------------\n protein=[]\n i=0\n while i < len(gseq): #ribosome movement\n rib=gseq[i:i+3 :]\n if rib in stop:\n break\n elif len(rib)<3:\n break\n \n j=0\n while j < len(gcode):\n if rib in gcode[j]:\n protein.append(aacode[j])\n i+=3\n break\n else:\n j+=1\n \n # print(protein) # KRAS protein aminoacid sequences\n protein_list=\"\".join(protein)\n return protein_list\n # print(protein_list)\n # print(len(protein_list)) #numbner of aminoacids of KRAS protein \n \n \n \n###version2-------------------------------------------------------------------------------------------\n # protein=[]\n # while len(gseq)>=3:\n # rib=gseq[0:3]\n \n # for i in range (len(gcode)):\n # for j in range(len(gcode[i])):\n # if rib==gcode[i][j]: # wihout using the if sth in list:\n # protein.append(aacode[i])\n # gseq=gseq[3:len(gseq)]\n # break\n \n \n # if len(gseq)<=3:\n # for m in range(len(stop)):\n # if rib==stop[m]:\n # gseq=gseq[3:len(gseq)]\n # print(\"\")\n # break\n \n \n # print(protein)\n\n\n###-----------------------------------------------------------------------------------------------------------------\n\ndef reverse_transcription(protein:str) -> str:\n \n phe1=['ttt','ttc']\n leu2=['tta','ttg','ctt','ctc','cta','ctg']\n ile3=['att','atc','ata']\n met4=['atg']\n val5=['gtt','gtc','gta','gtg']\n ser6=['tct','tcc','tca','tcg','agt','agc']\n pro7=['cct','ccc','cca','ccg']\n thr8=['act','acc','aca','acg']\n ala9=['gct','gcc','gca','gcg']\n tyr10=['tat','tac']\n his11=['cat','cac']\n gln12=['caa','cag']\n asn13=['aat','aac']\n lys14=['aaa','aag']\n asp15=['gat','gac']\n glt16=['gaa','gag']\n cys17=['tgt','tgc']\n trp18=['tgg']\n arg19=['cgt','cgc','cga','cgg','aga','agg']\n gly20=['ggt','ggc','gga','ggg']\n stop=['taa','tag','tga']\n \n gcode=[phe1,leu2,ile3,met4,val5,ser6,pro7,thr8,ala9,tyr10,\n his11,gln12,asn13,lys14,asp15,glt16,cys17,trp18,arg19,gly20]\n aacode=['F','L','I','M','V','S','P','T','A','Y','H','Q','N','K','D','E','C','W','R','G']\n \n print(len(protein))\n \n codon=[] \n n=0\n \n for i in protein:\n for n in range(len(aacode)):\n if i==aacode[n]:\n codon.append(gcode[n][0])\n \n print(codon)\n codon.append(stop[0])\n codon_original=\"\".join(codon)\n print(codon_original)\n print(len(codon_original))\n \n \n \n###------------------------------------------------------------------------------------------------------------\n# def mutatedgenetranslator(gseq:str, mutype:int, munum:int) -> str:\ndef gene_mutator(gseq:str, substitution:int, deletion:int, insertion:int) -> str:\n\n \"\"\"\n munum=int(input(\"determine the number of mutation: \"))\n print(\"determine the type of mutaion: \")\n print(\"1- point mutation (substitution) \")\n print(\"2- Deletion mutation\")\n print(\"3- Insertion mutation \")\n mutype=int(input())\n \"\"\"\n mutationProcess={\n \n 1:substitution,\n 2:deletion,\n 3:insertion\n }\n \n DNA_nt=[\"a\",\"c\",\"g\",\"t\"] #DNA nucleotide\n \n print(len(gseq),\"--------------length of original gseq\")\n gseq_list=list(gseq)\n \n###version 1----------------------------------------------------------------------------------------\n gseqCopy=gseq_list.copy()\n #code for randomly mutating the parent gene\n import random\n for keys in mutationProcess:\n if keys ==1 and mutationProcess[keys] !=0:\n for num in range(mutationProcess[keys]):\n \n mutation_point=random.randint(0, len(gseqCopy)-1)\n print('substitution mutation',mutation_point)\n mutation_point_code=gseq_list[mutation_point] #determine the nucleotide type of the genesequence mutation point where is our point of mutation\n DNA_3_nt=DNA_nt.copy() #list of our mutant nucleotide which want to be replaced with the original nuccleotide\n DNA_3_nt.remove(mutation_point_code) #remove the original neocleotide type(where is in the mutation point), from the 4-nucleotide type list\n mutant_nucleotide=DNA_3_nt[random.randint(0,2)] #random nucleotide between the remained nucleotide except the original nucleotide\n gseqCopy[mutation_point]=mutant_nucleotide #substitute the original bucleotide with the mutatnt one\n \n \n elif keys==2 and mutationProcess[keys] !=0:\n for num in range(mutationProcess[keys]):\n mutation_point=random.randint(0, len(gseqCopy)-1)\n print('deletion mutation',mutation_point)\n gseqCopy.pop(mutation_point)\n \n else:\n for num in range(mutationProcess[keys]):\n mutation_point=random.randint(0, len(gseqCopy)-1)\n print('insertion mutation',mutation_point)\n\n gseqCopy.insert(mutation_point, DNA_nt[random.randint(0, 3)]) #insert the mutatnt nucleotide in the place of the original one\n\n mutated_gseq=\"\".join(gseqCopy)\n return mutated_gseq #mutated gene\n\n\n# ###version 2----------------------------------------------\n# import random\n# a=0\n# while a < munum:\n# mutation_point=random.randint(0, len(gseq_list)-1)\n# # if mutation_point not in mut_point_list: #avoid repetitive mutation point\n# # mut_point_list.append(mutation_point)\n# # a+=1\n# a=a+1\n# DNA_3_nt=DNA_nt.copy() #list of our mutant nucleotide which want to be replaced with the original nuccleotide\n# mutation_point_code=gseq_list[mutation_point] #determine the nucleotide type of the genesequence mutation point where is our point of mutation\n# DNA_3_nt.remove(mutation_point_code) #remove the original neocleotide type(where is in the mutation point), from the 4-nucleotide type list\n# mutant_nucleotide=DNA_3_nt[random.randint(0,len(DNA_3_nt)-1)] #random nucleotide between the remained nucleotide except the original nucleotide\n \n# if mutype==1:\n# gseq_list[mutation_point]=mutant_nucleotide #substitute the original bucleotide with the mutatnt one\n# elif mutype==2:\n# gseq_list.pop(mutation_point)\n# else:\n# gseq_list.insert(mutation_point, DNA_nt[random.randint(0, 3)]) #insert the mutatnt nucleotide in the place of the original one\n \n# mutated_gseq=\"\".join(gseq_list)\n \n# print(mutated_gseq,\"------ mutant gseq\")\n# print(len(mutated_gseq),\"-----------length of mutated gene\")\n \n###--------------------------------------------------------------------------------------------------\n\ndef mutation_type(gseq: str, mutated_gseq: str)->str:\n \"\"\"\n \n Parameters\n ----------\n gseq : str\n original gene sequence\n mutated_gseq : str\n mutated gene sequence, obtained from gene_utator function\n\n Returns\n original and mutated protein and type of the mutation which has occured\n str\n\n \"\"\"\n \n import geneManipulators\n originalPro=geneManipulators.gene_translator(gseq)\n print(originalPro,'Original Pro')\n mutatedPro=geneManipulators.gene_translator(mutated_gseq)\n print(mutatedPro,'Mutated Pro')\n \n if mutatedPro == originalPro:\n print(\"Silent mutation\")\n elif len(mutatedPro)==len(originalPro) and mutatedPro != originalPro:\n print(\"Missense mutation\")\n elif len(mutatedPro)< len(originalPro):\n print(\"Nonsense mutation\")\n else:\n print(\"Frameshift mutation \")\n for t in range(len(mutatedPro)) :\n if t 1:\n model = torch.nn.DataParallel(model)\n model.load_state_dict(state_dict)\n\n # prepare model for testing\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = model.to(device)\n model.eval()\n\n total_loss = 0.0\n total_metrics = torch.zeros(len(metric_fns), device=device)\n num_sample = 100\n log_p_x = 0\n with torch.no_grad():\n for i, data in enumerate(tqdm(data_loader)):\n # target = torch.reshape(target[0],(-1, 784))\n data = data.to(device) # , target.to(device)\n output = model(data, num_sample)\n #\n # save sample images, or do something with output here\n #\n\n # for i in range(10):\n # if torch.equal(target[i], target[i+1]):\n # print('true')\n\n # computing loss, metrics on test set\n print(output['mu_0'].shape)\n print(data.shape)\n\n loss = loss_fn(output, data) # returned as tuple\n loss = loss[0] + loss[1]\n batch_size = data.shape[0]\n total_loss += loss.item() * batch_size\n for i, metric in enumerate(metric_fns):\n total_metrics[i] += metric(output, data) * batch_size\n log_p_x_l = []\n for i in range(num_sample):\n mu = output[f'mu_{i}']\n l1 = log_likelihood_bernoulli(data, mu)\n l2 = torch.sum(-sum(output[f'det_{i}']) + sum(output[f'log_z_{i}']) - sum(output[f'log_z_x_{i}']), dim=1)\n log_p_x_l.append(l1+l2)\n log_p_x_l = torch.stack(log_p_x_l, dim=1)\n log_p_x += (torch.logsumexp(log_p_x_l, dim=1) - np.log(num_sample)).sum()\n\n\n\n\n n_samples = len(data_loader.sampler) #check!! = 10,000\n print(n_samples)\n log = {'loss': total_loss / n_samples}\n log.update({met.__name__: total_metrics[i].item() / n_samples for i, met in enumerate(metric_fns)})\n log.update({'log_p_x': log_p_x / n_samples})\n print(log)\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch Template')\n\n parser.add_argument('-p', '--path', default=None, type=str,\n help='path to latest checkpoint (default: None)')\n parser.add_argument('-d', '--device', default=None, type=str,\n help='indices of GPUs to enable (default: all)')\n\n args = parser.parse_args()\n\n if args.path:\n config = torch.load(args.path)['config']\n if args.device:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.device\n\n main(config, args.path)","repo_name":"MordehayM/Latent-Dependency-Structure-with-IAF-Flow-optimization-on-Variational-Autoencoder","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71045612966","text":"# Given a string s and an integer k, return the length of the longest substring \n# of s such that the frequency of each character in this substring is greater \n# than or equal to k. \n# \n# \n# Example 1: \n# \n# \n# Input: s = \"aaabb\", k = 3\n# Output: 3\n# Explanation: The longest substring is \"aaa\", as 'a' is repeated 3 times.\n# \n# \n# Example 2: \n# \n# \n# Input: s = \"ababbc\", k = 2\n# Output: 5\n# Explanation: The longest substring is \"ababb\", as 'a' is repeated 2 times and \n# 'b' is repeated 3 times.\n# \n# \n# \n# Constraints: \n# \n# \n# 1 <= s.length <= 10â�´ \n# s consists of only lowercase English letters. \n# 1 <= k <= 10â�µ \n# \n# Related Topics Hash Table String Divide and Conquer Sliding Window ðŸ‘� 4000 👎\n# 329\n\nfrom typing import List, Optional\nfrom dataStructure.ListNode import ListNode\n\n# 没用å�ŒæŒ‡é’ˆï¼Œå› ä¸ºå�ŒæŒ‡é’ˆæœ‰ç‚¹éš¾ç�†è§£\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n # 这代ç �太牛逼了\n # def longestSubstring(self, s: str, k: int) -> int:\n # maxLength = 0\n # if len(s) < k:\n # return 0\n # setOfs = set(s)\n # for aChar in setOfs:\n # # 如果所有字符都大于k,那就直接返回len(s)\n # if s.count(aChar) < k:\n # seperations = s.split(aChar)\n # for seperation in seperations:\n # if seperation:\n # length = self.longestSubstring(seperation,k)\n # if length > maxLength:\n # maxLength = length\n # return maxLength\n # return len(s)\n def longestSubstring(self, s: str, k: int) -> int:\n if len(s) < k:\n return 0\n maxLength = 0\n setOfs = set(s)\n for aChar in setOfs:\n if s.count(aChar) < k:\n seperations = s.split(aChar)\n for sep in seperations:\n length = self.longestSubstring(sep, k)\n if length > maxLength:\n maxLength = length\n return maxLength\n return len(s)\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\n\nif __name__ == '__main__':\n a = Solution()\n # print(a.longestSubstring(s=\"abacbbc\", k=3))\n print(a.longestSubstring(s=\"aaaabbbbqqddweeriiiiirrroooweedd\", k=3))\n","repo_name":"ChaunceyBai98/LeetCodePython","sub_path":"leetcode/editor/en/[395]Longest Substring with At Least K Repeating Characters.py","file_name":"[395]Longest Substring with At Least K Repeating Characters.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32797325945","text":"import socket\nimport threading\nimport time\n\ndef handle_conn(conn,addr):\n while True:\n try:\n data = conn.recv(1024)\n if not data:\n print(\"远程主机断开连接!\")\n break\n print(\"recv:\",data.decode('utf-8'))\n conn.send(('%s:%s' % (time.asctime(), data.decode('utf-8'))).encode(\"utf-8\"))\n except Exception as e:\n print('addr:%s error:%s'%(addr,e))\n break\n\nsever = socket.socket()\n# port = ('localhost',5555)\nsever.bind(('localhost',5555))\nsever.listen(10)\nconn_list = []\n\nprint(\"waiting for connecting ...\")\nwhile True:\n socket,address = sever.accept()\n print(\"new come:\",address)\n conn = socket\n addr = address\n t = threading.Thread(target = handle_conn,args = (conn,addr))\n t.start()\n conn_list.append(conn)","repo_name":"starkbling/python-learning-notes","sub_path":"测试脚本/socket_sever.py","file_name":"socket_sever.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72858998246","text":"import logging\nimport requests\nimport os\nfrom dotenv import load_dotenv\nfrom aiogram import Bot, Dispatcher, executor, types\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\n\nload_dotenv()\n\n\nAPI_TOKEN = os.getenv('API_TOKEN')\nAPI_URL = os.getenv('API_URL')\n\nlogging.basicConfig(level=logging.INFO)\n\nbot = Bot(token=API_TOKEN)\ndp = Dispatcher(bot)\n\n\nasync def get_order(title: str):\n req = requests.get(f'{API_URL}api/order/{title}')\n return req.json()\n\ndef get_list():\n req = requests.get(f'{API_URL}api/list')\n list_of_anime = []\n for i in req.json():\n list_of_anime.append(i['title'])\n return list_of_anime\n\n@dp.message_handler(commands=['start'])\nasync def send_welcome(message: types.Message):\n await message.reply(\"Hi!\\nI'm ChūmonBot!\\n To get order of a specific anime enter /order \")\n\n@dp.message_handler(commands=['help'])\nasync def send_help(message: types.Message):\n TEXT = \"Welcome maester \\n\\n * To get order of a specific enter /order and don't forget only to use lowercase \\n\\n * To request order enter /request ANIME_TITLE \\n\\n If u r having issues contact me @Itachiinthesky\"\n rkm = InlineKeyboardMarkup(row_wigth=1)\n rkm.add(InlineKeyboardButton(\"Github\", \"https://github.com/Besufikad17/Chumon\"))\n await message.answer(TEXT,reply_markup=rkm)\n\n@dp.message_handler(commands=['request'])\nasync def submit_request(message: types.Message):\n anime_title = message.text[9:] \n req = requests.post(f'{API_URL}/api/request/{anime_title}')\n if req.status_code == 200 or req.status_code == 400:\n await message.reply(req.json()['msg'])\n else:\n print(req.json())\n\n\n@dp.message_handler(commands=['list'])\nasync def send_list(message: types.Message):\n TEXT = \"\"\n lists = get_list()\n for list_ in lists:\n TEXT += f\"\\n {list_}\"\n await message.answer(TEXT)\n\n@dp.message_handler(commands=['order'])\nasync def send_watch_order(message: types.Message):\n anime_title = message.text[7:]\n anime_title = anime_title.lower()\n\n if anime_title is None:\n await message.reply(\"That's not quite right!! \\n To get order of a specific anime enter /order \")\n else:\n res = await get_order(anime_title)\n \n if res is None or len(res) == 0:\n await message.reply(\"Can't find the anime :( try alternative titles\")\n else:\n rkm = InlineKeyboardMarkup(row_wigth=1)\n rkm.add(InlineKeyboardButton(\"More..\", \"https://www.reddit.com/r/anime/wiki/watch_order/\"))\n await message.answer(res[0]['order'], parse_mode=\"MARKDOWN\", reply_markup=rkm)\n\n\n@dp.message_handler()\nasync def echo(message: types.Message):\n await message.answer(\"Read instructions using /help mf\")\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)","repo_name":"Besufikad17/Chumon","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"10284115986","text":"from selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\nimport time\n\nclass SearchTest:\n\n def __init__(self):\n self.navegador = webdriver.Chrome(service=Service(ChromeDriverManager().install()))\n\n def check_response(self):\n try:\n self.navegador.get('https://dev.portaldeempregos.contmatic.com.br/')\n except:\n WebDriverException\n return False\n return True\n\n def handle_response(self):\n while not self.check_response():\n print('Você precisa estar conectado á rede da Contmatic para continuar.')\n print('Pressione Y para tentar novamente.')\n user_input = input()\n if user_input == 'Y':\n self.check_response()\n\n self.navegador.find_element(By.XPATH, \"/html/body/section/div/form/button\").click()\n\n\nsearchTest = SearchTest()\nsearchTest.check_response()\nsearchTest.handle_response()","repo_name":"evertonos2312/cont_bot_pcdz","sub_path":"bot_search_home.py","file_name":"bot_search_home.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14351401459","text":"\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\nimport bisect\nimport re\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 3:\n(080) is the area code for fixed line telephones in Bangalore.\nFixed line numbers include parentheses, so Bangalore numbers\nhave the form (080)xxxxxxx.)\n\nPart A: Find all of the area codes and mobile prefixes called by people\nin Bangalore.\n - Fixed lines start with an area code enclosed in brackets. The area\n codes vary in length but always begin with 0.\n - Mobile numbers have no parentheses, but have a space in the middle\n of the number to help readability. The prefix of a mobile number\n is its first four digits, and they always start with 7, 8 or 9.\n - Telemarketers' numbers have no parentheses or space, but they start\n with the area code 140.\n\nPrint the answer as part of a message:\n\"The numbers called by people in Bangalore have codes:\"\n \nThe list of codes should be print out one per line in lexicographic order with no duplicates.\n\nPart B: What percentage of calls from fixed lines in Bangalore are made\nto fixed lines also in Bangalore? In other words, of all the calls made\nfrom a number starting with \"(080)\", what percentage of these calls\nwere made to a number also starting with \"(080)\"?\n\nPrint the answer as a part of a message::\n\" percent of calls from fixed lines in Bangalore are calls\nto other fixed lines in Bangalore.\"\nThe percentage should have 2 decimal digits\n\"\"\"\n\n\n# part A\ndef is_bangalore_number(number):\n return True if number.startswith('(080)') else False\n\ndef extract_code(number):\n # print(number)\n match = re.search('^\\((\\d+)\\)',number)\n if match:\n return match.group(1)\n return number[:4]\n\ncalled_area_codes = []\ntotal_called = 0\ntotal_local_calls = 0\n\nfor call in calls: #65\n if is_bangalore_number(call[0]):\n # print(call[0],call[1])\n total_called += 1\n area_code = extract_code(call[1])\n if area_code == \"080\":\n total_local_calls += 1\n if not area_code in called_area_codes:\n called_area_codes.append(area_code) #73\n\nprint(\"The numbers called by people in Bangalore have codes:\")\nfor area_code in sorted(called_area_codes): # 76\n print(area_code)\n\n# part B\nprint(\"{0:.2f} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.\".format((total_local_calls/total_called) * 100))\n\n\n\"\"\"\nBig O Analysis for part A: O(n log n), where n is the size of calls list. \n\nExplanation:\nTime complexity to compute numbers called from fixed lines in Bangalore: O(n).\nThe amount of work done in functions is_bangalore_number() and extract_code()\nis rougly constant and is equal to O(1), \n\nThe worst case time (amortized) complexity of adding a area_code to \n'called_area_codes' list on line 73 is O(x), where x is the size of area_code\nlist. In the worst case, x could be same as n (size of the calls list); if,\nevery number is called by Bangalore area code. \n\nThe time complexity of line #76 is time to sort the called_area_codes list that\nis assumed to be O(n log n). \n\nTherefore, the total worst case time complexity of part A is: 1) time to add\narea coded to the called_area_codes list, 2) time to sort the called_area_codes\nlist. The total time complexity then is: O(n + n log n). That is asymptotically\nequal to O(n log n).\n\nfor the part b, assuming the format call, multiplicaton and division takes a \nconstant amout of time; the time complexity is O(1).\n\"\"\"\n","repo_name":"dkhroad/dsa","sub_path":"Task3.py","file_name":"Task3.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1898121776","text":"\"\"\"\nhttps://towardsdatascience.com/why-you-should-wrap-decorators-in-python-5ac3676835f9\n\nThe Problems of simple decorator\nDuring a debugging process, we sometimes need to inspect particular objects to understand the implementation details\nbetter. :\nand problem - info will be returned about decorated func and not original one\nprint(say_hello) # .inner_func at 0x1115d6160>\nhelp(say_hello) Help on function inner_func in module __main__: it’s showing the information about the inner function\nsay_hello.__doc__ # will return Inner function within the invocation_log\n\nIn addition, sometimes we want to save our code using serializers, such as the pickle module in the standard library.\nHowever, we can’t serialize the decorated function as its present form, because the module can’t serialize the\nlocal object which is in the scope of the decorator function\n\nprint(pickle.dumps(say_hello)) # AttributeError: Can't pickle local object 'invocation_log..inner_func'\n\nThe Solution\nwe can take advantage of the wraps function in the functools module in the standard library\nwraps function is a decorator itself, and we’ll use this function to decorate the inner function by configuring\nthe to-be-decorated function\n@wraps(func) # It’s just one line of code\n Let’s see how things are changed after this seemingly trivial change\n\"\"\"\nimport inspect\nimport pickle\nfrom functools import wraps\n\n\ndef invocation_log(func):\n @wraps(func) # It’s just one line of code\n def inner_func(*args, **kwargs):\n \"\"\"Inner function within the invocation_log\"\"\"\n print(f'Before Calling {func.__name__}')\n func(*args, **kwargs)\n print(f'After Calling {func.__name__}')\n\n return inner_func\n\n\n@invocation_log\ndef say_hello(name):\n \"\"\"Say hello to someone\"\"\"\n print(f\"Hello, {name}!\")\n\n\ndef check_decorator_wraps(decorated_func):\n print(decorated_func)\n help(decorated_func)\n print(decorated_func.__doc__)\n print(pickle.dumps(decorated_func)) # We’re now able to serialize the function for further processing.\n\n\nif __name__ == '__main__':\n print(inspect.getsource(say_hello)) # @invocation_log def say_hello(name): ..\n say_hello(\"Alex\") # Its decorated function\n check_decorator_wraps(say_hello)\n say_hello_dump = pickle.dumps(say_hello)\n loaded_func = pickle.loads(say_hello_dump)\n print(loaded_func) # # Its actually decorated function!\n loaded_func(\"Boba\")\n","repo_name":"fif911/desing_patterns","sub_path":"code_snippets/14. decorator_wraps.py","file_name":"14. decorator_wraps.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75440982563","text":"class Profesor:\r\n def __init__(self, nombre, materia, curso, division):\r\n self.__nombre = nombre\r\n self.__materia = materia\r\n self.__curso = curso\r\n self.__division = division\r\n\r\n @property\r\n def nombre(self):\r\n return self.__nombre\r\n\r\n @nombre.setter\r\n def nombre(self, nombre):\r\n self.__nombre = nombre\r\n\r\n @property\r\n def materia(self):\r\n return self.__materia\r\n\r\n @materia.setter\r\n def materia(self, materia):\r\n self.__materia = materia\r\n\r\n @property\r\n def curso(self):\r\n return self.__curso\r\n\r\n @curso.setter\r\n def curso(self, curso):\r\n self.__curso = curso\r\n\r\n @property\r\n def division(self):\r\n return self.__division\r\n\r\n @division.setter\r\n def division(self, division):\r\n self.__division = division\r\n\r\n def verNota(self, alumnosBDD):\r\n alumno = alumnosBDD.validarAlumno()\r\n\r\n if alumno:\r\n print(f\"Alumno: {alumno.nombre} - Calificacion: {alumno.nota}\")\r\n\r\n def cargarNota(self, alumnosBDD):\r\n alumno = alumnosBDD.validarAlumno()\r\n\r\n if alumno:\r\n while True:\r\n if alumno.nota == -1:\r\n try:\r\n nuevaNota = int(input(\"2. Ingrese la calificacion del Alumno: \"))\r\n if 0 <= nuevaNota <= 10:\r\n alumno.nota = nuevaNota\r\n alumnosBDD.actualizarArchivo()\r\n print(\"Nota cargada!\")\r\n return\r\n else:\r\n print(\"La nota ingresada no es valida! (0 a 10)\\n\")\r\n except:\r\n print(\"La nota debe ser un valor numerico!\\n\")\r\n else:\r\n print(\"La nota ya ha sido cargada! seleccione la opcion de modificar nota desde el menu.\")\r\n return\r\n\r\n def modificarNota(self, alumnosBDD):\r\n alumno = alumnosBDD.validarAlumno()\r\n\r\n if alumno:\r\n while True:\r\n if alumno.nota != -1:\r\n try:\r\n nuevaNota = int(input(\"2. Ingrese la calificacion del Alumno: \"))\r\n if 0 <= nuevaNota <= 10:\r\n alumno.nota = nuevaNota\r\n alumnosBDD.actualizarArchivo()\r\n print(\"Nota modificada!\")\r\n return\r\n else:\r\n print(\"La nota ingresada no es valida! (0 a 10)\\n\")\r\n except:\r\n print(\"La nota debe ser un valor numerico!\\n\")\r\n else:\r\n print(\"La nota aun no se ha cargado, debe ser cargada antes de ser modificada.\")\r\n return\r\n\r\n def eliminarNota(self, alumnosBDD):\r\n alumno = alumnosBDD.validarAlumno()\r\n\r\n if alumno:\r\n if alumno.nota != -1:\r\n alumno.nota = -1\r\n alumnosBDD.actualizarArchivo()\r\n print(\"Se ha eliminado la nota del alumno.\")\r\n return\r\n else:\r\n print(\"La nota ya se encontraba sin cargar.\")\r\n return\r\n","repo_name":"ernzxr/UNSL-Desarrollador-Python","sub_path":"Practico de Maquina POO/Profesor.py","file_name":"Profesor.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7819954942","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 15 10:30:52 2022\r\n\r\n@author: Dom Dai\r\n\"\"\"\r\n#xay dung base modul\r\n\r\nimport socket\r\nhost = '127.0.0.1'\r\nport = 9050\r\n\r\ndef create_socket(host,port):\r\n sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n sk.setsockopt(socket.SOL_SOCKET\r\n ,socket.SO_REUSEADDR, 1)\r\n sk.bind((host,port))\r\n sk.listen(10)\r\n return sk\r\ndef recv_msg(sk):\r\n #nhan cho den khi gap null\r\n data = bytearray()\r\n msg = ''\r\n while not msg:\r\n data_p = sk.recv(1024)\r\n if not data_p:\r\n raise ConnectionError()\r\n data = data + data_p\r\n #neu co null\r\n if b'\\0' in data_p:\r\n msg = data.rstrip()\r\n msg = msg.decode('utf-8')\r\n return msg\r\n\r\n#tao message (them ki tu null vao message)\r\ndef create_message(msg):\r\n msg = msg + '\\0'\r\n return msg.encode('utf-8')\r\ndef send_msg(sk,msg):\r\n data = create_message(msg)\r\n sk.sendall(data)","repo_name":"Daiappweb/CodeMang","sub_path":"LTTM/basemodule.py","file_name":"basemodule.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44156469649","text":"#!/usr/bin/env python\n\n## file LHEConverter.py\n# Converts LHE files to a flat NTuple in a .root file\n# Author Michael Eggleston\n\nimport sys, argparse\nfrom ROOT import std,TTree,TFile\nfrom array import array\nimport Event\n\nparser = argparse.ArgumentParser(description=\"Convert LHE files into ROOT NTuples.\")\nparser.add_argument('-i','--input-file',help='name of LHE file to convert',dest='in_file')\nparser.add_argument('-o','--output-file',help='name of .root file in which event data will be stored',dest='out_name')\n\n#All branch variables for the ttree will have m_ attached as a prefix\n\ndef getMetaInfo(meta_evt, line):\n data = []\n #Iterate over the line and skip over empty characters that will show up if multiple spaces exist between data in the LHE file\n for x in range(0,len(line)):\n if line[x] != '':\n data.append(float(line[x]))\n #Check that the list has the right number of data points, else the wrong line was parsed\n if len(data) == 6:\n #One more variable exists between the number of particles and event weight, not sure what it is, omitting from ntuple\n data.pop(1)\n meta_evt.setValues(data)\n else:\n print ('{} data points were found, when 6 were expected! Skipping to next event.'.format(len(data)))\n #TODO: actually force the parser to skip to next event\n\ndef main():\n args = parser.parse_args()\n #Check for an input file\n if len(sys.argv) == 0 or not args.in_file:\n parser.print_help()\n exit(1)\n #If no output file name is given, use the input file as a default, converted to .root format\n out_f_name = args.out_name\n if not args.out_name:\n out_f_name = args.in_file.split('.lhe')[0] + '.root'\n\n m_meta_event = Event.MetaEvent(0,0,0,0,0)\n\n #---------------------------------------------------------\n # Set up arrays for holding event info to be written to branches\n #---------------------------------------------------------\n m_num_particles = array('i',[0])\n m_event_weight = array('f',[0.0])\n m_event_scale = array('f',[0.0])\n m_alpha_em = array('f',[0.0])\n m_alpha_s = array('f',[0.0])\n\n m_pdgid = std.vector('int')()\n m_status = std.vector('int')()\n m_mother1 = std.vector('int')()\n m_mother2 = std.vector('int')()\n m_color1 = std.vector('int')()\n m_color2 = std.vector('int')()\n m_px = std.vector('float')()\n m_py = std.vector('float')()\n m_pz = std.vector('float')()\n m_e = std.vector('float')()\n m_m = std.vector('float')()\n m_tau = std.vector('float')()\n m_spin = std.vector('float')()\n\n #---------------------------------------------------------\n # Set up TTree and branches for storing info\n #---------------------------------------------------------\n out_file = TFile(out_f_name,'recreate')\n my_tree = TTree('mytree','tree of generated events')\n\n my_tree.Branch('numParticles',m_num_particles,'numParticles/I')\n my_tree.Branch('eventWeight',m_event_weight,'eventWeight/F')\n my_tree.Branch('eventScale',m_event_scale,'eventScale/F')\n my_tree.Branch('alphaEM',m_alpha_em,'alphaEM/F')\n my_tree.Branch('alphaS',m_alpha_s,'alphaS/F')\n my_tree.Branch('pdgID',m_pdgid)\n my_tree.Branch('pdgStatus',m_status)\n my_tree.Branch('mother1',m_mother1)\n my_tree.Branch('mother2',m_mother2)\n my_tree.Branch('color1',m_color1)\n my_tree.Branch('color2',m_color2)\n my_tree.Branch('px',m_px)\n my_tree.Branch('py',m_py)\n my_tree.Branch('pz',m_pz)\n my_tree.Branch('E',m_e)\n my_tree.Branch('Mass',m_m)\n my_tree.Branch('Tau',m_tau)\n my_tree.Branch('Spin',m_spin)\n\n #----------------------------------------------------------\n # Begin parsing for info\n #----------------------------------------------------------\n\n #Search for event tags in the file\n with open(args.in_file,'rt') as input_file:\n num_events = 0\n for line in input_file:\n if (line.find(\"\") != -1): num_events += 1\n print('There are {} events in this file.'.format(num_events))\n if num_events < 100: print(\"Because of small number of events, errors will be printed to terminal\")\n input_file.seek(0) #Reset the file iterator to beginning of file\n #TODO: replace this restart to start at the first event in the next iteration\n l_num_events = 0\n l_particle_num = 0\n is_event = False\n is_meta = False\n num_skipped_particles = 0\n print(\"Begin looping over events!\")\n for line in input_file:\n if (line.find(\"\") != -1): #String.find() returns the index at which the argument is found, or -1 if not found\n is_event = True\n is_meta = True\n l_num_events += 1\n continue\n if (line.find(\"\") != -1):\n is_event = False\n is_meta = False #Just in case this never got flipped back somehow\n my_tree.Fill() #Should fill the tree at the end of each event structure!\n #Clear vectors of event info\n m_pdgid.clear()\n m_status.clear()\n m_mother1.clear()\n m_mother2.clear()\n m_color1.clear()\n m_color2.clear()\n m_px.clear()\n m_py.clear()\n m_pz.clear()\n m_e.clear()\n m_m.clear()\n m_tau.clear()\n m_spin.clear()\n l_particle_num = 0\n if is_event and is_meta:\n getMetaInfo(m_meta_event,line.strip().split(' '))\n m_num_particles[0] = m_meta_event.getNumParticles()#num_particles\n m_event_weight[0] = m_meta_event.getEventWeight()#event_weight\n m_event_scale[0] = m_meta_event.getEventScale()#event_scale\n m_alpha_em[0] = m_meta_event.getAlphaEM()#alpha_em\n m_alpha_s[0] = m_meta_event.getAlphaS()#alpha_s\n is_meta = False\n continue\n elif is_event and not is_meta:\n if (line.find(\"<\") != -1) or (line.find(\"#\") != -1):\n continue\n\n l_particle_num += 1\n eventInfo = line.strip().split(' ')\n data = []\n for n in range(0,len(eventInfo)):\n if eventInfo[n] != '':\n data.append(float(eventInfo[n]))\n if len(data) != 13:\n num_skipped_particles += 1\n if (num_events > 100) and (l_num_events%1000 == 0):\n print('Event #{}, particle #{} has mismatched number of data elements! Printing Data:'.format(l_num_events,l_particle_num))\n elif (num_events < 100):\n print('Mismatched number of data elements! Printing data:\\n')\n else:\n m_pdgid.push_back(int(data[0]))\n m_status.push_back(int(data[1]))\n m_mother1.push_back(int(data[2]))\n m_mother2.push_back(int(data[3]))\n m_color1.push_back(int(data[4]))\n m_color2.push_back(int(data[5]))\n m_px.push_back(data[6])\n m_py.push_back(data[7])\n m_pz.push_back(data[8])\n m_e.push_back(data[9])\n m_m.push_back(data[10])\n m_tau.push_back(data[11])\n m_spin.push_back(data[12])\n print('{} particles were skipped for bad formatting.'.format(num_skipped_particles))\n\n out_file.Write()\n out_file.Close()\n print(\"Finished looping over events! All data written to {}.\".format(out_f_name))\n\nif __name__==\"__main__\":\n main()\n","repo_name":"M-Eggleston/LHE_NTuples","sub_path":"LHEConverter.py","file_name":"LHEConverter.py","file_ext":"py","file_size_in_byte":7792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23185296809","text":"from enum import Enum\n\n\nclass Vertragsstatus(str, Enum):\n \"\"\"\n Abbildung einer Statusinformation für Verträge.\n \"\"\"\n\n IN_ARBEIT = \"IN_ARBEIT\"\n UEBERMITTELT = \"UEBERMITTELT\"\n ANGENOMMEN = \"ANGENOMMEN\"\n AKTIV = \"AKTIV\"\n ABGELEHNT = \"ABGELEHNT\"\n WIDERRUFEN = \"WIDERRUFEN\"\n STORNIERT = \"STORNIERT\"\n GEKUENDIGT = \"GEKUENDIGT\"\n BEENDET = \"BEENDET\"\n","repo_name":"Hochfrequenz/intermediate-bo4e-migration-models","sub_path":"src/ibims/bo4e/enum/vertragsstatus.py","file_name":"vertragsstatus.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26448417452","text":"import random\n\nclass Block():\n\n def __init__(self,number):\n self.block_number = number\n self.clear = False\n\n def set_clear(self):\n self.clear = True\n\n def __repr__(self):\n return \"b{}\".format(self.block_number)\n\nclass Tower():\n\n def __init__(self,number):\n self.tower_number = number\n self.block_stack = [Block(self.tower_number+str(i)) for i in range(random.randint(3,5))]\n top_block = Block(self.tower_number+str(len(self.block_stack)+1))\n top_block.set_clear()\n self.block_stack.append(top_block)\n\n def pop_block(self):\n self.block_stack = self.block_stack[:-1]\n N = len(self.block_stack)\n if N:\n self.block_stack[N-1].set_clear()\n\n def get_blocks(self):\n return self.block_stack\n\n def get_top_block(self):\n N = len(self.block_stack)\n return self.block_stack[N-1]\n\n def contains(self,block):\n for b in self.block_stack:\n if block.block_number == b.block_number:\n return True\n return False\n\n def too_high(self):\n if len(self.block_stack) >= 3:\n return True\n return False\n\n def __repr__(self):\n r = \"[\"\n for block in self.get_blocks():\n r += str(block)+\", \"\n return r[:-2]+\"]\"\n\n def __str__(self):\n r = \"[\"\n for block in self.get_blocks():\n r += str(block)+\"_\"\n return r[:-2]+\"]\"\n \nclass Blocks_world():\n\n bk = [\"high_tower(+state,+tower)\",\n \"value(state)\"]\n\n def __init__(self,number=1,start=False):\n if start:\n self.state_number = number\n self.towers = [Tower(str(i+1)) for i in range(random.randint(1,3))]\n self.all_actions = []\n\n def get_all_actions(self):\n self.all_actions = []\n for tower in self.towers:\n for block in tower.get_blocks():\n self.all_actions.append((tower,block))\n\n def goal(self):\n for tower in self.towers:\n if tower.too_high():\n return False\n return True\n\n def getReward(self):\n if self.goal:\n return 100\n return -1\n\n def print_world(self):\n for tower in self.towers:\n print (tower)\n\n def execute_action(self,action):\n self.state_number += 1\n tower = action[0]\n block = action[1]\n if tower.contains(block):\n if block.clear:\n tower.pop_block()\n elif not block.clear:\n return self\n return self\n\n def get_state_facts(self):\n facts = []\n for tower in self.towers:\n if tower.too_high():\n facts.append(\"high_tower(s{},t{})\".format(self.state_number,tower.tower_number))\n return facts\n\n def sample(self,pdf):\n cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf]\n try:\n R = max(i for r in [random.random()] for i,c in cdf if c <= r)\n except ValueError:\n R = random.choice(self.all_actions)\n return R\n\n def execute_random_action(self):\n self.get_all_actions()\n N = len(self.all_actions)\n random_actions = []\n action_potentials = []\n for i in range(N):\n random_action = random.choice(self.all_actions)\n random_actions.append(random_action)\n action_potentials.append(random.randint(1,9))\n action_probabilities = [potential/float(sum(action_potentials)) for potential in action_potentials]\n actions_not_executed = [action for action in self.all_actions if action != random_action]\n probability_distribution_function = zip(random_actions,action_probabilities)\n sampled_action = self.sample(probability_distribution_function)\n new_state = self.execute_action(sampled_action)\n return (new_state,sampled_action,actions_not_executed)\n\n def __str__(self):\n return \"\".join([str(x) for x in self.towers])\n\n'''\nwith open(\"blocks_world_out.txt\",\"a\") as f:\n i = 0\n while i < 2:\n state = Blocks_world(start=True)\n state.print_world()\n f.write(\"start state: \"+str(state.get_state_facts())+\"\\n\")\n while not state.goal():\n f.write(\"=\"*80+\"\\n\")\n state_action_pair = state.execute_random_action()\n state = state_action_pair[0]\n f.write(str(state.get_state_facts())+\"\\n\")\n i += 1\n'''\n","repo_name":"Caithir/Non-parametric-Fitted-Relational-VI","sub_path":"GBFVI/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"4319562848","text":"# -*- coding:utf-8 -*-\n'''\nGiven a 32-bit signed integer, reverse digits of an integer.\n'''\nclass Solution:\n def reverse(self, x):\n if abs(x) < 10:\n return x\n boundary = 2 ** 31\n neg_boundary = -1 * boundary\n res = 0\n flag = 1 if x > 0 else -1\n x = abs(x)\n while x > 0:\n digit = x % 10\n x //= 10\n res = res * 10 + digit\n if res > boundary or res < neg_boundary:\n return 0\n return flag * res\n\ntest = Solution()\nprint(test.reverse(0))","repo_name":"jasminecjc/code-practice-python","sub_path":"Math/Reverse_Integer.py","file_name":"Reverse_Integer.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29885325625","text":"#!/usr/bin/python3\n\n###\n#\n# Power Functions Control Library\n# Interfaces Python to Lego Power Functions using the Single Function commands and LIRCD\n#\n###\n\nimport subprocess\n\nclass legopf:\n\t\"\"\"Control Lego Power Functions via LIRCD\"\"\"\n\n\n\t# Class instantiation\n\tdef __init__(self,channel,output):\n\t\t# Location of the irsend command. This is default and almost certainly fine.\n\t\tself.irsend = '/usr/bin/irsend'\n\t\t# Validate inputs\n\t\t## Channel\n\t\tif channel > 4 or channel < 1:\n\t\t\treturn { 'code': 0, 'message': 'PF channel must be between 1 and 4' }\n\t\t## Output\n\t\tif output not in ('B','R'):\n\t\t\treturn { 'code': 1, 'message': 'PF output must be (B)lue or (R)ed' }\n\t\tself.__channel = channel\n\t\tself.__output = output\n\n\t\t# When initialized, stop so we hvae a consistent state.\n\t\tself.set('BRAKE')\n\t\tself.state = 'BRAKE'\n\n\tdef __del__(self):\n\t\t# When shutting down, send a brake command.\n\t\tself.set('BRAKE')\n\n\tdef set(self,setting):\n\t\t# Where:\n\t\t# Channel = PF remote ID, 1-4\n\t\t# Output = PF Remote Output, either (R)ed or (B)lue\n\t\t# Setting = -7 to 7, or 'Brake'\n\t\t## Setting\n\t\ttry:\n\t\t\tint(setting)\n\t\t\tif int(setting) > 7 or int(setting) < -7:\n\t\t\t\treturn { 'code': 1, 'message': 'PF setting must be an integer between -7 and 7 or \\'BRAKE\\'' }\n\t\texcept:\n\t\t\tif setting != 'BRAKE':\n\t\t\t\treturn { 'code': 1, 'message': 'PF setting must be an integer between -7 and 7 or \\'BRAKE\\'' }\n\n\t\t# Assemble the command code from the channel, output, and setting.\n\t\tcommand_code = str(self.__channel) + self.__output + '_'\n\t\ttry:\n\t\t\t# Positive\n\t\t\tif int(setting) >= 0:\n\t\t\t\tcommand_code = command_code + str(setting)\n\t\t\t# Negative\n\t\t\telse:\n\t\t\t\tcommand_code = command_code + 'M' + str(abs(int(setting)))\n\t\texcept:\n\t\t\t# A word can't be converted to an integer, and we've already validated, so must be braking.\n\t\t\tcommand_code = command_code + 'BRAKE'\n\n\t\tprint('Sending command code: ' + command_code)\n\t\t# Send the command!\n\t\tirsend_completed = subprocess.run([self.irsend,'SEND_ONCE','LEGO_Single_Output',command_code])\n\t\tif irsend_completed.returncode > 0:\n\t\t\treturn { 'code': 1, 'message': 'PF irsend call returned error' }\n\t\telse:\n\t\t\tself.state = setting\n\t\t\treturn { 'code': 0, 'message': 'OK' }\n","repo_name":"chrisgilldc/brickmaster","sub_path":"lib/libpowerfunctions.py","file_name":"libpowerfunctions.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29562587414","text":"#! /usr/bin/env python3\nimport midi\nimport sys\ninfile = sys.argv[1]\npattern = midi.read_midifile(infile)\ntrack = pattern.pop()\nminmidi = 21\nmaxmidi = 108\nmidirange = maxmidi - minmidi\n\ntone = 0\nlength = 0\npause = 0\nvolume = 0\ntempo = 0\nprint(\"Rx RxStd Tx TxStd TxRx\")\nfor e in track:\n if e.name == \"Set Tempo\":\n tempo = e.get_bpm()\n if e.name == \"Note On\":\n tone = e.data[0]\n pause = e.tick\n if tone < 21:\n tone = 21\n volume = e.data[1]\n if e.name == \"Note Off\":\n length = e.tick\n print(f\"{tone} {length} {volume} {pause} {tempo}\")\n","repo_name":"cablelabs/mass","sub_path":"scripts/tostream.py","file_name":"tostream.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13233566582","text":"from __future__ import print_function\n\nimport cStringIO\n\nfrom _devbuild.gen.id_kind_asdl import Id\nfrom _devbuild.gen.option_asdl import option_i\nfrom _devbuild.gen.runtime_asdl import (\n value, value_e, value_t, value__Str, value__MaybeStrArray, value__AssocArray,\n lvalue, lvalue_e, lvalue_t, lvalue__Named, lvalue__Indexed, lvalue__Keyed,\n scope_e, scope_t, hay_node\n)\nfrom _devbuild.gen.syntax_asdl import loc\nfrom _devbuild.gen.types_asdl import opt_group_i\nfrom _devbuild.gen import runtime_asdl # for cell\nfrom asdl import runtime\nfrom core import error\nfrom core.pyerror import e_usage, e_die, log\nfrom core import pyos\nfrom core import pyutil\nfrom core import optview\nfrom core import ui\nfrom frontend import consts\nfrom frontend import match\nfrom mycpp import mylib\nfrom mycpp.mylib import print_stderr, tagswitch, iteritems, NewDict\nfrom osh import split\nfrom pylib import os_path\nfrom pylib import path_stat\n\nimport libc\nimport posix_ as posix\nfrom posix_ import X_OK # translated directly to C macro\n\nfrom typing import Tuple, List, Dict, Optional, Any, cast, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from _devbuild.gen.option_asdl import option_t\n from _devbuild.gen.runtime_asdl import cell, Proc\n from core import alloc\n from osh import sh_expr_eval\n\n\n# This was derived from bash --norc -c 'argv \"$COMP_WORDBREAKS\".\n# Python overwrites this to something Python-specific in Modules/readline.c, so\n# we have to set it back!\n# Used in both core/competion.py and osh/state.py\n_READLINE_DELIMS = ' \\t\\n\"\\'><=;|&(:'\n\nLINE_ZERO = -2 # special value that's not runtime.NO_SPID\n\n\n# flags for SetVar\nSetReadOnly = 1 << 0\nClearReadOnly = 1 << 1\nSetExport = 1 << 2\nClearExport = 1 << 3\nSetNameref = 1 << 4\nClearNameref = 1 << 5\n\n\nclass SearchPath(object):\n \"\"\"For looking up files in $PATH.\"\"\"\n\n def __init__(self, mem):\n # type: (Mem) -> None\n self.mem = mem\n self.cache = {} # type: Dict[str, str]\n\n def Lookup(self, name, exec_required=True):\n # type: (str, bool) -> Optional[str]\n \"\"\"\n Returns the path itself (for relative path), the resolve path, or None.\n \"\"\"\n if '/' in name:\n if path_stat.exists(name):\n return name\n else:\n return None\n\n # TODO: Could cache this computation to avoid allocating every time for all\n # the splitting.\n val = self.mem.GetValue('PATH')\n UP_val = val\n if val.tag_() == value_e.Str:\n val = cast(value__Str, UP_val)\n path_list = val.s.split(':')\n else:\n path_list = [] # treat as empty path\n\n for path_dir in path_list:\n full_path = os_path.join(path_dir, name)\n\n # NOTE: dash and bash only check for EXISTENCE in 'command -v' (and 'type\n # -t'). OSH follows mksh and zsh. Note that we can still get EPERM if\n # the permissions are changed between check and use.\n if exec_required:\n found = posix.access(full_path, X_OK)\n else:\n found = path_stat.exists(full_path) # for 'source'\n\n if found:\n return full_path\n\n return None\n\n def CachedLookup(self, name):\n # type: (str) -> Optional[str]\n if name in self.cache:\n return self.cache[name]\n\n full_path = self.Lookup(name)\n if full_path is not None:\n self.cache[name] = full_path\n return full_path\n\n def MaybeRemoveEntry(self, name):\n # type: (str) -> None\n \"\"\"When the file system changes.\"\"\"\n mylib.dict_erase(self.cache, name)\n\n def ClearCache(self):\n # type: () -> None\n \"\"\"For hash -r.\"\"\"\n self.cache.clear()\n\n def CachedCommands(self):\n # type: () -> List[str]\n return self.cache.values()\n\n\nclass ctx_Source(object):\n \"\"\"For source builtin.\"\"\"\n\n def __init__(self, mem, source_name, argv):\n # type: (Mem, str, List[str]) -> None\n mem.PushSource(source_name, argv)\n self.mem = mem\n self.argv = argv\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self.mem.PopSource(self.argv)\n\n\nclass ctx_Option(object):\n \"\"\"shopt --unset errexit { false } \"\"\"\n def __init__(self, mutable_opts, opt_nums, b):\n # type: (MutableOpts, List[int], bool) -> None\n for opt_num in opt_nums:\n mutable_opts.Push(opt_num, b)\n if opt_num == option_i.errexit:\n mutable_opts.errexit_disabled_spid.append(runtime.NO_SPID) # it wasn't disabled\n\n self.mutable_opts = mutable_opts\n self.opt_nums = opt_nums\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n for opt_num in self.opt_nums: # don't bother to do it in reverse order\n if opt_num == option_i.errexit:\n self.mutable_opts.errexit_disabled_spid.pop()\n self.mutable_opts.Pop(opt_num)\n\n\nclass ctx_AssignBuiltin(object):\n \"\"\"local x=$(false) is disallowed.\"\"\"\n def __init__(self, mutable_opts):\n # type: (MutableOpts) -> None\n self.strict = False\n if mutable_opts.Get(option_i.strict_errexit):\n mutable_opts.Push(option_i.allow_csub_psub, False)\n self.strict = True\n\n self.mutable_opts = mutable_opts\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n if self.strict:\n self.mutable_opts.Pop(option_i.allow_csub_psub)\n\n\nclass ctx_OilExpr(object):\n \"\"\" Command sub must fail in 'mystring' ++ $(false) \"\"\"\n def __init__(self, mutable_opts):\n # type: (MutableOpts) -> None\n mutable_opts.Push(option_i.command_sub_errexit, True)\n self.mutable_opts = mutable_opts\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self.mutable_opts.Pop(option_i.command_sub_errexit)\n\n\nclass ctx_ErrExit(object):\n \"\"\"Manages the errexit setting.\n\n - The user can change it with builtin 'set' at any point in the code.\n - These constructs implicitly disable 'errexit':\n - if / while / until conditions\n - ! (part of pipeline)\n - && ||\n \"\"\"\n def __init__(self, mutable_opts, b, span_id):\n # type: (MutableOpts, bool, int) -> None\n\n # If we're disabling it, we need a span ID. If not, then we should NOT\n # have one.\n assert b == (span_id == runtime.NO_SPID)\n\n mutable_opts.Push(option_i.errexit, b)\n mutable_opts.errexit_disabled_spid.append(span_id)\n\n self.strict = False\n if mutable_opts.Get(option_i.strict_errexit):\n mutable_opts.Push(option_i.allow_csub_psub, False)\n self.strict = True\n\n self.mutable_opts = mutable_opts\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self.mutable_opts.errexit_disabled_spid.pop()\n self.mutable_opts.Pop(option_i.errexit)\n\n if self.strict:\n self.mutable_opts.Pop(option_i.allow_csub_psub)\n\n\nclass ctx_HayNode(object):\n \"\"\" haynode builtin makes new names in the tree visible \"\"\"\n def __init__(self, hay_state, hay_name):\n # type: (Hay, Optional[str]) -> None\n #log('pairs %s', pairs)\n self.hay_state = hay_state\n self.hay_state.Push(hay_name)\n\n def __enter__(self):\n # type: () -> None\n return\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self.hay_state.Pop()\n\n\nclass ctx_HayEval(object):\n \"\"\"\n - Turn on shopt oil:all and _running_hay\n - Disallow recursive 'hay eval'\n - Ensure result is isolated for 'hay eval :result'\n\n More leakage:\n\n External:\n - execute programs (ext_prog)\n - redirect\n - pipelines, subshell, & etc?\n - do you have to put _running_hay() checks everywhere?\n\n Internal:\n\n - state.Mem()\n - should we at least PushTemp()?\n - But then they can do setglobal\n - Option state\n\n - Disallow all builtins except echo/write/printf?\n - maybe could do that at the top level\n - source builtin, read builtin\n - cd / pushd / popd\n - trap -- hm yeah this one is bad\n\n - procs? Not strictly necessary\n - you should be able to define them, but not call the user ...\n\n \"\"\"\n def __init__(self, hay_state, mutable_opts, mem):\n # type: (Hay, MutableOpts, Mem) -> None\n self.hay_state = hay_state\n self.mutable_opts = mutable_opts\n self.mem = mem\n\n if mutable_opts.Get(option_i._running_hay):\n # This blames the right 'hay' location\n e_die(\"Recursive 'hay eval' not allowed\")\n\n for opt_num in consts.OIL_ALL:\n mutable_opts.Push(opt_num, True)\n mutable_opts.Push(option_i._running_hay, True)\n\n self.hay_state.PushEval()\n self.mem.PushTemp()\n\n def __enter__(self):\n # type: () -> None\n return\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n\n self.mem.PopTemp()\n self.hay_state.PopEval()\n\n self.mutable_opts.Pop(option_i._running_hay)\n for opt_num in consts.OIL_ALL:\n self.mutable_opts.Pop(opt_num)\n\n\nclass Hay(object):\n \"\"\"State for DSLs.\"\"\"\n\n def __init__(self):\n # type: () -> None\n self.root_defs = hay_node()\n self.cur_defs = self.root_defs # Same as ClearDefs()\n self.def_stack = [self.root_defs]\n\n node = self._MakeOutputNode()\n self.result_stack = [node] # type: List[Dict[str, Any]]\n self.output = None # type: Dict[str, Any]\n\n def _MakeOutputNode(self):\n # type: () -> Dict[str, Any]\n d = NewDict()\n d['source'] = None \n d['children'] = []\n return d\n\n def PushEval(self):\n # type: () -> None\n\n # remove previous results\n node = self._MakeOutputNode()\n self.result_stack = [node]\n\n self.output = None # remove last reuslt\n\n def PopEval(self):\n # type: () -> None\n\n # Save the result\n self.output = self.result_stack[0]\n\n # Clear results\n node = self._MakeOutputNode()\n self.result_stack = [node]\n\n if mylib.PYTHON: # TODO: hay results should be a value_t tree\n\n def AppendResult(self, d):\n # type: (Dict[str, Any]) -> None\n \"\"\"Called by haynode builtin.\"\"\"\n self.result_stack[-1]['children'].append(d)\n\n def Result(self):\n # type: () -> Dict[str, Any]\n \"\"\" Called by hay eval and eval_hay() \"\"\"\n return self.output\n\n def HayRegister(self):\n # type: () -> Dict[str, Any]\n \"\"\" Called by _hay() function \"\"\"\n return self.result_stack[0]\n\n def Resolve(self, first_word):\n # type: (str) -> bool\n return first_word in self.cur_defs.children\n\n def DefinePath(self, path):\n # type: (List[str]) -> None\n \"\"\"Fill a tree from the given path.\"\"\"\n current = self.root_defs\n for name in path:\n if name not in current.children:\n current.children[name] = hay_node()\n current = current.children[name]\n\n def Reset(self):\n # type: () -> None\n\n # reset definitions\n self.root_defs = hay_node()\n self.cur_defs = self.root_defs\n\n # reset output\n self.PopEval()\n\n def Push(self, hay_name):\n # type: (Optional[str]) -> None\n \"\"\"\n package cppunit { } # pushes a namespace\n haynode package cppunit { } # just assumes every TYPE 'package' is valid\n \"\"\"\n if mylib.PYTHON:\n top = self.result_stack[-1]\n self.result_stack.append(top['children'][-1])\n\n #log('> PUSH')\n if hay_name is None:\n self.def_stack.append(self.cur_defs) # no-op\n else:\n # Caller should ensure this\n assert hay_name in self.cur_defs.children, hay_name\n\n self.cur_defs = self.cur_defs.children[hay_name]\n self.def_stack.append(self.cur_defs)\n\n def Pop(self):\n # type: () -> None\n self.def_stack.pop()\n self.cur_defs = self.def_stack[-1]\n\n if mylib.PYTHON:\n self.result_stack.pop()\n\n\nclass OptHook(object):\n \"\"\"Interface for option hooks.\"\"\"\n\n def __init__(self):\n # type: () -> None\n \"\"\"Empty constructor for mycpp.\"\"\"\n pass\n\n def OnChange(self, opt0_array, opt_name, b):\n # type: (List[bool], str, bool) -> bool\n \"\"\"This method is called whenever an option is changed.\n\n Returns success or failure.\n \"\"\"\n return True\n\n\ndef InitOpts():\n # type: () -> List[bool]\n\n opt0_array = [False] * option_i.ARRAY_SIZE\n for opt_num in consts.DEFAULT_TRUE:\n opt0_array[opt_num] = True\n return opt0_array\n\n\ndef MakeOpts(mem, opt_hook):\n # type: (Mem, OptHook) -> Tuple[optview.Parse, optview.Exec, MutableOpts]\n\n # Unusual representation: opt0_array + opt_stacks. For two features:\n # \n # - POSIX errexit disable semantics\n # - Oil's shopt --set nullglob { ... }\n #\n # We could do it with a single List of stacks. But because shopt --set\n # random_option { ... } is very uncommon, we optimize and store the ZERO\n # element of the stack in a flat array opt0_array (default False), and then\n # the rest in opt_stacks, where the value could be None. By allowing the\n # None value, we save ~50 or so list objects in the common case.\n \n opt0_array = InitOpts()\n # Overrides, including errexit\n no_stack = None # type: List[bool] # for mycpp\n opt_stacks = [no_stack] * option_i.ARRAY_SIZE # type: List[List[bool]]\n\n parse_opts = optview.Parse(opt0_array, opt_stacks)\n exec_opts = optview.Exec(opt0_array, opt_stacks)\n mutable_opts = MutableOpts(mem, opt0_array, opt_stacks, opt_hook)\n\n return parse_opts, exec_opts, mutable_opts\n\n\ndef _SetGroup(opt0_array, opt_nums, b):\n # type: (List[bool], List[int], bool) -> None\n for opt_num in opt_nums:\n b2 = not b if opt_num in consts.DEFAULT_TRUE else b\n opt0_array[opt_num] = b2\n\n\ndef MakeOilOpts():\n # type: () -> optview.Parse\n opt0_array = InitOpts()\n _SetGroup(opt0_array, consts.OIL_ALL, True)\n\n no_stack = None # type: List[bool]\n opt_stacks = [no_stack] * option_i.ARRAY_SIZE # type: List[List[bool]]\n\n parse_opts = optview.Parse(opt0_array, opt_stacks)\n return parse_opts\n\n\ndef _AnyOptionNum(opt_name):\n # type: (str) -> option_t\n opt_num = consts.OptionNum(opt_name)\n if opt_num == 0:\n e_usage('got invalid option %r' % opt_name)\n\n # Note: we relaxed this for Oil so we can do 'shopt --unset errexit' consistently\n #if opt_num not in consts.SHOPT_OPTION_NUMS:\n # e_usage(\"doesn't own option %r (try 'set')\" % opt_name)\n\n return opt_num\n\n\ndef _SetOptionNum(opt_name):\n # type: (str) -> option_t\n opt_num = consts.OptionNum(opt_name)\n if opt_num == 0:\n e_usage('got invalid option %r' % opt_name)\n\n if opt_num not in consts.SET_OPTION_NUMS:\n e_usage(\"invalid option %r (try shopt)\" % opt_name)\n\n return opt_num\n\n\nclass MutableOpts(object):\n\n def __init__(self, mem, opt0_array, opt_stacks, opt_hook):\n # type: (Mem, List[bool], List[List[bool]], OptHook) -> None\n self.mem = mem\n self.opt0_array = opt0_array\n self.opt_stacks = opt_stacks\n self.errexit_disabled_spid = [] # type: List[int]\n\n # Used for 'set -o vi/emacs'\n self.opt_hook = opt_hook\n\n def Init(self):\n # type: () -> None\n\n # This comes after all the 'set' options.\n UP_shellopts = self.mem.GetValue('SHELLOPTS')\n if UP_shellopts.tag_() == value_e.Str: # Always true in Oil, see Init above\n shellopts = cast(value__Str, UP_shellopts)\n self._InitOptionsFromEnv(shellopts.s)\n\n def _InitOptionsFromEnv(self, shellopts):\n # type: (str) -> None\n # e.g. errexit:nounset:pipefail\n lookup = shellopts.split(':')\n for opt_num in consts.SET_OPTION_NUMS:\n name = consts.OptionName(opt_num) \n if name in lookup:\n self._SetOldOption(name, True)\n\n def Push(self, opt_num, b):\n # type: (int, bool) -> None\n overlay = self.opt_stacks[opt_num]\n if overlay is None or len(overlay) == 0:\n self.opt_stacks[opt_num] = [b] # Allocate a new list\n else:\n overlay.append(b)\n\n def Pop(self, opt_num):\n # type: (int) -> bool\n overlay = self.opt_stacks[opt_num]\n assert overlay is not None\n return overlay.pop()\n\n def PushDynamicScope(self, b):\n # type: (bool) -> None\n \"\"\"\n b: False if it's a proc, and True if it's a shell function\n \"\"\"\n # If it's already disabled, keep it disabled\n if not self.Get(option_i.dynamic_scope):\n b = False\n self.Push(option_i.dynamic_scope, b)\n\n def PopDynamicScope(self):\n # type: () -> None\n self.Pop(option_i.dynamic_scope)\n\n def Get(self, opt_num):\n # type: (int) -> bool\n # Like _Getter in core/optview.py\n overlay = self.opt_stacks[opt_num]\n if overlay is None or len(overlay) == 0:\n return self.opt0_array[opt_num]\n else:\n return overlay[-1] # the top value\n\n def _Set(self, opt_num, b):\n # type: (int, bool) -> None\n \"\"\"Used to disable errexit. For bash compatibility in command sub.\"\"\"\n\n # Like _Getter in core/optview.py\n overlay = self.opt_stacks[opt_num]\n if overlay is None or len(overlay) == 0:\n self.opt0_array[opt_num] = b\n else:\n overlay[-1] = b # The top value\n\n def set_interactive(self):\n # type: () -> None\n self._Set(option_i.interactive, True)\n\n def set_redefine_proc(self):\n # type: () -> None\n \"\"\"For interactive shells.\"\"\"\n self._Set(option_i.redefine_proc, True)\n\n def set_redefine_module(self):\n # type: () -> None\n \"\"\"For interactive shells.\"\"\"\n self._Set(option_i.redefine_module, True)\n\n def set_emacs(self):\n # type: () -> None\n self._Set(option_i.emacs, True)\n\n def set_xtrace(self, b):\n # type: (bool) -> None\n self._Set(option_i.xtrace, b)\n\n def _SetArrayByNum(self, opt_num, b):\n # type: (int, bool) -> None\n if (opt_num in consts.PARSE_OPTION_NUMS and\n not self.mem.InGlobalNamespace()):\n e_die('Syntax options must be set at the top level '\n '(outside any function)')\n\n self._Set(opt_num, b)\n\n def SetDeferredErrExit(self, b):\n # type: (bool) -> None\n \"\"\"Set the errexit flag, possibly deferring it.\n\n Implements the unusual POSIX \"defer\" behavior. Callers: set -o errexit,\n shopt -s oil:all, oil:upgrade\n \"\"\"\n #log('Set %s', b)\n\n # Defer it until we pop by setting the BOTTOM OF THE STACK.\n self.opt0_array[option_i.errexit] = b\n\n def DisableErrExit(self):\n # type: () -> None\n \"\"\"Called by core/process.py to implement bash quirks.\"\"\"\n self._Set(option_i.errexit, False)\n\n def ErrExitDisabledSpanId(self):\n # type: () -> int\n \"\"\"If errexit is disabled by POSIX rules, return span ID for construct.\n\n e.g. the spid for 'if' or '&&' etc.\n\n Otherwise return runtime.NO_SPID\n \"\"\"\n # Bug fix: The errexit disabling inherently follows a STACK DISCIPLINE.\n # But we run trap handlers in the MAIN LOOP, which break this. So just\n # declare that it's never disabled in a trap.\n if self.Get(option_i._running_trap):\n return runtime.NO_SPID\n\n if len(self.errexit_disabled_spid) == 0:\n return runtime.NO_SPID\n\n return self.errexit_disabled_spid[-1]\n\n # Old complex logic. It turns out we don't need to detect whether it was\n # actually disabled. These are the \"strict_errexit without errexit\" cases\n # in spec/errexit-oil.\n \"\"\"\n overlay = self.opt_stacks[option_i.errexit]\n # log('overlay %s', overlay)\n # log('errexit_disabled_spid %s', self.errexit_disabled_spid)\n if overlay is None or len(overlay) == 0:\n return runtime.NO_SPID\n else:\n was_on = self.opt0_array[option_i.errexit] or (True in overlay)\n # top of stack == False means it's disabled\n if was_on and not overlay[-1]:\n return self.errexit_disabled_spid[-1]\n else:\n return runtime.NO_SPID\n \"\"\"\n\n def _SetOldOption(self, opt_name, b):\n # type: (str, bool) -> None\n \"\"\"Private version for synchronizing from SHELLOPTS.\"\"\"\n assert '_' not in opt_name\n assert opt_name in consts.SET_OPTION_NAMES\n\n opt_num = consts.OptionNum(opt_name)\n assert opt_num != 0, opt_name\n\n if opt_num == option_i.errexit:\n self.SetDeferredErrExit(b)\n else:\n if opt_num == option_i.verbose and b:\n print_stderr('Warning: set -o verbose not implemented')\n self._SetArrayByNum(opt_num, b)\n\n # note: may FAIL before we get here.\n\n success = self.opt_hook.OnChange(self.opt0_array, opt_name, b)\n\n def SetOldOption(self, opt_name, b):\n # type: (str, bool) -> None\n \"\"\" For set -o, set +o, or shopt -s/-u -o. \"\"\"\n _ = _SetOptionNum(opt_name) # validate it\n self._SetOldOption(opt_name, b)\n\n UP_val = self.mem.GetValue('SHELLOPTS')\n assert UP_val.tag_() == value_e.Str, UP_val\n val = cast(value__Str, UP_val)\n shellopts = val.s\n\n # Now check if SHELLOPTS needs to be updated. It may be exported.\n #\n # NOTE: It might be better to skip rewriting SEHLLOPTS in the common case\n # where it is not used. We could do it lazily upon GET.\n\n # Also, it would be slightly more efficient to update SHELLOPTS if\n # settings were batched, Examples:\n # - set -eu\n # - shopt -s foo bar\n if b:\n if opt_name not in shellopts:\n new_val = value.Str('%s:%s' % (shellopts, opt_name))\n self.mem.InternalSetGlobal('SHELLOPTS', new_val)\n else:\n if opt_name in shellopts:\n names = [n for n in shellopts.split(':') if n != opt_name]\n new_val = value.Str(':'.join(names))\n self.mem.InternalSetGlobal('SHELLOPTS', new_val)\n\n def SetAnyOption(self, opt_name, b):\n # type: (str, bool) -> None\n \"\"\" For shopt -s/-u and sh -O/+O. \"\"\"\n\n # shopt -s all:oil turns on all Oil options, which includes all strict #\n # options\n opt_group = consts.OptionGroupNum(opt_name)\n if opt_group == opt_group_i.OilUpgrade:\n _SetGroup(self.opt0_array, consts.OIL_UPGRADE, b)\n self.SetDeferredErrExit(b) # Special case\n return\n\n if opt_group == opt_group_i.OilAll:\n _SetGroup(self.opt0_array, consts.OIL_ALL, b)\n self.SetDeferredErrExit(b) # Special case\n return\n\n if opt_group == opt_group_i.StrictAll:\n _SetGroup(self.opt0_array, consts.STRICT_ALL, b)\n return\n\n opt_num = _AnyOptionNum(opt_name)\n\n if opt_num == option_i.errexit:\n self.SetDeferredErrExit(b)\n return\n\n self._SetArrayByNum(opt_num, b)\n\n def ShowOptions(self, opt_names):\n # type: (List[str]) -> None\n \"\"\" For 'set -o' and 'shopt -p -o' \"\"\"\n # TODO: Maybe sort them differently?\n\n if len(opt_names) == 0: # if none, supplied, show all\n opt_names = [consts.OptionName(i) for i in consts.SET_OPTION_NUMS]\n\n for opt_name in opt_names:\n opt_num = _SetOptionNum(opt_name)\n b = self.Get(opt_num)\n print('set %so %s' % ('-' if b else '+', opt_name))\n\n def ShowShoptOptions(self, opt_names):\n # type: (List[str]) -> None\n \"\"\" For 'shopt -p' \"\"\"\n\n # Respect option gropus.\n opt_nums = [] # type: List[int]\n for opt_name in opt_names:\n opt_group = consts.OptionGroupNum(opt_name)\n if opt_group == opt_group_i.OilUpgrade:\n opt_nums.extend(consts.OIL_UPGRADE)\n elif opt_group == opt_group_i.OilAll:\n opt_nums.extend(consts.OIL_ALL)\n elif opt_group == opt_group_i.StrictAll:\n opt_nums.extend(consts.STRICT_ALL)\n else:\n index = consts.OptionNum(opt_name)\n # Minor incompatibility with bash: we validate everything before\n # printing.\n if index == 0:\n e_usage('got invalid option %r' % opt_name)\n opt_nums.append(index)\n\n if len(opt_names) == 0:\n # If none supplied, show all>\n # TODO: Should this show 'set' options too?\n opt_nums.extend(consts.VISIBLE_SHOPT_NUMS)\n\n for opt_num in opt_nums:\n b = self.Get(opt_num)\n print('shopt -%s %s' % ('s' if b else 'u', consts.OptionName(opt_num)))\n\n\nclass _ArgFrame(object):\n \"\"\"Stack frame for arguments array.\"\"\"\n\n def __init__(self, argv):\n # type: (List[str]) -> None\n self.argv = argv\n self.num_shifted = 0\n\n def __repr__(self):\n # type: () -> str\n return '<_ArgFrame %s %d at %x>' % (self.argv, self.num_shifted, id(self))\n\n if mylib.PYTHON: # mycpp has problem with dict literal\n def Dump(self):\n # type: () -> Dict[str, Any]\n return {\n 'argv': self.argv,\n 'num_shifted': self.num_shifted,\n }\n\n def GetArgNum(self, arg_num):\n # type: (int) -> value_t\n index = self.num_shifted + arg_num - 1\n if index >= len(self.argv):\n return value.Undef()\n\n return value.Str(self.argv[index])\n\n def GetArgv(self):\n # type: () -> List[str]\n return self.argv[self.num_shifted : ]\n\n def GetNumArgs(self):\n # type: () -> int\n return len(self.argv) - self.num_shifted\n\n def SetArgv(self, argv):\n # type: (List[str]) -> None\n self.argv = argv\n self.num_shifted = 0\n\n\nif mylib.PYTHON:\n def _DumpVarFrame(frame):\n # type: (Dict[str, cell]) -> Any\n \"\"\"Dump the stack frame as reasonably compact and readable JSON.\"\"\"\n\n vars_json = {}\n for name, cell in frame.iteritems():\n cell_json = {} # type: Dict[str, Any]\n\n buf = mylib.BufWriter()\n if cell.exported:\n buf.write('x')\n if cell.readonly:\n buf.write('r')\n flags = buf.getvalue()\n if len(flags):\n cell_json['flags'] = flags\n\n # For compactness, just put the value right in the cell.\n val = None # type: value_t\n with tagswitch(cell.val) as case:\n if case(value_e.Undef):\n cell_json['type'] = 'Undef'\n\n elif case(value_e.Str):\n val = cast(value__Str, cell.val)\n cell_json['type'] = 'Str'\n cell_json['value'] = val.s\n\n elif case(value_e.MaybeStrArray):\n val = cast(value__MaybeStrArray, cell.val)\n cell_json['type'] = 'MaybeStrArray'\n cell_json['value'] = val.strs\n\n elif case(value_e.AssocArray):\n val = cast(value__AssocArray, cell.val)\n cell_json['type'] = 'AssocArray'\n cell_json['value'] = val.d\n\n vars_json[name] = cell_json\n\n return vars_json\n\n\nclass DirStack(object):\n \"\"\"For pushd/popd/dirs.\"\"\"\n def __init__(self):\n # type: () -> None\n self.stack = [] # type: List[str]\n self.Reset() # Invariant: it always has at least ONE entry.\n\n def Reset(self):\n # type: () -> None\n del self.stack[:] \n self.stack.append(posix.getcwd())\n\n def Push(self, entry):\n # type: (str) -> None\n self.stack.append(entry)\n\n def Pop(self):\n # type: () -> Optional[str]\n if len(self.stack) <= 1:\n return None\n self.stack.pop() # remove last\n return self.stack[-1] # return second to last\n\n def Iter(self):\n # type: () -> List[str]\n \"\"\"Iterate in reverse order.\"\"\"\n # mycpp REWRITE:\n #return reversed(self.stack)\n ret = [] # type: List[str]\n ret.extend(self.stack)\n ret.reverse()\n return ret\n\n\n# NOTE: not used!\nif mylib.PYTHON:\n def _FormatStack(var_stack):\n # type: (List[Any]) -> str\n \"\"\"Temporary debugging.\n\n TODO: Turn this into a real JSON dump or something.\n \"\"\"\n f = cStringIO.StringIO()\n for i, entry in enumerate(var_stack):\n f.write('[%d] %s' % (i, entry))\n f.write('\\n')\n return f.getvalue()\n\n\ndef _GetWorkingDir():\n # type: () -> str\n \"\"\"Fallback for pwd and $PWD when there's no 'cd' and no inherited $PWD.\"\"\"\n try:\n return posix.getcwd()\n except OSError as e:\n e_die(\"Can't determine working directory: %s\" % pyutil.strerror(e))\n\n\nclass DebugFrame(object):\n\n def __init__(self, bash_source, func_name, source_name, call_spid, argv_i,\n var_i):\n # type: (Optional[str], Optional[str], Optional[str], int, int, int) -> None\n self.bash_source = bash_source\n\n # ONE of these is set. func_name for 'myproc a b', and source_name for\n # 'source lib.sh'\n self.func_name = func_name\n self.source_name = source_name\n\n self.call_spid = call_spid \n self.argv_i = argv_i\n self.var_i = var_i\n\n\ndef _InitDefaults(mem):\n # type: (Mem) -> None\n\n # Default value; user may unset it.\n # $ echo -n \"$IFS\" | python -c 'import sys;print repr(sys.stdin.read())'\n # ' \\t\\n'\n SetGlobalString(mem, 'IFS', split.DEFAULT_IFS)\n\n # NOTE: Should we put these in a name_map for Oil?\n SetGlobalString(mem, 'UID', str(posix.getuid()))\n SetGlobalString(mem, 'EUID', str(posix.geteuid()))\n SetGlobalString(mem, 'PPID', str(posix.getppid()))\n\n SetGlobalString(mem, 'HOSTNAME', libc.gethostname())\n\n # In bash, this looks like 'linux-gnu', 'linux-musl', etc. Scripts test\n # for 'darwin' and 'freebsd' too. They generally don't like at 'gnu' or\n # 'musl'. We don't have that info, so just make it 'linux'.\n SetGlobalString(mem, 'OSTYPE', pyos.OsType())\n\n # For getopts builtin\n SetGlobalString(mem, 'OPTIND', '1')\n\n # When xtrace_rich is off, this is just like '+ ', the shell default\n SetGlobalString(mem, 'PS4', '${SHX_indent}${SHX_punct}${SHX_pid_str} ')\n\n # bash-completion uses this. Value copied from bash. It doesn't integrate\n # with 'readline' yet.\n SetGlobalString(mem, 'COMP_WORDBREAKS', _READLINE_DELIMS)\n\n # TODO on $HOME: bash sets it if it's a login shell and not in POSIX mode!\n # if (login_shell == 1 && posixly_correct == 0)\n # set_home_var ();\n\n\ndef _InitVarsFromEnv(mem, environ):\n # type: (Mem, Dict[str, str]) -> None\n\n # This is the way dash and bash work -- at startup, they turn everything in\n # 'environ' variable into shell variables. Bash has an export_env\n # variable. Dash has a loop through environ in init.c\n for n, v in iteritems(environ):\n mem.SetValue(lvalue.Named(n), value.Str(v), scope_e.GlobalOnly,\n flags=SetExport)\n\n # If it's not in the environment, initialize it. This makes it easier to\n # update later in MutableOpts.\n\n # TODO: IFS, etc. should follow this pattern. Maybe need a SysCall\n # interface? self.syscall.getcwd() etc.\n\n val = mem.GetValue('SHELLOPTS')\n if val.tag_() == value_e.Undef:\n SetGlobalString(mem, 'SHELLOPTS', '')\n # Now make it readonly\n mem.SetValue(\n lvalue.Named('SHELLOPTS'), None, scope_e.GlobalOnly, flags=SetReadOnly)\n\n # Usually we inherit PWD from the parent shell. When it's not set, we may\n # compute it.\n val = mem.GetValue('PWD')\n if val.tag_() == value_e.Undef:\n SetGlobalString(mem, 'PWD', _GetWorkingDir())\n # Now mark it exported, no matter what. This is one of few variables\n # EXPORTED. bash and dash both do it. (e.g. env -i -- dash -c env)\n mem.SetValue(\n lvalue.Named('PWD'), None, scope_e.GlobalOnly, flags=SetExport)\n\n val = mem.GetValue('PATH')\n if val.tag_() == value_e.Undef:\n # Setting PATH to these two dirs match what zsh and mksh do. bash and dash\n # add {,/usr/,/usr/local}/{bin,sbin}\n SetGlobalString(mem, 'PATH', '/bin:/usr/bin')\n\n\ndef InitMem(mem, environ, version_str):\n # type: (Mem, Dict[str, str], str) -> None\n \"\"\"\n Initialize memory with shell defaults. Other interpreters could have\n different builtin variables.\n \"\"\"\n SetGlobalString(mem, 'OIL_VERSION', version_str)\n _InitDefaults(mem)\n _InitVarsFromEnv(mem, environ)\n\n # MUTABLE GLOBAL that's SEPARATE from $PWD. Used by the 'pwd' builtin, but\n # it can't be modified by users.\n val = mem.GetValue('PWD')\n # should be true since it's exported\n assert val.tag_() == value_e.Str, val\n pwd = cast(value__Str, val).s\n mem.SetPwd(pwd)\n\n\ndef InitInteractive(mem):\n # type: (Mem) -> None\n \"\"\"Initialization that's only done in the interactive/headless shell.\"\"\"\n\n # Same default PS1 as bash\n if mem.GetValue('PS1').tag_() == value_e.Undef:\n SetGlobalString(mem, 'PS1', r'\\s-\\v\\$ ')\n\n\nclass ctx_Call(object):\n \"\"\"For function calls.\"\"\"\n\n def __init__(self, mem, mutable_opts, proc, argv):\n # type: (Mem, MutableOpts, Proc, List[str]) -> None\n mem.PushCall(proc.name, proc.name_spid, argv)\n mutable_opts.PushDynamicScope(proc.dynamic_scope)\n # It may have been disabled with ctx_ErrExit for 'if echo $(false)', but\n # 'if p' should be allowed.\n self.mem = mem\n self.mutable_opts = mutable_opts\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self.mutable_opts.PopDynamicScope()\n self.mem.PopCall()\n\n\nclass ctx_Temp(object):\n \"\"\"For FOO=bar myfunc, etc.\"\"\"\n\n def __init__(self, mem):\n # type: (Mem) -> None\n mem.PushTemp()\n self.mem = mem\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self.mem.PopTemp()\n\n\nclass ctx_Shvar(object):\n \"\"\"For shvar LANG=C _ESCAPER=posix-sh-word _DIALECT=ninja \"\"\"\n\n def __init__(self, mem, pairs):\n # type: (Mem, List[Tuple[str, str]]) -> None\n #log('pairs %s', pairs)\n self.mem = mem\n self.restore = [] # type: List[Tuple[lvalue_t, value_t]]\n self._Push(pairs)\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self._Pop()\n\n # Note: _Push and _Pop are separate methods because the C++ translation\n # doesn't like when they are inline in __init__ and __exit__.\n def _Push(self, pairs):\n # type: (List[Tuple[str, str]]) -> None\n for name, s in pairs:\n lval = lvalue.Named(name) # type: lvalue_t\n # LocalOnly because we are only overwriting the current scope\n old_val = self.mem.GetValue(name, scope_e.LocalOnly)\n self.restore.append((lval, old_val))\n self.mem.SetValue(lval, value.Str(s), scope_e.LocalOnly)\n\n def _Pop(self):\n # type: () -> None\n for lval, old_val in self.restore:\n if old_val.tag_() == value_e.Undef:\n self.mem.Unset(lval, scope_e.LocalOnly)\n else:\n self.mem.SetValue(lval, old_val, scope_e.LocalOnly)\n\n\nclass ctx_Registers(object):\n \"\"\"For $PS1, $PS4, $PROMPT_COMMAND, traps, and headless EVAL.\"\"\"\n\n def __init__(self, mem):\n # type: (Mem) -> None\n\n # Because some prompts rely on the status leaking. See issue #853.\n # PS1 also does.\n last = mem.last_status[-1]\n mem.last_status.append(last)\n mem.try_status.append(0)\n\n # TODO: We should also copy these values! Turn the whole thing into a\n # frame.\n mem.pipe_status.append([])\n mem.process_sub_status.append([])\n\n mem.regex_matches.append([])\n self.mem = mem\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n self.mem.regex_matches.pop()\n self.mem.process_sub_status.pop()\n self.mem.pipe_status.pop()\n self.mem.try_status.pop()\n self.mem.last_status.pop()\n\n\nclass ctx_ThisDir(object):\n \"\"\"For $_this_dir\"\"\"\n\n def __init__(self, mem, filename):\n # type: (Mem, Optional[str]) -> None\n self.do_pop = False\n if filename is not None: # script_name in main() may be -c, etc.\n d = os_path.dirname(os_path.abspath(filename))\n mem.this_dir.append(d)\n self.do_pop = True\n\n self.mem = mem\n\n def __enter__(self):\n # type: () -> None\n pass\n\n def __exit__(self, type, value, traceback):\n # type: (Any, Any, Any) -> None\n if self.do_pop:\n self.mem.this_dir.pop()\n\n\nclass Mem(object):\n \"\"\"For storing variables.\n\n Mem is better than \"Env\" -- Env implies OS stuff.\n\n Callers:\n User code: assigning and evaluating variables, in command context or\n arithmetic context.\n Completion engine: for COMP_WORDS, etc.\n Builtins call it implicitly: read, cd for $PWD, $OLDPWD, etc.\n\n Modules: cmd_eval, word_eval, expr_eval, completion\n \"\"\"\n def __init__(self, dollar0, argv, arena, debug_stack):\n # type: (str, List[str], alloc.Arena, List[DebugFrame]) -> None\n \"\"\"\n Args:\n arena: for computing BASH_SOURCE, etc. Could be factored out\n \"\"\"\n # circular dep initialized out of line\n self.exec_opts = None # type: optview.Exec\n self.unsafe_arith = None # type: sh_expr_eval.UnsafeArith\n\n self.dollar0 = dollar0\n self.argv_stack = [_ArgFrame(argv)]\n frame = NewDict() # type: Dict[str, cell]\n self.var_stack = [frame]\n\n self.arena = arena\n\n # The debug_stack isn't strictly necessary for execution. We use it for\n # crash dumps and for 4 parallel arrays: BASH_SOURCE, FUNCNAME,\n # CALL_SOURCE, and BASH_LINENO.\n self.debug_stack = debug_stack\n\n self.pwd = None # type: Optional[str]\n\n self.current_spid = runtime.NO_SPID\n\n self.line_num = value.Str('')\n\n # Done ONCE on initialization\n self.root_pid = posix.getpid()\n\n # TODO:\n # - These are REGISTERS mutated by user code.\n # - Call it self.reg_stack? with ctx_Registers\n # - push-registers builtin\n self.last_status = [0] # type: List[int] # a stack\n self.try_status = [0] # type: List[int] # a stack\n self.pipe_status = [[]] # type: List[List[int]] # stack\n self.process_sub_status = [[]] # type: List[List[int]] # stack\n\n # A stack but NOT a register?\n self.this_dir = [] # type: List[str]\n\n # 0 is the whole match, 1..n are submatches\n self.regex_matches = [[]] # type: List[List[str]]\n\n self.last_bg_pid = -1 # Uninitialized value mutable public variable\n\n def __repr__(self):\n # type: () -> str\n parts = [] # type: List[str]\n parts.append('')\n return '\\n'.join(parts) + '\\n'\n\n def SetPwd(self, pwd):\n # type: (str) -> None\n \"\"\"Used by builtins.\"\"\"\n self.pwd = pwd\n\n def InGlobalNamespace(self):\n # type: () -> bool\n \"\"\"For checking that syntax options are only used at the top level.\"\"\"\n return len(self.argv_stack) == 1\n\n def Dump(self):\n # type: () -> Tuple[Any, Any, Any]\n \"\"\"Copy state before unwinding the stack.\"\"\"\n if mylib.PYTHON:\n var_stack = [_DumpVarFrame(frame) for frame in self.var_stack]\n argv_stack = [frame.Dump() for frame in self.argv_stack]\n debug_stack = [] # type: List[Dict[str, Any]]\n for frame in self.debug_stack:\n d = {} # type: Dict[str, Any]\n if frame.func_name:\n d['func_called'] = frame.func_name\n elif frame.source_name:\n d['file_sourced'] = frame.source_name\n else:\n pass # It's a frame for FOO=bar? Or the top one?\n\n d['call_spid'] = frame.call_spid\n if frame.call_spid != runtime.NO_SPID: # first frame has this issue\n span = self.arena.GetToken(frame.call_spid)\n line_id = span.line_id\n d['call_source'] = ui.GetLineSourceString(self.arena, line_id)\n d['call_line_num'] = self.arena.GetLineNumber(line_id)\n d['call_line'] = self.arena.GetLine(line_id)\n\n d['argv_frame'] = frame.argv_i\n d['var_frame'] = frame.var_i\n debug_stack.append(d)\n\n return var_stack, argv_stack, debug_stack\n\n raise AssertionError()\n\n def SetCurrentSpanId(self, span_id):\n # type: (int) -> None\n \"\"\"Set the current source location, for BASH_SOURCE, BASH_LINENO, LINENO,\n etc.\n\n It's also set on SimpleCommand, ShAssignment, ((, [[, etc. and used as\n a fallback when e_die() didn't set any location information.\n \"\"\"\n if span_id == runtime.NO_SPID:\n # NOTE: This happened in the osh-runtime benchmark for yash.\n log('Warning: span_id undefined in SetCurrentSpanId')\n\n #import traceback\n #traceback.print_stack()\n return\n self.current_spid = span_id\n\n def CurrentSpanId(self):\n # type: () -> int\n return self.current_spid\n\n #\n # Status Variable Stack (for isolating $PS1 and $PS4)\n #\n\n def LastStatus(self):\n # type: () -> int\n return self.last_status[-1]\n\n def TryStatus(self):\n # type: () -> int\n return self.try_status[-1]\n\n def PipeStatus(self):\n # type: () -> List[int]\n return self.pipe_status[-1]\n\n def SetLastStatus(self, x):\n # type: (int) -> None\n self.last_status[-1] = x\n\n def SetTryStatus(self, x):\n # type: (int) -> None\n self.try_status[-1] = x\n\n def SetPipeStatus(self, x):\n # type: (List[int]) -> None\n self.pipe_status[-1] = x\n\n def SetProcessSubStatus(self, x):\n # type: (List[int]) -> None\n self.process_sub_status[-1] = x\n\n #\n # Call Stack\n #\n\n def PushCall(self, func_name, def_spid, argv):\n # type: (str, int, List[str]) -> None\n \"\"\"For function calls.\"\"\"\n self.argv_stack.append(_ArgFrame(argv))\n frame = NewDict() # type: Dict[str, cell]\n self.var_stack.append(frame)\n\n span = self.arena.GetToken(def_spid)\n source_str = ui.GetLineSourceString(self.arena, span.line_id)\n\n # bash uses this order: top of stack first.\n self._PushDebugStack(source_str, func_name, None)\n\n def PopCall(self):\n # type: () -> None\n self._PopDebugStack()\n self.var_stack.pop()\n self.argv_stack.pop()\n\n def PushSource(self, source_name, argv):\n # type: (str, List[str]) -> None\n \"\"\"For 'source foo.sh 1 2 3.\"\"\"\n if len(argv):\n self.argv_stack.append(_ArgFrame(argv))\n # Match bash's behavior for ${FUNCNAME[@]}. But it would be nicer to add\n # the name of the script here?\n self._PushDebugStack(source_name, None, source_name)\n\n def PopSource(self, argv):\n # type: (List[str]) -> None\n self._PopDebugStack()\n if len(argv):\n self.argv_stack.pop()\n\n def PushTemp(self):\n # type: () -> None\n \"\"\"For the temporary scope in 'FOO=bar BAR=baz echo'.\n\n Also for PS4 evaluation with more variables.\n \"\"\"\n # We don't want the 'read' builtin to write to this frame!\n frame = NewDict() # type: Dict[str, cell]\n self.var_stack.append(frame)\n self._PushDebugStack(None, None, None)\n\n def PopTemp(self):\n # type: () -> None\n self._PopDebugStack()\n self.var_stack.pop()\n\n def TopNamespace(self):\n # type: () -> Dict[str, runtime_asdl.cell]\n \"\"\"For eval_to_dict().\"\"\"\n return self.var_stack[-1]\n\n def _PushDebugStack(self, bash_source, func_name, source_name):\n # type: (Optional[str], Optional[str], Optional[str]) -> None\n # self.current_spid is set before every SimpleCommand, ShAssignment, [[, ((,\n # etc. Function calls and 'source' are both SimpleCommand.\n\n # These integers are handles/pointers, for use in CrashDumper.\n argv_i = len(self.argv_stack) - 1\n var_i = len(self.var_stack) - 1\n\n # The stack is a 5-tuple, where func_name and source_name are optional. If\n # both are unset, then it's a \"temp frame\".\n self.debug_stack.append(\n DebugFrame(bash_source, func_name, source_name, self.current_spid, argv_i, var_i)\n )\n\n def _PopDebugStack(self):\n # type: () -> None\n self.debug_stack.pop()\n\n #\n # Argv\n #\n\n def Shift(self, n):\n # type: (int) -> int\n frame = self.argv_stack[-1]\n num_args = len(frame.argv)\n\n if (frame.num_shifted + n) <= num_args:\n frame.num_shifted += n\n return 0 # success\n else:\n return 1 # silent error\n\n def GetArg0(self):\n # type: () -> value__Str\n \"\"\"Like GetArgNum(0) but with a more specific type.\"\"\"\n return value.Str(self.dollar0)\n\n def GetArgNum(self, arg_num):\n # type: (int) -> value_t\n if arg_num == 0:\n return value.Str(self.dollar0)\n\n return self.argv_stack[-1].GetArgNum(arg_num)\n\n def GetArgv(self):\n # type: () -> List[str]\n \"\"\"For $* and $@.\"\"\"\n return self.argv_stack[-1].GetArgv()\n\n def SetArgv(self, argv):\n # type: (List[str]) -> None\n \"\"\"For set -- 1 2 3.\"\"\"\n # from set -- 1 2 3\n self.argv_stack[-1].SetArgv(argv)\n\n #\n # Special Vars\n #\n\n def GetSpecialVar(self, op_id):\n # type: (int) -> value_t\n if op_id == Id.VSub_Bang: # $!\n n = self.last_bg_pid\n if n == -1:\n return value.Undef() # could be an error\n\n elif op_id == Id.VSub_QMark: # $?\n # External commands need WIFEXITED test. What about subshells?\n n = self.last_status[-1]\n\n elif op_id == Id.VSub_Pound: # $#\n n = self.argv_stack[-1].GetNumArgs()\n\n elif op_id == Id.VSub_Dollar: # $$\n n = self.root_pid\n\n else:\n raise NotImplementedError(op_id)\n\n return value.Str(str(n))\n\n #\n # Named Vars\n #\n\n def _ResolveNameOnly(self, name, which_scopes):\n # type: (str, scope_t) -> Tuple[Optional[cell], Dict[str, cell]]\n \"\"\"Helper for getting and setting variable.\n\n Returns:\n cell: The cell corresponding to looking up 'name' with the given mode, or\n None if it's not found.\n name_map: The name_map it should be set to or deleted from.\n \"\"\"\n if which_scopes == scope_e.Dynamic:\n for i in xrange(len(self.var_stack) - 1, -1, -1):\n name_map = self.var_stack[i]\n if name in name_map:\n cell = name_map[name]\n return cell, name_map\n no_cell = None # type: Optional[runtime_asdl.cell]\n return no_cell, self.var_stack[0] # set in global name_map\n\n if which_scopes == scope_e.LocalOnly:\n name_map = self.var_stack[-1]\n return name_map.get(name), name_map\n\n if which_scopes == scope_e.GlobalOnly:\n name_map = self.var_stack[0]\n return name_map.get(name), name_map\n\n if which_scopes == scope_e.LocalOrGlobal:\n # Local\n name_map = self.var_stack[-1]\n cell = name_map.get(name)\n if cell:\n return cell, name_map\n\n # Global\n name_map = self.var_stack[0]\n return name_map.get(name), name_map\n\n if which_scopes == scope_e.Parent:\n assert len(self.var_stack) >= 2\n name_map = self.var_stack[-2]\n return name_map.get(name), name_map\n\n raise AssertionError()\n\n def _ResolveNameOrRef(self, name, which_scopes, is_setref, ref_trail=None):\n # type: (str, scope_t, bool, Optional[List[str]]) -> Tuple[Optional[cell], Dict[str, cell], str]\n \"\"\"Look up a cell and namespace, but respect the nameref flag.\n\n Resolving namerefs does RECURSIVE calls.\n \"\"\"\n cell, name_map = self._ResolveNameOnly(name, which_scopes)\n\n if cell is None or not cell.nameref:\n if is_setref:\n e_die(\"setref requires a nameref (:out param)\")\n return cell, name_map, name # not a nameref\n\n val = cell.val\n UP_val = val\n with tagswitch(val) as case:\n if case(value_e.Undef):\n # This is 'local -n undef_ref', which is kind of useless, because the\n # more common idiom is 'local -n ref=$1'. Note that you can mutate\n # references themselves with local -n ref=new.\n if self.exec_opts.strict_nameref():\n e_die('nameref %r is undefined' % name)\n else:\n return cell, name_map, name # fallback\n\n elif case(value_e.Str):\n val = cast(value__Str, UP_val)\n new_name = val.s\n\n else:\n # SetValue() protects the invariant that nameref is Undef or Str\n raise AssertionError(val.tag_())\n\n # TODO: Respect eval_unsafe_arith here (issue 881). See how it's done in\n # 'printf -v' with MakeArithParser\n if not match.IsValidVarName(new_name):\n # e.g. '#' or '1' or ''\n if self.exec_opts.strict_nameref():\n e_die('nameref %r contains invalid variable name %r' % (name, new_name))\n else:\n # Bash has this odd behavior of clearing the nameref bit when\n # ref=#invalid#. strict_nameref avoids it.\n cell.nameref = False\n return cell, name_map, name # fallback\n\n # Check for circular namerefs.\n if ref_trail is None:\n ref_trail = [name]\n else:\n if new_name in ref_trail:\n e_die('Circular nameref %s' % ' -> '.join(ref_trail))\n ref_trail.append(new_name)\n\n # 'declare -n' uses dynamic scope. 'setref' uses parent scope to avoid the\n # problem of 2 procs containing the same variable name.\n which_scopes = scope_e.Parent if is_setref else scope_e.Dynamic\n cell, name_map, cell_name = self._ResolveNameOrRef(new_name, which_scopes,\n False, ref_trail=ref_trail)\n return cell, name_map, cell_name\n\n def IsAssocArray(self, name):\n # type: (str) -> bool\n \"\"\"Returns whether a name resolve to a cell with an associative array.\n \n We need to know this to evaluate the index expression properly -- should it\n be coerced to an integer or not?\n \"\"\"\n cell, _, _ = self._ResolveNameOrRef(name, self.ScopesForReading(), False)\n if cell:\n if cell.val.tag_() == value_e.AssocArray: # foo=([key]=value)\n return True\n return False\n\n def SetValue(self, lval, val, which_scopes, flags=0):\n # type: (lvalue_t, value_t, scope_t, int) -> None\n \"\"\"\n Args:\n lval: lvalue\n val: value, or None if only changing flags\n which_scopes:\n Local | Global | Dynamic - for builtins, PWD, etc.\n flags: packed pair (keyword_id, bit mask of set/clear flags)\n\n Note: in bash, PWD=/ changes the directory. But not in dash.\n \"\"\"\n keyword_id = flags >> 8 # opposite of _PackFlags\n is_setref = keyword_id == Id.KW_SetRef\n # STRICTNESS / SANENESS:\n #\n # 1) Don't create arrays automatically, e.g. a[1000]=x\n # 2) Never change types? yeah I think that's a good idea, at least for oil\n # (not sh, for compatibility). set -o strict_types or something. That\n # means arrays have to be initialized with let arr = [], which is fine.\n # This helps with stuff like IFS. It starts off as a string, and assigning\n # it to a list is an error. I guess you will have to turn this no for\n # bash?\n #\n # TODO:\n # - COMPUTED vars can't be set\n # - What about PWD / OLDPWD / UID / EUID ? You can simply make them\n # readonly.\n # - Maybe PARSE $PS1 and $PS4 when they're set, to avoid the error on use?\n # - Other validity: $HOME could be checked for existence\n\n UP_lval = lval\n with tagswitch(lval) as case:\n if case(lvalue_e.Named):\n lval = cast(lvalue__Named, UP_lval)\n assert lval.name is not None\n\n if keyword_id == Id.KW_SetRef:\n # Hidden interpreter var with __ prefix. Matches proc call in\n # osh/cmd_eval.py\n lval.name = '__' + lval.name # Mutating arg lval! Happens to be OK\n\n if flags & SetNameref or flags & ClearNameref:\n # declare -n ref=x # refers to the ref itself\n cell, name_map = self._ResolveNameOnly(lval.name, which_scopes)\n cell_name = lval.name\n else:\n # ref=x # mutates THROUGH the reference\n\n # Note on how to implement declare -n ref='a[42]'\n # 1. Call _ResolveNameOnly()\n # 2. If cell.nameref, call self.unsafe_arith.ParseVarRef() ->\n # braced_var_sub\n # 3. Turn braced_var_sub into an lvalue, and call\n # self.unsafe_arith.SetValue() wrapper with ref_trail\n cell, name_map, cell_name = self._ResolveNameOrRef(lval.name,\n which_scopes,\n is_setref)\n\n if cell:\n # Clear before checking readonly bit.\n # NOTE: Could be cell.flags &= flag_clear_mask \n if flags & ClearExport:\n cell.exported = False\n if flags & ClearReadOnly:\n cell.readonly = False\n if flags & ClearNameref:\n cell.nameref = False\n\n if val is not None: # e.g. declare -rx existing\n # Note: this DYNAMIC check means we can't have 'const' in a loop.\n # But that's true for 'readonly' too, and hoisting it makes more\n # sense anyway.\n if cell.readonly:\n # TODO: error context\n e_die(\"Can't assign to readonly value %r\" % lval.name)\n cell.val = val # CHANGE VAL\n\n # NOTE: Could be cell.flags |= flag_set_mask \n if flags & SetExport:\n cell.exported = True\n if flags & SetReadOnly:\n cell.readonly = True\n if flags & SetNameref:\n cell.nameref = True\n\n else:\n if val is None: # declare -rx nonexistent\n # set -o nounset; local foo; echo $foo # It's still undefined!\n val = value.Undef() # export foo, readonly foo\n\n cell = runtime_asdl.cell(bool(flags & SetExport),\n bool(flags & SetReadOnly),\n bool(flags & SetNameref),\n val)\n name_map[cell_name] = cell\n\n # Maintain invariant that only strings and undefined cells can be\n # exported.\n assert cell.val is not None, cell\n\n if cell.val.tag_() not in (value_e.Undef, value_e.Str):\n if cell.exported:\n e_die(\"Only strings can be exported\") # TODO: error context\n if cell.nameref:\n e_die(\"nameref must be a string\")\n\n elif case(lvalue_e.Indexed):\n lval = cast(lvalue__Indexed, UP_lval)\n assert isinstance(lval.index, int), lval\n\n # There is no syntax 'declare a[x]'\n assert val is not None, val\n\n # TODO: relax this for Oil\n assert val.tag_() == value_e.Str, val\n rval = cast(value__Str, val)\n\n # 'setref' array[index] not implemented here yet\n #if keyword_id == Id.KW_SetRef:\n # lval.name = '__' + lval.name\n\n # TODO: All paths should have this? We can get here by a[x]=1 or\n # (( a[ x ] = 1 )). Maybe we should make them different?\n left_spid = lval.spids[0] if len(lval.spids) else runtime.NO_SPID\n\n # bash/mksh have annoying behavior of letting you do LHS assignment to\n # Undef, which then turns into an INDEXED array. (Undef means that set\n # -o nounset fails.)\n cell, name_map, _ = self._ResolveNameOrRef(lval.name, which_scopes,\n is_setref)\n if not cell:\n self._BindNewArrayWithEntry(name_map, lval, rval, flags)\n return\n\n if cell.readonly:\n e_die(\"Can't assign to readonly array\", loc.Span(left_spid))\n\n UP_cell_val = cell.val\n # undef[0]=y is allowed\n with tagswitch(UP_cell_val) as case2:\n if case2(value_e.Undef):\n self._BindNewArrayWithEntry(name_map, lval, rval, flags)\n return\n\n elif case2(value_e.Str):\n # s=x\n # s[1]=y # invalid\n e_die(\"Can't assign to items in a string\", loc.Span(left_spid))\n\n elif case2(value_e.MaybeStrArray):\n cell_val = cast(value__MaybeStrArray, UP_cell_val)\n strs = cell_val.strs\n\n n = len(strs)\n index = lval.index\n if index < 0: # a[-1]++ computes this twice; could we avoid it?\n index += n\n\n if 0 <= index and index < n:\n strs[index] = rval.s\n else:\n # Fill it in with None. It could look like this:\n # ['1', 2, 3, None, None, '4', None]\n # Then ${#a[@]} counts the entries that are not None.\n #\n # TODO: strict_array for Oil arrays won't auto-fill.\n n = index - len(strs) + 1\n for i in xrange(n):\n strs.append(None)\n strs[lval.index] = rval.s\n return\n\n # This could be an object, eggex object, etc. It won't be\n # AssocArray shouldn because we query IsAssocArray before evaluating\n # sh_lhs_expr. Could conslidate with s[i] case above\n e_die(\"Value of type %s can't be indexed\" % ui.ValType(cell.val),\n loc.Span(left_spid))\n\n\n elif case(lvalue_e.Keyed):\n lval = cast(lvalue__Keyed, UP_lval)\n # There is no syntax 'declare A[\"x\"]'\n assert val is not None, val\n assert val.tag_() == value_e.Str, val\n rval = cast(value__Str, val)\n\n left_spid = lval.spids[0] if len(lval.spids) else runtime.NO_SPID\n\n cell, name_map, _ = self._ResolveNameOrRef(lval.name, which_scopes,\n is_setref)\n if cell.readonly:\n e_die(\"Can't assign to readonly associative array\", loc.Span(left_spid))\n\n # We already looked it up before making the lvalue\n assert cell.val.tag_() == value_e.AssocArray, cell\n cell_val2 = cast(value__AssocArray, cell.val)\n\n cell_val2.d[lval.key] = rval.s\n\n else:\n raise AssertionError(lval.tag_())\n\n def _BindNewArrayWithEntry(self, name_map, lval, val, flags):\n # type: (Dict[str, cell], lvalue__Indexed, value__Str, int) -> None\n \"\"\"Fill 'name_map' with a new indexed array entry.\"\"\"\n no_str = None # type: Optional[str]\n items = [no_str] * lval.index\n items.append(val.s)\n new_value = value.MaybeStrArray(items)\n\n # arrays can't be exported; can't have AssocArray flag\n readonly = bool(flags & SetReadOnly)\n name_map[lval.name] = runtime_asdl.cell(False, readonly, False, new_value)\n\n def InternalSetGlobal(self, name, new_val):\n # type: (str, value_t) -> None\n \"\"\"For setting read-only globals internally.\n\n Args:\n name: string (not Lhs)\n new_val: value\n\n The variable must already exist.\n\n Use case: SHELLOPTS.\n \"\"\"\n cell = self.var_stack[0][name]\n cell.val = new_val\n\n def GetValue(self, name, which_scopes=scope_e.Shopt):\n # type: (str, scope_t) -> value_t\n \"\"\"Used by the WordEvaluator, ArithEvalutor, oil_lang/expr_eval.py, etc.\n\n TODO:\n - Many of these should be value.Int, not value.Str\n - And even later _pipeline_status etc. should be lists of integers, not\n strings\n \"\"\"\n assert isinstance(name, str), name\n\n if which_scopes == scope_e.Shopt:\n which_scopes = self.ScopesForReading()\n #log('which_scopes %s', which_scopes)\n\n # TODO: Optimize this by doing a single hash lookup:\n # COMPUTED_VARS = {'PIPESTATUS': 1, 'FUNCNAME': 1, ...}\n # if name not in COMPUTED_VARS: ...\n\n if name == 'ARGV':\n # TODO:\n # - Reuse the MaybeStrArray?\n # - @@ could be an alias for ARGV (in command mode, but not expr mode)\n return value.MaybeStrArray(self.GetArgv())\n\n # \"Registers\"\n if name == '_status':\n if mylib.PYTHON:\n # TODO: value.Int()\n return value.Obj(self.TryStatus())\n else:\n return value.Undef() # STUB\n\n if name == '_this_dir':\n if len(self.this_dir) == 0:\n # e.g. osh -c '' doesn't have it set\n # Should we give a custom error here?\n # If you're at the interactive shell, 'source mymodule.oil' will still\n # work because 'source' sets it.\n return value.Undef()\n else:\n return value.Str(self.this_dir[-1]) # top of stack\n\n if name in ('PIPESTATUS', '_pipeline_status'):\n pipe_strs = [str(i) for i in self.pipe_status[-1]] # type: List[str]\n return value.MaybeStrArray(pipe_strs)\n\n if name == '_process_sub_status': # Oil naming convention\n # TODO: Shouldn't these be real integers?\n sub_strs = [str(i) for i in self.process_sub_status[-1]] # type: List[str]\n return value.MaybeStrArray(sub_strs)\n\n if name == 'BASH_REMATCH':\n return value.MaybeStrArray(self.regex_matches[-1]) # top of stack\n\n # Do lookup of system globals before looking at user variables. Note: we\n # could optimize this at compile-time like $?. That would break\n # ${!varref}, but it's already broken for $?.\n if name == 'FUNCNAME':\n # bash wants it in reverse order. This is a little inefficient but we're\n # not depending on deque().\n strs = [] # type: List[str]\n for frame in reversed(self.debug_stack):\n if frame.func_name is not None:\n strs.append(frame.func_name)\n if frame.source_name is not None:\n strs.append('source') # bash doesn't tell you the filename.\n # Temp stacks are ignored\n return value.MaybeStrArray(strs) # TODO: Reuse this object too?\n\n # This isn't the call source, it's the source of the function DEFINITION\n # (or the sourced # file itself).\n if name == 'BASH_SOURCE':\n strs = []\n for frame in reversed(self.debug_stack):\n if frame.bash_source is not None:\n strs.append(frame.bash_source)\n return value.MaybeStrArray(strs) # TODO: Reuse this object too?\n\n # This is how bash source SHOULD be defined, but it's not!\n if 0:\n if name == 'CALL_SOURCE':\n strs = []\n for frame in reversed(self.debug_stack):\n # should only happen for the first entry\n if frame.call_spid == runtime.NO_SPID:\n continue\n if frame.call_spid == -2:\n strs.append('-') # Bash does this to line up with main?\n continue\n span = self.arena.GetToken(frame.call_spid)\n source_str = ui.GetLineSourceString(self.arena, span.line_id)\n strs.append(source_str)\n return value.MaybeStrArray(strs) # TODO: Reuse this object too?\n\n if name == 'BASH_LINENO':\n strs = []\n for frame in reversed(self.debug_stack):\n # should only happen for the first entry\n if frame.call_spid == runtime.NO_SPID:\n continue\n if frame.call_spid == LINE_ZERO:\n strs.append('0') # Bash does this to line up with main?\n continue\n span = self.arena.GetToken(frame.call_spid)\n line_num = self.arena.GetLineNumber(span.line_id)\n strs.append(str(line_num))\n return value.MaybeStrArray(strs) # TODO: Reuse this object too?\n\n if name == 'LINENO':\n assert self.current_spid != -1, self.current_spid\n span = self.arena.GetToken(self.current_spid)\n # TODO: maybe use interned GetLineNumStr?\n self.line_num.s = str(self.arena.GetLineNumber(span.line_id))\n return self.line_num\n\n if name == 'BASHPID': # TODO: Oil name for it\n return value.Str(str(posix.getpid()))\n\n # In the case 'declare -n ref='a[42]', the result won't be a cell. Idea to\n # fix this:\n # 1. Call self.unsafe_arith.ParseVarRef() -> braced_var_sub\n # 2. Call self.unsafe_arith.GetNameref(bvs_part), and get a value_t\n # We still need a ref_trail to detect cycles.\n cell, _, _ = self._ResolveNameOrRef(name, which_scopes, False)\n if cell:\n return cell.val\n\n return value.Undef()\n\n def GetCell(self, name, which_scopes=scope_e.Shopt):\n # type: (str, scope_t) -> cell\n \"\"\"Get both the value and flags.\n\n Usages:\n - the 'pp' builtin.\n - declare -p\n - ${x@a}\n - to test of 'TZ' is exported in printf? Why?\n \"\"\"\n if which_scopes == scope_e.Shopt:\n which_scopes = self.ScopesForReading()\n\n cell, _ = self._ResolveNameOnly(name, which_scopes)\n return cell\n\n def Unset(self, lval, which_scopes):\n # type: (lvalue_t, scope_t) -> bool\n \"\"\"\n Returns:\n Whether the cell was found.\n \"\"\"\n # TODO: Refactor lvalue type to avoid this\n UP_lval = lval\n\n with tagswitch(lval) as case:\n if case(lvalue_e.Named): # unset x\n lval = cast(lvalue__Named, UP_lval)\n var_name = lval.name\n elif case(lvalue_e.Indexed): # unset 'a[1]'\n lval = cast(lvalue__Indexed, UP_lval)\n var_name = lval.name\n elif case(lvalue_e.Keyed): # unset 'A[\"K\"]'\n lval = cast(lvalue__Keyed, UP_lval)\n var_name = lval.name\n else:\n raise AssertionError()\n\n if which_scopes == scope_e.Shopt:\n which_scopes = self.ScopesForWriting()\n\n cell, name_map, cell_name = self._ResolveNameOrRef(var_name, which_scopes, False)\n if not cell:\n return False # 'unset' builtin falls back on functions\n if cell.readonly:\n raise error.Runtime(\"Can't unset readonly variable %r\" % var_name)\n\n with tagswitch(lval) as case:\n if case(lvalue_e.Named): # unset x\n # Make variables in higher scopes visible.\n # example: test/spec.sh builtin-vars -r 24 (ble.sh)\n mylib.dict_erase(name_map, cell_name)\n\n # alternative that some shells use:\n # name_map[cell_name].val = value.Undef()\n # cell.exported = False\n\n # This should never happen because we do recursive lookups of namerefs.\n assert not cell.nameref, cell\n\n elif case(lvalue_e.Indexed): # unset 'a[1]'\n lval = cast(lvalue__Indexed, UP_lval)\n # Note: Setting an entry to None and shifting entries are pretty\n # much the same in shell.\n\n val = cell.val\n UP_val = val\n if val.tag_() != value_e.MaybeStrArray:\n raise error.Runtime(\"%r isn't an array\" % var_name)\n\n val = cast(value__MaybeStrArray, UP_val)\n strs = val.strs\n\n n = len(strs)\n last_index = n - 1\n index = lval.index\n if index < 0:\n index += n\n\n if index == last_index:\n # Special case: The array SHORTENS if you unset from the end. You\n # can tell with a+=(3 4)\n strs.pop()\n elif 0 <= index and index < last_index:\n strs[index] = None\n else:\n # If it's not found, it's not an error. In other words, 'unset'\n # ensures that a value doesn't exist, regardless of whether it\n # existed. It's idempotent.\n # (Ousterhout specifically argues that the strict behavior was a\n # mistake for Tcl!)\n pass\n\n elif case(lvalue_e.Keyed): # unset 'A[\"K\"]'\n lval = cast(lvalue__Keyed, UP_lval)\n\n val = cell.val\n UP_val = val\n\n # note: never happens because of mem.IsAssocArray test for lvalue.Keyed\n #if val.tag_() != value_e.AssocArray:\n # raise error.Runtime(\"%r isn't an associative array\" % lval.name)\n\n val = cast(value__AssocArray, UP_val)\n mylib.dict_erase(val.d, lval.key)\n\n else:\n raise AssertionError(lval)\n\n return True\n\n def ScopesForReading(self):\n # type: () -> scope_t\n \"\"\"Read scope.\"\"\"\n return (\n scope_e.Dynamic if self.exec_opts.dynamic_scope() else\n scope_e.LocalOrGlobal\n )\n\n def ScopesForWriting(self):\n # type: () -> scope_t\n \"\"\"Write scope.\"\"\"\n return (\n scope_e.Dynamic if self.exec_opts.dynamic_scope() else\n scope_e.LocalOnly\n )\n\n def ClearFlag(self, name, flag):\n # type: (str, int) -> bool\n \"\"\"Used for export -n.\n\n We don't use SetValue() because even if rval is None, it will make an Undef\n value in a scope.\n \"\"\"\n cell, name_map = self._ResolveNameOnly(name, self.ScopesForReading())\n if cell:\n if flag & ClearExport:\n cell.exported = False\n if flag & ClearNameref:\n cell.nameref = False\n return True\n else:\n return False\n\n def GetExported(self):\n # type: () -> Dict[str, str]\n \"\"\"Get all the variables that are marked exported.\"\"\"\n # TODO: This is run on every SimpleCommand. Should we have a dirty flag?\n # We have to notice these things:\n # - If an exported variable is changed.\n # - If the set of exported variables changes.\n\n exported = {} # type: Dict[str, str]\n # Search from globals up. Names higher on the stack will overwrite names\n # lower on the stack.\n for scope in self.var_stack:\n for name, cell in iteritems(scope):\n # TODO: Disallow exporting at assignment time. If an exported Str is\n # changed to MaybeStrArray, also clear its 'exported' flag.\n if cell.exported and cell.val.tag_() == value_e.Str:\n val = cast(value__Str, cell.val)\n exported[name] = val.s\n return exported\n\n def VarNames(self):\n # type: () -> List[str]\n \"\"\"For internal OSH completion and compgen -A variable.\n\n NOTE: We could also add $? $$ etc.?\n \"\"\"\n ret = [] # type: List[str]\n # Look up the stack, yielding all variables. Bash seems to do this.\n for scope in self.var_stack:\n for name in scope:\n ret.append(name)\n return ret\n\n def VarNamesStartingWith(self, prefix):\n # type: (str) -> List[str]\n \"\"\"For ${!prefix@}\"\"\"\n # Look up the stack, yielding all variables. Bash seems to do this.\n names = [] # type: List[str]\n for scope in self.var_stack:\n for name in scope:\n if name.startswith(prefix):\n names.append(name)\n return names\n\n def GetAllVars(self):\n # type: () -> Dict[str, str]\n \"\"\"Get all variables and their values, for 'set' builtin. \"\"\"\n result = {} # type: Dict[str, str]\n for scope in self.var_stack:\n for name, cell in iteritems(scope):\n # TODO: Show other types?\n val = cell.val\n if val.tag_() == value_e.Str:\n str_val = cast(value__Str, val)\n result[name] = str_val.s\n return result\n\n def GetAllCells(self, which_scopes):\n # type: (scope_t) -> Dict[str, cell]\n \"\"\"Get all variables and their values, for 'set' builtin. \"\"\"\n result = {} # type: Dict[str, cell]\n\n if which_scopes == scope_e.Dynamic:\n scopes = self.var_stack\n elif which_scopes == scope_e.LocalOnly:\n scopes = self.var_stack[-1:]\n elif which_scopes == scope_e.GlobalOnly:\n scopes = self.var_stack[0:1]\n elif which_scopes == scope_e.LocalOrGlobal:\n scopes = [self.var_stack[0]]\n if len(self.var_stack) > 1:\n scopes.append(self.var_stack[-1])\n else:\n raise AssertionError()\n\n for scope in scopes:\n for name, cell in iteritems(scope):\n result[name] = cell\n return result\n\n def IsGlobalScope(self):\n # type: () -> bool\n return len(self.var_stack) == 1\n\n def ClearMatches(self):\n # type: () -> None\n top = self.regex_matches[-1]\n del top[:] # no clear() in Python 2\n\n def SetMatches(self, matches):\n # type: (List[str]) -> None\n self.regex_matches[-1] = matches\n\n def GetMatch(self, i):\n # type: (int) -> Optional[str]\n top = self.regex_matches[-1]\n if i < len(top):\n return top[i]\n else:\n return None\n\n#\n# Wrappers to Set Variables\n#\n\ndef OshLanguageSetValue(mem, lval, val, flags=0):\n # type: (Mem, lvalue_t, value_t, int) -> None\n \"\"\" Like 'setvar' (scope_e.LocalOnly), unless dynamic scope is on.\n \n That is, it respects shopt --unset dynamic_scope.\n\n Used for assignment builtins, (( a = b )), {fd}>out, ${x=}, etc.\n \"\"\"\n which_scopes = mem.ScopesForWriting()\n mem.SetValue(lval, val, which_scopes, flags=flags)\n\n\ndef BuiltinSetValue(mem, lval, val):\n # type: (Mem, lvalue_t, value_t) -> None\n \"\"\"Equivalent of x=$y or setref x = y \n \n Called by BuiltinSetString and BuiltinSetArray\n Used directly by printf -v because it can mutate an array\n \"\"\"\n mem.SetValue(lval, val, mem.ScopesForWriting())\n\n\ndef BuiltinSetString(mem, name, s):\n # type: (Mem, str, str) -> None\n \"\"\"Set a string by looking up the stack.\n\n # Equivalent of:\n proc p(:myref) {\n setref myref = 's'\n }\n\n Used for 'read', 'getopts', completion builtins, etc.\n \"\"\"\n assert isinstance(s, str)\n BuiltinSetValue(mem, lvalue.Named(name), value.Str(s))\n\n\ndef BuiltinSetArray(mem, name, a):\n # type: (Mem, str, List[str]) -> None\n \"\"\"Set an array by looking up the stack.\n\n # Equivalent of:\n proc p(:myref) {\n setref myref = %(a b c)\n }\n\n Used by compadjust, read -a, etc.\n \"\"\"\n assert isinstance(a, list)\n BuiltinSetValue(mem, lvalue.Named(name), value.MaybeStrArray(a))\n\n\ndef SetGlobalString(mem, name, s):\n # type: (Mem, str, str) -> None\n \"\"\"Helper for completion, etc.\"\"\"\n assert isinstance(s, str)\n val = value.Str(s)\n mem.SetValue(lvalue.Named(name), val, scope_e.GlobalOnly)\n\n\ndef SetGlobalArray(mem, name, a):\n # type: (Mem, str, List[str]) -> None\n \"\"\"Used by completion, shell initialization, etc.\"\"\"\n assert isinstance(a, list)\n mem.SetValue(lvalue.Named(name), value.MaybeStrArray(a), scope_e.GlobalOnly)\n\n\ndef ExportGlobalString(mem, name, s):\n # type: (Mem, str, str) -> None\n \"\"\"Helper for completion, $PWD, $OLDPWD, etc.\"\"\"\n assert isinstance(s, str)\n val = value.Str(s)\n mem.SetValue(lvalue.Named(name), val, scope_e.GlobalOnly, flags=SetExport)\n\n#\n# Wrappers to Get Variables\n#\n\ndef GetString(mem, name):\n # type: (Mem, str) -> str\n \"\"\"\n Wrapper around GetValue(). Check that HOME, PWD, OLDPWD, etc. are strings.\n bash doesn't have these errors because ${array} is ${array[0]}.\n\n TODO: We could also check this when you're storing variables?\n \"\"\"\n val = mem.GetValue(name)\n UP_val = val\n with tagswitch(val) as case:\n if case(value_e.Undef):\n raise error.Runtime(\"$%s isn't defined\" % name)\n elif case(value_e.Str):\n return cast(value__Str, UP_val).s\n else:\n # User would have to 'unset HOME' to get rid of exported flag\n raise error.Runtime(\"$%s should be a string\" % name)\n\n\ndef MaybeString(mem, name):\n # type: (Mem, str) -> Optional[str]\n \"\"\"\n Like GetString(), but doesn't throw an exception.\n \"\"\"\n try:\n return GetString(mem, name)\n except error.Runtime:\n return None\n\n\ndef GetInteger(mem, name):\n # type: (Mem, str) -> int\n \"\"\"\n For OPTIND variable used in getopts builtin. TODO: it could be value.Int() ?\n \"\"\"\n val = mem.GetValue(name)\n if val.tag_() != value_e.Str:\n raise error.Runtime(\n '$%s should be a string, got %s' % (name, ui.ValType(val)))\n s = cast(value__Str, val).s\n try:\n i = int(s)\n except ValueError:\n raise error.Runtime(\"$%s doesn't look like an integer, got %r\" % (name, s))\n return i\n","repo_name":"orgTestCodacy11KRepos110MB/repo-3432-oil","sub_path":"core/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":72749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72310710885","text":"def solution(n):\n num = ''\n for i in range(n):\n num += str(i)\n\n return int(num[n])\n\nprint(solution(15))\n\n# n의 범위가 1 <= n <= 100,000,000 이기 때문에 당연히 이렇게 할 경우 런타임에러 또는 효율성에 문제가 발생한다.\n# 그러므로 어떤 자리수인지 특정하여 앞의 숫자들은 제하고 단위 내에서 탐색하는 알고리즘을 구상하자.\n\ndef solution(n):\n num = 0\n i = 1\n\n while num < n: \n num += 10**i - 10**(i-1)\n if num > n:\n num -= 10**i - 10**(i-1)\n break\n i += 1\n\n a, b = divmod((n - num),i)\n result = int(str(10**(i-1) + a)[b])\n\n return result\n\nprint(solution(100000000))\n\n# 기존이 코드는 input으로 1억을 넣으면 1억번의 for문을 동작해야 하지만,\n# 아래와 같은 코드를 작성하면 9번의 동작으로 결과값이 반환된다.","repo_name":"leeminseok8/algorithm","sub_path":"programers/코테/answer1.py","file_name":"answer1.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71104581924","text":"import random\n\ndef rps():\n # List of computer Options\n actions = [\"r\", \"p\", \"s\"]\n\n # Variables for user's and computer's Points\n user_points = 0\n comp_points = 0\n\n # Variable for number of rounds\n rounds = 1\n\n # Introduction - asks user what their name is\n name = input(\"Today we will be playing Rock, Paper, Scissors. What's your name? \")\n print(\"Welcome \" + name + \"! Let's get started!!\")\n\n # While the rounds are less than or equal to 3 the game will be played\n while rounds <= 3:\n # User input to ask what their move is\n user_guess = input(\"Rock, Paper, Scissors! (r, p, s): \")\n\n # Random function to allow the computer to pick a move\n computer_guess = random.choice(actions)\n\n # Adds a round played to the rounds variable\n rounds += 1\n\n # If/Else statement to determine whether the user or computer receives a point\n if user_guess == computer_guess:\n print(\"Oops! We guessed the same move. Lets go again!\")\n rounds -= 1\n continue\n elif user_guess == \"r\" and computer_guess == \"s\":\n user_points += 1\n print(\"Haha! Rock beats Scissors, point for \" + name + \"!\")\n elif user_guess == \"p\" and computer_guess == \"r\":\n user_points += 1\n print(\"Haha! Paper beats Rock, point for \" + name + \"!\")\n elif user_guess == \"s\" and computer_guess == \"p\":\n user_points += 1\n print(\"Haha! Scissors beats Paper, point for \" + name + \"!\")\n elif user_guess == \"s\" and computer_guess == \"r\":\n comp_points += 1\n print(\"Aww... Rock beats Scissors, point for computer!\")\n elif user_guess == \"r\" and computer_guess == \"p\":\n comp_points += 1\n print(\"Aww... Paper beats Rock, point for computer!\")\n elif user_guess == \"p\" and computer_guess == \"s\":\n comp_points += 1\n print(\"Aww... Scissors beats Paper, point for computer!\")\n\n # If/Else statement to determines if the user won or lost \n if user_points > comp_points:\n print(\"YAY! \" + name + \" won with \" + str(user_points) + \" points! The computer had \" + str(comp_points) + \" points.\")\n else:\n print(\"Aww \" + name + \" lost to the computer... we only had \" + str(user_points) + \" points and the computer had \" + str(comp_points) + \" points.\")\n\n # Asks the user if they would like to play again with an If/Else statement\n play = input(\"Want to play again? y/n: \")\n if play == \"y\":\n rps()\n else:\n print(\"We'll play again another time. Bye Bye!\")\n\n# Starts the game\nrps()\n\n\n\n\n# Clear Terminal\n# 1. nano ~/.bash_profile\n# 2. export PS1=\"\\$ \"\n# 3. source ~/.bash_profile\n# Use the source command every time terminal is started, undo changes once complete\n\n\n","repo_name":"aidsemancik/python-rps","sub_path":"rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12981658931","text":"from stores.stores import Store\nimport bs4\nimport requests\n\n\nclass Adorama(Store):\n\n def __init__(self):\n self.storeName = \"Adorama\"\n self.OOS_MSG = \"Temporarily not available\"\n\n def findTitle(self, browser):\n # To do. Not able to find the title\n return super().findTitle(browser)\n\n def checkInventory(self, url, browser):\n super().printUrl(url)\n res = requests.get(url, headers={\"User-Agent\": \"Mozilla/5.0\"})\n browser.get(url)\n # res.raise_for_status()\n # soup = bs4.BeautifulSoup(res.text, \"lxml\")\n soup = bs4.BeautifulSoup(res.text, \"html.parser\")\n # soup.select\n if ((self.OOS_MSG in soup.text) or (\"sold out\" in soup.text)):\n print(self.storeName + \" OOS XXX \")\n return False\n else:\n print(self.storeName + \" *** HAS it\")\n return True\n# elem = soup.select_one('#XBRRT00001B_btn')\n# elem.text == \"\\r\\n Temporarily not available\\r\\n \\r\\n\"\n# noStarchSoup = bs4.BeautifulSoup(res.text, 'html.parser')\n# https://stackoverflow.com/questions/50454896/access-denied-while-scraping-a-website-with-selenium-in-python\n","repo_name":"superzjn/inv_checker","sub_path":"stores/adorama.py","file_name":"adorama.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7469020408","text":"# api methods for navigating/browsing opcua server nodes\nimport backend.globals as gl\nfrom flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for, jsonify\n)\nfrom backend.utils import create_desc_dict\nfrom asyncua import ua\n\n\nbp = Blueprint('browse', __name__, url_prefix='/browse')\n\n\n@bp.route(\"/\", methods=[\"GET\"])\ndef browse():\n return \"browse\"\n\n\n# only for debugging backend without frontend\n# doesn't work if you run this in a docker container,\n# cause default url references localhost.\n@bp.route(\"/temporary_connect\", methods=['GET'])\ndef temporary_connect():\n default_url = \"opc.tcp://localhost:4840/\"\n gl.uaclient.connect(default_url)\n return jsonify(gl.uaclient.connected)\n\n\n@bp.route('/root', methods=['GET'])\ndef root():\n root = gl.uaclient.client.nodes.root\n description = gl.uaclient.get_node_desc(root)\n description = create_desc_dict(description)\n return jsonify(description)\n\n\n@bp.route('/children')\ndef get_children():\n # returns description of all the children of specified node. gives the following child-attributes:\n # nodeid, namespace, displayname, nodeclass\n if not gl.uaclient.connected:\n return 'not connected'\n if 'id' in request.args and 'ns' in request.args:\n id = request.args['id']\n ns = request.args['ns']\n node = gl.uaclient.get_node(f\"ns={ns};i={id}\")\n children = gl.uaclient.get_children(node)\n children = [create_desc_dict(ch) for ch in children]\n return jsonify(children)\n else:\n return \"specify id and ns (namespace)\"\n\n\n@bp.route('/nodes')\ndef get_node_attributes():\n # this method returns specified attributes of the node\n # what attributes do we want? \n attrs = [ua.AttributeIds.BrowseName, ua.AttributeIds.DisplayName, ua.AttributeIds.DataType, ua.AttributeIds.MinimumSamplingInterval, ua.AttributeIds.NodeId, ua.AttributeIds.Value, ua.AttributeIds.NodeClass]\n if 'id' in request.args and 'ns' in request.args:\n id = request.args['id']\n ns = request.args['ns']\n if gl.uaclient.connected:\n node = gl.uaclient.get_node(f\"ns={ns};i={id}\")\n attributes = gl.uaclient.get_all_attributes(node, all=False, attributes=attrs)\n return jsonify(attributes)\n return jsonify(\"client not connected\")\n else:\n return jsonify(\"specify id and ns (namespace)\")\n","repo_name":"Marlazzar/web-opcua-connector","sub_path":"backend/api_browse.py","file_name":"api_browse.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70665497445","text":"import pytest\n\nfrom project.favorites.admin import FavoriteAdmin\n\n\nclass TestAdmin:\n def test_should_validate_static_elements_of_admin_when_it_is_called(self):\n favorite_class = FavoriteAdmin\n list_display = favorite_class.list_display\n search_fields = favorite_class.search_fields\n list_per_page = favorite_class.list_per_page\n list_max_show_all = favorite_class.list_max_show_all\n\n list_display_expected = [\n 'id',\n 'product_id',\n 'created_at',\n 'updated_at',\n ]\n search_fields_expected = [\n 'id',\n 'product_id',\n 'client__id',\n 'client__name'\n ]\n\n pytest.assume(list_display == list_display_expected)\n pytest.assume(search_fields == search_fields_expected)\n pytest.assume(list_per_page == 30)\n pytest.assume(list_max_show_all == 30)\n","repo_name":"duducp/django-drf","sub_path":"src/project/favorites/tests/test_admin.py","file_name":"test_admin.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14764499381","text":"if __name__ == \"__main__\":\n line = input()\n split_line = line.split(\" \")\n n = int(split_line.pop(0))\n m = int(split_line.pop(0))\n print(n, m)\n print(split_line)\n element_matrix = []\n for i in range(n):\n element_row = [int(element) for element in split_line]\n # casting elements from split_line list to an row of the matrix\n element_matrix.append(element_row)\n matrix = [[element_matrix[i][j] * 2 for j in range(m)] for i in range(n)]\n print(matrix)\n","repo_name":"StefBelcev/PythonCourse","sub_path":"exercises/double_matrix.py","file_name":"double_matrix.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5393671870","text":"# -*-coding:utf-8-*-\n\nimport socket\nimport os\nfrom app_project.src.util.app_log import my_log\n\n\n# os.popen() 功能强于os.system() , os.popen() 可以返回回显的内容,以文件描述符返回。\ndef check_port(host, port):\n \"\"\"检查指定端口是否被占用\"\"\"\n logger = my_log()\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n sock.connect((host, port))\n sock.shutdown(2)\n except OSError as msg:\n logger.info(\"port %s is Availible!\" % port)\n # print(msg)\n return True\n else:\n logger.info(\"port %s is Used!\" % port)\n return False\n\n\ndef release_port(port):\n \"\"\"释放指定的端口\"\"\"\n logger = my_log()\n # 查找对应的端口\n cmf_find = \"netstat -ano | findstr %s\" % port\n # 返回执行后的结果\n result = os.popen(cmf_find).read()\n # print(result)\n # 获取端口对应的pid\n if str(port) and \"LISTENING\" in result:\n str_list = result.split()\n pid = str_list[4]\n # 关闭被占用端口的pid\n cmd_kill = \"taskkill -f -pid %s\" % pid\n os.popen(cmd_kill)\n logger.info(\"port %s is release Success!\" % port)\n return True\n else:\n logger.info(\"port %s is release Failed!\" % port)\n return False\n\n\n# Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。\n# 注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。\n# Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串\n\nif __name__ == '__main__':\n host = \"127.0.0.1\"\n port1 = 4723\n port2 = 4725\n check_port(host, port1)\n check_port(host, port2)\n release_port(port1)\n release_port(port2)\n","repo_name":"johnsonliu33/myPythonProject","sub_path":"app_project/src/baseView/appium_port.py","file_name":"appium_port.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38790958074","text":"import numpy as np\n\n#path = \"/mnt/Daten/Documents/allnewmeasurement2017/protonmeasurement/neutron/normal/\"\n\npath=\"/Users/piet/Documents/build-muondetector1/\"\n\ndata0 = np.genfromtxt(path+\"muon_Hits_nt_data_t0.csv\", delimiter=\",\")\ndata1 = np.genfromtxt(path+\"muon_Hits_nt_data_t1.csv\", delimiter=\",\")\ndata2 = np.genfromtxt(path+\"muon_Hits_nt_data_t2.csv\", delimiter=\",\")\ndata3 = np.genfromtxt(path+\"muon_Hits_nt_data_t3.csv\", delimiter=\",\")\nm = np.concatenate((data0, data1, data2, data3))\n\n\nelectrons = m[np.logical_or((m[:, 5] == 1),(m[:,5] == 2))]\nmuons = m[np.logical_or((m[:, 5] == 3),(m[:,5] == 4))]\nprotons = m[m[:,5] == 5]\ngamma = m[m[:,5] == 0]\nneutron = m[m[:,5] == 6]\n\nmuNuc = protons[protons[:,4]== 5]\nphNuc = protons[protons[:,4]== 6]\nprIn = protons[protons[:,4]== 7]\nnIn = protons[protons[:,4]== 8]\ncaptureprot = protons[protons[:,4]== 2]\n\notherprot = protons[np.logical_and((protons[:,4] < 5),(protons[:,4]!=2))]\n\ndecay = electrons[electrons[:, 4] == 1]\ncapture = electrons[electrons[:, 4] == 2]\nbound = electrons[electrons[:, 4] == 3]\nioni = electrons[electrons[:, 4] == 4]\nother = electrons[electrons[:, 4] == 0]\n\nprint(\"Whole data set: \" + str(len(m)))\nprint(\"Electrons: \" + str(len(electrons)))\nprint(\"Muons: \" + str(len(muons)))\nprint(\"Protons: \" + str(len(protons)))\nprint(\"Photons: \" + str(len(gamma)))\n\nnp.savetxt(path+\"decayelectrons.csv\", decay, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"capturedelectrons.csv\", capture, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"muons.csv\", muons, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"muonNuclear.csv\", muNuc, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"photonNuclear.csv\", phNuc, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"protonInelastic.csv\", prIn, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"neutronInelastic.csv\", nIn, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"captureprotons.csv\", captureprot, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"otherprot.csv\", otherprot, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"gamma.csv\", gamma, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"otherelectrons.csv\", other, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"bounddecayelectrons.csv\", bound, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"ionizationelectrons.csv\", ioni, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\nnp.savetxt(path+\"neutron.csv\", neutron, delimiter=\",\", fmt=\"%7.7f\", newline=\"\\n\")\n","repo_name":"pcgrub/muondetector","sub_path":"utils/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28047087318","text":"# credits: https: https://towardsdatascience.com/building-a-convolutional-neural-network-cnn-in-keras-329fbbadc5f5\nfrom keras.datasets import mnist\nfrom tensorflow.python.saved_model import builder as saved_model_builder\nfrom tensorflow.python.saved_model import tag_constants, signature_constants\nimport tensorflow as tf\nfrom keras.callbacks import CSVLogger\nimport datetime\n\n\nfrom keras.utils import to_categorical\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten\n\nclass cnn:\n\n def __init__(self):\n #create model\n self.model = Sequential()\n def design_model(self,hidden_list,width,height,activation_list,kernel_size):\n hidden_list = hidden_list.split()\n activation_list = activation_list.split()\n kernel_size = kernel_size.split()\n\n #add model layers\n self.model.add(Conv2D(int(hidden_list[0]), kernel_size=int(kernel_size[0]), activation=activation_list[0], input_shape=(int(width),int(height),1)))\n for i in range(1,len(hidden_list) - 1):\n self.model.add(Conv2D(int(hidden_list[i]), kernel_size=int(kernel_size[i]), activation=activation_list[i]))\n self.model.add(Flatten())\n self.model.add(Dense(int(hidden_list[-1]), activation=activation_list[-1]))\n\n\n def model_train(self,X_train, y_train, X_test, y_test,epochs,logcsv=\"callback_log.csv\"):\n #train the model\n callback = [CSVLogger(filename=logcsv)]\n self.model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=int(epochs),callbacks=callback)\n\n def model_compile(self,optimizer,loss):\n #compile model using accuracy to measure model performance\n self.model.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])\n\n def model_predict(self):\n\n #predict first 4 images in the test set\n self.model.predict(X_test[:4])\n\n def model_save(self,folder,model_version):\n init_op = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init_op)\n x = self.model.input\n y = self.model.output\n prediction_signature = tf.saved_model.signature_def_utils.predict_signature_def({\"inputs\": x},{\"prediction\": y})\n valid_prediction_signature = tf.saved_model.signature_def_utils.is_valid_signature(prediction_signature)\n if (valid_prediction_signature == False):\n raise ValueError(\"Error: Prediction signature not valid!\")\n suffix = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S\")\n folder = folder + model_version + \"_\" + suffix\n builder = saved_model_builder.SavedModelBuilder(folder)\n #legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')\n builder.add_meta_graph_and_variables(\n sess, [tag_constants.SERVING],\n signature_def_map={\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: prediction_signature,\n },)\n #legacy_init_op=legacy_init_op)\n\n # save model\n builder.save()\n sess.close()\n","repo_name":"rc1208/Keras-without-Keras","sub_path":"tensorflow_serving/model_volume/neural_nets/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"424927055","text":"# -*- coding:utf-8 -*-\n__Author__ = \"KrianJ wj_19\"\n__Time__ = \"2020/3/5 15:41\"\n__doc__ = \"\"\" 将mat转换成二维矩阵\"\"\"\n\nimport numpy as np\nfrom numpy import column_stack, row_stack\nfrom sklearn import preprocessing\nfrom PIL import Image\n\n\ndef dim3to2(data, direction=2):\n \"\"\"\n :param data: 三维矩阵\n :param direction: 解构方向\n :return: 标准化后的二维矩阵\n \"\"\"\n n = data.shape[direction] # 解构三维矩阵方向\n data_ = []\n for page in range(n):\n if direction == 2:\n sample = list(data[:, :, page].flatten())\n elif direction == 1:\n sample = list(data[:, page, :].flatten())\n elif direction == 0:\n sample = list(data[page, :, :].flatten())\n else:\n return None\n data_.append(sample)\n data_ = preprocessing.scale(np.array(data_))\n return data_\n\n\ndef augmentMatrix(A, aug=1, axis=1):\n \"\"\"\n 增广矩阵A\n :param A: 矩阵A\n :param aug: 增广参数\n :param axis: 增广方向,1: 列增广,0:行增广\n :return: 增广矩阵A*\n \"\"\"\n if axis == 1:\n rows = A.shape[0]\n if aug == 1:\n aug_col = np.ones(rows)\n return column_stack((A, aug_col))\n else:\n aug_col = np.array([aug]*rows)\n return column_stack((A, aug_col))\n elif axis == 0:\n cols = A.shape[1]\n if aug == 1:\n aug_col = np.ones(cols)\n return row_stack((A, aug_col))\n else:\n aug_col = np.array([aug]*cols)\n return row_stack((A, aug_col))\n\n\ndef Image2Matrix(img):\n \"\"\"图片转矩阵\"\"\"\n pass\n\n\ndef Matrix2Image(mtx):\n \"\"\"矩阵转图片\"\"\"\n new_im = Image.fromarray(mtx.astype(np.uint8))\n return new_im\n\n\nif __name__ == '__main__':\n from PIL import Image\n # A = np.array(([1,2,3],\n # [4,5,6],\n # [7,8,9]))\n # print(augmentMatrix(A, axis=0))\n path = r'training_set\\handWritingNum\\2\\10.bmp'\n img = np.array(Image.open(path))\n data = dim3to2(img, direction=2)\n print(data.shape)\n\n\n\n","repo_name":"KrianJ/ML_learning","sub_path":"PR/mat2mtx.py","file_name":"mat2mtx.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16501219784","text":"#!/usr/bin/python\nimport os\nimport sys\nimport pprint\n\n#class FSanalytics(object):\nclass FS(object):\n def __init__(self, name):\n self.name = name\n\n def get_files_dir(self, path=None):\n if path is None:\n path = self.name\n files = []\n files = [file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))]\n return files\n\n def get_dirs_dir(self, path=None):\n if path is None:\n path = self.name\n dirs = []\n dirs = [file for file in os.listdir(path) if os.path.isdir(os.path.join(path, file))]\n return dirs\n\n def get_file_stats(self, path=None):\n files = {}\n data = {}\n if path is None:\n path = self.name\n for filename in os.listdir(path):\n filename = os.path.join(path, filename)\n files[filename] = posix2dict(os.stat(filename))\n if os.path.isfile(filename):\n files[filename]['type'] = 'file'\n elif os.path.isdir(filename):\n files[filename]['type'] = 'dir'\n else:\n files[filename]['type'] = ['link']\n \"\"\"\n for root, dirs, files in os.walk(path):\n #import pdb;pdb.set_trace()\n data[root] = {}\n data[root]['dirs'] = dirs\n data[root]['files'] = files\n return data\n \"\"\"\n return files\n\n def get_dir_stats(self, path=None):\n if path is None:\n path = self.name\n parent_d = {}\n for idir in self.get_dirs_dir(path=path):\n idir = os.path.join(path,idir)\n parent_d[idir] = self.get_file_stats(idir)\n return parent_d\n\n def list_files(self, path=None):\n if path is None:\n path = self.name\n for root, dirs, files in os.walk(path):\n level = root.replace(path, '').count(os.sep)\n indent = ' ' * 4 * (level)\n print('{}{}/'.format(indent, os.path.basename(root)))\n subindent = ' ' * 4 * (level + 1)\n for f in files:\n print('{}{}'.format(subindent, f))\n\ndef posix2dict(stats):\n d = {}\n d['st_mode'] = stats.st_mode\n d['st_ino'] = stats.st_ino\n d['st_dev'] = stats.st_dev\n d['st_nlink'] = stats.st_nlink\n d['st_uid'] = stats.st_uid\n d['st_gid'] = stats.st_gid\n d['st_size'] = stats.st_size\n d['st_atime'] = stats.st_atime\n d['st_mtime'] = stats.st_mtime\n d['st_ctime'] = stats.st_ctime\n return d\n\nfs = FS(sys.argv[1])\npprint.pprint(fs.get_file_stats())\n","repo_name":"TejasaVi/miscellaneous","sub_path":"python/fs-walkthrough/fs_walkthrough.py","file_name":"fs_walkthrough.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"790721317","text":"from django.conf.urls.defaults import *\n\nfrom django.views.generic.simple import direct_to_template\n\nfrom django.views.generic.list_detail import object_list\nfrom tagging.views import tagged_object_list\n\nfrom .models import Entry\n\n\nurlpatterns = patterns('main.views',\n\n url(r\"^$\", direct_to_template, {\n \"template\": \"homepage.html\",\n }, name=\"home\"),\n\n url(r'^home$', 'home', name=\"main_user_home\"),\n url(r'^search/?$', 'search', name=\"main_search\"),\n url(r'^t:(?P[^/]+)/?$', \n 'by_tag', dict(username=''), name=\"main_tag\"),\n url(r'^u:(?P[^/]+)/post$', \n 'post', name=\"main_post\"),\n url(r'^u:(?P[^/]+)/?$', \n 'profile', name=\"main_profile\"),\n url(r'^u:(?P[^/]+)/t:(?P[^/]+)/?$', \n 'by_tag', name=\"main_profile_tag\"),\n url(r'^u:(?P[^/]+)/e:(?P[^/]+)/?$', \n 'entry_detail', name=\"main_entry_detail_uuid\"),\n url(r'^u:(?P[^/]+)/(?P[^/]+)/?$', \n 'entry_detail', name=\"main_entry_detail\"),\n\n url(r'^opensearch.xml$', direct_to_template,\n { 'template': 'main/opensearch.xml',\n 'mimetype': 'application/opensearchdescription+xml' },\n name=\"opensearch\"),\n\n# url(r'feeds/(?P[^/]+)/all/', RecentSubmissionsFeed(), \n# name=\"demos_feed_recent\"),\n# url(r'feeds/(?P[^/]+)/featured/', FeaturedSubmissionsFeed(), \n# name=\"demos_feed_featured\"),\n# url(r'feeds/(?P[^/]+)/search/(?P[^/]+)/$', SearchSubmissionsFeed(), \n# name=\"demos_feed_search\"),\n# url(r'feeds/(?P[^/]+)/tag/(?P[^/]+)/$', TagSubmissionsFeed(), \n# name=\"demos_feed_tag\"),\n# url(r'feeds/(?P[^/]+)/profile/(?P[^/]+)/?$', ProfileSubmissionsFeed(), \n# name=\"demos_feed_profile\"),\n \n)\n","repo_name":"lmorchard/interocitor","sub_path":"apps/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"74070840486","text":"#!/usr/bin/env python3\n\nfrom error_handling import proc_error\n\n# Used to convert tokenised process values into a process object\nclass Process:\n # Include additional process attributes for round-robin processes\n def __init__(self, name=None, priority=0, burst=0, arrival=0, turnaround=0):\n\n # attributes also have default values\n self.name = name\n self.priority = int(priority)\n self.burst = int(burst)\n self.arrival = int(arrival) # used in rr\n self.remaining = int(burst) # used in rr, intially the same as the CPU burst\n self.turnaround = int(turnaround)\n\n\n# Converts list of processes with tokenised values into Process objects\ndef process_obj(tasks):\n p_objs = [] # list of process objects will be returned\n\n for i in range(len(tasks)):\n t = tasks[i]\n\n # Pass the process to the error handling and check if it is -1, -2, -3\n if not proc_error(t, i + 1): # pass process in list and line number in file\n # add name, priority and burst given in input\n p_objs.append(Process(t[0], t[1], t[2]))\n\n # ERROR HANDLING -> If we got no valid processes after file processing\n if len(p_objs) == 0:\n exit(\"-> No valid processes to run\") # Exit the program with error message\n\n return p_objs # return list of processes object \n","repo_name":"olojo-99/CPU-Scheduling","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31709107966","text":"import arrow\nimport pytest\nfrom django.urls import reverse\n\nfrom billing.lib.test import json_contains\n\nfrom ..models import Service\n\n\n@pytest.mark.django_db\ndef test_service_period_days():\n service = Service.objects.get(pk=1)\n assert service.period_days == 93\n service.period = 5\n service.save()\n assert service.period_days == 155\n\n\n@pytest.mark.django_db\ndef test_service_period_in_months():\n assert Service.objects.get(pk=2).period_in_months == 12\n Service.objects.filter(pk=2).update(period=3)\n assert Service.objects.get(pk=2).period_in_months == 36\n assert Service.objects.get(pk=1).period_in_months == 3\n\n\n@pytest.mark.django_db\ndef test_service_default_dates():\n service = Service.objects.get(pk=1)\n format = '%d.%m.%Y %H:%I'\n begin = arrow.utcnow()\n end = begin.shift(months=+3)\n\n assert begin.datetime.strftime(\n format) == service.get_default_begin().strftime(format)\n assert end.datetime.strftime(format) == service.get_default_end().strftime(\n format)\n\n\ndef test_services_list_by_user(client):\n response = client.get(reverse('service-list'))\n assert response.status_code == 401\n\n\ndef test_service_list_by_admin(admin_client):\n response = admin_client.get(reverse('service-list'))\n assert response.status_code == 200\n assert len(response.json()['results']) == 4\n json_contains(response, 'Test service three')\n\n\ndef test_service_list_by_admin_ru(admin_client, settings):\n settings.LANGUAGE_CODE = 'ru'\n response = admin_client.get(reverse('service-list'))\n assert response.status_code == 200\n assert len(response.json()['results']) == 4\n json_contains(response, 'Описание тестового сервиса 2')\n\n\ndef test_service_display_by_admin(admin_client):\n response = admin_client.get(reverse('service-detail', args=[1]))\n assert response.status_code == 200\n response_json = response.json()\n assert response_json['title'] == 'Test service one'\n assert response_json['price'] == 12332.00\n\n\ndef test_service_display_by_user(client):\n response = client.get(reverse('service-detail', args=[2]))\n assert response.status_code == 401\n","repo_name":"webmalc/maxibooking-billing-django","sub_path":"finances/test/test_services.py","file_name":"test_services.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"73142723365","text":"import os\nimport torch\nimport numpy as np\nimport random\n\ndef targetToFloat(target):\n # if target == \"positive\":\n # return [0, 0, 1], 2 #[0.0, 0.0, 1.0], 2\n # elif target == \"negative\":\n # return [1, 0, 0], 0 #[1.0, 0.0, 0.0], 0\n # else:\n # return [0, 1, 0], 1 #[0.0, 1.0, 0.0], 1\n if target == \"positive\": #Use Floats for BCELoss, Longs for CrossEntropyLoss\n return [0.0, 0.0, 1.0], 2 \n elif target == \"negative\":\n return [1.0, 0.0, 0.0], 0 \n else:\n return [0.0, 1.0, 0.0], 1 \n \nclass Dictionary(object):\n def __init__(self):\n self.word2idx = {}\n self.idx2word = []\n\n def add_word(self, word):\n if word not in self.word2idx:\n self.idx2word.append(word)\n self.word2idx[word] = len(self.idx2word) - 1\n return self.word2idx[word]\n\n def __len__(self):\n return len(self.idx2word)\n\n\nclass Corpus(object):\n def __init__(self, path):\n self.dictionary = Dictionary()\n self.dictionary.add_word(\"\")\n self.train, self.train_t, self.train_len, self.tweet_len, self.train_weights = self.tokenize_single(os.path.join(path, 'train.txt'))\n self.valid, self.valid_t, self.valid_len, self.tweet_len, self.valid_weights= self.tokenize_single(os.path.join(path, 'valid.txt'))\n self.test, self.test_t, self.test_len, self.tweet_len, self.test_weights = self.tokenize_single(os.path.join(path, 'test.txt'))\n\n def tokenize_single(self, path):\n assert os.path.exists(path)\n \n random.seed(1234)\n\n with open(path, 'r') as f:\n tokens = 0\n tweet_amount = 0\n for line in f:\n target, sentence = line.split(None, 1)\n words = sentence.split()\n tokens += len(words)\n tweet_amount += 1\n for word in words:\n self.dictionary.add_word(word)\n\n tweet_len = tokens // tweet_amount\n\n with open(path, 'r') as f:\n ids = torch.LongTensor(tokens)\n targets = torch.FloatTensor(tokens, 3)\n token = 0\n for line in f:\n target, sentence = line.split(None, 1)\n words = sentence.split()\n for word in words:\n ids[token] = self.dictionary.word2idx[word]\n this_target, _ = targetToFloat(target)\n for j in range(3):\n targets[token][j] = this_target[j]\n token += 1\n \n tot = targets.sum(0)\n weights = tot.sum()/tot\n print(path, \"tweet_len: \", tweet_len, \"tweet_amount \",tweet_amount, \"classes\", tot) \n \n return ids, targets, tweet_amount, tweet_len, weights\n \n \n def shuffle_content(self, epoch):\n l = self.tweet_len\n idx = np.arange(self.train_len)\n np.random.seed(epoch)\n np.random.shuffle(idx)\n new_train = torch.LongTensor(self.train_len * self.tweet_len)\n new_train_t = torch.FloatTensor(self.train_len * self.tweet_len, 3)\n for i in range(self.train_len):\n for n in range(l):\n new_train[l * i + n] = self.train[l * idx[i] + n]\n new_train_t[l * i + n] = self.train_t[l * idx[i] + n]\n self.train = new_train\n self.train_t = new_train_t\n ","repo_name":"davide-belli/twitter-sentiment-analysis","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"11719747651","text":"import json\nfrom Products.ZenRRD.CommandParser import CommandParser\nfrom Products.ZenUtils.Utils import prepId\n\n\nclass serveradmin(CommandParser):\n\n def processResults(self, cmd, result):\n components = dict()\n service = dict()\n caches = dict()\n peers = dict()\n lines = cmd.result.output.splitlines()\n\n # Legacy output\n if not cmd.result.output.startswith('{'):\n output = dict(line.split(' = ') for line in lines)\n for key in output:\n if key.startswith('caching:CacheDetails:'):\n short = key.replace(\n 'caching:CacheDetails:_array_index:',\n ''\n )\n idx = int(short.split(':')[0])\n k = short.split(':')[1]\n v = output.get(key).replace('\"', '')\n if idx not in caches:\n caches[idx] = dict()\n caches[idx].update({k: v})\n elif key.startswith('caching:Peers:'):\n short = key.replace('caching:Peers:_array_index:', '')\n short = short.replace('details:', '')\n if ('capabilities' not in key\n and 'local-network' not in key):\n idx = int(short.split(':')[0])\n k = short.split(':')[1]\n v = output.get(key).replace('\"', '')\n if idx not in peers:\n peers[idx] = dict()\n peers[idx].update({k: v})\n else:\n k = key.split(':')[1]\n service.update({k: output.get(key).replace('\"', '')})\n\n # JSON output\n else:\n for line in lines:\n output = json.loads(line)\n service.update(output.get('result', dict()))\n if 'PackageCountCustom' in output:\n service.update(output)\n\n # Mimic structure of legacy output\n keys = service.get('CacheDetails', dict()).keys()\n for idx in range(0, len(keys)):\n value = service.get('CacheDetails', dict()).get(keys[idx])\n caches[idx] = {\n 'MediaType': keys[idx],\n 'BytesUsed': value,\n }\n if len(keys) - 1 == idx:\n break\n\n peer_count = 0\n for peer in service.get('Peers', list()):\n peers[peer_count] = peer\n peer_count += 1\n for peer in service.get('Parents', list()):\n peers[peer_count] = peer\n peer_count += 1\n\n # Generate missing datapoints\n total_returned = service.get('TotalBytesReturnedToClients', 0)\n total_returned += service.get('TotalBytesReturnedToChildren', 0)\n total_returned += service.get('TotalBytesReturnedToPeers', 0)\n service['TotalBytesReturned'] = total_returned\n total_stored = service.get('TotalBytesStoredFromOrigin', 0)\n total_stored += service.get('TotalBytesStoredFromParents', 0)\n total_stored += service.get('TotalBytesStoredFromPeers', 0)\n service['TotalBytesStored'] = total_stored\n\n # Caching Service\n component_id = prepId('CachingService')\n if component_id not in components:\n components[component_id] = dict()\n\n datapoints = [\n 'CacheFree',\n 'CacheLimit',\n 'CacheUsed',\n 'PackageCountCustom',\n 'PersonalCacheFree',\n 'PersonalCacheLimit',\n 'PersonalCacheUsed',\n 'RegistrationStatus',\n 'TotalBytesDropped',\n 'TotalBytesImported',\n 'TotalBytesReturned',\n 'TotalBytesReturnedToChildren',\n 'TotalBytesReturnedToClients',\n 'TotalBytesReturnedToPeers',\n 'TotalBytesStored',\n 'TotalBytesStoredFromOrigin',\n 'TotalBytesStoredFromParents',\n 'TotalBytesStoredFromPeers',\n ]\n\n for measure in datapoints:\n if measure in service:\n value = int(service[measure])\n components[component_id][measure] = value\n\n # Calculate cache hit ratio\n # TotalBytesReturned & TotalBytesStored are used as Derive/Counter\n # datapoints in Zenoss, and the ratio can't be calculated from the rate\n if ('TotalBytesReturned' in components[component_id]\n and 'TotalBytesStored' in components[component_id]\n and components[component_id]['TotalBytesStored'] > 0):\n returned = components[component_id]['TotalBytesReturned']\n stored = components[component_id]['TotalBytesStored']\n ratio = float(returned) / float(stored)\n components[component_id]['CacheHitRatioCustom'] = ratio\n\n # Fixups for unconfigured Cache Limit and negative Cache Free\n for category in ['Cache', 'PersonalCache']:\n limit = int(service.get(category + 'Limit', 0))\n used = int(service.get(category + 'Used', 0))\n free = int(service.get(category + 'Free', 0))\n if free < 0:\n limit = used if limit == 0 else limit\n avail = limit - used\n # CacheLimit - CacheUsed > space available on disk\n # so CacheFree value is negative\n free = avail + free if avail > 0 else 0\n components[component_id]['DiskExceededCustom'] = 2\n else:\n limit = used + free if limit == 0 else limit\n avail = limit - used\n # Unsure what CacheFree of 10 MB means when there's\n # a 20 GB difference between CacheLimit and CacheUsed\n free = avail if avail > free else free\n components[component_id][category + 'Limit'] = limit\n components[component_id][category + 'Free'] = free\n if 'DiskExceededCustom' not in components[component_id]:\n components[component_id]['DiskExceededCustom'] = 1\n\n # Transform state strings into integers\n # so they can be monitored by a performance template\n attr_map = dict()\n attr_map['CacheStatus'] = {\n 'OK': 1,\n 'LOWSPACE': 2,\n }\n\n attr_map['StartupStatus'] = {\n 'OK': 1,\n 'PENDING': 2,\n 'FAILED': 3,\n 'NO_AUTO_ENABLE': 4,\n }\n\n attr_map['state'] = {\n 'RUNNING': 1,\n 'STARTING': 2,\n 'STOPPED': 3,\n }\n\n attr_map['RegistrationError'] = {\n 'WIRELESS_PORTABLE_NOT_SUPPORTED': 3,\n 'INVALID_IP_RANGE': 4,\n 'PUBLIC_IP_NOT_IN_RANGE': 5,\n 'TOO_MANY_PRIVATE_ADDRESSES': 6,\n 'INVALID_DEVICE': 7,\n 'NOT_ACTIVATED': 8,\n }\n\n attr_map['Active'] = {\n 'no': 0,\n 'yes': 1,\n False: 0,\n True: 1,\n }\n\n for attr in attr_map:\n if attr in service:\n value = attr_map[attr].get(service[attr], -2)\n components[component_id][attr] = value\n\n if 'RegistrationError' not in components[component_id]:\n components[component_id]['RegistrationError'] = 1\n\n # Individual cache\n for idx in caches:\n cache = caches.get(idx)\n component_id = prepId(cache.get('MediaType'))\n if component_id not in components:\n components[component_id] = dict()\n value = int(cache.get('BytesUsed'))\n components[component_id]['BytesUsed'] = value\n\n # Peer server\n health_map = {\n 'no': 0,\n 'yes': 1,\n False: 0,\n True: 1,\n }\n\n for idx in peers:\n peer = peers.get(idx)\n id_str = 'peercache_{0}'.format(\n peer.get('address', peer.get('guid', ''))\n )\n component_id = prepId(id_str)\n if component_id not in components:\n components[component_id] = dict()\n value = health_map.get(peer.get('healthy'), 0)\n components[component_id]['healthy'] = value\n\n for point in cmd.points:\n if point.component in components:\n values = components[point.component]\n if point.id in values:\n result.values.append((point, values[point.id]))\n","repo_name":"daviswr/ZenPacks.daviswr.OSX.Server.Caching","sub_path":"ZenPacks/daviswr/OSX/Server/Caching/parsers/serveradmin.py","file_name":"serveradmin.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"1586428880","text":"# -*- coding: utf-8 -*-\n# python 2.7\n# import the main window object (mw) from ankiqt\nfrom aqt import mw\n# import the \"show info\" tool from utils.py\nfrom aqt.utils import showInfo\n# import all of the Qt GUI library\nfrom aqt.qt import *\nfrom .. import config_parser\n\n# deck_name = u'Words'\n# model_name = u'Default plugin template'\n\n\n#deck_name = u'語彙'\nmodel_name = u'Japanese-eng words'\n\n\ndef get_deck_name(card):\n return card.col.decks.name(card.did)\n\n\ndef get_card(id):\n return mw.col.getCard(id)\n\n\ndef find_cards(search_term):\n return mw.col.findCards(search_term)\n\n\ndef is_card_in_collection(expression, reading):\n ids = find_cards(expression)\n for id in ids:\n card = get_card(id)\n # if get_deck_name(card) == deck_name:\n note = card.note()\n if expression == note.items()[0][1] and reading == note.items()[1][1]:\n return True\n return False\n\n\ndef reset_card_due_stats(card):\n card.queue = 2\n card.type = 2\n card.due = mw.col.sched.today\n card.ivl = 1\n card.factor = 1000\n card.col.sched._updateStats(card, 'rev')\n card.flushSched()\n\n\ndef add_word_card(expression, reading, meaning):\n deck = find_deck()\n model = find_model(deck)\n set_deck_id(model, deck['id'])\n select_model_internally_for_note_creation(model)\n note = make_note()\n add_info_to_note(note, expression, reading, meaning)\n mw.col.addNote(note)\n note.flush()\n\n\ndef find_deck():\n deck = mw.col.decks.byName(config_parser.deck_name)\n if deck is None:\n mw.col.decks.id(config_parser.deck_name)\n deck = mw.col.decks.byName(config_parser.deck_name)\n return deck\n\n\ndef find_model(deck):\n model = mw.col.models.byName(model_name)\n if model is None:\n add_model(model_name, deck['id'])\n model = mw.col.models.byName(model_name)\n return model\n\n\ndef set_deck_id(model, did):\n model['tmpls'][0]['did'] = did\n\n\ndef select_model_internally_for_note_creation(model):\n mw.col.models.setCurrent(model)\n\n\ndef make_note():\n return mw.col.newNote(False)\n\n\ndef add_info_to_note(note, expression, reading, meaning):\n new_card_data = (expression, reading, meaning)\n i = 0\n for (name, value) in note.items():\n if i < 3:\n note[name] = value + new_card_data[i]\n else:\n note[name] = value + \"\"\n i += 1\n\n\ndef add_model(name, id):\n m = mw.col.models.new(name)\n newfield = mw.col.models.newField(\"Expression\")\n newfield2 = mw.col.models.newField(\"Reading\")\n newfield3 = mw.col.models.newField(\"Meaning\")\n mw.col.models.addField(m, newfield)\n mw.col.models.addField(m, newfield2)\n mw.col.models.addField(m, newfield3)\n template = mw.col.models.newTemplate(\"template\")\n template[\n 'qfmt'] = \"{{Expression}}\"\n template[\n 'afmt'] = \"{{FrontSide}}
{{Reading}}
{{Meaning}}

\"\n template['did'] = id\n mw.col.models.addTemplate(m, template)\n mw.col.models.add(m)\n","repo_name":"kamonene/Anki-japanese-dictionary-plugin---WIP","sub_path":"jp_eng_jisho_import/API/anki_api_interface.py","file_name":"anki_api_interface.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14839897386","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404\nfrom django.http import HttpResponseRedirect, Http404, JsonResponse\nfrom django.core.urlresolvers import reverse\n\nfrom django.contrib.auth.decorators import login_required\n\nfrom datetime import datetime\n\nfrom .models import Gallery, GalleryImage, GalleryComment\n\ndef index(request):\n galleries = Gallery.objects.all()\n return render(request, 'gallery/index.html', {'galleries':galleries})\n\ndef gallery(request, gallery_id):\n gallery = get_object_or_404(Gallery, slug=gallery_id)\n images = get_list_or_404(GalleryImage, gallery=gallery)\n return render(request, 'gallery/gallery.html', {'gallery': gallery, 'images': images})\n\ndef image(request, gallery_id, image_id):\n image_id = int(image_id);\n gallery = get_object_or_404(Gallery, slug=gallery_id)\n\n try:\n image = GalleryImage.objects.filter(gallery=gallery)[image_id-1]\n except IndexError:\n raise Http404(\"Image does not exist\")\n\n total_images = GalleryImage.objects.filter(gallery=gallery).count()\n\n if (request.user.is_authenticated()):\n comments = GalleryComment.objects.filter(image=image).exclude(user=request.user).order_by('user', '-date').distinct('user')\n try:\n user_comment = GalleryComment.objects.filter(image=image, user=request.user).order_by('date').last()\n except GalleryComment.DoesNotExist:\n user_comment = None\n else:\n comments = GalleryComment.objects.filter(image=image).order_by('user', '-date').distinct('user')\n user_comment = None\n\n if image_id > 1:\n previous_page = image_id - 1\n else:\n previous_page = False\n if image_id < total_images:\n next_page = image_id + 1\n else:\n next_page = False\n\n return render(request, 'gallery/image.html', {\n 'gallery': gallery,\n 'image': image,\n 'current_page': image_id,\n 'next_page': next_page,\n 'previous_page': previous_page,\n 'total_pages': total_images,\n 'comments': comments,\n 'user_comment': user_comment,\n 'current_user': request.user\n })\n\n@login_required\ndef comment(request, gallery_id, image_id):\n image_id = int(image_id);\n gallery = get_object_or_404(Gallery, slug=gallery_id)\n\n try:\n image = GalleryImage.objects.filter(gallery=gallery)[image_id-1]\n except IndexError:\n raise Http404(\"Image does not exist\")\n\n GalleryComment.objects.create(\n image = image,\n user = request.user,\n comment = request.POST['comment'],\n date = datetime.now()\n );\n\n if 'ajax' in request.POST:\n return JsonResponse({'success':'true'})\n else:\n return HttpResponseRedirect(reverse('gallery:image', args=(gallery_id, image_id)))","repo_name":"zackw/gallery.owlfolio.org","sub_path":"gallery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40742762811","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.http import Http404, HttpResponse\nfrom django.conf import settings\nfrom django.core.urlresolvers import resolve\n\nfrom django.views.decorators.cache import cache_page\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.contrib import messages\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth import login, logout\nfrom django.contrib.auth import authenticate\n\nfrom django.core.paginator import Paginator, EmptyPage\nfrom django.core.urlresolvers import reverse\nfrom django.core.cache import cache\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom ads.models import Ad, District, Category, SubCategory, PaidOption, Town, ImageAttachment, VisitHistory, VideoAttachment\nfrom ads import forms\nfrom ads.forms import ImageAttachmentForm, VideoAttachmentForm\nfrom easy_thumbnails.templatetags.thumbnail import thumbnail_url\nfrom ads import tasks\nfrom rudeword.models import RudeWord, WordAnalyser\nfrom recipes.email import get_mailbox_by_email\n\nfrom haystack.models import SearchResult\n\n\nimport json\nfrom datetime import datetime\nimport urllib\nimport hashlib\n\nfrom os.path import basename\nimport re\n\n\nfrom email_templates.models import EmailTemplate\nfrom registration import signals\n\n\ndef home(request):\n categories = Category.objects.all()\n ordering = [1, 4, 8, 11, 14, 2, 5, 9, 12, 15, 3, 6, 10, 13]\n categories = sorted(categories, key=lambda i: ordering.index(i.id))\n return render(request, 'ads/home.html', {'form': forms.FilterSearchForm(hide_fields=['offering',\n 'category', 'district']),\n 'categories': categories})\n\n\ndef category(request, slug, page=None):\n cat = Category.objects.filter(slug=slug)[:1][0]\n page, form, counts, params = get_listing_items(request, page, cat)\n\n # params without category\n data = request.GET.copy()\n str_data = {}\n for k, v in data.iteritems():\n str_data[k] = unicode(v).encode('utf-8')\n params = urllib.urlencode(str_data, True)\n\n private = None\n if 'private' in request.GET:\n private = \"private\" if request.GET.get('private') == \"private\" else \"business\"\n return render(request, 'ads/category.html',\n {'page': page,\n 'form': form,\n 'today': datetime.now(),\n 'category': cat.id,\n 'cat': cat,\n 'counts': counts,\n 'params': params,\n 'private': private,\n 'referer': (_('Search'), \"search\")})\n\n\ndef search(request, page=None):\n page, form, counts, params = get_listing_items(request, page)\n private = None\n if 'private' in request.GET:\n private = \"private\" if request.GET.get('private') == \"private\" else \"business\"\n\n return render(request, 'search/search.html', {'page': page,\n 'today': datetime.now(),\n 'form': form,\n 'counts': counts,\n 'params': params,\n 'private': private,\n 'q': request.GET.get('q'),\n 'referer': (_('Search'), \"search\")})\n\n\ndef get_listing_items(request, page=None, cat=None): # this is not view, just same code for two views above\n limit = 12\n data = request.GET.copy()\n if cat:\n data['category'] = cat.id\n\n str_data = {}\n for k, v in data.iteritems():\n str_data[k] = unicode(v).encode('utf-8')\n params = urllib.urlencode(str_data, True)\n\n cache_key = 'search_' + params + '_p' + str(page or 1)\n cache_key = hashlib.md5(cache_key).hexdigest()\n cache_context = cache.get(cache_key)\n if cache_context is None:\n if cat is None and 'category' in request.GET and request.GET['category']:\n cat = Category.objects.get(pk=request.GET['category'])\n\n form_class = Ad.get_search_form(request, cat)\n form = form_class(data, label_suffix=\"\")\n objects = form.search()\n\n # filter by private here, cos we need all/private/business stats\n all_ads = None\n private = None\n if 'private' in data:\n all_ads = objects.count()\n objects = objects.filter(private=int(data['private'] == \"private\"))\n private = \"private\" if data['private'] == \"private\" else \"business\"\n\n paginator = Paginator(objects, limit)\n try:\n page = paginator.page(page or 1)\n except EmptyPage:\n raise Http404\n\n if private is None:\n all_ads = paginator.count\n private_c = objects.filter(private=1).count()\n business_c = all_ads - private_c\n elif private == 'private':\n private_c = paginator.count\n business_c = all_ads - private_c\n else:\n business_c = paginator.count\n private_c = all_ads - business_c\n counts = {'all': all_ads,\n 'private': private_c,\n 'business': business_c}\n\n # !!!! prepare data !!!!\n ids = [int(obj.pk) for obj in page.object_list]\n # for haystack results check that items still in DB and fetch them\n if page.object_list and isinstance(page.object_list[0], SearchResult):\n ads = {obj.id: obj for obj in Ad.objects.filter(id__in=ids)[:limit]}\n new_object_list = []\n for obj in page.object_list:\n if int(obj.pk) in ads:\n new_object_list.append(ads[int(obj.pk)])\n page.object_list = new_object_list\n\n images = ImageAttachment.objects.all().filter(ad_id__in=ids)\n logos = {ad_id: None for ad_id in ids}\n for img in images:\n logos[img.ad_id] = img\n dist_ids = [obj.district_id for obj in page.object_list]\n districts = {dist.id: dist for dist in District.objects.all().filter(id__in=set(dist_ids))}\n\n if cat:\n categories = {cat.id: cat}\n else:\n cat_ids = [obj.category_id for obj in page.object_list]\n categories = {cat.id: cat for cat in Category.objects.all().filter(id__in=set(cat_ids))}\n\n sub_cat_ids = []\n for obj in page.object_list:\n if obj.sub_category_id:\n sub_cat_ids.append(obj.sub_category_id)\n sub_categories = {cat.id: cat for cat in SubCategory.objects.all().filter(id__in=set(sub_cat_ids))}\n\n new = []\n for obj in page.object_list:\n obj.category = categories[obj.category_id]\n if obj.sub_category_id:\n obj.sub_category = sub_categories[obj.sub_category_id]\n if obj.district_id:\n obj.district = districts[obj.district_id]\n obj.logo = logos[obj.id]\n new.append(obj)\n page.object_list = new\n\n page.paginator.object_list = page.object_list\n cache.set(cache_key, {'page': page, 'counts': counts, 'form': form}, 3600)\n else:\n counts = cache_context['counts']\n form = cache_context['form']\n page = cache_context['page']\n\n return page, form, counts, params\n\n\n\n\ndef autocomplete(request):\n sqs = Ad.search(request.GET, True)[:5]\n suggestions = [result.title for result in sqs]\n import re\n q = request.GET.get('q', '')\n regexp = re.compile(r'[\\w]*[\\s\\W]*[\\w]*' + re.escape(q) + r'[\\w]*[\\s\\W]*[\\w]*', re.IGNORECASE | re.UNICODE)\n res = []\n for item in suggestions:\n match = regexp.search(item)\n if match is not None:\n res.append(match.group(0))\n else:\n res.append(item)\n\n # Make sure you return a JSON object, not a bare list.\n # Otherwise, you could be vulnerable to an XSS attack.\n the_data = json.dumps({\n 'results': res\n })\n return HttpResponse(the_data, content_type='application/json')\n\n\ndef ajax_get_filters(request, cat_id, sub_cat_id):\n if request.GET.get('offering'):\n form_class = forms.FilterSearchForm\n else:\n try:\n if sub_cat_id != '0':\n cat = get_object_or_404(SubCategory, pk=sub_cat_id)\n if cat.form_filter is None:\n cat = cat.category\n else:\n cat = get_object_or_404(Category, pk=cat_id)\n except Category.DoesNotExist:\n form_class = forms.PriceSearchForm\n else:\n if cat.form_filter:\n try:\n form_class = getattr(forms, cat.form_filter)\n except AttributeError:\n form_class = forms.PriceSearchForm\n else:\n form_class = forms.PriceSearchForm\n form = form_class({'category': cat_id, 'sub_category': sub_cat_id})\n return render(request, 'ads/additional_filters.html', {'form': form, 'is_ajax': True})\n\n\n@cache_page(3600)\ndef get_district_opts(request, town_id):\n return render(request, 'ads/district_options.html', {'options': District.objects.filter(town_id=town_id)})\n\n\ndef detail(request, slug, ad_id):\n # messages.success(request, _('Your add was successfully added.'))\n # messages.info(request, 'Three credits remain in your account.')\n # messages.warning(request, 'Your account expires in three days.')\n # messages.error(request, 'Document deleted because you use rude words in it :\"dfgdfgdg\", \"dgdfgdfgg\", \"drfgfffffffffffffhgfhgf\", \"drgggggg\", \"dfgdfgdg\", \"dgdfgdfgg\", \"drfgfffffffffffffhgfhgf\", \"drgggggg\".')\n\n cache_key = 'detail_%s' % ad_id\n ad = cache.get(cache_key)\n if ad is None:\n ad = get_object_or_404(Ad, pk=ad_id)\n ad.town, ad.category, ad.sub_category, ad.user = ad.town, ad.category, ad.sub_category, ad.user\n ad.similars = ad.similar.all()\n ad.images, ad.videos = ad.imageattachment_set.all(), ad.videoattachment_set.all()\n\n if ad.blocked is not False and request.user.id == ad.user.id:\n if ad.rude_words:\n messages.error(request, _('Your ad was blocked, because you use rude words in it: %s') % \", \".join([w.id for w in ad.rude_words.all()]))\n else:\n messages.error(request, _('Your ad was blocked by admin'))\n elif ad.disabled or ad.blocked is not False:\n raise Http404()\n\n # for breadcrumb\n referer = (_('Search'), reverse('search', args=(1,)) + '?'\n + urllib.urlencode({'category': ad.category_id,\n 'town': ad.town_id,\n 'district': ad.district_id if ad.district_id else '',\n 'offering': \"\" if ad.offering else 1}), \"search\")\n\n if 'HTTP_REFERER' in request.META:\n referer_arr = request.META['HTTP_REFERER'].split('/')[:4]\n if referer_arr == request.build_absolute_uri(reverse('search', args=(1,))).split('/')[:4]:\n referer = (_('Search'), request.META['HTTP_REFERER'], \"search\")\n elif referer_arr == request.build_absolute_uri(reverse('profile')).split('/')[:4]:\n referer = (_('Profile'), request.META['HTTP_REFERER'], \"user\")\n\n\n # save last viewed\n ad.add_to_visited(request)\n cache.set(cache_key, ad, 3600)\n\n if request.user.is_authenticated():\n ids_q = VisitHistory.objects.filter(user=request.user).exclude(ad_id=ad_id)[:3].values_list('ad', flat=True)\n ids = [aid for aid in ids_q]\n history = Ad.objects.filter(id__in=ids)\n else:\n history = Ad.objects.filter(pk__in=request.session['history']).exclude(pk=ad_id)[:3] if request.session['history'] else []\n return render(request, 'ads/detail.html', {'ad': ad, 'referer': referer, 'today': datetime.now(),\n 'send_form': forms.SendToFriendForm(initial={'ad_id': ad_id}),\n 'history': history})\n\n\ndef ajax_send_to_friend(request):\n from email_templates.models import EmailTemplate\n if request.method == 'POST':\n form = forms.SendToFriendForm(request.POST)\n if form.is_valid():\n try:\n ad = Ad.objects.get(pk=form.cleaned_data['ad_id'])\n except Ad.DoesNotExist:\n return HttpResponse(json.dumps({'error': 'Ad does not exist anymore'}), content_type=\"application/json\")\n else:\n # from django.core.mail import EmailMessage\n # email = EmailMessage(ad.title, ad.desc, to=[form.cleaned_data['email']])\n # email.send()\n images = ad.imageattachment_set.all()\n if images:\n image = images[0]\n else:\n image = None\n email = EmailTemplate.objects.get(pk='send_ad_to_friend')\n email.send(form.cleaned_data['email'], None, ad=ad, image=image.file.url if image is not None else None)\n\n return HttpResponse(json.dumps({'success': 1}), content_type=\"application/json\")\n return HttpResponse(json.dumps({'error': 'method'}), content_type=\"application/json\")\n\n\ndef post_ad(request):\n\n files = {'images': [], 'video': []}\n\n if request.method == \"POST\":\n\n from_class = Ad.get_form_class(request.POST.get('category'), request.POST.get('sub_category'),\n request.POST.get('offering') == \"True\")\n form = from_class(request.POST, anonym=(not request.user.is_authenticated()))\n if form.is_valid():\n obj = form.save(commit=False) # returns unsaved instance\n if request.user.is_authenticated():\n obj.user = request.user\n if not obj.district:\n obj.town = Town.objects.get(pk=request.session.get('TOWN_SELECTED', 1))\n obj.save()\n obj.blocked = WordAnalyser.block_object(obj, Ad.fields_for_analyse)\n if obj.blocked is not False:\n obj.save()\n else:\n try:\n obj.user = get_user_model().objects.get(email=form.cleaned_data['email'])\n except get_user_model().DoesNotExist:\n obj.user = get_user_model().objects.create_user(form.cleaned_data['email'], None, is_active=False)\n finally:\n obj.save_as_disabled(form.cleaned_data['email'])\n\n tasks.find_similar(obj.id)\n Ad.save_files(request.POST, obj)\n if obj.disabled:\n return redirect('activate_ad', ad_id=obj.id)\n else:\n messages.success(request, _('Your add was successfully added.'))\n return redirect(obj.get_absolute_url())\n else:\n for img_id in request.POST.getlist('images[]'):\n file_obj = ImageAttachment.objects.get(pk=img_id)\n if file_obj:\n files['images'].append(file_obj)\n for vid_id in request.POST.getlist('video[]'):\n file_obj = VideoAttachment.objects.get(pk=vid_id)\n if file_obj:\n files['video'].append(file_obj)\n else:\n from_class = Ad.get_form_class(offering=True)\n form = from_class(anonym=(not request.user.is_authenticated()))\n\n return render(request, 'ads/post_ad.html', {'form': form,\n 'files': files,\n 'images_limit': settings.UPLOAD_IMAGES_LIMIT - len(files['images']),\n 'video_limit': settings.UPLOAD_VIDEO_LIMIT - len(files['video'])})\n\n\ndef activate_ad(request, ad_id):\n ad = get_object_or_404(Ad, id=ad_id)\n if not ad.disabled:\n return redirect(ad.get_absolute_url())\n messages.warning(request, _('Go to your Email-inbox and click on link to activate this ad.'))\n return render(request, 'ads/activate_ad.html', {'ad': ad, 'mail_inbox': get_mailbox_by_email(ad.user.email)})\n\n\ndef activate_ad_key(request, ad_id, activation_key):\n ad = Ad.objects.get(pk=ad_id)\n if not ad.disabled:\n return redirect(ad.get_absolute_url())\n if ad.activation_key == activation_key:\n ad.disabled = False\n ad.activation_key = 'ACTIVATED'\n ad.save()\n if not request.user.is_authenticated():\n user = authenticate(username=ad.user.email, password=None, anonymus=True)\n login(request, user)\n messages.success(request, _('Your add was successfully activated.'))\n return redirect(ad.get_absolute_url())\n return redirect('activate_ad', ad_id=ad.id)\n\n\n@login_required\ndef edit_ad(request, ad_id=None):\n instance = get_object_or_404(Ad, id=ad_id, user_id=request.user.id)\n\n if request.method == \"POST\":\n cache_key = 'detail_%s' % ad_id\n cache.delete(cache_key)\n offering = request.POST.get('offering')\n if offering:\n offering = True if offering == 'True' else False\n\n from_class = Ad.get_form_class(request.POST.get('category'),\n request.POST.get('sub_category'),\n (offering if offering is not None else instance.offering))\n\n form = from_class(request.POST, instance=instance)\n\n if form.is_valid():\n obj = form.save(commit=False)\n obj.blocked = WordAnalyser.block_object(obj, Ad.fields_for_analyse)\n obj.save()\n tasks.find_similar(obj.id)\n Ad.save_files(request.POST, obj)\n messages.success(request, _('Your add was successfully updated.'))\n return redirect(obj.get_absolute_url())\n else:\n from_class = Ad.get_form_class(instance.category,\n instance.sub_category if hasattr(instance, 'sub_category') else None,\n instance.offering)\n form = from_class(instance=instance)\n\n files = {'images': instance.imageattachment_set.all(), 'video': instance.videoattachment_set.all()}\n\n return render(request, 'ads/post_ad.html', {'form': form,\n 'files': files,\n 'images_limit': settings.UPLOAD_IMAGES_LIMIT - len(files['images']),\n 'video_limit': settings.UPLOAD_VIDEO_LIMIT - len(files['video'])})\n\n\n#@cache_page(3600)\ndef ajax_get_fields(request, cat_id, sub_cat_id):\n if sub_cat_id != '0':\n cat = SubCategory.objects.get(pk=sub_cat_id)\n if cat.form_add is None:\n cat = cat.category\n else:\n cat = Category.objects.get(pk=cat_id)\n\n from_class = Ad.get_form_class(cat_id, sub_cat_id if sub_cat_id != '0' else None,\n offering=not request.GET.get('looking', False))\n\n form = from_class(initial={'category': cat_id, 'sub_category': sub_cat_id})\n cont = {'form': form} # if cat.form_add else {}\n return render(request, 'ads/additional_fields.html', cont)\n\n\n@csrf_exempt\ndef file_upload(request, ftype):\n response = {'OK': 0}\n if request.method == 'POST':\n print(request.FILES)\n print(request.POST)\n if ftype == 'video':\n form = VideoAttachmentForm(request.POST, request.FILES)\n\n else: # image\n form = ImageAttachmentForm(request.POST, request.FILES)\n if form.is_valid():\n obj = form.save(commit=False)\n obj.save()\n thumb = thumbnail_url(obj.file, 'photo') if ftype != 'video' else \"\"\n response = {'OK': 1, 'id': obj.id, 'url': thumb, 'name': re.sub(\"_[^_]*(?=\\.[^\\.]*$)\", \"\", basename(obj.file.name))}\n else:\n response['error'] = form.errors['file']\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\n@login_required\ndef paid_option(request, option_id, ad_id):\n option = PaidOption.objects.get(pk=option_id)\n ad = Ad.objects.get(pk=ad_id)\n is_available = option.is_available(request.user.score)\n\n if is_available:\n if request.method == 'POST':\n if option.uid == 'premium_status':\n ad.set_premium(option.duration)\n elif option.uid == 'vip_status':\n ad.set_vip(option.duration)\n else:\n return redirect(ad.get_absolute_url())\n ad.save()\n request.user.score -= option.cost\n request.user.save()\n return redirect(ad.get_absolute_url())\n else:\n messages.error(request, 'You have not enough money on your balance.')\n\n return render(request, 'ads/paid_option.html', {'option': option, 'ad': ad, 'is_available': is_available,\n 'referer': (_('Search'), \"search\", \"search\")})\n\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n form = forms.UserForm(request.POST, instance=request.user)\n if form.is_valid():\n form.save()\n messages.success(request, _('Your profile info was saved.'))\n else:\n form = forms.UserForm(instance=request.user)\n return render(request, 'ads/profile.html', {'form': form, 'type': 'info'})\n\n\n@login_required\ndef profile_ads(request, page):\n if request.method == 'POST':\n pid = disable = None\n if 'disable' in request.POST:\n disable = True\n pid = request.POST['disable']\n elif 'restore' in request.POST:\n disable = False\n pid = request.POST['restore']\n if pid is not None:\n ad = Ad.objects.get(pk=pid)\n if ad.user == request.user:\n ad.disabled = disable\n ad.save()\n messages.success(request, _('Your add was successfully disabled.') if disable else _('Your add was successfully enabled.'))\n return render(request, 'ads/profile_ads.html', {'page': Paginator(request.user.ad_set.all(), 10).page(page or 1),\n 'page_num': page, 'type': 'ads_list'})\n\n\n@login_required\ndef profile_visits(request, page):\n if 'history' in request.session and request.session['history']:\n ads = Ad.objects.filter(pk__in=request.session['history'])\n for ad in ads:\n visit, created = VisitHistory.objects.get_or_create(ad=ad, user=request.user)\n request.session['history'] = []\n request.session.modified = True\n page = page or 1\n objects = VisitHistory.objects.filter(user=request.user)\n return render(request, 'ads/profile_visits.html', {'page': Paginator(objects, 10).page(page),\n 'page_num': page, 'type': 'visits'})\n\n\ndef ajax_task_state(request):\n from celery.result import AsyncResult\n result = AsyncResult(request.GET.get('task_id'))\n return HttpResponse(json.dumps({'status': result.status, 'ready': result.ready(),\n 'result': result.result, 'state': result.state}), content_type=\"application/json\")\n\n\ndef error404(request):\n return render(request, 'errors/404.html', {'body_cls': 'errorPage'})\n\n\ndef error500(request):\n return render(request, 'errors/500.html', {'body_cls': 'errorPage'})\n\n\n\nimport locale\nimport sys\n\ndef view_locale(request):\n loc_info = \"getlocale: \" + str(locale.getlocale()) + \\\n \"
getdefaultlocale(): \" + str(locale.getdefaultlocale()) + \\\n \"
fs_encoding: \" + str(sys.getfilesystemencoding()) + \\\n \"
sys default encoding: \" + str(sys.getdefaultencoding()) + \\\n \"
sys default encoding: \" + str(sys.getdefaultencoding())\n return HttpResponse(loc_info)\n\n","repo_name":"alekseystryukov/estate_ads","sub_path":"ads/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10612288010","text":"import sqlite3 as sl\nimport os\n\ndef remove():\n os.remove(\"database.db\")\n\ndef init():\n os.remove(\"database.db\")\n\n con = sl.connect(\"database.db\")\n c = con.cursor()\n\n try:\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS client (\n ID INTEGER PRIMARY KEY,\n Surname VARCHAR,\n Name VARCHAR,\n Email VARCHAR)\"\"\")\n print(\"client table initiated.\")\n\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS product (\n ID INTEGER PRIMARY KEY,\n Name VARCHAR,\n Price INTEGER,\n MagazineState INTEGER\n )\"\"\")\n print(\"product table initiated.\")\n\n c.execute(\"\"\"CREATE TABLE IF NOT EXISTS \"order\" (\n ID INTEGER PRIMARY KEY,\n ClientID INTEGER,\n ProductList VARCHAR,\n OrderStatus VARCHAR CHECK(OrderStatus IN ('pending', 'finished')),\n FOREIGN KEY(ClientID) REFERENCES client(ID)\n )\"\"\")\n print(\"order table initiated.\")\n\n print(\"all orders initiated\")\n except EOFError:\n print(\"Error in initiating tables\")\n \n con.commit()\n con.close()\n\ndef select(table, all=False, check = \"ID\", by = \"\"):\n con = sl.connect(\"database.db\")\n c = con.cursor()\n\n if all:\n res = c.execute(\"SELECT * FROM \" + table).fetchall()\n else:\n res = c.execute(\"SELECT * FROM \\\"\" + table + \"\\\" WHERE \" + check + \" = \" + str(by)).fetchall()\n \n con.commit()\n con.close()\n return res\n\ndef insert(table, values):\n con = sl.connect(\"database.db\")\n c = con.cursor()\n\n atbs = str(list(values.keys()))[1:-1].replace(\"\\'\", \"\")\n vals = str(list(values.values()))[1:-1]\n\n c.execute(\"INSERT INTO \" + table + \" (\" + atbs + \") VALUES (\" + vals + \")\")\n\n con.commit()\n con.close()\n\ndef delete(table, id):\n con = sl.connect(\"database.db\")\n c = con.cursor()\n\n c.execute(\"DELETE FROM \" + table + \" WHERE ID = \" + str(id))\n\n con.commit()\n con.close()\n\ndef update(table, values, id):\n con = sl.connect(\"database.db\")\n c = con.cursor()\n\n atbs = str(list(values.keys()))[1:-1].replace(\"\\'\", \"\")\n vals = str(list(values.values()))[1:-1]\n c.execute(\"UPDATE \" + table + \" SET (\" + atbs + \") = (\" + vals + \") WHERE ID =\" + str(id))\n\n con.commit()\n con.close()\n","repo_name":"tymek-gryszkalis/MWOLab2","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26160686984","text":"import torch\nimport torchvision.models as models\n\nweights = models.ResNet18_Weights.DEFAULT\npreprocess = weights.transforms()\nmodel = models.resnet18(weights=weights)\nlayer = model._modules.get('avgpool')\nmodel.eval()\ndef get_vector(image):\n # Create a PyTorch tensor with the transformed image\n t_img = preprocess(image)\n # Create a vector of zeros that will hold our feature vector\n my_embedding = torch.zeros(512)\n\n # Define a function that will copy the output of a layer\n def copy_data(m,i,o):\n my_embedding.copy_(o.flatten()) # <-- flatten\n\n # Attach that function to our selected layer\n h = layer.register_forward_hook(copy_data)\n # Run the model on our transformed image\n with torch.no_grad(): # <-- no_grad context\n model(t_img.unsqueeze(0)) # <-- unsqueeze\n # Detach our copy function from the layer\n h.remove()\n # Return the feature vector\n return my_embedding","repo_name":"santiagoflorez98/GAD-tpIntegrador","sub_path":"vectorizacion.py","file_name":"vectorizacion.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13097651555","text":"from sys import stdin\n\n\ndef solution(N, edges):\n board = [[0]*N for _ in range(N)]\n for a, b in map(lambda x: (x[0]-1, x[1]-1), edges):\n board[a][b] = board[b][a] = 1\n\n count = 0\n\n START = 0\n stack, visited = [goto for goto, routed in enumerate(board[START]) if routed], {START}\n while stack:\n at = stack.pop()\n if at in visited:\n continue\n visited.add(at)\n count += 1\n for goto, routed in enumerate(board[at]):\n if routed:\n stack.append(goto)\n\n return count\n\n\nlexer = lambda :[int(c) for c in stdin.readline().strip().split(' ')]\nfor _ in range(int(stdin.readline())):\n N, M = lexer()\n edges = [lexer() for _ in range(M)]\n print(solution(N, edges))\n\n","repo_name":"grasshopperTrainer/coding_practice","sub_path":"baekjoon/accepted/MST 최소신장 트리/9372 상근이의 여행.py","file_name":"9372 상근이의 여행.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12087494678","text":"#-*- coding: UTF-8 -*-\n#-----------------------------------\n# python2.7\n# author:loster\n# description:解析xml\n#-------------------------------------\nimport xml.etree.ElementTree as ET\n\ndef getXml(fileName):\n root = ET.fromstring(fileName)#.getroot() #获得根节点\n resultList = [] \n walkXml(root,resultList,root.tag)\n return resultList\n\ndef walkXml(root,resultList,tempLists):\n if tempLists == 'root':\n tempLists = \"\"\n tempList = tempLists+',\"'+root.tag+'\"'\n resultList.append(tempList)\n children_node = root.getchildren()\n if len(children_node) == 0:\n return\n for child in children_node:\n walkXml(child,resultList,tempList)\n return\n\ndef parseXmlString(xmlStr):\n return getXml(xmlStr),getXmlTag(xmlStr)\n\ndef getXmlTag(fileName):\n root = ET.fromstring(fileName)#.getroot() #获得根节点\n resultListTag = [] \n walkXmlTag(root,resultListTag)\n return resultListTag\n\ndef walkXmlTag(root,resultListTag):\n tempListTag = root.tag\n resultListTag.append(tempListTag)\n children_node = root.getchildren()\n if len(children_node) == 0:\n return\n for child in children_node:\n walkXmlTag(child,resultListTag)\n return\n#if __name__ == \"__main__\":\n# file_name = \"diamondShopDialog.xml\"\n# R = getXml(file_name)\n# for r in R:\n# print \"{\"+r[8:]+\"}\"\n \n \n","repo_name":"iloster/webAutoBuild","sub_path":"ParseXml.py","file_name":"ParseXml.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23074065396","text":"# Jeremy Ng 500882192\n# CPS842 Project\n\nimport sys\nfrom porter import PorterStemmer\nfrom parse import parse\n\n\nclass DocumentCollection:\n # Constructor\n def __init__(self):\n self.index = {}\n self.stopWords = set()\n self.dictionary = {}\n\n # Function to add new document\n def addDocument(self, index, title, abstract, date, authors):\n self.index[index] = {\n \"title\": title,\n \"abstract\": abstract,\n \"date\": date,\n \"authors\": authors\n }\n\n # Open and read common_words files\n def readStopWordsFile(self, file):\n with open(file, \"r\") as words:\n for word in words:\n # [0:-1] to remove newline character\n self.stopWords.add(word[0:-1])\n words.close()\n\n # Function to read and parse files\n def readDocuments(self, collection):\n # Open and read CACM file\n with open(collection, \"r\") as document:\n index = 0\n title = []\n abstract = []\n date = \"\"\n authors = []\n mode = \".I\"\n modeSet = [\".T\", \".W\", \".B\", \".A\", \".N\", \".K\", \".C\", \".X\"]\n for line in document:\n if line.startswith(\".I\"):\n # Store previous index information\n self.addDocument(index, title, abstract, date, authors)\n # Clear variables and set new index\n index = line[3:-1]\n title = []\n abstract = []\n date = \"\"\n authors = []\n # Set mode\n for string in modeSet:\n if line.startswith(string):\n mode = string\n break\n # If line is not setting mode then store data. [0:-1] to remove newline character\n else:\n if mode == \".T\":\n for word in parse(line[0:-1].lower()):\n if \"-s\" in sys.argv or \"-stop\" in sys.argv:\n if word not in self.stopWords:\n title += [word]\n else:\n title += [word]\n if mode == \".W\":\n for word in parse(line[0:-1].lower()):\n if \"-s\" in sys.argv or \"-stop\" in sys.argv:\n if word not in self.stopWords:\n abstract += [word]\n else:\n abstract += [word]\n if mode == \".B\":\n date = line[0:-1]\n if mode == \".A\":\n authors.append(line[0:-1])\n # Edge case for last index\n self.addDocument(index, title, abstract, date, authors)\n # Delete this record\n del self.index[0]\n document.close()\n\n # Apply porter's stemming algorithm to every word of our documents\n def porterStemmingAlgorithm(self):\n porter = PorterStemmer()\n for key in self.index:\n for i in range(len(self.index[key][\"title\"])):\n self.index[key][\"title\"][i] = porter.stem(\n self.index[key][\"title\"][i])\n for i in range(len(self.index[key][\"abstract\"])):\n self.index[key][\"abstract\"][i] = porter.stem(\n self.index[key][\"abstract\"][i])\n\n # Add to dictionary\n def addToDictionary(self, index, word, position):\n if word not in self.dictionary:\n self.dictionary[word] = {\n \"df\": 1,\n \"docID\": {\n index: {\n \"tf\": 1,\n \"position\": [position]\n }\n }\n }\n else:\n if index not in self.dictionary[word][\"docID\"]:\n self.dictionary[word][\"df\"] += 1\n self.dictionary[word][\"docID\"][index] = {\n \"tf\": 1,\n \"position\": [position]\n }\n else:\n self.dictionary[word][\"docID\"][index][\"tf\"] += 1\n self.dictionary[word][\"docID\"][index][\"position\"] += [position]\n\n # Create word dictionary\n def createDictionary(self):\n for key in self.index:\n position = 1\n for word in self.index[key][\"title\"] + self.index[key][\"abstract\"]:\n self.addToDictionary(key, word, position)\n position += 1\n\n # Make dictionary and postings lists files\n def createFiles(self):\n dictionaryFile = open(\"../output/dictionary.txt\", \"w\")\n postingsLists = open(\"../output/postingsLists.txt\", \"w\")\n if \"-p\" in sys.argv or \"-porter\" in sys.argv:\n dictionaryFile.write(\".porter yes\\n\")\n else:\n dictionaryFile.write(\".porter no\\n\")\n for key in sorted(self.dictionary):\n dictionaryFile.write(f'{key} {self.dictionary[key][\"df\"]}\\n')\n postingsLists.write(f'.{key}\\n')\n for index in self.dictionary[key][\"docID\"]:\n postingsLists.write(\n f'{index} {self.dictionary[key][\"docID\"][index][\"tf\"]} {self.dictionary[key][\"docID\"][index][\"position\"]}\\n')\n dictionaryFile.close()\n postingsLists.close()\n\n\ndef main():\n docCol = DocumentCollection()\n\n if \"-s\" in sys.argv or \"-stop\" in sys.argv:\n docCol.readStopWordsFile(\"../data/common_words\")\n\n docCol.readDocuments(\"../data/cacm.all\")\n\n if \"-p\" in sys.argv or \"-porter\" in sys.argv:\n docCol.porterStemmingAlgorithm()\n\n docCol.createDictionary()\n\n docCol.createFiles()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"KingJeremyNg/cps842","sub_path":"src/invert.py","file_name":"invert.py","file_ext":"py","file_size_in_byte":5824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18550911007","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division, print_function\n\nimport os\nimport glob\nimport h5py\nimport fitsio\nimport numpy as np\n\nfns = glob.glob(\"data/k2/*.fits.gz\")\nbase_fns = [os.path.split(fn)[1] for fn in fns]\nn = len(fns)\nmeta = np.empty(n, dtype=[\n (\"fn\", np.str_, max(map(len, base_fns))), (\"ra\", float), (\"dec\", float),\n (\"xmin\", int), (\"xmax\", int), (\"ymin\", int), (\"ymax\", int)\n])\n\nprint(\"First pass...\")\nfor i, fn in enumerate(fns):\n meta[\"fn\"][i] = base_fns[i]\n hdr = fitsio.read_header(fn, 2)\n meta[\"ra\"][i] = hdr[\"RA_OBJ\"]\n meta[\"dec\"][i] = hdr[\"DEC_OBJ\"]\n meta[\"xmin\"][i] = hdr[\"CRVAL1P\"]\n meta[\"xmax\"][i] = hdr[\"CRVAL1P\"] + hdr[\"NAXIS1\"]\n meta[\"ymin\"][i] = hdr[\"CRVAL2P\"]\n meta[\"ymax\"][i] = hdr[\"CRVAL2P\"] + hdr[\"NAXIS2\"]\n\n# Normalize the axes.\nmeta[\"xmax\"] -= meta[\"xmin\"].min()\nmeta[\"xmin\"] -= meta[\"xmin\"].min()\nmeta[\"ymax\"] -= meta[\"ymin\"].min()\nmeta[\"ymin\"] -= meta[\"ymin\"].min()\n\nprint(\"Second pass...\")\nimg, mask = None, None\nquality = None\nfor i, fn in enumerate(fns):\n tbl = fitsio.read(fn)\n xi, yi = np.meshgrid(range(meta[\"xmin\"][i], meta[\"xmax\"][i]),\n range(meta[\"ymin\"][i], meta[\"ymax\"][i]))\n flux = tbl[\"FLUX\"]\n if img is None:\n img = np.empty((len(flux), meta[\"xmax\"].max(),\n meta[\"ymax\"].max()), dtype=float)\n mask = np.zeros(img.shape[1:], dtype=bool)\n img[:, xi, yi] = flux\n mask[xi, yi] = True\n time = tbl[\"TIME\"]\n\n# Save a FITS image for WCS calibration using astrometry.net\nfitsio.write(\"data/k2.fits\", img[-1], clobber=True)\n\n# Save the block of frames as a huge HDF5 file.\nprint(\"Saving...\")\nwith h5py.File(\"data/k2.h5\", \"w\") as f:\n f.create_dataset(\"frames\", data=img)\n f.create_dataset(\"mask\", data=mask)\n f.create_dataset(\"time\", data=time)\n","repo_name":"dfm/photoica","sub_path":"stitch.py","file_name":"stitch.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26898629479","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python3\n\nimport Tkinter as tk\nimport os\nimport csv\nimport tkSimpleDialog as sd\nimport webbrowser\nfrom Tkinter import *\nfrom tkFileDialog import *\n\n\n\n#=================================================\n# PEINTS_GUI\n#=================================================\n\n\nclass main_window(tk.Frame):\n\n def __init__(self, master):\n self.initial_param()\n self.read_prerun()\n\n self.master = master\n tk.Frame.__init__(self, self.master)\n self.frame = tk.Frame(self.master, padx=30, pady=10)\n self.create_gui()\n\n\n def create_gui(self):\n self.template_btn = tk.Button(self.frame, text=\"Template\", width=10, height=2, command=self.askstr_tmpl)\n self.template_btn.grid(row=0,column=0)\n self.label_temp = tk.Label(self.frame, text=\"No template indicated.\", padx=5)\n self.label_temp.grid(row=0,column=1,columnspan=3, sticky=\"w\")\n\n self.seq_btn = tk.Button(self.frame, text=\"Sequence\", width=10, height=2, command=self.askstr_seq)\n self.seq_btn.grid(row=1,column=0)\n self.label_seq = tk.Label(self.frame, text=\"No sequence indicated.\", padx=5)\n self.label_seq.grid(row=1,column=1,columnspan=3, sticky=\"w\")\n\n self.BT_dir_btn = tk.Button(self.frame, text=\"Beamtime\\ndirectory\", width=10, height=2, command=self.askstr_bt_dir)\n self.BT_dir_btn.grid(row=2,column=0)\n self.label_bt_dir = tk.Label(self.frame, text=\"Select a beamtime directory.\", padx=5)\n self.label_bt_dir.grid(row=2,column=1, columnspan=3, sticky=\"w\")\n\n self.act_site_btn = tk.Button(self.frame, text=\"Target site\", width=10, height=2, command=self.askstr_activesite)\n self.act_site_btn.grid(row=3,column=0)\n self.label_actsite = tk.Label(self.frame, text=\"Input active site\", padx=5)\n self.label_actsite.grid(row=3,column=1, columnspan=3, sticky=\"w\")\n\n self.sg_btn = tk.Button(self.frame, text=\"Space\\ngroup\", width=10, height=2, command=self.askstr_sg)\n self.sg_btn.grid(row=4,column=0)\n self.label_sg = tk.Label(self.frame, text=\"Space group : automatic\", padx=5)\n self.label_sg.grid(row=4,column=1, columnspan=3, sticky=\"w\")\n\n self.cutoff_ios_btn = tk.Button(self.frame, text=\"Cut-off\\nI/sigma(I)\", width=10, height=2,\n command=self.askstr_cutoff)\n self.cutoff_ios_btn.grid(row=5,column=0)\n self.label_cutoff_ios = tk.Label(self.frame, text=\"Cut-off I/sigma(I) : 2.0\", padx=5)\n self.label_cutoff_ios.grid(row=5,column=1, columnspan=3, sticky=\"w\")\n\n self.run_mode = {\"overwrite\": self.flag_overwrite, \"skip\": self.flag_skip_processed_data}\n run_mode_frame = LabelFrame(self.frame, text=\"Run mode\")\n self.run_mode_var = IntVar()\n self.run_mode_var.set(0)\n\n def change_state_run_mode():\n checked = self.run_mode_var.get()\n if checked == 0:\n self.run_mode_process_all_rbtn.configure(state=\"active\")\n self.flag_skip_processed_data = False\n elif checked == 1:\n self.run_mode_skip_processed_rbtn.configure(state=\"active\")\n self.flag_skip_processed_data = True\n self.run_mode[\"skip\"] = self.flag_skip_processed_data\n\n self.run_mode_process_all_rbtn = tk.Radiobutton(run_mode_frame,\n text=\"Process all data\",\n variable=self.run_mode_var,\n value=0,\n width=16,\n height=2,\n # justify=\"left\",\n command=change_state_run_mode)\n self.run_mode_skip_processed_rbtn = tk.Radiobutton(run_mode_frame,\n text=\"Skip processed data\",\n variable=self.run_mode_var,\n value=1,\n width=16,\n height=2,\n # justify=\"left\",\n command=change_state_run_mode)\n\n self.run_mode_process_all_rbtn.grid(row=0, column=0, padx=10)\n self.run_mode_skip_processed_rbtn.grid(row=0, column=1, padx=10)\n\n self.flag_overwrite_blv = BooleanVar()\n self.flag_overwrite_blv.set(False)\n v = IntVar()\n v.set(0)\n buttons = []\n\n def cmd_overwrite():\n self.flag_overwrite = self.flag_overwrite_blv.get()\n if self.flag_overwrite:\n print(\"PEINTS overwrites output files\")\n else:\n print(\"PEINTS does NOT overwrite output files\")\n self.run_mode[\"flag_overwrite\"] = self.flag_overwrite\n\n overwrite_cbtn = Checkbutton(run_mode_frame,\n text=\"overwrite\",\n variable=self.flag_overwrite_blv,\n command=cmd_overwrite)\n overwrite_cbtn.grid(row=1, column=0, columnspan=2)\n run_mode_frame.grid(row=6,column=0,columnspan=4)\n\n self.data_name = \"XDS_ASCII.HKL\"\n data_name_frame = LabelFrame(self.frame, text=\"Data name\", width=36)\n self.data_name_var = IntVar()\n self.data_name_var.set(0)\n\n self.data_name_xds = tk.Radiobutton(data_name_frame,\n text=\"XDS_ASCII.HKL\",\n variable=self.data_name_var,\n value=0,\n width=16,\n height=2,\n justify=\"left\",\n command=self.change_state_data)\n self.data_name_aimless = tk.Radiobutton(data_name_frame,\n text=\"aimless.mtz\",\n variable=self.data_name_var,\n value=1,\n width=16,\n height=2,\n justify=\"left\",\n command=self.change_state_data)\n self.data_name_xds.pack(side=\"left\", padx=10)\n self.data_name_aimless.pack(side=\"right\", padx=10)\n data_name_frame.grid(row=7,column=0,columnspan=4)\n\n # =================================================\n # entrybox for number of processors\n # =================================================\n # self.label5 = tk.Label(frame,text=\"Input number of CPU\")\n # self.label5.pack(anchor=\"w\", padx=20)\n # self.EditBox = tk.Entry(frame)\n # self.EditBox.insert(tk.END,\"number of CPU\")\n # self.EditBox.pack(anchor=\"w\", padx=10)\n\n self.run_btn = tk.Button(self.frame, text=\" RUN PEINTS \", height=2, width=10, command=self.run_peints, fg=\"green\")\n self.run_btn.grid(row=8,column=0)\n self.quit_btn = tk.Button(self.frame, text=\" QUIT \", height=2,command=quit)\n self.quit_btn.grid(row=8,column=1)\n self.result_btn = tk.Button(self.frame, text=\"View result\", height=2,width=10,command=self.view_result)\n self.result_btn.grid(row=8,column=2)\n self.prep_dir_btn = tk.Button(self.frame, text=\"Prep\\ndirectories\", height=2,width=10, fg=\"blue\", command=self.prep_dir)\n self.prep_dir_btn.grid(row=8,column=3)\n\n # =================================================\n # checkbox for MR by MOLREP\n # =================================================\n self.flag_molrep_blv = BooleanVar()\n self.flag_molrep_blv.set(True)\n v = IntVar()\n v.set(0)\n buttons = []\n\n def cmd_molrep():\n self.flag_molrep = self.flag_molrep_blv.get()\n if self.flag_molrep:\n print(\"Perform MR by MOLREP\")\n else:\n print(\"No MR by MOLREP, only REFMAC5\")\n\n option_frame = LabelFrame(self.frame, text=\"Options\", width=35)\n molrep_run_cbtn = Checkbutton(option_frame, text=\"MR\", variable=self.flag_molrep_blv, command=cmd_molrep)\n molrep_run_cbtn.grid(row=0,column=0)\n buttons.append(molrep_run_cbtn)\n\n\n # =================================================\n # checkbox for image capture by coot\n # =================================================\n self.flag_coot_blv = BooleanVar()\n self.flag_coot_blv.set(True)\n v = IntVar()\n v.set(0)\n buttons = []\n\n def cmd_coot():\n self.flag_coot = self.flag_coot_blv.get()\n if self.flag_coot:\n print(\"PEINTS will capture images with coot\")\n else:\n print(\"PEINTS will NOT capture images with coot\")\n\n image_capture_cbtn = Checkbutton(option_frame,\n text=\"image capture by coot\",\n variable=self.flag_coot_blv,\n command=cmd_coot)\n #option_frame = LabelFrame(option_frame, labelwidget=image_capture_cbtn)\n image_capture_cbtn.grid(row=0,column=1)\n buttons.append(image_capture_cbtn)\n option_frame.grid(row=9,column=0, columnspan=4, sticky=\"w,e\")\n\n # =================================================\n # checkbox for PHENIX\n # =================================================\n self.flag_phenix_blv = BooleanVar()\n self.flag_phenix_blv.set(False)\n self.flag_phaser_blv = BooleanVar()\n self.flag_phaser_blv.set(False)\n self.flag_sa_blv = BooleanVar()\n self.flag_sa_blv.set(False)\n self.flag_water_blv = BooleanVar()\n self.flag_water_blv.set(False)\n\n\n v = IntVar()\n v.set(0)\n buttons = []\n\n def phenix_change_state():\n self.flag_phenix = self.flag_phenix_blv.get()\n self.flag_pr = self.flag_phenix_blv.get()\n if self.flag_phenix:\n new_state = 'normal'\n print(\"PEINTS will use PHENIX\")\n self.flag_phaser_blv.set(True)\n self.data_name_xds.configure(state=\"active\")\n self.data_name_var.set(0)\n self.flag_phaser = True\n# self.data_name = \"XDS_ASCII.HKL\"\n else:\n new_state = 'disabled'\n print(\"PEINTS will NOT use PHENIX\")\n self.flag_phaser_blv.set(False)\n self.flag_sa_blv.set(False)\n self.flag_water_blv.set(False)\n\n for b in buttons:\n b.configure(state=new_state)\n\n self.change_state_data()\n\n phenix_cb = Checkbutton(self.frame,\n text='PHENIX',\n variable=self.flag_phenix_blv,\n command=phenix_change_state)\n phenix_frame = LabelFrame(self.frame, labelwidget=phenix_cb)\n\n\n def cmd_phaser():\n self.flag_phaser = self.flag_phaser_blv.get()\n if self.flag_phaser:\n print(\"MR will be performed with PHASER\")\n else:\n print(\"MR will be performed with MOLREP\")\n\n phaser_cbtn = Checkbutton(phenix_frame,\n text=\"PHASER\",\n variable=self.flag_phaser_blv,\n state='disabled',\n command=cmd_phaser)\n phaser_cbtn.pack(side=\"left\")\n buttons.append(phaser_cbtn)\n\n def cmd_sa():\n self.flag_sa = self.flag_sa_blv.get()\n if self.flag_sa:\n print(\"PEINTS-phenix.refine with simulated annealing\")\n print(self.flag_sa)\n else:\n print(\"PEINTS-phenix.refine without simulated annealing\")\n print(self.flag_sa)\n\n sa_cbtn = Checkbutton(phenix_frame,\n text=\"simulated annealing\",\n variable=self.flag_sa_blv,\n state='disabled',\n command=cmd_sa)\n sa_cbtn.pack(side=\"left\")\n buttons.append(sa_cbtn)\n\n def cmd_water():\n self.flag_water = self.flag_water_blv.get()\n if self.flag_water:\n print(\"PEINTS-phenix.refine will put water molecules\")\n print(self.flag_water)\n\n else:\n print(\"PEINTS-phenix.refine will NOT put water molecules\")\n print(self.flag_water)\n\n water_cbtn = Checkbutton(phenix_frame,\n text=\"input water\",\n variable=self.flag_water_blv,\n state='disabled',\n command=cmd_water)\n water_cbtn.pack(side=\"left\")\n buttons.append(water_cbtn)\n phenix_frame.grid(row=10,column=0,columnspan=4, sticky=\"w,e\")\n\n\n self.frame.pack()\n\n\n\n #=================================================\n # commands for buttons\n #=================================================\n \n def askstr_tmpl(self):\n self.flag_temp_push = 1\n self.template = askopenfilename(filetypes = [('Image Files', ('.pdb', '.cif', '.csv')),\n ('PDB Files', '.pdb'),\n ('CIF Files', '.cif'),\n ('CSV Files', '.csv')],\n initialdir = os.path.dirname(self.template))\n self.set_tmpl_label(os.path.basename(self.template))\n \n def set_tmpl_label(self, template):\n self.label_temp.config(text=\"Template : \" + str(template))\n\n def askstr_seq(self):\n self.flag_seq_push = 1\n self.sequence = askopenfilename(filetypes = [('Seq Files', ('.seq', '.pir', '.txt')),\n ('Seq Files', '.seq'),\n ('Pir Files', '.pir'),\n ('FASTA Files', '.fasta'),\n ('Txt Files', '.txt')],\n initialdir = os.path.dirname(self.sequence))\n self.set_seq_label(os.path.basename(self.sequence))\n \n def set_seq_label(self, seq):\n self.label_seq.config(text=\"Sequence : \" + str(seq))\n\n def askstr_bt_dir(self):\n self.flag_prgdir_push = 1\n self.BT_dir = askdirectory(initialdir=self.BT_dir)\n self.set_bt_dir_label(self.BT_dir)\n\n def set_bt_dir_label(self, BT_dir):\n self.label_bt_dir.config(text=\"Beamtime directory : ... \" + str(BT_dir[-30:]))\n \n def askstr_activesite(self):\n self.targetsite = sd.askstring(\"input your target site\",\n 'chainID/residue No./atom \\n'\n 'e.g.1) A/110/CZ\\n'\n 'e.g.2) A/110/CZ_A/100/CA',\n initialvalue='A/110/CZ')\n self.set_targetsite_label(self.targetsite)\n\n def askstr_sg(self):\n self.spacegroup = sd.askstring(\"input spacegroup\",\n \"default=automatic\",\n initialvalue=\"automatic\")\n self.set_sg_label()\n def set_sg_label(self):\n self.label_sg.config(text=\"Spacegroup : \"+self.spacegroup)\n\n def set_targetsite_label(self, targetsite):\n self.label_actsite.config(text=\"Target site : \" + str(targetsite))\n\n def askstr_cutoff(self):\n self.cutoff_ios = sd.askstring(\"Input I/sigma(I) for data cut-off\",\n 'default = 2.0',\n initialvalue='2.0')\n self.set_cutoff_label(self.cutoff_ios)\n def set_cutoff_label(self, cutoff_ios):\n self.label_cutoff_ios.config(text=\"Cut-off I/sigma(I) : \" + str(cutoff_ios))\n\n def change_state_data(self):\n checked = self.data_name_var.get()\n if checked == 0:\n self.data_name_xds.configure(state=\"active\")\n self.data_name = \"XDS_ASCII.HKL\"\n print(\"Data processing from XDS\")\n elif checked == 1:\n self.data_name_aimless.configure(state=\"active\")\n self.data_name = \"aimless.mtz\"\n print(\"Data processing from AIMLESS\")\n\n\n\n def initial_param(self):\n args = sys.argv\n self.progdir = os.path.dirname(os.path.abspath(args[0]))\n self.BT_dir = os.getcwd()\n self.path_name = \"\"\n self.template = \"\"\n self.sequence = \"\"\n self.spacegroup = \"automatic\"\n self.data_name = \"XDS_ASCII.HKL\"\n self.targetsite = \"\"\n self.cutoff_ios = \"2.0\"\n self.flag_molrep = True\n self.flag_coot = True\n self.flag_skip_processed_data = False\n self.flag_overwrite = False\n self.flag_phenix = False\n self.flag_phaser = False\n self.flag_pr= False\n self.flag_water= False\n self.flag_sa= False\n self.flag_temp_push = 0\n self.flag_seq_push = 0\n self.flag_prgdir_push = 0\n\n\n def run_peints(self):\n if self.flag_temp_push == 1 and self.flag_prgdir_push == 1:\n if self.flag_seq_push == 0:\n self.sequence = \"\"\n self.update_input_csv()\n\n print(\"Run PEINTS!\")\n import manage\n manage.Manage(self.input_file)\n\n os.chdir(self.BT_dir)\n elif self.flag_temp_push == 0:\n print(\"Select your template model.\")\n elif self.flag_prgdir_push == 0:\n print(\"Select your beam time directory.\")\n\n def read_prerun(self):\n self.input_file = os.path.join(self.progdir, \"INPUT.csv\")\n\n files = os.listdir(self.progdir)\n if self.input_file in files:\n csv_file = open(self.input_file, \"r\")\n f = csv.DictReader(csv_file)\n input_dict_list = [raw for raw in f]\n input_dict = input_dict_list[0]\n csv_file.close()\n print(input_dict)\n\n self.template = input_dict[\"template\"]\n self.BT_dir = input_dict[\"beamtime_directory\"]\n self.sequence = input_dict[\"sequence\"]\n self.spacegroup = input_dict[\"spacegroup\"]\n self.targetsite = input_dict[\"targetsite\"]\n self.cutoff_ios = input_dict[\"cutoff_ios\"]\n self.data_name = input_dict[\"data_name\"]\n self.flag_molrep = input_dict[\"flag_molrep\"]\n self.flag_coot = input_dict[\"flag_coot\"]\n self.flag_skip_processed_data = input_dict[\"flag_skip_processed_data\"]\n self.flag_overwrite = input_dict[\"flag_overwrite\"]\n self.flag_phenix = input_dict[\"flag_phenix\"]\n self.flag_phaser = input_dict[\"flag_phaser\"]\n self.flag_pr= input_dict[\"flag_pr\"]\n self.flag_water= input_dict[\"flag_water\"]\n self.flag_sa = input_dict[\"flag_sa\"]\n\n else:\n pass\n\n def update_input_csv(self):\n body = \"progdir,template,beamtime_directory,sequence,spacegroup,targetsite,cutoff_ios,data_name,\" \\\n \"flag_molrep,flag_coot,flag_skip_processed_data,flag_overwrite,\" \\\n \"flag_phenix,flag_phaser,flag_pr,flag_water,flag_sa\\n\"\n body += self.progdir+\",\"\n body += self.template+\",\"\n body += self.BT_dir+\",\"\n body += self.sequence + \",\"\n body += self.spacegroup + \",\"\n body += self.targetsite + \",\"\n body += self.cutoff_ios + \",\"\n body += self.data_name + \",\"\n body += str(self.flag_molrep) + \",\"\n body += str(self.flag_coot) + \",\"\n body += str(self.flag_skip_processed_data) + \",\"\n body += str(self.flag_overwrite) + \",\"\n body += str(self.flag_phenix) + \",\"\n body += str(self.flag_phaser) + \",\"\n body += str(self.flag_pr) + \",\"\n body += str(self.flag_water) + \",\"\n body += str(self.flag_sa)\n csv_file = open(self.input_file, \"w\")\n csv_file.write(body)\n csv_file.close()\n print(\"INPUT FILE UPDATED.\")\n\n def prep_dir(self):\n\n print(\"\"\"\n \n --- Project-based directory-hierarchy ---\n \n [selected_Beamtime directory]\n |\n +- [Protein directory]\n | |\n | +-[peints_tmp directory] \n | |\n | +-[Beamtime directory]\n | |\n | +-[Container directory]\n | | \n | +-[Crystal directory]\n | |\n | +-[premo directory]\n | |\n | +-[fastxds directory]\n \"\"\")\n print(self.template)\n\n if self.template == \"\":\n print(\"Select CSV file from Template button.\")\n else:\n if self.template.split(\".\")[-1] != \"csv\":\n print(\"Select CSV file from Template button.\")\n else:\n csv_file = open(self.template, \"r\")\n f = csv.DictReader(csv_file)\n csv_dict_list = []\n for raw in f:\n csv_dict_list.append(raw)\n csv_file.close()\n\n ### create protein dirs ###\n for raw in csv_dict_list:\n protein_id = raw[\"Protein\"]\n protein_dir = os.path.join(self.BT_dir, protein_id)\n try:\n os.makedirs(protein_dir)\n except:\n pass\n\n ### create premo dir-hierarchy ###\n protein_bt_dir = os.path.join(protein_dir, os.path.basename(self.BT_dir))\n container_dir = os.path.join(protein_bt_dir, raw[\"ContainerID\"])\n crystal_dir = os.path.join(container_dir, raw[\"Directory\"])\n premo_dir = os.path.join(crystal_dir, \"premo\")\n data_dir = os.path.join(premo_dir, \"fastxds\")\n\n try:\n os.makedirs(protein_bt_dir)\n except:\n pass\n try:\n os.makedirs(container_dir)\n except:\n pass\n try:\n os.makedirs(crystal_dir)\n except:\n pass\n try:\n os.makedirs(premo_dir)\n except:\n pass\n try:\n os.makedirs(data_dir)\n except:\n pass\n\n def view_result(self):\n browser = webbrowser.get('\"/Applications/Firefox.app/Contents/MacOS/firefox\" %s')\n if self.template != \"\":\n result = self.BT_dir + \"/\" + \"peints_result.html\"\n browser.open(result)\n browser.close()\n else:\n print(\"Perform PEINTS...\")\n\n\n\n#=================================================\n# main function\n#=================================================\nif __name__ == '__main__':\n root = Tk()\n root.title(u'PEINTS -MR for ligand screening-')\n# root['bg']=\"#CCFFCC\"\n mw = main_window(root)\n root.mainloop();\n raw_input()\n\n def quit():\n root.quit()\n","repo_name":"KotaroKoiwai/PEINTS","sub_path":"peints_gui.py","file_name":"peints_gui.py","file_ext":"py","file_size_in_byte":23799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"14456959662","text":"from numpy import *\nfrom random import randint\n\ndef main():\n gameBoard = [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]\n flower = [random.randint(0,4), random.randint(0,4)]\n gameBoard[flower[0]][flower[1]] = \"F\"\n kangaroo = [0,0]\n gameBoard[kangaroo[0]][kangaroo[1]] = \"K\"\n \n for i in gameBoard:\n print(i)\n \n gameBoard[kangaroo[0]][kangaroo[1]] = \"0\"\n hopToFlower(gameBoard)\n hopToPlantFlower(gameBoard)\n \ndef hopToFlower(board):\n colHop = int(input(\"Input the column you want to hop to (0-4): \"))\n rowHop = int(input(\"Input the row you want to hop to (0-4): \"))\n \n kangaroo = [rowHop,colHop]\n board[kangaroo[0]][kangaroo[1]] = \"K\" \n \n for i in board:\n print(i)\n \n board[kangaroo[0]][kangaroo[1]] = \"0\"\n \ndef hopToPlantFlower(board):\n rowHop = int(input(\"Input the row you want to hop to plant the flower (0-4): \"))\n colHop = int(input(\"Input the column you want to hop to plant the flower (0-4): \"))\n \n flower = [rowHop,colHop]\n board[flower[0]][flower[1]] = \"F\"\n \n if(colHop + 1 <= 4):\n kangaroo = [rowHop, colHop + 1]\n board[kangaroo[0]][kangaroo[1]] = \"K\"\n elif(colHop - 1 >= 0):\n kangaroo = [rowHop, colHop-1]\n board[kangaroo[0]][kangaroo[1]] = \"K\"\n \n for i in board:\n print(i)\n \n \n \nmain()","repo_name":"ColbyH99/Assignment9","sub_path":"pluckAndPlant.py","file_name":"pluckAndPlant.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28140145178","text":"from tkinter import *\nimport pandas as pd\nimport collections\n\ndef browse():\n from tkinter.filedialog import askopenfilename\n\n Tk().withdraw()\n filename = askopenfilename()\n return filename\n\nprint('Pick survey')\nsurvey=browse()\nprint('pick answer key')\nanswers=browse()\n\nsurvey_data=pd.read_csv(survey)\nanswer_data=pd.read_csv(answers)\n\ndef calc_score(row):\n score=0\n for i in range(1,10):\n print('Q' + str(i) + ' ' + str(survey_data['Q' + str(i)][row]) + ' ' + str(answer_data['Q' + str(i)][0])+str(str(survey_data['Q'+str(i)][row])==str(answer_data['Q'+str(i)][0])))\n if (str(survey_data['Q'+str(i)][row])==str(answer_data['Q'+str(i)][0])):\n score+=1\n return score\n\ndic=collections.defaultdict(lambda :0)\nfor index in range(0,len(survey_data['ID'])):\n no=0\n if(survey_data['Finished'][index]==True or survey_data['Finished'][index]=='TRUE' and survey_data['ID'][index] not in dic.keys() ):\n dic[survey_data['ID'][index]]=calc_score(index)\n elif (survey_data['ID'][index] in dic.keys()):\n tempscore=calc_score(index)\n if(tempscore>dic[survey_data['ID'][index]]):\n dic[survey_data['ID'][index]] = calc_score(index)\n print('Happened'+str(no))\n no+=1\n\n\n\n\ndf=pd.DataFrame.from_dict(dic,orient='index')\n\ndf.to_csv('PreTest Scores.csv')\n\n\n","repo_name":"taisazero/GraderPy","sub_path":"prepost_survey_grader.py","file_name":"prepost_survey_grader.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14353042359","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\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom bs4 import BeautifulSoup\nPATH='C:\\Program Files\\chromedriver.exe'\nimport requests\ndriver=webdriver.Chrome(PATH)\nurl=\"https://turbofuture.com/internet/Short-Captions-for-Profile-Pictures\"\ndriver.get(url)\ndriver.maximize_window()\n\n\n# This function is for clicking event on interctable object in the page\ndef button_click(button):\n driver.execute_script(\"arguments[0].click();\", button)\n\n\n# This function gives us the list of urls\ndef get_urls(data):\n urls=[]\n for link in data:\n if ( link.get_attribute('href').find(\"Caption\") or link.get_attribute('href').find(\"Captions\") or link.get_attribute('href').find(\"Quotes\") )!=-1:\n urls.append(\"https://turbofuture.com\"+link.get_attribute('href'))\n return urls \n\n# # This code is for scraping the captions\ndef get_data(url_string): \n captions=[]\n pg=requests.get(url_string)\n my_data=BeautifulSoup(pg.content, 'html.parser')\n my_data=my_data.find_all('ul')\n for ul in my_data:\n ul=ul.find_all('li')\n if(len(ul)>30):\n for li in ul:\n captions.append(li.text)\n return captions\n\n\n\n\n# This portio of code is for clicking the load more button 9 times\nfor i in range(9):\n load_more = WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable((By.CLASS_NAME, 'm-component-footer--loader'))\n )\n button_click(load_more)\n \ndata = driver.find_elements(By.TAG_NAME,'phoenix-super-link') # this gives all the phoenix-super-link tag in the page\nmy_urls=get_urls(data)\n\nmy_captions=[]\n\nfor i in range (len(my_urls)):\n my_captions.append(get_data(my_urls[i]))\n\n\n\n# Creating a .txt file and writing the captions over it\n \nfile = open('captions.txt','w',encoding=\"utf-8\")\nfor obj in my_captions:\n for caption in obj:\n file.write(caption+\"\\n\")\nfile.close() \ndriver.quit()\n","repo_name":"Aashish365/CaptionsScraper","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9327573601","text":"import csv\nimport sys\nsys.path.append('/vagrant/data-science-from-scratch/code/') \nimport working_with_data as wwd\n\ndef load_ad_data():\n with open('Advertising.csv') as f:\n reader = csv.DictReader(f)\n data = [row for row in reader]\n parsers = {'Row': int, 'TV': float, 'Radio': float, 'Newspaper': float, 'Sales': float}\n data = [wwd.parse_dict(row, parsers) for row in data]\n return data\n","repo_name":"colgate-cosc480ds/lecture","sub_path":"lectures/lecture14linear-regression-iii/lecture14.py","file_name":"lecture14.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"75324508644","text":"import torch\r\nimport torch.nn.functional as F\r\nfrom math import log\r\nfrom numpy import array\r\nfrom get_data import tokenizer1\r\nfrom torch.autograd import Variable\r\nfrom chatspace import ChatSpace\r\nspacer = ChatSpace()\r\nfrom konlpy.tag import Mecab\r\nimport re\r\n\r\ndef tokenizer1(text):\r\n result_text = re.sub('[-=+.,#/\\:$@*\\\"※&%ㆍ!?』\\\\‘|\\(\\)\\[\\]\\<\\>`\\'…》;]', '', text)\r\n a = Mecab().morphs(result_text)\r\n return ([a[i] for i in range(len(a))])\r\n\r\ndef _get_length_penalty(text, alpha=1.2, min_length=5):\r\n p_list = []\r\n for i in range(len(text)):\r\n temp_text = tokenizer1(text[i][0])\r\n length = len(temp_text) \r\n p_list.append(((5 + length) ** alpha) / (5 + 1) ** alpha)\r\n \r\n lp_list = [ text[j][1]/p_list[j] for j in range(len(text)) ]\r\n return lp_list\r\n\r\ndef compair_beam_and_greedy(beam_pair, greedy_pair):\r\n lp_list = _get_length_penalty(beam_pair)\r\n gr_lp_list = _get_length_penalty(greedy_pair)\r\n\r\n low_val = float('inf')\r\n checked_sen = \"\"\r\n for idx in range(len(beam_pair)):\r\n if lp_list[idx] < low_val:\r\n low_val = lp_list[idx]\r\n checked_sen = beam_pair[idx][0]\r\n \r\n print(\" beam output > \", checked_sen, \" |\", low_val)\r\n print(\"greedy output > \", greedy_pair[0][0],\" |\", gr_lp_list[0])\r\n if low_val < gr_lp_list[0]:\r\n print(\"use beam\")\r\n else:\r\n print(\"use greedy\")\r\n\r\ndef cal_score(pred, score):\r\n \r\n pred = F.softmax(pred, dim=-1)\r\n pred_ids = pred.max(dim=-1)[0]\r\n pred_ids = pred_ids.to('cpu').tolist()\r\n score = score * -log(pred_ids)\r\n\r\n return score\r\n\r\ndef Beam_Search(data, k, first, sequences):\r\n #sequences = [[list(), 1.0]]\r\n \r\n if first:\r\n data = data.squeeze(0)\r\n else:\r\n data = data.unsqueeze(0)\r\n data = F.softmax(data, dim=-1)\r\n\r\n for row in data:\r\n all_candidates = list()\r\n for i in range(len(sequences)):\r\n seq, score = sequences[i]\r\n for j in range(len(row)):\r\n no_tensor_row = row[j].to('cpu').tolist()\r\n candidate = [seq + [j], score * -log(no_tensor_row)]\r\n all_candidates.append(candidate)\r\n ordered = sorted(all_candidates, key=lambda tup:tup[1])\r\n sequences = ordered[:k]\r\n\r\n return(sequences)\r\n\r\ndef beam(args, dec_input, enc_input_index, model, first, device, k_, LABEL):\r\n temp_dec_input = torch.zeros([k_,1], dtype=torch.long)\r\n temp_dec_input = temp_dec_input + dec_input\r\n deliver_high_beam_value = torch.zeros([k_,1], dtype=torch.long)\r\n return_sentence_beamVal_pair = []\r\n check_k = [float('inf')] * k_\r\n sequences = [[list(), 1.0]]\r\n end_sentence = []\r\n end_idx = []\r\n\r\n if first:\r\n y_pred = model(enc_input_index.to(device), dec_input.to(device))\r\n first_beam_sequence = Beam_Search(y_pred, k_, True, sequences)\r\n \r\n for i in range(len(deliver_high_beam_value)):\r\n deliver_high_beam_value[i] = first_beam_sequence[i][0][0]\r\n \r\n temp_dec_input = torch.cat(\r\n [temp_dec_input.to(torch.device('cpu')),\r\n deliver_high_beam_value.to(torch.device('cpu'))], dim=-1)\r\n \r\n check_num = 0\r\n beam_input_sequence = first_beam_sequence\r\n \r\n for i in range(args.max_len):\r\n which_value = [float('inf')] * k_\r\n which_node = [0] * k_\r\n\r\n for j in range(len(temp_dec_input)):\r\n if temp_dec_input[j][-1] == torch.LongTensor([3]):\r\n continue\r\n y_pred = model(enc_input_index.to(device), temp_dec_input[j].unsqueeze(0).to(device))\r\n beam_seq = Beam_Search(y_pred.squeeze(0)[-1], k_, False, [beam_input_sequence[j]])\r\n \r\n beam_input_sequence[j] = [[beam_seq[0][0][-1]], beam_seq[0][1]]\r\n which_node[j] = beam_seq[0][0][-1] # k개의 output중 누적확률 높은 거 get\r\n \r\n for l in range(len(deliver_high_beam_value)):\r\n if temp_dec_input[j][-1] == torch.LongTensor([3]):\r\n continue\r\n deliver_high_beam_value[l] = which_node[l]\r\n \r\n temp_dec_input = torch.cat(\r\n [temp_dec_input.to(torch.device('cpu')),\r\n deliver_high_beam_value.to(torch.device('cpu'))], dim=-1)\r\n \r\n for x in range(len(temp_dec_input)):\r\n for y in range(len(temp_dec_input[x])):\r\n if temp_dec_input[x][y] == torch.LongTensor([3]) and check_k[x] == float('inf'):\r\n check_k[x] = beam_input_sequence[x][1]\r\n\r\n if i+1 == args.max_len:\r\n for k in range(k_):\r\n for kk in range(len(temp_dec_input[k])):\r\n if temp_dec_input[k][kk] == torch.LongTensor([3]):\r\n check_num += 1\r\n end_sentence.append(temp_dec_input[k])\r\n end_idx.append(k)\r\n break\r\n \r\n for l in range(len(end_sentence)):\r\n pred = []\r\n for idx in range(len(end_sentence[l])):\r\n \r\n if end_sentence[l][idx] == torch.LongTensor([3]):\r\n pred_sentence = \"\".join(pred)\r\n pred_str = spacer.space(pred_sentence)\r\n #print(pred_str, \" |\", check_k[end_idx[l]])\r\n return_sentence_beamVal_pair.append([pred_str, check_k[end_idx[l]]])\r\n break\r\n else:\r\n if idx == 0:\r\n continue\r\n pred.append(LABEL.vocab.itos[end_sentence[l][idx]]) \r\n return return_sentence_beamVal_pair\r\n\r\ndef inference(device, args, TEXT, LABEL, model, sa_model):\r\n from KoBERT.Sentiment_Analysis_BERT_main import bert_inference\r\n sentence = input(\"문장을 입력하세요 : \")\r\n se_list = [sentence]\r\n\r\n # https://github.com/SKTBrain/KoBERT\r\n # SKT 에서 공개한 KoBert Sentiment Analysis 를 통해 입력문장의 긍정 부정 판단.\r\n sa_label = int(bert_inference(sa_model, se_list))\r\n\r\n sa_token = ''\r\n # SA Label 에 따른 encoder input 변화.\r\n if sa_label == 0:\r\n sa_token = TEXT.vocab.stoi['']\r\n else:\r\n sa_token = TEXT.vocab.stoi['']\r\n\r\n enc_input = tokenizer1(sentence)\r\n enc_input_index = []\r\n\r\n for tok in enc_input:\r\n enc_input_index.append(TEXT.vocab.stoi[tok])\r\n\r\n # encoder input string to index tensor and plus \r\n if args.per_soft:\r\n enc_input_index.append(sa_token)\r\n\r\n for j in range(args.max_len - len(enc_input_index)):\r\n enc_input_index.append(TEXT.vocab.stoi[''])\r\n\r\n enc_input_index = Variable(torch.LongTensor([enc_input_index]))\r\n\r\n dec_input = torch.LongTensor([[LABEL.vocab.stoi['']]])\r\n #print(\"긍정\" if sa_label == 1 else \"부정\")\r\n\r\n model.eval()\r\n pred = []\r\n \r\n beam_k = 10\r\n beam_sen_val_pair = beam(args, dec_input, enc_input_index, model, True, device, beam_k, LABEL)\r\n greedy_pair = []\r\n for i in range(args.max_len):\r\n y_pred = model(enc_input_index.to(device), dec_input.to(device))\r\n if i == 0:\r\n score = cal_score(y_pred.squeeze(0)[-1], 1.0)\r\n else:\r\n score = cal_score(y_pred.squeeze(0)[-1], score )\r\n \r\n y_pred_ids = y_pred.max(dim=-1)[1]\r\n \r\n if (y_pred_ids[0, -1] == LABEL.vocab.stoi['']):\r\n y_pred_ids = y_pred_ids.squeeze(0)\r\n #print(\">\", end=\" \")\r\n for idx in range(len(y_pred_ids)):\r\n if LABEL.vocab.itos[y_pred_ids[idx]] == '':\r\n pred_sentence = \"\".join(pred)\r\n pred_str = spacer.space(pred_sentence)\r\n #print(pred_str, \" |\", score)\r\n greedy_pair.append([pred_str, score])\r\n break\r\n else:\r\n pred.append(LABEL.vocab.itos[y_pred_ids[idx]])\r\n \r\n compair_beam_and_greedy(beam_sen_val_pair, greedy_pair)\r\n return 0\r\n\r\n dec_input = torch.cat(\r\n [dec_input.to(torch.device('cpu')),\r\n y_pred_ids[0, -1].unsqueeze(0).unsqueeze(0).to(torch.device('cpu'))], dim=-1)\r\n \r\n \r\n","repo_name":"BM-K/Styling-Chatbot-with-Transformer","sub_path":"Chatbot/generation.py","file_name":"generation.py","file_ext":"py","file_size_in_byte":8323,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"52"} +{"seq_id":"1290284088","text":"with open(\"part1.txt\", \"r\") as file:\n data = file.readline()\n\n ignore = False\n garbage = False\n score = 0\n curr_depth = 0\n removed = 0\n for char in data:\n if garbage:\n if ignore:\n ignore = False\n continue\n if char == \"!\":\n ignore = True\n elif char == \">\": # end garbage\n garbage = False\n else:\n removed += 1\n else:\n if char == \"{\": # open group\n curr_depth += 1\n score += curr_depth\n elif char == \"}\": # close group\n curr_depth -= 1\n elif char == \"<\": # start garbage\n garbage = True\n print(score)\n print(removed)","repo_name":"kihira/AdventOfCode2017","sub_path":"day9/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25282073797","text":"#!/usr/bin/env python3\n# read and plot lattices\n\n# Check files\nwith open('./lattice_output.txt') as f:\n latout = f.readlines()\n\n# attempt to get site types\nwith open('./lattice_input.dat') as g:\n for iLine in g.readlines():\n if 'site_type_names' in iLine:\n site_names = [i for i in iLine.split()[1:]]\n\n# Get coords: site_dict dictionary of sites by index\nlat_cell = [[float(i) for i in latout[j].split()[1:3]] for j in range(2)]\nsite_dict = {}\nsite_type = {}\nfor isite in latout[2:]:\n isite_ = isite.split()\n site_type[int(isite_[3])] = {'x':[], 'y':[], 'site_num':[]}\n site_dict[int(isite_[0])] = {'site_type': int(isite_[3]),\n 'position':[float(i) for i in isite_[1:3]],\n 'coordination': int(isite_[4]),\n 'neighbours': [int(i) for i in isite_[5:] if not i=='0']\n }\n# for debug dictionary of sites by index\n[print(str(i)+' = '+site_dict[i].__str__()) for i in site_dict]; print('-'*80)\n\n# Get coords: site_types dictionary of sites by site type\nfor i in list(site_dict.keys()):\n isite = site_dict[i]\n site_type[isite['site_type']]['x'].append(isite['position'][0])\n site_type[isite['site_type']]['y'].append(isite['position'][1])\n site_type[isite['site_type']]['site_num'].append(i)\n\n# debug\n# for i in list(site_type.keys()):\n# [print(str(i)+'-'+str(j)+'='+str(site_type[i][j])) for j in list(site_type[i].keys())]\n# print('.'*20)\n# print('-'*80)\n\n# plotting\nimport matplotlib.pyplot as plt\nncolspecies = int(len(site_type)/8) if int(len(site_type)/8) > 0 else 1\nfig, ax = plt.subplots(1,1, figsize=(7+1.06*ncolspecies,4.), dpi=80)\nplt.subplots_adjust(left=0.09, right=0.94-.11*ncolspecies+.01*(ncolspecies-1),\n top=0.95, bottom=0.12)\nax.set_aspect('equal', adjustable='box')\n\n\nfor itype in list(site_type.keys()):\n plt.scatter(site_type[itype]['x'], site_type[itype]['y'],\n alpha=.3, marker='o', s=80)\n#if input(' > add bonds ? (def=False/*=True) : '):\n# bonds=[]\n# for i in list(site_dict.keys()):\n# for j in site_dict[i]['neighbours']:\n\ntry:\n while True:\n addthis = int(input(' > Add site number (def=False/*=True)? : '))\n #plt.scatter(site_dict[addthis]['position'][0],\n # site_dict[addthis]['position'][1],\n # marker='$'+str(addthis)+'$', color='k', s=20)\n plt.annotate(str(addthis),\n xy=(site_dict[addthis]['position'][0], site_dict[addthis]['position'][1]),\n xycoords='data', va='center', ha='center')\nexcept ValueError:\n pass\n\n# add box\nif input(' > Add box (*/def=False) ?: '):\n draw_box = [[0,0], lat_cell[0], [i+j for i, j in zip(lat_cell[0], lat_cell[1])], lat_cell[1], [0,0]]\n plt.plot([i[0] for i in draw_box], [i[1] for i in draw_box], color='k', alpha=.5, linestyle='dashed')\n\n\nplt.show()\n\n\n\n\n\n","repo_name":"sebagodoy/Zacros_tools","sub_path":"zacros.Plot.lattice.py","file_name":"zacros.Plot.lattice.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36389821036","text":"#Range Sum of BST\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n def rangeSumBST(self, root, low, high):\n \"\"\"\n :type root: TreeNode\n :type low: int\n :type high: int\n :rtype: int\n \"\"\"\n left_sum=0\n right_sum=0\n total_sum=0\n if root.left != None:\n left_sum = self.rangeSumBST(root.left,low,high)\n if root.right != None:\n right_sum = self.rangeSumBST(root.right,low,high)\n total_sum= left_sum+right_sum\n if root.val<=high and root.val>=low:\n total_sum=total_sum+root.val\n \n return total_sum\n \n \n \n \n","repo_name":"jmesich/leetcode","sub_path":"nov15.py","file_name":"nov15.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72898461604","text":"from django.test import TestCase\nfrom rest_framework.test import APIClient\n\nclass teste(TestCase):\n\n @classmethod\n def setUp(cls):\n super(teste, cls)\n cls.client = APIClient()\n\n# Teste get\n def test_register1(self):\n response = self.client.get('/usuarios')\n assert response.status_code == 200\n\n# Teste post\n def test_register2(self):\n data = {\n \"nome\": \"teste\",\n \"email\": \"teste@teste.com\", \n \"senha\": \"teste123\",\n \"tipo\": 1,\n }\n response = self.client.post('/usuarios', data)\n assert response.status_code == 201\n\n# Teste caso o email nao estiver no formato correto\n def test_register3(self):\n data = {\n \"nome\": \"teste\",\n \"email\": \"teste\",\n \"senha\": \"teste123\",\n \"tipo\": 1,\n }\n response = self.client.post('/usuarios', data)\n assert response.status_code == 400\n\n# Teste caso o email estiver vazio\n def test_register4(self):\n data = {\n \"nome\": \"teste\",\n \"email\": \" \",\n \"senha\": \"teste123\",\n \"tipo\": 1,\n }\n response = self.client.post('/usuarios', data)\n assert response.status_code == 400\n\n# Teste caso o nome estiver vazio\n def test_register5(self):\n data = {\n \"nome\": \" \",\n \"email\": \"teste@teste.com\",\n \"senha\": \"teste123\",\n \"tipo\": 1,\n }\n response = self.client.post('/usuarios', data)\n assert response.status_code == 400\n\n# Teste caso senha estiver vazia\n def test_register6(self):\n data = {\n \"nome\": \"teste\",\n \"email\": \"teste@teste.com\",\n \"senha\": \" \",\n \"tipo\": 1,\n }\n response = self.client.post('/usuarios', data)\n assert response.status_code == 400\n\n","repo_name":"agildojunior/APIintegrador","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32059224830","text":"\"\"\"\nia.cecil\n\nCopyleft 2012-2023 Iuri Guilherme \n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\nMA 02110-1301, USA.\n\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom aiogram import (\n filters,\n types,\n)\n\nclass IsReplyToIdFilter(filters.BoundFilter):\n key = 'is_reply_to_id'\n def __init__(self, is_reply_to_id):\n self.is_reply_to_id = is_reply_to_id\n async def check(self, msg: types.Message):\n if msg.reply_to_message and (\n msg.reply_to_message.from_user.id == self.is_reply_to_id\n ):\n return True\n\nclass WhoJoinedFilter(filters.BoundFilter):\n key = 'unwanted'\n def __init__(self, unwanted):\n self.unwanted = unwanted\n async def check(self, msg: types.Message):\n if 'new_chat_member' in msg and str(\n msg['new_chat_member'].get('first_name', ''\n ).lower() in self.unwanted\n ):\n return True\n","repo_name":"iuriguilherme/iacecil","sub_path":"src/iacecil/controllers/aiogram_bot/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"27546763456","text":"# -*- coding: utf-8 -*-\n# @author WuJing\n# @created 2023/4/4\nfrom typing import Tuple\nimport tensorlayerx as tlx\nimport gammagl\nfrom gammagl.sparse import SparseGraph\n\n\ndef saint_subgraph(src: SparseGraph, node_idx) -> Tuple:\n row, col, value = src.coo()\n rowptr = src.storage.rowptr()\n\n # data = torch.ops.torch_sparse.saint_subgraph(node_idx, rowptr, row, col)\n data = gammagl.ops.sparse.saint_subgraph(node_idx, rowptr, row, col)\n row, col, edge_index = data\n\n if value is not None:\n value = tlx.gather(value, edge_index)\n\n out = SparseGraph(row=row, rowptr=None, col=col, value=value,\n sparse_sizes=(node_idx.shape[0], node_idx.shape[0]),\n is_sorted=True)\n return out, edge_index\n\n\nSparseGraph.saint_subgraph = saint_subgraph\n","repo_name":"BUPT-GAMMA/GammaGL","sub_path":"gammagl/sparse/saint.py","file_name":"saint.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"52"} +{"seq_id":"2043032169","text":"piersTravelEvents = str(input()).split(\" \")\n\npiers = int(piersTravelEvents[0])\ntravel = int(piersTravelEvents[1])\nevents = int(piersTravelEvents[2])\nids = []\n\nclass customers():\n def __init__(self, customerID: int, taps: list):\n self.customerID = customerID\n self.taps = taps\n\n def add_tap(self, tap):\n self.taps.append(tap)\n\n def get_ID(self):\n return self.customerID\n \n def get_taps(self):\n return self.taps\n \n def remove_taps(self):\n try:\n self.taps.reverse()\n self.taps.pop()\n self.taps.pop()\n self.taps.reverse()\n return 0\n except:\n return 1\n\n def calc_trip(self):\n sum = 0\n\n while len(self.taps) != 0:\n try:\n total = int(self.taps[0]) - int(self.taps[1])\n except:\n total = 100\n\n if total < 0:\n total = total * -1\n\n if total == 0:\n sum = sum + 100\n\n self.remove_taps()\n\n sum = sum + total\n\n return sum\n\ncustomer = []\n\nfor event in range(events):\n tapEvents = str(input()).split(\" \")\n customerID = tapEvents[1]\n Pier = tapEvents[0]\n shouldAdd = True\n\n for cust in customer:\n if cust.get_ID() == customerID:\n cust.add_tap(Pier)\n shouldAdd = False\n break\n else:\n shouldAdd = True\n \n if shouldAdd:\n shouldAdd = False\n customer.append(customers(customerID, [Pier]))\n ids.append(customerID)\n \n\nnot_found = True\n\nfor id in ids:\n for cust in customer:\n if id == cust.get_ID():\n not_found = False\n break\n else:\n not_found = True\n if not_found:\n customer.append(customers(id,[]))\n\ncustomer.sort(key=customers.get_ID())\n\nsum = \"\"\n\nfor custom in customer:\n trip = custom.calc_trip()\n sum = sum + str(trip) + \" \"\n\nsum = sum[:-1]\nprint(sum)","repo_name":"wotanut/UKIEPC","sub_path":"b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22415814417","text":"#To find the factorial of a number using recursion\ndef fact(num):\n if num==0:\n return 1\n elif num==1:\n return 1\n else:\n return num*fact(num-1)\nnum=int(input(\"Enter the positive integer:\"))\nprint(\"The factorial of \",num,\" is \",fact(num))\n","repo_name":"Sowbarnikasaravanan/python-programming","sub_path":"Factorialusingrec.py","file_name":"Factorialusingrec.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13118980647","text":"import GPIBPrologix\nimport csv \nimport time\nimport datetime\n\nGPIB = GPIBPrologix.ResourceManager(\"/dev/ttyACM0\")\n\n#Init Prema3040\ninst1 = GPIB.open_resource(7)\n\ninst1.query(\"R3\") #Resistance mode 3, PT100 1mA\ninst1.query(\"F2\") #Auto filter\ninst1.query(\"T7\") #Set integration time 4S\ninst1.query(\"CN0\") #Only data on query\n\ninst1.query(\"O4\") #4 Wire\ninst1.query(\"U1\") #Basic unit ON\n\ninst1.query(\"AZA1\") #Auto zero on\ninst1.query(\"AZT0300\")#Auto zero every 300seconds\n\ninst1.query(\"MAR\") #Front, Channel A, RTD\ntime.sleep(20)\nwhile(1):\n try:\n counter = 0\n a = inst1.query(\"RD?\") #Query a measurement\n prevA = a \n while(a == prevA and counter < 50):\n a = inst1.query(\"RD?\")\n time.sleep(0.1)\n counter = counter + 1\n print(round((float(a[:10])-100)/0.385,4))\n except:\n print(\"error\")\n time.sleep(1)\n","repo_name":"xansmolzy/GPIB-Scripts","sub_path":"Prema3040.py","file_name":"Prema3040.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42235699449","text":"class Solution(object):\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n ans = []\n tmp = 1\n zeroFlag = 0\n for item in nums:\n if item != 0:\n tmp *= item\n if item == 0:\n zeroFlag += 1\n if zeroFlag > 1:\n return [0]*len(nums)\n for i in range(len(nums)):\n if nums[i] == 0:\n ans.append(tmp)\n else:\n if zeroFlag == 1:\n ans.append(0)\n else:\n ans.append(tmp / nums[i])\n return ans\n\nclass Solution(object):\n def productExceptSelf(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n l = len(nums)\n ans = []\n for i in range(1, l):\n ans.append(ans[i-1] * nums[i-1])\n right = 1\n for i in range(l-1, -1, -1):\n ans[i] *= right\n right *= nums[i]\n return ans\n","repo_name":"lyiker/leetcode","sub_path":"leetcode-py/leetcode238.py","file_name":"leetcode238.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38857896036","text":"import random\nfrom pathlib import Path\n\nimport guidance\nfrom loguru import logger\n\nfrom llama_cpp_guidance.llm import LlamaCpp\n\nlogger.enable(\"llama_cpp_guidance\")\n\n# set the default language model used to execute guidance programs\nguidance.llm = LlamaCpp(\n model_path=Path(\"../../llm/models/gguf/pygmalion-2-13b.Q4_K_M.gguf\"),\n n_gpu_layers=1,\n n_threads=8,\n seed=random.randint(0, 1000000),\n)\n\n# we can use the {{gen}} command to generate text from the language model\n# note that we used a ~ at the start of the command tag to remove the whitespace before\n# it (just like in Handlebars)\n\n# we can pre-define valid option sets\nvalid_weapons = [\"sword\", \"axe\", \"mace\", \"spear\", \"bow\", \"crossbow\"]\nvalid_armor = [\"leather\", \"chainmail\", \"plate\"]\n\nname_program = guidance(\n \"\"\"The following is a character profile for an RPG game in JSON format.\n```json\n{\n \"description\": \"{{description}}\",\n \"first_name\": \"{{gen 'first_name' temperature=0.8 max_tokens=12 stop=[' ', '\"']}}\",\n \"last_name\": \"{{gen 'last_name' temperature=0.8 max_tokens=12 stop=[' ', '\"']}}\",\n}```\"\"\",\n logging=True,\n)\n\nname_output = name_program(\n description=\"A quick and nimble fighter.\",\n)\n\n\n# define the prompt\nprogram = guidance(\n \"\"\"The following is a character profile for an RPG game in JSON format.\n```json\n{\n \"description\": \"{{description}}\",\n \"name\": \"{{ name }}\",\n \"age\": {{gen 'age' pattern='[0-9]+' stop=',' temperature=1}},\n \"armor\": \"{{select 'armor' logprobs='logprobs' options=valid_armor}}\",\n \"weapon\": \"{{select 'weapon' options=valid_weapons}}\",\n \"class\": \"{{gen 'class' stop='\"'}}\",\n \"mantra\": \"{{gen 'mantra' temperature=0.8 stop='\"'}}\",\n \"strength\": {{gen 'strength' pattern='[0-9]+' stop=','}},\n \"items\": [{{#geneach 'character_items' num_iterations=3}}\n \"{{gen 'this' stop='\"' temperature=0.95}}\",{{/geneach}}\n ]\n}```\"\"\",\n logging=True,\n)\n\n# execute the prompt\noutput = program(\n description=\"A quick and nimble rouge that murdered a lich using a crossbow\",\n valid_weapons=valid_weapons,\n valid_armor=valid_armor,\n name=name_output[\"first_name\"] + \" \" + name_output[\"last_name\"],\n)\nprint(output)\n","repo_name":"nicholasyager/llama-cpp-guidance","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"52"} +{"seq_id":"20975195584","text":"import definitions\n\ndef isidentifier(token):\n \"\"\" Decides whether a string is a valid identifier (for variable etc)\"\"\"\n return token.isalpha() # <==== NEEDS CHANGED, will do for now\n \ndef iswhitespace(char):\n \"\"\" Decides whether the character passed is whitespace \"\"\"\n if char in definitions.WHITESPACE:\n return True\n else:\n return False\n\ndef istoken(token):\n \"\"\" Decides whether a string is a valid token \"\"\"\n if token in definitions.KEYWORDS:\n return True\n elif token in definitions.SYMBOLS:\n return True\n elif token in definitions.UNARY_OPS:\n return True\n elif token.isdecimal():\n return True\n elif isidentifier(token):\n return True\n else:\n return False\n\ndef gettokens(filename):\n \"\"\" Returns a list of tokens \"\"\"\n\n # Read from a file containing the code to parse\n with open(filename) as f:\n data = f.read()\n\n tokens = []\n\n cur_tok = data[0] # Start with just the first character\n\n for next_char in data[1:]+' ': # Loops through every character ( extra whitespace added to catch last token )\n if istoken(cur_tok): # If the current token is valid\n if not istoken(cur_tok+next_char): # Would the next character make token with this one?\n # If not then\n tokens.append(cur_tok) # We've found a token of just this character\n\n # Is the next char whitespace or the start of a new token\n if iswhitespace(next_char):\n cur_tok = '' # Its just whitespace, forget about it\n else:\n cur_tok = next_char # the next char starts a token\n\n else:\n # The current token is not a token on its own and we should concatenate the next character\n cur_tok += next_char\n\n else:\n # Current string is not a token\n if iswhitespace(cur_tok):\n # Could be whitespace\n cur_tok = ''\n else:\n # Could be part of a new token\n cur_tok += next_char\n\n return tokens\n\n\nclass TokenGenerator:\n # Creates a 'generator' that can be called on with next() but also has .peak() functionality to look ahead\n\n def __init__(self, filename):\n # get tokens from file\n self.tokens = gettokens(filename)\n self.i = 0\n\n # overload the next() method\n def __next__(self):\n # check that tokens[i] exists\n if self.i < len(self.tokens):\n value = self.tokens[self.i]\n self.i += 1\n return value\n else:\n # else raise similar error to a generator\n raise StopIteration\n\n # look one value ahead but don't increase i\n def peak(self):\n if self.i < len(self.tokens):\n return self.tokens[self.i]\n else:\n return None","repo_name":"IainMcWhinnie/Compiler-Project","sub_path":"tokenize.py","file_name":"tokenize.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33837460174","text":"from unicodedata import name\nfrom django.urls import path\nfrom . import views\nurlpatterns = [\n\n\n \n # --------------------------- OrderManagement -------------------------- #\n path('placeorder',views.PlaceOrder,name='PlaceOrder'),\n path('payPalPayment',views.payPalPayment,name='PayPalPayment'),\n path('CashOnDelivery',views.CashonDelivery,name='CashonDelivery'),\n path('UseWallet',views.UseWallet,name='UseWallet'),\n path('WalletPayment',views.WalletPayment,name='WalletPayment'),\n path('remove_wallet',views.remove_wallet,name='remove_wallet'),\n path('razorPayPayment',views.razorPayPayment,name='RazorPayPayment'),\n path('success',views.success,name='success'),\n\n path('orderconfirmed',views.orderConfirmed,name='OrderConfirmed'),\n path('invoice/',views.invoice,name='Invoice'),\n path('vieworderdetails',views.vieworder_Details,name='ViewOrderDetails'),\n\n path('cancelorder/',views.Cancelorder,name='Cancelorder'),\n path('returnorder/',views.order_Returned,name='OrderReturn'),\n path('cancelorderprofile/',views.Cancelorderfromprofile,name='CancelorderProfile'),\n \n path('payment-done/',views.payment_done,name='payment_done'),\n path('payment-cancelled/',views.payment_canceled,name='payment_cancelled'),\n\n # -------------------------------- applycoupon ------------------------------- #\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n]","repo_name":"vrroshni/Ecommerce_Website","sub_path":"Django_EcommerceProject/Order/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"26915942320","text":"from dokus.util import warn, find_lines, verify_identifier\n\ndef get_declares(text, filename=None):\n lines = find_lines(text)\n\n declares = []\n comments = []\n\n for index, (lineno, _content, start) in enumerate(lines):\n content = _content.strip()\n\n if content.startswith('function '):\n start += len(_content) - len(content)\n declare = _parse(text[start:], filename, lineno)\n\n if declare != None:\n declare.update({\n 'start': start,\n 'index': index,\n 'lineno': lineno,\n 'comments': comments\n })\n\n declares.append(declare)\n\n if content.startswith('//'):\n comments.append((content[2:], lineno))\n else:\n comments = []\n\n return declares\n\ndef _parse(blob, filename=None, lineno=None):\n size = 0\n\n p1 = blob.find('(')\n p2 = blob.find(')')\n p3 = blob.find('{')\n p4 = blob.find('\\n')\n\n if p1 == -1 or p2 == -1 or p3 == -1:\n warn('Invalid function declaration - missing tokens', filename=filename, lineno=lineno)\n return\n\n if p2 < p1 or p3 < p1 or p3 < p2 or (p4 != -1 and p4 < p1):\n warn('Invalid function declaration - wrong token order', filename=filename, lineno=lineno)\n return\n\n name = blob[9:p1].rstrip()\n\n if not verify_identifier(name, True):\n warn('Invalid identifier \\'{}\\''.format(name), filename=filename, lineno=lineno)\n return\n\n args = _parse_args(blob[p1 + 1:p2])\n\n if args and '::' in name:\n args = args[1:]\n\n if args != None:\n return {\n 'name': name,\n 'args': args,\n 'code': blob[:p2 + 1]\n }\n\n warn('Invalid argument list', filename=filename, lineno=lineno)\n\ndef _parse_args(text):\n if not text.split():\n return []\n\n split = map(lambda v: v.strip(), text.split(','))\n\n for item in split:\n if not item or item[0] != '%' or not verify_identifier(item[1:]):\n return\n\n return map(lambda v: v[1:], split)","repo_name":"qoh/dokus","sub_path":"dokus/declare.py","file_name":"declare.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37016609691","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\codereload\\spy.py\r\nimport inspect\r\nimport logging\r\nimport os\r\nimport sys\r\nimport time\r\nimport osutils\r\nimport signals\r\nimport uthread2 as uthread\r\nimport win32api\r\nimport zipfileutils\r\nfrom .xreload import xreload\r\nlog = logging.getLogger(__name__)\r\n\r\nclass FolderReloaderSpy(object):\r\n\r\n def __init__(self, waitables, paths, translationPaths = None):\r\n self.on_file_reloaded = signals.Signal()\r\n self.on_file_reload_failed = signals.Signal()\r\n self.runningCheckAt = 0\r\n self.startedAt = int(time.time())\r\n self.processed = {}\r\n self.waitables = waitables\r\n self.translationPaths = translationPaths or []\r\n if isinstance(paths, basestring):\r\n paths = [paths]\r\n self.handles = {}\r\n paths = map(os.path.abspath, paths)\r\n commonprefix = os.path.commonprefix(paths)\r\n if commonprefix:\r\n paths = [commonprefix]\r\n for path in paths:\r\n if not os.path.exists(path):\r\n log.warn(\"SpyFolder: Can't spy on non-existing folder %s\" % path)\r\n continue\r\n handle = win32api.FindFirstChangeNotification(path, True, win32api.FILE_NOTIFY_CHANGE_LAST_WRITE)\r\n if handle == win32api.INVALID_HANDLE_VALUE:\r\n log.warn('SpyFolder: got invalid handle for %s' % path)\r\n continue\r\n waitables.InsertHandle(handle, self)\r\n self.handles[handle] = path\r\n log.info('AutoCompiler: Now spying on %s using handle %s.', path, handle)\r\n\r\n def __del__(self):\r\n for handle in self.handles.keys():\r\n win32api.FindCloseChangeNotification(handle)\r\n\r\n def on_object_signaled(self, handle, abandoned):\r\n if abandoned:\r\n return\r\n win32api.FindNextChangeNotification(handle)\r\n self.process_folder(self.handles[handle])\r\n\r\n OnObjectSignaled = on_object_signaled\r\n\r\n def poll_for_changes(self):\r\n for handle, path in self.handles.items():\r\n if win32api.WaitForSingleObject(handle):\r\n win32api.FindNextChangeNotification(handle)\r\n self.process_folder(path)\r\n\r\n PollForChanges = poll_for_changes\r\n\r\n def reload_file(self, filename):\r\n filename = os.path.abspath(filename)\r\n filenameWoExt, extension = os.path.splitext(filename)\r\n filenameTargets = [filenameWoExt]\r\n for mapFrom, mapTo in self.translationPaths:\r\n if filenameWoExt.startswith(mapFrom):\r\n filenameTargets.append(filenameWoExt.replace(mapFrom, mapTo))\r\n\r\n for mname, module in sys.modules.items():\r\n if not module or not hasattr(module, '__file__'):\r\n continue\r\n try:\r\n modulefile = os.path.abspath(inspect.getfile(module)).rsplit('.', 1)[0]\r\n except TypeError:\r\n continue\r\n\r\n if modulefile in filenameTargets:\r\n with open(filename) as stream:\r\n source = stream.read() + '\\n'\r\n log.info('Compiling %s using source %s', module.__name__, filename)\r\n code = compile(source, filename, 'exec')\r\n log.info('Reloading %s', module)\r\n xreload(module, code)\r\n self.on_file_reloaded(filename, module)\r\n\r\n ReloadFile = reload_file\r\n\r\n def process_folder(self, path):\r\n toProcess = []\r\n filenames = []\r\n for modulename, moduleinfo in sys.modules.items():\r\n try:\r\n filenames.append(moduleinfo.__file__)\r\n except AttributeError:\r\n continue\r\n except ImportError as e:\r\n log.error('unable to monitor %s due to import error: %s', modulename, str(e))\r\n continue\r\n\r\n for filename in filenames:\r\n if not filename.lower().endswith('.py'):\r\n continue\r\n try:\r\n sourceFileDate = osutils.get_modified_time(filename)\r\n except WindowsError:\r\n if not zipfileutils.is_inside_zipfile(filename):\r\n log.exception('Failed to find %s', filename)\r\n continue\r\n\r\n lastCompile = self.processed.get(filename, self.startedAt)\r\n if sourceFileDate > lastCompile:\r\n toProcess.append(filename)\r\n self.processed[filename] = sourceFileDate\r\n\r\n if toProcess:\r\n log.info('Reloading: %s', str(toProcess))\r\n for sourceFile in toProcess:\r\n try:\r\n tstart = time.clock()\r\n self.reload_file(sourceFile)\r\n tdiff = time.clock() - tstart\r\n log.info('Took %.3fs to reload %s', tdiff, os.path.basename(sourceFile))\r\n except Exception:\r\n log.exception(\"ReloadFile failed for '%s'.\", sourceFile)\r\n self.on_file_reload_failed(sourceFile, sys.exc_info())\r\n\r\n ProcessFolder = process_folder\r\n\r\n\r\ndef __reload_update__(old_module_dict):\r\n log.info('autocompile module got reloaded. old dict keys: %s', old_module_dict.keys())\r\n\r\n\r\ndef spy(paths, delay = 0.5):\r\n if isinstance(paths, basestring):\r\n paths = [paths]\r\n waitables = win32api.Waitables()\r\n folderspy = FolderReloaderSpy(waitables, paths)\r\n tasklet = uthread.start_tasklet(_poll_spy, folderspy, delay)\r\n return (folderspy, tasklet)\r\n\r\n\r\ndef _poll_spy(spyfolder, delay):\r\n while True:\r\n spyfolder.waitables.Wait(0)\r\n uthread.sleep(delay)\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/codereload/spy.py","file_name":"spy.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"29558598230","text":"from flask import Flask, render_template, request\nfrom keras.models import load_model\nimport cv2\nimport numpy as np\nimport tensorflow as tf\n\napp = Flask(__name__)\n\ndic = {0 : 'Áo thun', 1 : 'Quần dài', 2: 'Áo len', 3: 'Đầm', 4: 'Áo khoác',\n 5: 'Sandal', 6: 'Áo sơ mi', 7:'Giày thể thao', 8: 'Túi xách', 9: 'Ủng'}\n\nmodel = load_model('VGG16_50epoch.h5')\nmodel.make_predict_function()\n\ndef predict_label(path_file):\n\timage = cv2.imread(path_file)\n\timage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\timage = cv2.resize(image,(28,28))\n\n\timage = 1 - image/255\n\timage = np.expand_dims(image, 2)\n\timage = tf.expand_dims(image, 0)\n\n\tpre = model.predict(image)\n\tprediction=np.argmax(pre,axis=1)\n\tprint([prediction[0]])\n\treturn dic[prediction[0]]\n \n# routes\n@app.route(\"/\", methods=['GET', 'POST'])\ndef main():\n\treturn render_template(\"index.html\")\n\n@app.route(\"/submit\", methods = ['GET', 'POST'])\ndef get_output():\n\tif request.method == 'POST':\n\t\timg = request.files['my_image']\n\n\t\timg_path = \"static/\" + img.filename\t\n\t\timg.save(img_path)\n\n\t\tp = predict_label(img_path)\n\treturn render_template(\"index.html\", prediction = p, img_path = img_path)\n\n\nif __name__ =='__main__':\n\tapp.run(debug = True)","repo_name":"pvthachh/WEB-Flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42132704640","text":"#from typing import List\n#import random\n#import subprocess\n#import sys\nimport numpy\nimport pandas\nimport MDAnalysis\nfrom MDAnalysis.analysis import contacts\nfrom statsmodels.stats.multicomp import pairwise_tukeyhsd\nfrom scipy.stats import ttest_ind, shapiro, f_oneway, ranksums\n\n#def calculate_SASA(xtcFileStr: str, tprFileStr: str, beginStr: str, endStr: str, supressOutputBool: bool):\n# #the input file to specify protein is sasa_protein.txt (a value of 6)\n# processCommandList: List = []\n# processCommandList[0] = \"gmx\"\n# processCommandList[1] = \"sasa\"\n# processCommandList[2] = \"-f\"\n# processCommandList[3] = xtcFileStr\n# processCommandList[4] = \"-s\"\n# processCommandList[5] = tprFileStr\n#\n# result = subprocess.run([processCommandList, capture_output=True, text=True)\n#\n# if supressOutputBool == False:\n# print(\"stdout\", result.stdout)\n# print(\"stderr\", result.stderr)\n# pass\nNORMAL_STR = \"normal\"\nRADIUS = 10\nPROTEIN_SELECTION_STR: str = \"protein\"\nLIPID_SELECTION_STR: str = \"resname DPPC or resname POPC\"\nFRAME_COLLECTION_POINT_INT: int = 1 #this must change\nPROTEIN_STR: str = \"Protein\"\nLIPID_STR: str = \"Lipid\"\nPROTEIN_LIPID_STR: str = \"ProteinLipid\"\nCONTROL_DIR_STR: str = \"CONTROLS/\"\n\n#load the control metrics\nallMonomerProteinArray = numpy.loadtxt(CONTROL_DIR_STR + \"allMonomerProteinArray.txt\")\nmonomerDimerProteinArray = numpy.loadtxt(CONTROL_DIR_STR + \"monomerDimerProteinArray.txt\")\ntwoDimersProteinArray = numpy.loadtxt(CONTROL_DIR_STR + \"twoDimersProteinArray.txt\")\nmonomerTrimerProteinArray = numpy.loadtxt(CONTROL_DIR_STR + \"monomerTrimerProteinArray.txt\")\nfourmerProteinArray = numpy.loadtxt(CONTROL_DIR_STR + \"fourmerProteinArray.txt\")\n\nallMonomerLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"allMonomerLipidArray.txt\")\nmonomerDimerLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"monomerDimerLipidArray.txt\")\ntwoDimersLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"twoDimersLipidArray.txt\")\nmonomerTrimerLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"monomerTrimerLipidArray.txt\")\nfourmerLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"fourmerLipidArray.txt\")\n\nallMonomerProteinLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"allMonomerProteinLipidArray.txt\")\nmonomerDimerProteinLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"monomerDimerProteinLipidArray.txt\")\ntwoDimersProteinLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"twoDimersProteinLipidArray.txt\")\nmonomerTrimerProteinLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"monomerTrimerProteinLipidArray.txt\")\nfourmerProteinLipidArray = numpy.loadtxt(CONTROL_DIR_STR + \"fourmerProteinLipidArray.txt\")\n\n\ndef gen_final_frames(epocDirStr: str, popSizeInt: int):\n print(\"Retrieving all frames after the \" + str(FRAME_COLLECTION_POINT_INT) + \" frame.\")\n scoreList = []\n for i in range(popSizeInt): #0, 1, 2, ... popSizeInt-1\n groFileStr: str = epocDirStr + str(i) + \"/npt_prod.gro\"\n xtcFileStr: str = epocDirStr + str(i) + \"/npt_prod.xtc\"\n universe = MDAnalysis.Universe(groFileStr, xtcFileStr)\n proteinAG = universe.select_atoms(PROTEIN_SELECTION_STR)\n lipidAG = universe.select_atoms(LIPID_SELECTION_STR)\n\n timeSeriesList = []\n for timeStepTS in universe.trajectory:\n currentFrameInt: int = timeStepTS.frame\n\n if currentFrameInt >= FRAME_COLLECTION_POINT_INT:\n distanceProteinArray = contacts.distance_array(proteinAG.positions, proteinAG.positions, box=timeStepTS.dimensions)\n distanceLipidArray = contacts.distance_array(lipidAG.positions, lipidAG.positions, box=timeStepTS.dimensions)\n distanceProteinLipidArray = contacts.distance_array(proteinAG.positions, lipidAG.positions, box=timeStepTS.dimensions)\n\n contactsProteinInt: int = contacts.contact_matrix(distanceProteinArray, RADIUS).sum().item()\n contactsLipidInt: int = contacts.contact_matrix(distanceLipidArray, RADIUS).sum().item()\n contactsProteinLipidInt: int = contacts.contact_matrix(distanceProteinLipidArray, RADIUS).sum().item()\n\n timeSeriesList.append([contactsProteinInt, contactsLipidInt, contactsProteinLipidInt])\n\n\n timeSeriesArray = numpy.array(timeSeriesList)\n timeSeriesDF = pandas.DataFrame(timeSeriesArray, columns=[PROTEIN_STR, LIPID_STR, PROTEIN_LIPID_STR])\n scoreList.append(calculate_score(timeSeriesDF, i))\n\n return scoreList\n\ndef calculate_score(timeSeriesDF, individualIDInt: int):\n print(\"Calculating score for individual \" + str(individualIDInt))\n proteinArray = timeSeriesDF[PROTEIN_STR]\n lipidArray = timeSeriesDF[LIPID_STR]\n proteinLipidArray = timeSeriesDF[PROTEIN_LIPID_STR]\n fitnessScoreList = []\n \n proteinList = []\n stat, p = compare_2_groups(proteinArray, allMonomerProteinArray, NORMAL_STR)\n proteinList.append(stat)\n stat, p = compare_2_groups(proteinArray, monomerDimerProteinArray, NORMAL_STR)\n proteinList.append(stat)\n stat, p = compare_2_groups(proteinArray, twoDimersProteinArray, NORMAL_STR)\n proteinList.append(stat)\n fitnessScoreList.append(stat)\n stat, p = compare_2_groups(proteinArray, monomerTrimerProteinArray, NORMAL_STR)\n proteinList.append(stat)\n stat, p = compare_2_groups(proteinArray, fourmerProteinArray, NORMAL_STR)\n proteinList.append(stat)\n\n lipidList = []\n stat, p = compare_2_groups(lipidArray, allMonomerLipidArray, NORMAL_STR)\n lipidList.append(stat)\n stat, p = compare_2_groups(lipidArray, monomerDimerLipidArray, NORMAL_STR)\n lipidList.append(stat)\n stat, p = compare_2_groups(lipidArray, twoDimersLipidArray, NORMAL_STR)\n lipidList.append(stat)\n fitnessScoreList.append(stat)\n stat, p = compare_2_groups(lipidArray, monomerTrimerLipidArray, NORMAL_STR)\n lipidList.append(stat)\n stat, p = compare_2_groups(lipidArray, fourmerLipidArray, NORMAL_STR)\n lipidList.append(stat)\n\n proteinLipidList = []\n stat, p = compare_2_groups(proteinLipidArray, allMonomerProteinLipidArray, NORMAL_STR)\n proteinLipidList.append(stat)\n stat, p = compare_2_groups(proteinLipidArray, monomerDimerProteinLipidArray, NORMAL_STR)\n proteinLipidList.append(stat)\n stat, p = compare_2_groups(proteinLipidArray, twoDimersProteinLipidArray, NORMAL_STR)\n proteinLipidList.append(stat)\n fitnessScoreList.append(stat)\n stat, p = compare_2_groups(proteinLipidArray, monomerTrimerProteinLipidArray, NORMAL_STR)\n proteinLipidList.append(stat)\n stat, p = compare_2_groups(proteinLipidArray, fourmerProteinLipidArray, NORMAL_STR)\n proteinLipidList.append(stat)\n\n return(fitnessScoreList, proteinList, lipidList, proteinLipidList)\n\n\ndef compare_2_groups(array1NP, array2NP, testTypeStr: str):\n if testTypeStr == NORMAL_STR:\n stat, p = ttest_ind(array1NP, array2NP)\n else: \n stat, p = ranksums(array1NP, array2NP)\n \n return stat, p\n\n\ndef retrieve_score(scoreList):\n returnScoreList = []\n for individualScoresList in scoreList:\n twoDimerScoreList = individualScoresList[0]\n score = sum(twoDimerScoreList)/len(twoDimerScoreList)\n returnScoreList.append(score)\n \n return(returnScoreList)\n\n\n\n\n","repo_name":"acnash/SoftMachine","sub_path":"SCRIPTS/GA_analysis.py","file_name":"GA_analysis.py","file_ext":"py","file_size_in_byte":7187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8316004394","text":"#!/usr/bin/env python\n#coding:utf-8\n\n'''\nCreated on 2016年6月12日\n\n@author: lichen\n'''\n\nclass string_base(object):\n '''\n 字符串常用方法类\n '''\n\n '''\n def __init__(self, params):\n\n '''\n \n def cutline(self,strs):\n '''\n 已空格为分隔符️切割多行文本,返回值为每行的每一个单词的map\n ''' \n cutlinelist=strs.splitlines()\n linewordlist=[]\n report={}\n for i,line in enumerate(cutlinelist):\n for linewords in line.split():\n linewordlist.append(linewords)\n report[i+1]=linewordlist\n linewordlist=[]\n return report\n \n \n \n \n \n ","repo_name":"blacklc/Practice-for-python","sub_path":"src/base_class/String_base.py","file_name":"String_base.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4488680463","text":"from libqtile import widget\nfrom .theme import colors\n#import battery\n\n\n\nimport subprocess\nfrom libqtile.widget import base\n\n\nimport os\nimport re\nimport socket\nimport subprocess\nfrom libqtile import qtile\nfrom libqtile.config import Click, Drag, Group, KeyChord, Key, Match, Screen\nfrom libqtile.command import lazy\nfrom libqtile import layout, bar, widget, hook\nfrom libqtile.lazy import lazy\nfrom libqtile.utils import guess_terminal\n\n\n\n\n#------------------------------\n# Get the icons at https://www.nerdfonts.com/cheat-sheet (you need a Nerd Font)\n\ndef base(fg='text', bg='dark'): \n return {\n 'foreground': colors[fg],\n 'background': colors[bg],\n # 'foregeound_alert': color[af],\n#\t'background':[\"#000000.00\"]\n }\n\n\ndef separator():\n return widget.Sep(**base(), linewidth=0, padding=10)\n\n\ndef icon(fg='rojo', bg='dark', fontsize=16, text=\"?\"):\n return widget.TextBox(\n **base(fg, bg),\n fontsize=fontsize,\n text=text,\n padding=1\n )\n\n\ndef powerline(fg=\"azul\", bg=\"dark\"):\n return widget.TextBox(\n **base(fg, bg),\n text=\"\", # Icon: nf-oct-triangle_left\n fontsize=42,\n padding=-3\n )\n\n\ndef workspaces(): \n return [\n separator(),\n widget.GroupBox(\n **base(fg='azul'),\n font='UbuntuMono Nerd Font',\n fontsize=19,\n margin_y=3,\n margin_x=0,\n padding_y=8,\n padding_x=5,\n borderwidth=1,\n active=colors['active'],\n inactive=colors['inactive'],\n rounded=True,\n highlight_method='block',\n urgent_alert_method='block',\n urgent_border=colors['urgent'],\n this_current_screen_border=colors['focus'],\n this_screen_border=colors['grey'],\n other_current_screen_border=colors['dark'],\n other_screen_border=colors['dark'],\n disable_drag=True\n ),\n separator(),\n widget.WindowName(**base(fg='focus'), fontsize=18, padding=5,font='iosevka regular'),\n separator(),\n ]\n\n\ndef workspaces_b():\n return [\n separator(),\n separator(),\n widget.WindowName(**base(fg='azul'), padding=5,\n font='iosevka regular',\n fontsize=20,\n ),\n separator(),\n ]\n\nprimary_widgets = [\n *workspaces(),\n\n separator(),\n powerline('temp5','dark'),\n\n widget.Wttr(**base(bg='temp5',fg='blanco'),\n lang='es',\n location={\n\t'Reus': 'Reus',\n#\t'41.15883703110864, 1.1074393937575309': 'Reus',\n# '64.127146,-21.873472': 'Reykjavik',\n# '~Vostok Station': 'Nice place',\n\t},\n\tformat='%m %M',\n\tunits='m',\n\tupdate_interval=30,\n\tfontsize=16, font='iosevka regular',\n ),\n\n powerline('temp4','temp5'),\n widget.Wttr(**base(bg='temp4',fg='blanco'),\n\tlang='es',\n\tlocation={'Reus':'Reus', },\n\tformat='%w %c ',\n\tunits='m',\n\tupdate_interval=30,\n\tfontsize=16, font='iosevka regular',\n\t),\n\n\tpowerline('temp3','temp4'),\n\twidget.Wttr(**base(bg='temp3',fg='blanco'),\n\tlang='es',\n\tlocation={'Reus':'Reus',},\n\tformat='T: %t Rf: %f ',\n\tunits='m',\n\tupdate_interval=15,\n\tfontsize=16, font='iosevka regular',\n\t),\n\n powerline('temp2','temp3'),\n widget.Wttr(**base(bg='temp2',fg='blanco'),\n lang='es',\n\tlocation={'Reus':'Reus', },\n\tformat=' %P ',\n\tunits='m',\n\tupdate_interval=30,\n\tfontsize=16, font='iosevka regular',\n ),\n powerline('temp1','temp2'),\n widget.Wttr(**base(bg='temp1',fg='blanco'),\n lang='es',\n\tlocation={'Reus':'Reus', },\n\tformat=' H: %h ',\n\tunits='m',\n\tupdate_interval=30,\n\tfontsize=16, font='iosevka regular',\n\t),\n\n# hay que dublicar el codigo de weather\n\n powerline('oceano', 'temp1'),\n widget.CurrentLayoutIcon(**base(bg='oceano',fg='blanco'), scale=0.65),\n powerline('rosa', 'oceano'),\n icon(bg=\"rosa\",fg=\"blanco\", fontsize=17, text=' '), # Icon: nf-mdi-calendar_clock\n widget.Clock(**base(bg='rosa',fg='blanco'), format='%d/%m-%H:%M:%S ', fontsize=16, font='iosevka regular'),\n powerline('dark', 'rosa'),\n\n\n]\n\nsecondary_widgets = [\n\t*workspaces_b(),\n\n\tseparator(),\n\tpowerline('color4', 'dark'),\n\twidget.Net(**base(bg='color4', fg='blanco'), scale=20.65, padding=25,\n\tfont='iosevka regular',\n\tfontsize=14,\n\tmargin_y=3,\n\tmargin_x=0,\n\tpadding_y=8,\n\tpadding_x=5),\n\n\n\tpowerline('verde', 'color4'),\n\twidget.CPU(**base(bg='verde', fg='blanco'), scale=0.65, padding=5,font='iosevka regular',\n\t\tfontsize=14,margin_y=3,margin_x=0,padding_y=8,padding_x=5,\n\n\t),\n\n\n\tpowerline('rojo', 'verde'),\n\twidget.Memory(**base(bg='rojo', fg='blanco'), \n\t\tformat='{MemUsed: .0f}{mm}/{MemTotal: .0f}{mm}/{MemPercent: .0f}% /{Buffers: .0f}{mm}' ,font='iosevka regular',\n\t\tfontsize=14,margin_y=3,margin_x=0,padding_y=8,padding_x=5\n\t),\n\n\tpowerline('naranja', 'rojo'),\n\ticon(bg=\"naranja\", fg=\"blanco\", text=' '), # Icon: nf-fa-download --UPDATES SYS\n\twidget.CheckUpdates(\n\t\tfont='iosevka regular',\n\t\tscale=10.65,\n\t\tpadding=5,\n\t\tbackground=colors['naranja'],\n\t\tcolour_have_updates=colors['blanco'],\n\t\tcolour_no_updates=colors['azul'],\n\t\tno_update_string='0',\n\t\tdisplay_format='{updates}',\n\t\tupdate_interval=1800,\n\t\tcustom_command='checkupdates',\n\t),\n\n\n]\n\n\n\nwidget_defaults = {\n 'font': 'UbuntuMono Nerd Font Bold',\n 'fontsize': 14,\n 'padding': 1,\n}\nextension_defaults = widget_defaults.copy()\n\n","repo_name":"NEYKTO/dotfiles","sub_path":".config/qtile/settings/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28351474091","text":"\nfrom flask import render_template, flash, redirect, url_for, request, g, send_from_directory, app\nfrom application import celery, UPLOAD_FOLDER, security, cache, db, mail\nfrom .forms import PostForm, CommentForm, UserEditForm, ProductForm, EditPostForm, ContactForm, MessageForm, ProfileSettingsForm\nfrom werkzeug import secure_filename\nfrom .models import PostComReaction, ProdComReaction, ProductReaction, Pagination, Tag, Message, Topic\nfrom flask_json import jsonify\nfrom werkzeug.datastructures import CombinedMultiDict\nfrom urllib.request import urlopen\nfrom flask_security import login_required, current_user\nfrom flask_mail import Message as FlaskMessage\nimport facebook\nPOSTS_PER_PAGE = 6\nimport flask\nimport sys\nfrom smtplib import SMTPException\n\nfrom .helpers import *\nfrom PIL import Image, ImageDraw\n\n\nsys.path.append(flask)\n@celery.task\ndef send_async_notification(subject, sender, recipients, text_body, html_body):\n \"\"\"Background task to send an email with Flask-Mail.\"\"\"\n msg = FlaskMessage(subject,\n sender=sender,\n recipients=recipients)\n msg.body = text_body\n msg.html = html_body\n try:\n mail.send(msg)\n except SMTPException as e:\n with open('/var/log/mail/mail.log', 'a') as the_file:\n the_file.write(str(e) + \"sender:\" +sender + \"recipientd:\" +recipients + \"text_body:\"+text_body)\n\n return True\n\ndef send_mail_notification(notification):\n receiver = get_or_abort_user(User, id = notification.user_id)\n if receiver.allow_mail_notification:\n text_body = render_template(\"mails/notification_mail.txt\", receiver=receiver, notification=notification,\n info=notification.get_data())\n html_body = render_template(\"mails/notification_mail.html\", receiver=receiver,\n notification=notification, info=notification.get_data())\n\n send_async_notification.delay(\"Уведомление aqua.name\", sender=\"contact.me@aqua.name\",\n recipients=[receiver.email],\n text_body=text_body,\n html_body=html_body\n )\n\n return True\n\n\n@app.route('/dialogs/', methods = ['POST', 'GET'])\n@login_required\ndef dialogs(user_id):\n dialogs = get_dialogs_by_user_id(current_user.id)\n users_dict = get_users_for_dialog(dialogs, current_user)\n return render_template(\"dialogs.html\", dialogs = dialogs, users_dict=users_dict)\n\n@app.route('/send_message', methods = ['POST'])\n@login_required\ndef send_message():\n form = MessageForm(CombinedMultiDict((request.files, request.form)))\n if form.validate_on_submit():\n print(\"validates\")\n dialog = get_or_create_dialog(form.receiver_id.data, current_user.id)\n filename = create_filename(form.file.data)\n message = create_obj(Message, sender_id = current_user.id, receiver_id = form.receiver_id.data, participants=dialog.participants, file = filename, text = form.text.data, dialog_id = dialog.id)\n notification = create_notification(form.receiver_id.data, \"message\", {\"message_id\": message.id, \"sender_name\": current_user.username} )\n send_mail_notification(notification)\n update_dialog(dialog, short_text=message.text[:30], last_receiver = message.receiver_id, last_massage_date = message.sent_at, readed = False)\n\n return jsonify({\"user_id\" : current_user.id})\n\n\n\n@app.route('/messages_box/', methods = ['POST', \"GET\"])\n@login_required\ndef messages_box():\n page = request.args.get(\"page\")\n if not page:\n page = 1\n else:\n page = int(page) + 1\n\n form = MessageForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'GET':\n\n\n close_message_notification(current_user.id)\n messages = get_paginated_mesages(request.args.get(\"dialog_id\"), page)\n message_was_read(messages.items, current_user)\n\n dialog = get_one_obj(Dialog, id = request.args.get(\"dialog_id\"))\n dialog_was_read(dialog, current_user.id)\n\n form.receiver_id.data = get_other_participant(dialog, current_user.id)\n\n data = {'messages': render_template('messages_box.html', page = page,\n form=form, messages=messages, dialog_id = request.args.get(\"dialog_id\")),\n \"page\": page,\n \"dialog_id\": dialog.id}\n\n if request.method == 'POST' and form.validate_on_submit():\n dialog = get_or_create_dialog(form.receiver_id.data, current_user.id)\n\n filename = create_filename(form.file.data)\n message = create_obj(Message, sender_id = current_user.id, receiver_id = form.receiver_id.data, participants=dialog.participants, file = filename, text = form.text.data, dialog_id = dialog.id)\n notification = create_notification(form.receiver_id.data, \"message\", {\"message\":message.id, \"sender_name\":current_user.username} )\n send_mail_notification(notification)\n updated_dialog = update_dialog(dialog, short_text=message.text[:30], last_receiver = message.receiver_id, last_massage_date = message.sent_at, readed=False)\n messages = get_paginated_mesages(dialog.id, page)\n\n data = {'messages': render_template('messages_box.html',\n form=form, messages=messages, page =1, dialog_id = dialog.id),\n \"dialog_text\" : updated_dialog.short_text,\n \"dialog_id\" : updated_dialog.id}\n\n return jsonify(data)\n\n\n\n@app.route('/uploads/')\ndef uploaded_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'],\n filename)\n\n\n\n@celery.task\ndef publish_async_facebook(text, image):\n photo = open(os.path.join(UPLOAD_FOLDER, image), \"rb\")\n graph = facebook.GraphAPI(\"\")\n if image:\n graph.put_photo(message=text, image=photo, link=\"https://aqua.name/\")\n else:\n graph.put_object(\"\", \"feed\", message=text, link=\"https://aqua.name/\")\n return True\n\n\n\n\n@celery.task\ndef close_async_notification(user_id):\n \"\"\"Background task to make user's notifications closed.\"\"\"\n close_not_message_notification(user_id)\n return True\n\n@celery.task\ndef send_async_email(title, message):\n \"\"\"Background task to send an email with Flask-Mail.\"\"\"\n msg = FlaskMessage(title,\n sender=\"contact.me@aqua.name\",\n recipients=[\"contact.me@aqua.name\"])\n msg.body = message\n mail.send(msg)\n return True\n\n\n\n@app.route('/contact_us', methods=['GET', 'POST'])\ndef contact_us():\n form = ContactForm(request.form)\n if request.method == 'POST' and form.validate_on_submit():\n send_async_email.delay(form.email.data, form.message.data)\n flash(\"Ваше сообщение было отправлено\")\n return redirect(url_for('index'))\n if current_user.is_authenticated:\n if current_user.email:\n form.email.data = current_user.email\n return render_template(\"contact_us.html\", form=form)\n\n\n\n\n\n@app.before_request\ndef before_request():\n if current_user.is_authenticated:\n if current_user.last_seen:\n current_time = datetime.utcnow()\n if current_time - current_user.last_seen > timedelta(minutes=10):\n current_user.last_seen = datetime.utcnow() # update user.last_seen every 10 minutes\n db.session.add(current_user)\n db.session.commit()\n else:\n current_user.last_seen = datetime.utcnow()\n db.session.add(current_user)\n db.session.commit()\n\n notifications = get_open_notifications(current_user.id) #cashed notification\n for n in notifications:\n if n.name == \"message\":\n g.have_message = True #check if user has new messages\n else:\n g.new_notification = True\n\n\n\n\n# custom pipeline for python social auth\ndef save_profile(backend, user, response, *args, **kwargs):\n if backend.name == 'facebook':\n user = get_one_obj(User, id=user.id)\n url = \"http://graph.facebook.com/%s/picture?type=large\" % response['id']\n filename = str( response['id']) + \"avatar.png\"\n avatar = urlopen(url).read()\n fout = open(UPLOAD_FOLDER +\"/\" + filename , \"wb\") # filepath is where to save the image\n fout.write(avatar)\n fout.close()\n update_user_rows(user, username = response.get('name'), avatar = filename, social = True )\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n@app.route('/confirm_email')\ndef confirm_email():\n return render_template('confirm_email.html')\n\n@app.route('/')\ndef index():\n posts = get_posts_ordering(Post.published_at.desc(), 1, POSTS_PER_PAGE)\n products = get_products_ordering(Product.like_count.desc(), 1, POSTS_PER_PAGE)\n topics = get_all_obj(Topic)\n return render_template('home.html', user=current_user,\n posts=posts, products=products,\n topics = topics,\n products_relationship=get_products_relationship(products, current_user),\n posts_relationship = get_posts_relationship(posts, current_user))\n\n\n@app.route('/popular_product', methods=['GET', 'POST'])\n@app.route('/popular_product/', methods=['GET', 'POST'])\ndef popular_product(page=1):\n count = count_all_products()\n if request.args.get(\"sort\") == \"rating\":\n products = get_products_ordering(Product.like_count.desc(), page, POSTS_PER_PAGE)\n else:\n products = get_products_ordering(Product.published_at.desc(), page, POSTS_PER_PAGE)\n pagination = Pagination(page, POSTS_PER_PAGE, count)\n products_relationships=get_products_relationship(products, current_user)\n return render_template('popular_product.html',\n products_relationships = products_relationships,\n sort=request.args.get(\"sort\"),\n products = products, pagination=pagination,)\n\n\n\n\n@app.route('/last_posts', methods=['GET', 'POST'])\n@app.route('/last_posts/', methods=['GET', 'POST'])\ndef last_posts(page=1):\n if request.args.get(\"sort\") == \"rating\": # sort by datetime\n posts = get_posts_ordering(Post.like_count.desc(), page, POSTS_PER_PAGE)\n\n\n else: # sort by rating\n posts = get_posts_ordering(Post.published_at.desc(), page, POSTS_PER_PAGE)\n comments = get_last_comments_for_posts()\n comments_rel={}\n get_many_authors(comments, comments_rel)\n get_post_for_comments(comments, comments_rel)\n count = count_all_posts()\n pagination = Pagination(page, POSTS_PER_PAGE, count)\n posts_relationships=get_posts_relationship(posts, current_user)\n tags = get_last_tags()\n return render_template('last_posts.html',\n posts=posts, comments = comments, tags=tags,\n posts_relationships = posts_relationships,\n pagination=pagination, comments_rel=comments_rel,\n sort=request.args.get(\"sort\"))\n\n\n\n@app.route('/topic/', methods=['GET', 'POST'])\n@app.route('/topic//', methods=['GET', 'POST'])\ndef topic(topic, page=1):\n if request.args.get(\"sort\") == \"rating\": # sort by datetime\n posts = get_posts_ordering(Post.like_count.desc(), page, POSTS_PER_PAGE, topic_id=topic)\n\n else: # sort by rating\n posts = get_posts_ordering(Post.published_at.desc(), page, POSTS_PER_PAGE, topic_id=topic)\n topic = get_one_obj(Topic, id=topic)\n count = count_all_posts(topic_id=topic.id)\n pagination = Pagination(page, POSTS_PER_PAGE, count)\n posts_relationships=get_posts_relationship(posts, current_user)\n\n return render_template('topic.html',\n posts=posts,\n topic = topic,\n posts_relationships = posts_relationships,\n pagination=pagination,\n sort=request.args.get(\"sort\"))\n\n\n\n\n\n@app.route('/add_post', methods = ['GET', 'POST'])\n@login_required\ndef add_post():\n form = PostForm(CombinedMultiDict((request.files, request.form)))\n if request.is_xhr:\n tags = get_tags_all()\n filtered_tags = filter_tags(tags, request.form.get(\"letter\"))\n data = {'tags_menu': render_template('tags_menu.html',\n tags=filtered_tags)}\n return jsonify(data)\n\n if request.method == 'POST' and form.validate_on_submit():\n filename = create_filename(form.file.data)\n if form.topic_id.data:\n topic_id = int(form.topic_id.data)\n else:\n topic_id = 0\n post = create_obj(Post,\n title=form.title.data.strip(),\n body=form.body.data.strip(),\n user_id=current_user.id,\n image=filename,\n topic_id = topic_id)\n\n for t in form.tags.data:\n tag_name = t[\"name\"][:32]\n if tag_name:\n tag = get_or_create(Tag, name = tag_name)\n if tag[1]: # if tag created\n post.tags.append(tag[0])\n db.session.commit()\n if form.facebook_post.data:\n publish_async_facebook.delay(post.body, post.image)\n flash(\"Ваш пост был опубликован на фейбсук\")\n\n return redirect(url_for('singlepost', postid=post.id))\n return render_template(\"add_post.html\", form=form)\n\n\n\n\n\n\n@app.route('/user/')\ndef user(username):\n page = 1\n user = get_or_abort_user(User, username=username)\n print(user.allow_mail_notification, user.profile_settings)\n form = MessageForm(CombinedMultiDict((request.files, request.form)))\n form.receiver_id.data = user.id\n\n rating = count_user_rating(user)\n side_posts = get_posts_ordering(Post.published_at.desc(), page, POSTS_PER_PAGE)\n # show users posts, comments, products and saved in user profile page.\n # if user is a profile owner or user hasn't profile settings - show all containers with this content.\n # When page rendering, it show only posts container, other part rendering by ajax on click.\n\n # if current user is not profile owner, rendered content depends on profile settings.\n if user.profile_settings and current_user != user:\n profile_settings = json.loads(str(user.profile_settings))\n col_md = 0\n for value in profile_settings.values():\n if value:\n col_md +=1\n col_md = int(12 /col_md)\n\n if profile_settings[\"show_posts\"] or current_user == user:\n POSTS_PER_USER_PAGE = count_post_by_user_id(user.id)\n posts = get_posts_ordering(Post.published_at.desc(), page, POSTS_PER_USER_PAGE, user_id=user.id)\n posts_relationships = get_posts_relationship(posts, current_user)\n return render_template('user.html', posts_relationships =posts_relationships,tags=get_last_tags(),\n profile_settings=profile_settings, active_container = \"post\",\n user=user, user_id=user.id, posts=posts, side_posts=side_posts, rating=rating, form=form, col_md=col_md)\n\n elif profile_settings[\"show_comments\"]:\n COMMENTS_PER_PAGE = count_post_comments_by_user_id(user.id)\n comments = get_post_comments_by_user_id(Comment.timestamp.desc(), user.id, page,\n COMMENTS_PER_PAGE)\n comments_relationships = get_post_comment_relationships(comments, current_user)\n return render_template('user.html', comments_relationships=comments_relationships, tags=get_last_tags(),\n profile_settings=profile_settings,user=user, user_id=user.id, comments=comments,\n side_posts=side_posts, rating=rating, form=form, col_md=col_md, active_container = \"comment\")\n\n elif profile_settings[\"show_products\"]:\n PRODUCTS_PER_PAGE = count_product_by_user_id(user.id)\n products = get_products_ordering(Product.published_at.published_at(), page, PRODUCTS_PER_PAGE, user.id)\n products_relationships = get_products_relationship(products, current_user)\n return render_template('user.html', products_relationships=products_relationships, tags=get_last_tags(),\n profile_settings=profile_settings, user=user, user_id=user.id, products=products,\n side_posts=side_posts, rating=rating, form=form, col_md=col_md, active_container = \"product\")\n\n elif profile_settings[\"show_saved\"]:\n posts = get_favourite(id, Post, Post.published_at.desc())\n posts_relationships=get_products_relationship(posts,current_user)\n return render_template('user.html', posts_relationships=posts_relationships, tags=get_last_tags(),\n profile_settings=profile_settings, user=user, user_id=user.id, posts=posts,\n side_posts=side_posts, rating=rating, form=form, col_md=col_md, active_container = \"saved\")\n\n\n\n POSTS_PER_USER_PAGE = count_post_by_user_id(user.id)\n posts = get_posts_ordering(Post.published_at.desc(), page, POSTS_PER_USER_PAGE, user_id=user.id)\n posts_relationships = get_posts_relationship(posts, current_user)\n return render_template('user.html', posts_relationships=posts_relationships, tags=get_last_tags(),\n active_container=\"post\", profile_settings =None,\n user=user, user_id=user.id, posts=posts, side_posts=side_posts, rating=rating, form=form,\n col_md=3)\n\n\n\n\n\n\n\n# user_contain* - are the views, that render with ajax part of user container(in profile)\n# These are posts, product, comments and favourites written(added) by user\n@app.route('/user_contain_comment', methods=['POST'])\ndef user_contain_comment():\n page =1\n if request.form.get('contain') == \"comment\":\n COMMENTS_PER_PAGE = count_post_comments_by_user_id(request.form.get('user_id'))\n if request.form.get('sort') == \"date\":\n comments = get_post_comments_by_user_id(Comment.timestamp.desc(), request.form.get('user_id'), page, COMMENTS_PER_PAGE)\n else:\n comments = get_post_comments_by_user_id(Comment.like_count.desc(), request.form.get('user_id'), page, COMMENTS_PER_PAGE)\n comments_relationships = get_post_comment_relationships(comments, current_user)\n\n data = {'com_container': render_template('/user_container/user_contain_comment.html',\n comments_relationships=comments_relationships, comments=comments,\n user_id=request.form.get('user_id')\n )}\n else:\n COMMENTS_PER_PAGE = count_product_comments_by_user_id(request.form.get('user_id'))\n if request.form.get('sort') == \"date\":\n comments = get_product_comments_by_user_id(CommentProduct.timestamp.desc(), request.form.get('user_id'), page, COMMENTS_PER_PAGE)\n else:\n comments = get_product_comments_by_user_id( CommentProduct.like_count.desc(), request.form.get('user_id'), page, COMMENTS_PER_PAGE)\n print(comments)\n comments_relationships = get_prod_comment_relationships(comments, current_user)\n data = {'com_container': render_template('/user_container/user_contain_prod_comment.html',\n comments_relationships=comments_relationships, comments=comments,\n user_id=request.form.get('user_id')\n )}\n return jsonify(data)\n\n\n\n@app.route('/user_contain_product', methods=['POST'])\ndef user_contain_product():\n page = 1\n PRODUCTS_PER_PAGE = count_product_by_user_id(request.form.get('user_id'))\n if request.form.get('sort') == \"date\":\n products = get_products_ordering(Product.published_at.desc(), page, PRODUCTS_PER_PAGE, request.form.get('user_id'))\n\n else:\n products = get_products_ordering(Product.like_count.desc(), page, PRODUCTS_PER_PAGE, request.form.get('user_id'))\n products_relationship = get_products_relationship(products, current_user)\n\n data = {'product_container': render_template('/user_container/user_contain_product.html',\n products_relationship=products_relationship, products=products,\n user_id=request.form.get('user_id'),\n )}\n return jsonify(data)\n\n\n@app.route('/user_contain_post', methods=['POST', 'GET'])\ndef user_contain_post():\n page = 1\n POSTS_PER_USER_PAGE = count_post_by_user_id(request.form.get('user_id'))\n if request.form.get('sort') == \"date\":\n posts = get_posts_ordering(Post.published_at.desc(), page, POSTS_PER_USER_PAGE, user_id=request.form.get('user_id'))\n else:\n posts = get_posts_ordering(Post.like_count.desc(),page, POSTS_PER_USER_PAGE, user_id=request.form.get('user_id'))\n posts_relationships = get_posts_relationship(posts, current_user)\n data = {'post_container': render_template('/user_container/user_contain_post.html',\n posts_relationships=posts_relationships,\n posts=posts,\n user_id=request.form.get('user_id')\n )}\n return jsonify(data)\n\n\n@app.route('/user_contain_favourite', methods=['POST'])\ndef user_contain_favourite():\n id = request.form.get('user_id')\n if request.form.get('contain') == \"product\":\n if request.form.get('sort') == \"date\":\n products=get_favourite(id, Product, Product.published_at.desc())\n else:\n products = get_favourite(id, Product, Product.like_count.desc())\n\n data = {'favourite_container': render_template('/user_container/user_contain_prod_saved.html',\n products_relationships = get_products_relationship(products, current_user),\n products=products,\n user_id=request.form.get('user_id')\n )}\n if request.form.get('contain') == \"post\":\n if request.form.get('sort') == \"date\":\n posts = get_favourite(id, Post, Post.published_at.desc(), )\n else:\n posts = get_favourite(id, Post, Post.like_count.desc())\n\n data = {'favourite_container': render_template('/user_container/user_contain_post_saved.html',\n posts_relationship = get_posts_relationship(posts, current_user),\n posts=posts,\n user_id=request.form.get('user_id')\n )}\n\n return jsonify(data)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n@app.route('/user_notification/')\ndef user_notification(user_id):\n notifications = get_not_message_notifications(user_id)\n info = {}\n for n in notifications:\n info[n.id] = n.get_data()\n\n close_async_notification.delay(user_id)\n\n\n return render_template('users_notifications.html', notifications = notifications, info = info)\n # notifications_relationships=notifications_relationships)\n\n@celery.task\ndef async_crop(data_image, username):\n user = get_for_update(User, username=username)\n\n # get params to crop image\n width = float(data_image.get(\"width\"))\n height = float(data_image.get(\"height\"))\n x0 = int(float(data_image.get(\"x\")))\n y0 = int(float(data_image.get(\"y\")))\n x1 = x0 + width\n y1 = y0 + height\n\n # crop image and made circle\n image = Image.open(os.path.join(UPLOAD_FOLDER, user[0].avatar))\n im = image.crop((x0, y0, x1, y1))\n bigsize = (im.size[0] * 3, im.size[1] * 3)\n mask = Image.new('L', bigsize, 0)\n draw = ImageDraw.Draw(mask)\n draw.ellipse((0, 0) + bigsize, fill=255)\n mask = mask.resize(im.size, Image.ANTIALIAS)\n im.putalpha(mask)\n\n # save image\n filename = secure_filename(\"min_\" + user[0].avatar)\n filename_png = filename[:-3] + \"png\" # convert to png\n im.save(os.path.join(UPLOAD_FOLDER, filename_png))\n update_rows(user, avatar_min=filename_png)\n delete_user_cache(username)\n return True\n\n\n\n@app.route('/crop_image', methods=['GET', 'POST'])\n@login_required\ndef crop_image():\n username = current_user.username\n user = get_one_obj(User, username=username)\n if request.method == 'POST':\n data_image = request.form.to_dict()\n result = async_crop.delay(data_image, username) # give it celery\n return redirect(url_for('user', username=username))\n else:\n return render_template('crop_image.html',\n user=user)\n\n\n\n@app.route('/user_edit/', methods=['GET', 'POST'])\n@login_required\ndef user_edit(username):\n form = UserEditForm(CombinedMultiDict((request.files, request.form)))\n user = get_for_update(User, username=username)\n if current_user == user[0]:\n if request.method == 'POST' and form.validate_on_submit():\n if form.file.data:\n filename = create_filename(form.file.data) # create secure filename\n else:\n filename = user[0].avatar\n\n updated_user = update_user_rows(user[0],avatar=filename,\n username=form.username.data,\n about_me=form.about_me.data)\n if form.file.data is not None:\n return redirect(url_for('crop_image'))\n else:\n return redirect(url_for('user', username=updated_user.username))\n else:\n form.username.data = user[0].username\n form.about_me.data = user[0].about_me\n return render_template('user_edit.html',\n user=user[0],\n form=form)\n else:\n return render_template('home.html')\n\n\n@app.route('/post/', methods=['GET', 'POST'])\ndef singlepost(postid=None):\n form = CommentForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'GET':\n post = get_or_abort_post(Post, id=postid)\n\n if post.deleted:\n return render_template(\"deleted_object.html\", object=post)\n\n posts = get_posts_ordering(Post.published_at.desc(), 1, POSTS_PER_PAGE) # posts for side box\n editable = check_post_editable(post) # check if user can edit post\n comments = get_all_comments_by_post_id(post.id)\n\n post_author = get_one_obj(User, id=post.user_id)\n if_favorite = check_if_post_favourite(current_user, post) # check if post added to favourite by user, False for not login too\n comments_relationships = get_post_comment_relationships(comments, current_user)\n if current_user.is_authenticated:\n post_liked = get_one_obj(PostReaction, user_id=current_user.id,\n post_id=postid) # check if the post liked by user\n else:\n post_liked = False # for not authenticated users\n return render_template(\"single_post.html\", editable=editable, post_author=post_author,\n comments_relationships=comments_relationships, tags=get_last_tags(),\n posts=posts, post=post, form=form, comments=comments, if_favorite=if_favorite,\n post_liked=post_liked, comment_tree=get_comment_dict(comments))\n\n if request.method == 'POST' and form.validate_on_submit():\n post = get_or_abort_post(Post, id=postid)\n\n filename = create_filename(form.file.data)\n parent = request.args.get('parent')\n if request.args.get('parent') is None:\n parent = 0\n\n comment = create_obj(Comment, text=form.text.data, user_id=current_user.id,\n post_id=postid, image=filename, parent=parent)\n if post.user_id != current_user.id: # not to notify about your own comments\n\n if comment.parent == 0:\n\n\n notification = create_notification(post.user_id, \"comment_on_post\", json_data(postid, post.title, comment.id, current_user.username)) # notification for comment on post\n send_mail_notification(notification)\n else:\n parent_comment = get_one_obj(Comment, id = parent)\n\n notification = create_notification(post.user_id, \"comment_on_post\", json_data(postid, post.title, comment.id,\n current_user.username)) # notification for comment on post\n send_mail_notification(notification)\n notification = create_notification(parent_comment.user_id, \"comment_on_post_comment\", json_data(postid, post.title, comment.id, current_user.username)) # notification for parent comment on comment\n send_mail_notification(notification)\n\n comments = get_all_comments_by_post_id(postid)\n comments_relationships = get_post_comment_relationships(comments, current_user)\n\n data = {'comments': render_template('comments.html', comments_relationships=comments_relationships, comments=comments,\n comment_tree=get_comment_dict(comments), form=form)}\n return jsonify(data)\n\n\n\n\n\n@app.route('/product/', methods=['GET', 'POST'])\ndef singleproduct(product_id=None):\n form = CommentForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'GET':\n product = get_or_abort_product(Product, id=product_id)\n product_author = get_one_obj(User, id=product.user_id)\n product_images= get_all_obj(ProductImage, product_id = product.id)\n\n if product.deleted:\n return render_template(\"deleted_object.html\", object=product)\n products=get_products_ordering(Product.published_at.desc(), 1, 10) # products for side box\n images_dict={}\n products_images=get_many_images(products, images_dict)\n comments = get_all_comments_by_product_id(product_id)\n for c in comments:\n print(c.product_id, \"single\")\n if_favorite = check_if_product_favourite(current_user, product) # check if post added to favourite by user, False for not login too\n if current_user.is_authenticated:\n product_liked = get_one_obj(ProductReaction, user_id=current_user.id,\n product_id=product.id) # check if the product liked by user\n else:\n product_liked = False\n comments_relationships = get_prod_comment_relationships(comments, current_user)\n\n return render_template(\"single_product.html\",\n if_favorite=if_favorite, product_liked=product_liked, products_images=products_images,\n products=products, comments_relationships=comments_relationships,\n product=product, comments=comments, product_author=product_author,\n form=form, product_images=product_images, comment_tree=get_comment_dict(comments))\n if request.method == 'POST' and form.validate_on_submit():\n filename = create_filename(form.file.data)\n parent = request.args.get('parent')\n if request.args.get('parent') is None:\n parent = 0\n comment = create_obj(CommentProduct, text=form.text.data,\n user_id=current_user.id, product_id=product_id,\n image=filename, parent=parent)\n comments = get_all_comments_by_product_id(product_id)\n\n data = {'comments' : render_template('product_comments.html',\n comments_relationships=get_prod_comment_relationships(comments, current_user),\n comments=comments,\n comment_tree=get_comment_dict(comments), form=form)}\n return jsonify(data)\n\n\n\n\n@app.route('/add_product', methods = ['GET', 'POST'])\n@login_required\ndef add_product():\n form = ProductForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'POST' and form.validate():\n product = create_obj(Product, title=form.title.data.strip(),\n price=form.price.data.strip(),\n description=form.description.data.strip(),\n user_id=current_user.id )\n images = request.files.getlist(\"images\")\n if images:\n for img in images:\n print(img, \"filenameeeeeee\")\n filename = create_filename(img)\n\n new_image = create_obj(ProductImage, user_id=current_user.id,\n filename=filename,\n product_id=product.id)\n if form.facebook_post.data:\n publish_async_facebook.delay(product.description, filename)\n flash(\"Ваш продукт был опубликован на фейбсук\")\n return redirect(url_for('singleproduct', product_id=product.id))\n return render_template(\"add_product.html\", form=form)\n\n\n\n@app.route('/like_post', methods=['POST'])\ndef like_post():\n react_type = request.form.get('type')\n if react_type == None:\n react_type = \"like\"\n post = get_one_obj(Post, id=request.form.get('id'))\n data = increase_count(post, PostReaction, react_type,\n post_id=request.form.get('id'), user_id=current_user.id) # increase vote count of post\n return jsonify(data)\n\n\n@app.route('/like_comment', methods=['POST'])\ndef like_comment():\n react_type = request.form.get('type')\n if react_type == None:\n react_type = \"like\"\n comment = get_one_obj(Comment, id=request.form.get('id'))\n data = increase_count(comment, PostComReaction, react_type,\n comment_id=request.form.get('id'), user_id=current_user.id) # increase vote count of post\n return jsonify(data)\n\n\n\n@app.route('/like_product', methods=['POST'])\ndef like_product():\n react_type = request.form.get('type')\n if react_type == None:\n react_type = \"like\"\n product = get_one_obj(Product, id=request.form.get('id'))\n data = increase_count(product, ProductReaction, react_type, product_id=request.form.get('id'),\n user_id=current_user.id) # increase vote count of post\n return jsonify(data)\n\n\n@app.route('/like_prodcomment', methods=['POST'])\ndef like_prodcomment():\n react_type = request.form.get('type')\n if react_type == None:\n react_type = \"like\"\n comment = get_one_obj(CommentProduct, id=request.form.get('id'))\n data = increase_count(comment, ProdComReaction, react_type, comment_id=request.form.get('id'),\n user_id=current_user.id) # increase vote count of comment\n return jsonify(data)\n\n\n\n@app.route('/unlike_post', methods=['POST'])\ndef unlike_post():\n post = get_one_obj(Post, id=request.form.get('id'))\n data = check_decrease_count(post, PostReaction, post_id=request.form.get('id'),\n user_id=current_user.id) # increase vote count of post if like doesn't exist\n return jsonify(data)\n\n\n@app.route('/unlike_comment', methods=['POST'])\ndef unlike_comment():\n comment = get_one_obj(Comment, id=request.form.get('id'))\n data = check_decrease_count(comment, PostComReaction, comment_id=request.form.get('id'),\n user_id=current_user.id) # increase vote count of post if like doesn't exist\n return jsonify(data)\n\n\n@app.route('/unlike_product', methods=['POST'])\ndef unlike_product():\n product = get_one_obj(Product, id=request.form.get('id'))\n data = check_decrease_count(product, ProductReaction, product_id=request.form.get('id'),\n user_id=current_user.id) # increase vote count of post if like doesn't exist\n return jsonify(data)\n\n\n@app.route('/unlike_prodcomment', methods=['POST'])\ndef unlike_prodcomment():\n comment = get_one_obj(CommentProduct, id=request.form.get('id'))\n data = check_decrease_count(comment, ProdComReaction, comment_id=request.form.get('id'),\n user_id=current_user.id) # increase vote count of post if like doesn't exist\n return jsonify(data)\n\n\n# render comment form for comment with parent (after click discussion button)\n@app.route('/comment_form', methods=['POST'])\ndef comment_form():\n form = CommentForm(request.form)\n data = {'com_form': render_template('comment_form.html', post_id=request.form.get('post_id'),\n parent_id=request.form.get('parent_id'), form=form)}\n return jsonify(data)\n\n\n# render comment form for comment with parent (after click discussion button)\n@app.route('/product_comment_form', methods=['POST'])\ndef product_comment_form():\n form = CommentForm(request.form)\n data = {'com_form': render_template('product_comment_form.html',\n product_id=request.form.get('product_id'),\n parent_id=request.form.get('parent_id'), form=form)}\n return jsonify(data)\n\n\n\n@app.route('/add_fav_product', methods=['POST'])\ndef add_fav_product():\n product = get_or_abort_product(Product, id=request.form.get(\"product_id\"))\n add_prod_fav(current_user, product)\n return jsonify(request.form.get(\"product_id\"))\n\n\n@app.route('/add_fav_post', methods=['GET', 'POST'])\ndef add_fav_post():\n post=get_or_abort_post(Post, id=request.form.get(\"post_id\"))\n add_post_fav(current_user, post)\n return jsonify(request.form.get(\"post_id\"))\n\n\n@app.route('/delete_fav_post', methods=['GET', 'POST'])\ndef delete_fav_post():\n post = get_or_abort_post(Post, id=request.form.get(\"post_id\"))\n delete_post_fav(current_user, post)\n return jsonify(request.form.get(\"post_id\"))\n\n\n\n@app.route('/delete_fav_product', methods=['GET', 'POST'])\ndef delete_fav_product():\n product = get_or_abort_product(Product, id=request.form.get(\"product_id\"))\n delete_prod_fav(current_user, product)\n return jsonify(request.form.get(\"product_id\"))\n\n\n\n# sort comment on page '/single_post' and update data with ajax\n@app.route('/post_contain_comment', methods=['POST'])\ndef post_contain_comment():\n form = CommentForm(request.form)\n comments = get_all_comments_by_post_id(request.form.get('post_id'))\n comment_tree = get_comment_dict(comments, Comment, request.form.get('sort'), post_id=request.form.get('post_id'))\n data = {'comments': render_template('comments.html',\n comments_relationships=get_post_comment_relationships(comments, current_user),\n postid=request.form.get('post_id'),\n comments=comments,\n comment_tree=comment_tree,\n form=form)}\n return jsonify(data)\n\n\n# sort comment on page '/single_product' and update data with ajax\n@app.route('/product_contain_comment', methods=['POST'])\ndef product_contain_comment():\n form = CommentForm(request.form)\n print(request.form.get('product_id'), \"idddddddddddddd\")\n comments = get_all_comments_by_product_id(request.form.get('product_id'))\n for c in comments:\n print(c.product_id)\n comment_tree = get_comment_dict(comments, CommentProduct, request.form.get('sort'), product_id=request.form.get('product_id'))\n data = {'comments': render_template('product_comments.html',\n comments_relationships=get_prod_comment_relationships(comments, current_user),\n product_id=request.form.get('product_id'),\n comments=comments,\n comment_tree=comment_tree,\n form=form)}\n return jsonify(data)\n\n\n# The form rendered(get request) under the comment, that must be edited;\n# with post request renders with ajax part of page, that contain one comment with update data;\n# only one comment reloaded on the page this way\n@app.route('/edit_prod_comment/', methods=['GET', 'POST'])\ndef edit_prod_comment(comment_id=None):\n form = CommentForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'GET':\n comment = get_one_obj(CommentProduct, id=comment_id)\n if not check_com_editable(comment):\n data = {'noedit': \"No_editable\"}\n return jsonify(data)\n form.text.data = comment.text\n data = {'form': render_template('edit_comment.html',\n url=\"edit_prod_comment\",\n comment=comment,\n form=form)}\n return jsonify(data)\n if request.method == 'POST':\n filename = create_filename(form.file.data)\n comment = get_one_obj(CommentProduct, id=comment_id)\n update_comments_row(comment, text=form.text.data, image=filename)\n comment_list =[]\n comment_list.append(comment)\n comments_relationships = get_prod_comment_relationships(comment_list, current_user)\n\n data = {'comment': render_template('/comment_box/product_comment_box.html',\n comments_relationships=comments_relationships,\n comment=comment)}\n\n return jsonify(data)\n\n\n@app.route('/edit_post_comment/', methods=['GET', 'POST'])\ndef edit_post_comment(comment_id=None):\n form = CommentForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'GET':\n comment = get_one_obj(Comment, id=comment_id)\n if not check_com_editable(comment):\n data = {'noedit': \"No_editable\"}\n return jsonify(data)\n form.text.data = comment.text\n data = {'form': render_template('edit_comment.html',\n url = \"edit_post_comment\",\n comment=comment,\n form=form)}\n return jsonify(data)\n if request.method == 'POST':\n filename = create_filename(form.file.data)\n comment = get_one_obj(Comment, id=comment_id)\n update_comments_row(comment, text=form.text.data, image=filename)\n comment_list = []\n comment_list.append(comment)\n data = {'comment': render_template('/comment_box/post_comment_box.html',\n comments_relationships=get_post_comment_relationships(comment_list, current_user),\n comment=comment)}\n return jsonify(data)\n\n\n\n\n@app.route('/delete_post_comment', methods=['POST'])\ndef delete_post_comment():\n comment = get_one_obj(Comment, id = request.form.get(\"id\"))\n if not check_com_editable(comment):\n data = {'nodelet': \"No deletable\"}\n else:\n delete_object(comment)\n data = {'deleted': \"Comment has been deleted\"}\n return jsonify(data)\n\n\n@app.route('/delete_prod_comment', methods=['POST'])\ndef delete_prod_comment():\n comment = get_one_obj(CommentProduct, id=request.form.get(\"id\"))\n if not check_com_editable(comment):\n data = {'nodelet': \"No deletable\"}\n else:\n delete_object(comment)\n data = {'deleted': \"Comment has been deleted\"}\n return jsonify(data)\n\n\n@app.route('/delete_product', methods=['POST'])\ndef delete_product():\n product = get_one_obj(Product, id=request.form.get(\"id\"))\n delete_object(product)\n return redirect(url_for('popular_product'))\n\n\n@app.route('/edit_product', methods=['POST', 'GET'])\ndef edit_product():\n form = ProductForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'GET':\n product = get_one_obj(Product, id=request.args.get(\"id\"))\n form.description.data = product.description\n form.title.data=product.title\n form.price.data = product.price\n\n if request.method == 'POST' and form.validate_on_submit():\n\n product = get_one_obj(Product, id=request.args.get(\"id\"))\n update_product_rows(product, description=form.description.data,\n title=form.title.data,\n price=form.price.data,)\n images = request.files.getlist(\"images\")\n if images:\n for img in images:\n filename = create_filename(img)\n print(filename, \"filename\")\n new_image = create_obj(ProductImage, user_id=current_user.id,\n filename=filename,\n product_id=product.id)\n\n return redirect(url_for('singleproduct', product_id=request.args.get(\"id\")))\n return render_template(\"edit_product.html\", form=form, id=request.args.get(\"id\"))\n\n\n@app.route('/delete_post', methods=['POST'])\ndef delete_post():\n post = get_one_obj(Post, id=request.form.get(\"id\"))\n delete_object(post)\n return redirect(url_for('last_posts'))\n\n\n@app.route('/edit_post', methods=['POST', 'GET'])\ndef edit_post():\n form = EditPostForm(CombinedMultiDict((request.files, request.form)))\n if request.method == 'GET':\n post = get_one_obj(Post, id=request.args.get(\"id\"))\n if not check_post_editable(post):\n return redirect(url_for('singlepost', postid=request.args.get(\"id\")))\n form.body.data=post.body\n form.title.data=post.title\n return render_template(\"edit_post.html\", form=form, id=request.args.get(\"id\"))\n\n elif request.method == 'POST' and form.validate_on_submit():\n post = get_one_obj(Post, id=request.args.get(\"id\"))\n if form.file.data:\n filename = create_filename(form.file.data)\n else:\n filename = post.image\n update_post_rows(post, body=form.body.data,\n title=form.title.data,\n image=filename)\n return redirect(url_for('singlepost', postid=request.args.get(\"id\")))\n\n\n@app.route('/search', methods = ['POST'])\n@login_required\ndef search():\n if not g.search_form.validate_on_submit():\n return redirect(url_for('index'))\n return redirect(url_for('search_results', query = g.search_form.search.data))\n\n\n@app.route('/search_results/')\n@login_required\ndef search_results(query):\n only_tag = request.args.get(\"only_tag\")\n # if search only by tagname\n if only_tag:\n posts= get_posts_by_tagname(query)\n\n else: #if use tagname search and full text search\n posts = get_posts_search(query)\n\n return render_template('search_results.html',\n query = query,\n posts = posts,\n posts_relationships = get_posts_relationship(posts, current_user))\n\n\n@app.route('/profile_settings/', methods=['GET', 'POST'])\n@login_required\ndef profile_settings():\n\n form = ProfileSettingsForm(request.form)\n if request.method == 'GET':\n form.allow_mail_notification.data= current_user.allow_mail_notification\n if current_user.profile_settings:\n profile_settings = json.loads(str(current_user.profile_settings))\n print(profile_settings)\n form.show_comments.data = profile_settings[\"show_comments\"]\n form.show_posts.data = profile_settings[\"show_posts\"]\n form.show_products.data = profile_settings[\"show_products\"]\n form.show_saved.data = profile_settings[\"show_saved\"]\n\n if request.method == 'POST' and form.validate_on_submit():\n print(form.data)\n change_settings(current_user, form.allow_mail_notification.data, {\"show_comments\":form.show_comments.data,\n \"show_posts\":form.show_posts.data,\n \"show_products\":form.show_products.data,\n \"show_saved\":form.show_saved.data} )\n flash(\"Настройки были сохранены\")\n return redirect(url_for(\"user\", username=current_user.username))\n\n return render_template(\"profile_settings.html\", form=form)\n\n\n","repo_name":"Taniadz/fish","sub_path":"application/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":48697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71196899685","text":"from rest_framework import serializers\nfrom .models import Project, TechincalSkillset\n\nclass TechincalSkillsetSerializer(serializers.ModelSerializer):\n class Meta:\n model = TechincalSkillset\n fields = (\"frontend\",\"backend\",\"databases\",\"infrastructure\")\n\nclass ProjectSerializer(serializers.ModelSerializer):\n technical_skillset = TechincalSkillsetSerializer()\n class Meta:\n model = Project\n fields = ('id','title','technologies','technical_skillset')\n\n def create(self, validated_data):\n skillset = validated_data.pop('technical_skillset')\n data,_ = TechincalSkillset.objects.get_or_create(**skillset)\n obj = Project.objects.create(technical_skillset=data,**validated_data)\n return obj\n \n","repo_name":"akshitajain917/project_gallery","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10692624860","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nimport numpy as np\n\nfrom const import *\n\n\nclass CrossEntropy(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, props, tgt):\n tgt_props = props.gather(2, tgt.unsqueeze(2)).squeeze()\n mask = (tgt > 0).float()\n return -(tgt_props * mask).sum() / mask.sum()\n\n\nclass SelfCriticCriterion(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, props, s_words, tgt, advantage):\n advantage = (advantage - advantage.mean()) / \\\n advantage.std().clamp(min=1e-8)\n s_props = props.gather(2, s_words.unsqueeze(2)).squeeze()\n mask = (tgt > 0).float()\n advantage = advantage.unsqueeze(1).repeat(1, mask.size(1))\n advantage = advantage.detach()\n\n return - (s_props * mask * advantage).sum() / mask.sum()\n\n\nclass Model(nn.Module):\n def __init__(self, args):\n super().__init__()\n for k, v in args.__dict__.items():\n self.__setattr__(k, v)\n\n self.torch = torch.cuda if args.use_cuda else torch\n self.bsz = args.batch_size\n self.rnn_hsz = args.rnn_hsz\n self.max_len = args.max_len\n\n self.src_emb = nn.Embedding(\n args.src_vs, args.emb_dim, padding_idx=PAD)\n self.tgt_emb = nn.Embedding(\n args.tgt_vs, args.emb_dim, padding_idx=PAD)\n self.enc = nn.LSTM(args.emb_dim, args.rnn_hsz, 1,\n batch_first=True,\n dropout=args.dropout)\n self.dec_hidden = nn.Linear(args.rnn_hsz, args.rnn_hsz)\n self.dec = nn.LSTM(args.rnn_hsz, args.rnn_hsz, 1,\n batch_first=True,\n dropout=args.dropout)\n self.out = nn.Linear(self.rnn_hsz, args.tgt_vs)\n\n def encode(self, src_inp):\n emb = self.src_emb(src_inp)\n _, (hidden, _) = self.enc(emb)\n dec_hidden = self.dec_hidden(hidden)\n\n weight = next(self.parameters()).data\n c = Variable(weight.new(1, self.bsz, self.rnn_hsz).zero_())\n\n return (dec_hidden.contiguous(), c.contiguous())\n\n def forward(self, src_inp, tgt_inp):\n hiiden = self.encode(src_inp)\n word = Variable(self.torch.LongTensor([[BOS]] * self.bsz))\n emb = self.tgt_emb(word)\n outputs = []\n\n for i in range(self.max_len):\n _, hiiden = self.dec(emb, hiiden)\n props = F.log_softmax(self.out(hiiden[0][-1]), dim=-1)\n emb = self.tgt_emb(tgt_inp[:, i]).unsqueeze(1)\n\n outputs.append(props.unsqueeze(1))\n\n return torch.cat(outputs, 1)\n\n def sample(self, src_inp, max_props=True):\n hiiden = self.encode(src_inp)\n word = Variable(self.torch.LongTensor([[BOS]] * self.bsz))\n emb = self.tgt_emb(word)\n outputs, words = [], []\n\n for i in range(self.max_len):\n _, hiiden = self.dec(emb, hiiden)\n props = F.log_softmax(self.out(hiiden[0][-1]), dim=-1)\n\n if max_props:\n _, word = props.max(-1, keepdim=True)\n else:\n _props = props.data.clone().exp()\n word = Variable(_props.multinomial(1))\n outputs.append(props.unsqueeze(1))\n\n emb = self.tgt_emb(word)\n words.append(word)\n\n if max_props:\n return torch.cat(words, 1)\n\n else:\n return torch.cat(words, 1), torch.cat(outputs, 1)\n","repo_name":"ne7ermore/torch-light","sub_path":"reinforced-translate/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","stars":526,"dataset":"github-code","pt":"52"} +{"seq_id":"25894342187","text":"from django.urls import include, path\nfrom drf_yasg.views import get_schema_view\nfrom drf_yasg import openapi\nfrom rest_framework import routers\nfrom rest_api.views import (\n WelcomeView, \n DoctorViewSet, \n AppointmentViewSet\n)\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Doctor's appointment Manager\",\n default_version='v1',\n description=\"Doctor's Appointment Manager API\",\n contact=openapi.Contact(email=\"lumidelaoye22@gmail.com\")\n ),\n public=True\n)\n\nrouter = routers.DefaultRouter()\nrouter.register(r'doctor', DoctorViewSet, basename='doctor')\nrouter.register(r'appointment', AppointmentViewSet, basename='appointment')\n\nurlpatterns = [\n path(r'', include(router.urls)),\n path(\"welcome\", WelcomeView.as_view(), name=\"welcome\"),\n path(\n 'swagger',\n schema_view.with_ui('swagger', cache_timeout=0),\n name='schema-swagger-ui'\n ),\n path(\n 'redoc/',\n schema_view.with_ui('redoc', cache_timeout=0),\n name='schema-redoc'\n ),\n]","repo_name":"lumidelaoye/Doctor-Appointments","sub_path":"assessment/rest_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11745657728","text":"import vampire\n\nconfig = vampire.loadConfig(__req__,\".vampire\")\nlayouts = config.get(\"Handlers\",\"layouts_root\")\nlayout = vampire.importModule(\"basic\",layouts,__req__)\n\nclass Template(layout.Template):\n\n no_cache = True\n\n def renderTemplate(self):\n\n config = self.req.get_config()\n\n def renderItem(node,key):\n node.key.content = key\n node.value.content = config[key]\n\n keys = list(config.keys())\n keys.sort()\n\n self.template.item.repeat(renderItem,keys)\n\nhandler_html = vampire.Instance(Template)\n","repo_name":"GrahamDumpleton-abandoned/vampire","sub_path":"examples/templates/python_config.py","file_name":"python_config.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73227340325","text":"import sys\nfrom pathlib import Path\nimport torch\nimport numpy as np\nfrom omegaconf import OmegaConf\nfrom einops import rearrange\n\nfrom torch import autocast\nfrom contextlib import nullcontext\nfrom math import sqrt\nfrom adapt import ScoreAdapter\n\nimport warnings\nfrom transformers import logging\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nlogging.set_verbosity_error()\n\n\ndevice = torch.device(\"cuda\")\n\n\ndef curr_dir():\n return Path(__file__).resolve().parent\n\n\ndef add_import_path(dirname):\n sys.path.append(str(\n curr_dir() / str(dirname)\n ))\n\n\ndef load_model_from_config(config, ckpt, verbose=False):\n from ldm.util import instantiate_from_config\n print(f\"Loading model from {ckpt}\")\n pl_sd = torch.load(ckpt, map_location=\"cpu\")\n if \"global_step\" in pl_sd:\n print(f\"Global Step: {pl_sd['global_step']}\")\n sd = pl_sd[\"state_dict\"]\n model = instantiate_from_config(config.model)\n m, u = model.load_state_dict(sd, strict=False)\n if len(m) > 0 and verbose:\n print(\"missing keys:\")\n print(m)\n if len(u) > 0 and verbose:\n print(\"unexpected keys:\")\n print(u)\n\n model.to(device)\n model.eval()\n return model\n\n\ndef load_sd1_model(ckpt_root):\n ckpt_fname = ckpt_root / \"stable_diffusion\" / \"sd-v1-5.ckpt\"\n cfg_fname = curr_dir() / \"sd1\" / \"configs\" / \"v1-inference.yaml\"\n H, W = 512, 512\n\n config = OmegaConf.load(str(cfg_fname))\n model = load_model_from_config(config, str(ckpt_fname))\n return model, H, W\n\n\ndef load_sd2_model(ckpt_root, v2_highres):\n if v2_highres:\n ckpt_fname = ckpt_root / \"sd2\" / \"768-v-ema.ckpt\"\n cfg_fname = curr_dir() / \"sd2/configs/stable-diffusion/v2-inference-v.yaml\"\n H, W = 768, 768\n else:\n ckpt_fname = ckpt_root / \"sd2\" / \"512-base-ema.ckpt\"\n cfg_fname = curr_dir() / \"sd2/configs/stable-diffusion/v2-inference.yaml\"\n H, W = 512, 512\n\n config = OmegaConf.load(f\"{cfg_fname}\")\n model = load_model_from_config(config, str(ckpt_fname))\n return model, H, W\n\n\ndef _sqrt(x):\n if isinstance(x, float):\n return sqrt(x)\n else:\n assert isinstance(x, torch.Tensor)\n return torch.sqrt(x)\n\n\nclass StableDiffusion(ScoreAdapter):\n def __init__(self, variant, v2_highres, prompt, scale, precision):\n if variant == \"v1\":\n add_import_path(\"sd1\")\n self.model, H, W = load_sd1_model(self.checkpoint_root())\n elif variant == \"v2\":\n add_import_path(\"sd2\")\n self.model, H, W = load_sd2_model(self.checkpoint_root(), v2_highres)\n else:\n raise ValueError(f\"{variant}\")\n\n ae_resolution_f = 8\n\n self._device = self.model._device\n\n self.prompt = prompt\n self.scale = scale\n self.precision = precision\n self.precision_scope = autocast if self.precision == \"autocast\" else nullcontext\n self._data_shape = (4, H // ae_resolution_f, W // ae_resolution_f)\n\n self.cond_func = self.model.get_learned_conditioning\n self.M = 1000\n noise_schedule = \"linear\"\n self.noise_schedule = noise_schedule\n self.us = self.linear_us(self.M)\n\n def data_shape(self):\n return self._data_shape\n\n @property\n def σ_max(self):\n return self.us[0]\n\n @property\n def σ_min(self):\n return self.us[-1]\n\n @torch.no_grad()\n def denoise(self, xs, σ, **model_kwargs):\n with self.precision_scope(\"cuda\"):\n with self.model.ema_scope():\n N = xs.shape[0]\n c = model_kwargs.pop('c')\n uc = model_kwargs.pop('uc')\n cond_t, σ = self.time_cond_vec(N, σ)\n unscaled_xs = xs\n xs = xs / _sqrt(1 + σ**2)\n if uc is None or self.scale == 1.:\n output = self.model.apply_model(xs, cond_t, c)\n else:\n x_in = torch.cat([xs] * 2)\n t_in = torch.cat([cond_t] * 2)\n c_in = torch.cat([uc, c])\n e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2)\n output = e_t_uncond + self.scale * (e_t - e_t_uncond)\n\n if self.model.parameterization == \"v\":\n output = self.model.predict_eps_from_z_and_v(xs, cond_t, output)\n else:\n output = output\n\n Ds = unscaled_xs - σ * output\n return Ds\n\n def cond_info(self, batch_size):\n prompts = batch_size * [self.prompt]\n return self.prompts_emb(prompts)\n\n @torch.no_grad()\n def prompts_emb(self, prompts):\n assert isinstance(prompts, list)\n batch_size = len(prompts)\n with self.precision_scope(\"cuda\"):\n with self.model.ema_scope():\n cond = {}\n c = self.cond_func(prompts)\n cond['c'] = c\n uc = None\n if self.scale != 1.0:\n uc = self.cond_func(batch_size * [\"\"])\n cond['uc'] = uc\n return cond\n\n def unet_is_cond(self):\n return True\n\n def use_cls_guidance(self):\n return False\n\n def snap_t_to_nearest_tick(self, t):\n j = np.abs(t - self.us).argmin()\n return self.us[j], j\n\n def time_cond_vec(self, N, σ):\n if isinstance(σ, float):\n σ, j = self.snap_t_to_nearest_tick(σ) # σ might change due to snapping\n cond_t = (self.M - 1) - j\n cond_t = torch.tensor([cond_t] * N, device=self.device)\n return cond_t, σ\n else:\n assert isinstance(σ, torch.Tensor)\n σ = σ.reshape(-1).cpu().numpy()\n σs = []\n js = []\n for elem in σ:\n _σ, _j = self.snap_t_to_nearest_tick(elem)\n σs.append(_σ)\n js.append((self.M - 1) - _j)\n\n cond_t = torch.tensor(js, device=self.device)\n σs = torch.tensor(σs, device=self.device, dtype=torch.float32).reshape(-1, 1, 1, 1)\n return cond_t, σs\n\n @staticmethod\n def linear_us(M=1000):\n assert M == 1000\n β_start = 0.00085\n β_end = 0.0120\n βs = np.linspace(β_start**0.5, β_end**0.5, M, dtype=np.float64)**2\n αs = np.cumprod(1 - βs)\n us = np.sqrt((1 - αs) / αs)\n us = us[::-1]\n return us\n\n @torch.no_grad()\n def encode(self, xs):\n model = self.model\n with self.precision_scope(\"cuda\"):\n with self.model.ema_scope():\n zs = model.get_first_stage_encoding(\n model.encode_first_stage(xs)\n )\n return zs\n\n @torch.no_grad()\n def decode(self, xs):\n with self.precision_scope(\"cuda\"):\n with self.model.ema_scope():\n xs = self.model.decode_first_stage(xs)\n return xs\n\n\ndef test():\n sd = StableDiffusion(\"v2\", True, \"haha\", 10.0, \"autocast\")\n print(sd)\n\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"pals-ttic/sjc","sub_path":"adapt_sd.py","file_name":"adapt_sd.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","stars":464,"dataset":"github-code","pt":"52"} +{"seq_id":"8669715177","text":"from kpis import KPIs\nfrom currentkpis import CurrentKPIs\nfrom forecastkpis import ForecastKPIs\n\n# Report on current KPI values\nkpis = KPIs()\nwith CurrentKPIs(kpis), ForecastKPIs(kpis):\n kpis.set_kpis(25, 10, 5)\n kpis.set_kpis(100, 50, 30)\n kpis.set_kpis(50, 10, 20)\n\nprint(\"*****No longer in context manager.\\n\\n\")\nkpis.set_kpis(150, 110, 120)\n","repo_name":"syurskyi/Python_Topics","sub_path":"120_design_patterns/019_observer/examples/3-Observer Pattern/Observer/Assignment/Solution/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"20551867691","text":"import uuid\n\nfrom nectar_metrics import config\nfrom nectar_metrics import gnocchi\nfrom nectar_metrics.senders import base\n\n\nCONF = config.CONFIG\n\n\nclass GnocchiSender(base.BaseSender):\n\n def __init__(self):\n super(GnocchiSender, self).__init__()\n self.client = gnocchi.get_client()\n self.archive_policy = CONF.get('gnocchi', 'archive_policy')\n\n def send_metric(self, resource_type, resource_name, metric, value, time,\n by_name=False, create_resource=True):\n if by_name:\n terms = [{'=': {'name': resource_name}},\n {'=': {'ended_at': None}}]\n else:\n terms = [{'=': {'id': resource_name}}]\n\n resources = self.client.resource.search(\n resource_type=resource_type,\n query={'and': terms})\n num_resources = len(resources)\n if num_resources == 1:\n resource = resources[0]\n elif num_resources == 0:\n if not create_resource:\n self.log.error(\"Could not find resource %s\", resource_name)\n return\n\n if by_name:\n args = {'id': str(uuid.uuid4()), 'name': resource_name}\n else:\n args = {'id': resource_name}\n resource = self.client.resource.create(\n resource_type=resource_type,\n resource=args)\n else:\n self.log.error(\"More than 1 resource exists for type: %s and \"\n \"name: %s\" % (resource_type, resource_name))\n return\n\n metric_id = resource.get('metrics', {}).get(metric)\n if not metric_id:\n gmetric = self.client.metric.create(\n metric={'name': metric, 'resource_id': resource.get('id'),\n 'archive_policy_name': self.archive_policy})\n metric_id = gmetric.get('id')\n\n self.log.debug(\"Resource: %s:%s metric: %s\" % (resource_type,\n resource,\n metric))\n self.client.metric.add_measures(metric=metric_id,\n measures=[dict(timestamp=time,\n value=float(value))])\n\n def send_by_az(self, az, metric, value, time):\n self.send_metric('availability-zone', az, metric, value, time)\n\n def send_by_az_by_domain(self, az, domain, metric, value, time):\n metric = \"%s-%s\" % (metric, az)\n self.send_metric('domain', domain, metric, value, time)\n\n def send_by_tenant(self, tenant, metric, value, time):\n self.send_metric('project', tenant, metric, value, time)\n\n def send_by_az_by_tenant(self, az, tenant, metric, value, time):\n metric = \"%s-%s\" % (metric, az)\n self.send_metric('project', tenant, metric, value, time)\n\n def send_by_az_by_home(self, az, home, metric, value, time):\n metric = \"%s-%s\" % (metric, az)\n self.send_metric('allocation_home', home, metric, value, time)\n\n def send_by_host_by_home(self, host, home, metric, value, time):\n _type = 'resource_provider'\n metric = \"%s.usage.%s.%s\" % (_type, home,\n metric.replace('used_', '').rstrip('s'))\n # Don't create missing resources, since they should be created by\n # the resource_provider ceilometer poller.\n self.send_metric(_type, host, metric, value, time,\n by_name=True, create_resource=False)\n\n def send_capacity_by_site(self, site, scope, metric, value, time):\n metric = \"capacity.%s.%s\" % (scope, metric)\n self.send_metric('site', site, metric, value, time,\n by_name=True)\n\n def send_usage_by_site(self, site, scope, metric, value, time):\n metric = \"usage.%s.%s\" % (scope, metric)\n self.send_metric('site', site, metric, value, time,\n by_name=True)\n\n def send_availability_by_site(self, site, scope, metric, value, time):\n metric = \"availability.%s.%s\" % (scope, metric)\n self.send_metric('site', site, metric, value, time,\n by_name=True)\n\n def send_by_idp(self, idp, metric, value, time):\n return self.send_metric('idp', idp, metric, value, time)\n\n def send_global(self, metric, value, time):\n return self.send_metric('generic', 'global-stats', metric, value, time)\n","repo_name":"NeCTAR-RC/nectar-metrics","sub_path":"nectar_metrics/senders/gnocchi.py","file_name":"gnocchi.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"8381573316","text":"def solution(ex):\n sorted_ex = sorted(ex, key=lambda x: x[0])\n result = []\n\n for range in sorted_ex:\n if result and range[0] <= result[-1][1]:\n result[-1] = (result[-1][0], max(range[1], result[-1][1]))\n else:\n result.append(range)\n\n return result\n\ndef merge(arr):\n sorted_arr = sorted(arr, key=lambda x: x[0])\n result = []\n\n for ex in sorted_arr:\n if result and result[-1][1] >= ex[0]:\n result[-1] = (result[-1][0], max(result[-1][1], ex[1]))\n else:\n result.append(ex)\n\n return result\n\n\nif __name__ == '__main__':\n example = [\n (1, 3), (5, 8), (4, 10), (20, 25)\n ]\n print(example)\n print(solution(example))\n print(merge(example))","repo_name":"moonpiderman/all-of-algorithm","sub_path":"BankSalad/practice/snap.py","file_name":"snap.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74804761125","text":"import base64\nimport logging\nimport time\nfrom io import BytesIO\n\n\nfrom odoo import _, api, models\n\nfrom .common import getLinkedDocument, getPDFStream, moduleName, usefulInfos\n\n#constant\nFIRST_LEVEL=0\nBOM_SHOW_FIELDS=['Position','Code','Description','Quantity']\n\n\nthisModuleName=moduleName()\n\ndocRepository=\"\"\n\n\nclass report_spare_parts_header(models.AbstractModel):\n _name = 'report.pdm.spare_bom_header'\n _description = \"Report Spare Bom Header\"\n\n def _get_report_values(self, docids, data=None):\n products = self.env['product.product'].browse(docids)\n return {'docs': products,\n 'time': time,\n 'getLinkedDocument': getLinkedDocument}\n\n\nclass report_spare_parts_document(models.AbstractModel):\n \"\"\"\n Evaluates the BoM structure spare parts manual\n \"\"\"\n _name = 'report.pdm.spare_pdf_one'\n _description = \"Report Spare Bom One Level\"\n\n @api.model\n def create(self, components):\n ret=(False, '')\n recursion=True\n if self._name == 'report.pdm.spare_pdf_one':\n recursion=False\n componentType=self.env['product.product']\n bomType=self.env['mrp.bom']\n _, bookCollector = usefulInfos(self.env)\n for component in components:\n self.processedObjs = []\n buf = self.getFirstPage([component.id])\n bookCollector.addPage(buf)\n self.getSparePartsPdfFile(component, bookCollector, componentType, bomType, recursion)\n if not(bookCollector is None):\n pdf_string = BytesIO()\n bookCollector.collector.write(pdf_string)\n output= pdf_string.getvalue()\n pdf_string.close()\n byteString = b\"data:application/pdf;base64,\" + base64.b64encode(output)\n ret=byteString.decode('UTF-8')\n else:\n logging.warning('Unable to create PDF')\n return ret\n\n def getSparePartsPdfFile(self, product, bookCollector, componentTemplate, bomTemplate, recursion):\n if not(product in self.processedObjs):\n packedObjs = []\n bomObjs = bomTemplate.search([('product_id', '=', product.id), ('type', '=', 'spbom')])\n if len(bomObjs) < 1:\n bomObjs = bomTemplate.search([('product_tmpl_id', '=', product.product_tmpl_id.id), ('type', '=', 'spbom')])\n\n if not(bomObjs==None) and (len(bomObjs)>0):\n self.processedObjs.append(product)\n pdf = self.env.ref('pdm.bom_structure_one').render_qweb_pdf([bomObjs.id])[0]\n if not(pdf==None):\n pageStream = BytesIO()\n pageStream.write(pdf)\n bookCollector.addPage(pageStream)\n for pageStream, status in self.getSparePdfbyProduct(bomObjs.product_id):\n bookCollector.addPage(pageStream, status)\n \n for bom_line in bomObjs.bom_line_ids:\n packedObjs.append(bom_line.product_id)\n if recursion and (len(packedObjs) > 0):\n for packedObj in list(set(packedObjs).difference(set(self.processedObjs))):\n self.getSparePartsPdfFile(packedObj, bookCollector, componentTemplate, bomTemplate, recursion)\n\n def getSparePdfbyProduct(self, product):\n ret=[]\n for objDocument in getLinkedDocument(product, checkStatus=False, used4Spare=True):\n value=getPDFStream(docRepository, objDocument)\n if value:\n ret.append((value, _(objDocument.state)))\n return ret\n\n def getFirstPage(self, ids):\n strbuffer = BytesIO()\n pdf = self.env.ref('pdm.report_pdm_product_spare_parts_header').render_qweb_pdf(ids)[0]\n strbuffer.write(pdf)\n return strbuffer\n\n @api.model\n def _get_report_values(self, docids, data=None):\n documents = self.env['product.product'].browse(docids)\n return {'docs': documents,\n 'get_content': self.create}\n\n\nclass ReportSpareDocumentAll(report_spare_parts_document):\n _name = 'report.pdm.spare_pdf_all'\n _description = \"Report Spare Bom All Levels\"\n\n","repo_name":"falconsoft3d/odoo-sh-12-ynext","sub_path":"pdm/reports/report/spare_parts_manual.py","file_name":"spare_parts_manual.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19838197147","text":"import gzip\nfrom time import time\n\n\nclass Utils(object):\n\n @staticmethod\n def create_labels_dict(labels_file):\n s = time()\n if labels_file.endswith(\".gz\"):\n f = gzip.open(labels_file, mode='rt')\n else:\n f = open(labels_file)\n labels_dict = {}\n for row in f:\n vals = row.strip().split('\\t')\n if 'node1' in vals and 'node2' in vals:\n node1_index = vals.index('node1')\n node2_index = vals.index('node2')\n else:\n labels_dict[vals[node1_index]] = vals[node2_index].split('@')[0]\n print(f'Time taken to create labels dict: {time() - s}')\n return labels_dict\n","repo_name":"usc-isi-i2/kgtk-search","sub_path":"iwfs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"71447785124","text":"#no 2 proyek praktikum pemrograman\n#konversi string ke bahasa G tahun 90an\ntxt = input(\"Masukan Kalimat : \")\n\ndef bahasaG(txt):\n dictionary = {'a': 'aga', 'e':'ege', 'i': 'igi', 'o': 'ogo', 'u': 'ugu', 'A': 'Aga', 'E':'Ege', 'I': 'Igi', 'O': 'Ogo', 'U': 'Ugu'}\n transTable = txt.maketrans(dictionary)\n txt = txt.translate(transTable)\n print(txt)\n \nbahasaG(txt)\n","repo_name":"Ivan027void/mikrotik","sub_path":"bahasaG.py","file_name":"bahasaG.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"id","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"27815911316","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Noticia',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('titulo', models.CharField(max_length=100)),\n ('descripcion', models.CharField(max_length=200, blank=True)),\n ('imagen', models.ImageField(upload_to=b'imagenes/noticias')),\n ('publicada', models.DateTimeField(auto_now_add=True)),\n ('vistas', models.PositiveIntegerField(default=0)),\n ('creador', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['-publicada'],\n },\n ),\n ]\n","repo_name":"aaj/conecta2server","sub_path":"noticias/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71853693286","text":"from bson.objectid import ObjectId\nfrom pymongo import MongoClient\nimport json \n\nmyClient = MongoClient(\"mongodb://localhost:27017/\")\nmy_db = myClient[\"chatt\"]\n\nbot_col = my_db[\"bot\"]\nintent_col = my_db[\"intent\"]\nentity_col = my_db[\"entity\"]\n\n\ndef find_all_bot(search: str,sort_type: str, field: str):\n list_bot=[]\n \n _sort={\"asc\":1, \"desc\":-1,\"1\":1,\"-1\":-1}\n\n if(_sort.get(sort_type) != None):\n sort_type=_sort.get(sort_type)\n else:\n sort_type=1\n\n for bot in bot_col.find({\"name\":{\"$regex\":search}}).sort(field,sort_type):\n list_bot.append({ \"id\": str(bot[\"_id\"]) ,\"name\":bot[\"name\"],\"description\":bot[\"description\"],\"enabled\":bot[\"enabled\"],\n \"config\":bot[\"config\"],\"owner\":bot[\"owner\"] })\n return list_bot\n\ndef find_bot_by_id(bot_id: str):\n bot = bot_col.find_one({\"_id\": ObjectId(bot_id)})\n data= { \"id\": str(bot[\"_id\"]) ,\"name\":bot[\"name\"],\"description\":bot[\"description\"],\n \"enabled\":bot[\"enabled\"], \"config\":bot[\"config\"],\"owner\":bot[\"owner\"] }\n return data\n\ndef create_bot(bot: json):\n bot_col.insert_one(bot)\n return {\"message\":\"success\"}\n\ndef update_bot(bot_id: str , bot: json):\n bot_col.update_one({\"_id\":ObjectId(bot_id)}, {\"$set\": bot})\n return {\"message\":\"success\"} \n\ndef delete_bot(bot_id: str):\n bot_col.delete_one({\"_id\":ObjectId(bot_id)})\n return {\"message\":\"success\"}\n\n\n\n#lấy tất cả bot\n# for bot in bot_col.find():\n# print(bot)\n\n# lấy 1 document\n# bot = bot_col.find_one();\n# print(\"\\n lấy 1 bot:\")\n# print(bot) \n\n#lấy tất cả document có keyword bot\n# print(\"\\n lay thong tin name theo key\")\n# for bot in bot_col.find({\"name\":{\"$regex\": \"3\"} }):\n# print(bot)\n\n\n## lấy 1 document theo id\n# bot = bot_col.find_one({\"_id\":ObjectId(\"619f46464d46e782bca7c931\")})\n# print(bot)\n\n\n## lấy 2 document\n# print(\"lấy 2 document bot\")\n# for bot in bot_col.find().limit(2).sort(\"name\",-1):\n# print(bot)\n\n##insert 1 object Id\n# dict={\"name\": \"bot demo\", \"description\":\"this is bot demo\",\"enabled\":True, \"config\":\"auto\"}\n# bot_col.insert_one(dict)\n\n##update 1 bot theo id\n# bot_col.update({\"_id\":ObjectId(\"61a08fa9cd7d9254b0c3bb07\")},\n# {'$set':{\"name\":\"bot demo update\"} } ) \n\n##delete 1 bot theo id\n# bot_col.delete_one({\"_id\": ObjectId(\"61a08e99edc4de293aad71ba\")})\n\n## sắp xếp theo name theo asc\n# print(\"sắp xếp theo asc\")\n# botList = bot_col.find().sort(\"name\")\n# for bot in botList :\n# print(bot)\n\n## sắp xếp name theo desc\n# print(\"sắp xếp theo desc\") \n# botList = bot_col.find().sort(\"name\",-1)\n# for bot in botList :\n# print(bot)\n\n\n##insert 1000 bot\n# dict={\"name\": \"bot demo\", \"description\":\"this is bot demo\",\"enabled\":True, \"config\":\"auto\"}\n# int[1000]\n# bot_col.insert_one(dict)\n\n# bot = bot_col.find_one()\n# print(str(bot[\"_id\"]))\n\n\n\n\n## insert 1000 document bot, entity, intent\n## insert 1000 bot\n# cnt=1000\n# while(cnt):\n# dict_bot={\"name\": \"bot demo\", \"description\":\"this is bot demo\",\"enabled\":True, \"config\":\"auto\",\"owner\":\"\"}\n# name= \"bot demo \"+str(cnt) \n# description=\"this is bot demo \" + str(cnt)\n# dict_bot['name']=name\n# dict_bot['description'] = description\n# bot_col.insert_one(dict_bot)\n# cnt-=1\n\n\n# count = 1000\n# while(count):\n# cnt=1000\n# while(cnt):\n# bot=bot_col.find_one({\"name\":\"bot demo \"+str(cnt)})\n# bot_id = str(bot['_id'])\n\n# dict_entity ={\"name\":\"\",\"bg_color\":\"red\",\"fg_color\":\"C00000\",\"bot\":bot_id}\n# dict_entity[\"name\"]=\"entity \"+ str(count) + \" of bot \"+str(cnt)\n# entity_col.insert_one(dict_entity)\n\n# dict_intent ={\"name\":\"\",\"description\":\"\",\"bot\":bot_id}\n# dict_intent[\"name\"]=\"intent \"+ str(count) + \" of bot \"+str(cnt) \n# dict_intent[\"description\"] = \"this is intent \"+str(count) + \"of bot \"+str(cnt) \n# intent_col.insert_one(dict_intent)\n# cnt-=1\n# count-=1\n\n# tạo chỉ mục đơn của entity\n# reps= entity_col.create_index([(\"bot\",1)])\n# print(reps)\n\n# xóa index\n# reps = entity_col.drop_index([(\"bot\",1)])\n# print(reps)\n## tạo chỉ mục đơn của intent bot\n# reps = intent_col.create_index([(\"bot\",1)])\n# print(reps)\n\n\n# tìm tất cả entity của bot 1000\n\n# bot_id=\"61a0b47f24140ca79113ab86\"\n\n# print(\"entity\")\n# for entity in entity_col.find({\"bot\":bot_id}):\n# print(entity);\n\n# print(\"intent : \")\n# for intent in intent_col.find({\"bot\":bot_id}):\n# print(intent)\n\n# bot = bot_col.find_one({\"name\":\"bot demo 999\"})\n# bot_id = str(bot[\"_id\"])1\n\n# entity = entity_col.find_one({\"bot\":bot_id})\n# intent = intent_col.find_one({\"bot\":bot_id})\n# print(\"\\n bot:\",bot)\n# print(\"\\n entity :\",entity)\n# print(\"\\n intent: \", intent)\n\n\n\n\n# bot_col.delete_many({})\n# entity_col.delete_many({})\n# intent_col.delete_many({})\n\n\n \n \n\n \n\n\n\n \n\n\n","repo_name":"DinhHuyKhanh/fastApi","sub_path":"Buoi_3/models/bot_service.py","file_name":"bot_service.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10894893938","text":"import sys, os\n# location of utils file:\nsys.path.append(os.path.join(os.path.abspath(__file__), \"../../\"))\nsys.path.append(os.path.join(os.path.abspath(__file__), \"../../../\"))\n\nimport vsketch\nfrom shapely import geometry, affinity\n\nimport utils \n\nclass Day03SpaceSketch(vsketch.SketchClass):\n \n bg_line_count = vsketch.Param(100)\n bg_step = vsketch.Param(0.3)\n\n def draw(self, vsk: vsketch.Vsketch) -> None:\n vsk.size(\"200mmx125mm\", landscape=False)\n vsk.scale(\"mm\")\n\n \n bg_lines_coords = []\n bg_lines_coords_2 = []\n bg_lines_coords_3 = []\n\n bg_line_count = utils.css_to_mm(vsk.height) / self.bg_step\n\n for y in range(int(bg_line_count/3)):\n y = vsk.map(y, 0, bg_line_count /3, 0, utils.css_to_mm(vsk.height))\n bg_lines_coords.append(((-10,y),(210,y)))\n bg_lines_coords_2.append(((-10,y + self.bg_step),(210,y + self.bg_step)))\n bg_lines_coords_3.append(((-10,y + self.bg_step * 2),(210,y + self.bg_step * 2)))\n \n bg_lines = geometry.MultiLineString(bg_lines_coords)\n bg_lines_2 = geometry.MultiLineString(bg_lines_coords_2)\n bg_lines_3 = geometry.MultiLineString(bg_lines_coords_3)\n\n stars = geometry.MultiPoint([(10,10), (20,20), (20,50), (160,30)])\n # vsk.geometry(stars.buffer(10))\n\n circle = geometry.Point(100,62.5).buffer(40 , resolution=32)\n circle2 = geometry.Point(97,59.5).buffer(35 , resolution=32)\n circle3 = geometry.Point(96,58.5).buffer(34 , resolution=32)\n\n\n rect = geometry.Polygon([(0,0), (200,0), (200,125), (0,125)])\n\n \n space = rect.difference(circle).difference(stars.buffer(vsk.random(3)))\n space2 = rect.difference(circle2).difference(stars.buffer(vsk.random(3)))\n space3 = rect.difference(circle3).difference(stars.buffer(vsk.random(3)))\n \n # space2 = space2.difference(stars.buffer(5))\n\n vsk.geometry(bg_lines.intersection(space))\n vsk.geometry(bg_lines_2.intersection(space2))\n vsk.geometry(bg_lines_3.intersection(space3))\n \n\n\n\n def finalize(self, vsk: vsketch.Vsketch) -> None:\n vsk.vpype(\"linemerge linesimplify reloop linesort\")\n\n\nif __name__ == \"__main__\":\n Day03SpaceSketch.display()\n","repo_name":"hapiel/Genuary-2022","sub_path":"scraps/day03_space/sketch_day03_space.py","file_name":"sketch_day03_space.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"70497928165","text":"# Process FINRA Short Daily Data feeds\n # Source: https://github.com/amor71/FINRAShortData\n # https://developer.finra.org/docs#query_api-equity-equity_short_interest_standardized\n # FINRA Developer Credentials are required: https://developer.finra.org/create-account?Forward_URL=https://gateway.finra.org/app/dfo-console?rcpRedirNum=1\n # API key: https://gateway.finra.org/app/api-console/add-credential\n\nimport asyncio\nimport concurrent.futures\nimport time\nfrom typing import Optional, Tuple\n\nimport pandas as pd\nimport requests\n\nurl: str = \"https://api.finra.org/data/group/OTCMarket/name/regShoDaily\"\n\n\ndef _requests_get(token: str, chunk_size: int, offset: int) -> pd.DataFrame:\n r = requests.get(\n url=url,\n headers={\n \"Authorization\": f\"Bearer {token}\",\n \"Accept\": \"application/json\",\n },\n params={\"limit\": chunk_size, \"offset\": offset},\n )\n r.raise_for_status()\n\n if r.status_code in (429, 502):\n print(f\"{url} return {r.status_code}, waiting and re-trying\")\n time.sleep(10)\n return _requests_get(token, chunk_size, offset)\n\n x = r.json()\n df = pd.DataFrame(x)\n df.rename(\n columns={\n \"securitiesInformationProcessorSymbolIdentifier\": \"symbol\",\n \"totalParQuantity\": \"volume\",\n \"shortParQuantity\": \"shorts\",\n \"shortExemptParQuantity\": \"exempt\",\n },\n inplace=True,\n )\n df.drop([\"reportingFacilityCode\", \"marketCode\"], axis=1, inplace=True)\n return df\n\n\ndef get_chunk_and_size(token: str) -> Tuple[int, int]:\n \"\"\"Return the optimal chunk size and total number of data-points,\n Chunk size is used internally, by the process() function\n to reduce the number of calls to the FINRA end-point,\n it is also used as the 'offset' step when calling process() directly with restrictions.\n Input Arguments: token obtained from the auth() function.\n Returns: tuple with chunk size followed by number of data-points to be loaded from FINRA end-point.\n \"\"\"\n r = requests.get(\n url=url,\n headers={\n \"Authorization\": f\"Bearer {token}\",\n \"Accept\": \"application/json\",\n },\n params={\"limit\": 1},\n )\n r.raise_for_status()\n return int(r.headers[\"Record-Max-Limit\"]), int(r.headers[\"Record-Total\"])\n\n\nasync def process(\n token: str, offset: int = 0, limit: Optional[int] = None\n) -> pd.DataFrame:\n\n chunk_size, max_records = get_chunk_and_size(token)\n\n if limit:\n max_records = min(max_records, limit)\n\n print(f\"loading data (chunk_size={chunk_size}, offset={offset}, max_records={max_records-offset})...\")\n with concurrent.futures.ThreadPoolExecutor() as executor:\n loop = asyncio.get_event_loop()\n futures = [\n loop.run_in_executor(executor, _requests_get, token, chunk_size, offset)\n for offset in range(offset, max_records, chunk_size)\n ]\n df = (pd.concat(await asyncio.gather(*futures)).groupby([\"tradeReportDate\", \"symbol\"]).sum())\n\n df[\"short_percent\"] = round(100.0 * df.shorts / df.volume, 1)\n\n return df","repo_name":"alexanu/Python_Trading_Snippets","sub_path":"FINRA_shorts.py","file_name":"FINRA_shorts.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"9372020464","text":"##\n## I've got a lot of help from a Chan-uk Joo's code and Sung Kim's code\n## (https://github.com/jcwleo/Reinforcement_Learning/tree/master/Breakout)\n## (https://github.com/hunkim/ReinforcementZeroToAll/blob/master/07_3_dqn_2015_cartpole.py)\n## Thanks a lot to above two people!!\n##\n\n\nimport gym\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport random\nfrom scipy.misc import imresize\nfrom skimage.color import rgb2gray\nfrom skimage.transform import resize\nfrom collections import deque\n\n\ntf.set_random_seed(777)\n\nlearning_rate = 0.005\ndis = .99\nMAX_EPISODE = 500000\nBATCH_SIZE = 28\nREPLAY_MEMORY = 50000\n\nhistory = np.zeros([42, 42, 4], dtype=np.uint8)\n\nenv = gym.make('Breakout-v0')\n\noutput_size = 3\n\ndef crop_image(image, height_range=(34,195)):\n\th_begin, h_end = height_range\n\treturn image[h_begin:h_end, ...]\n\ndef resize_image(image, HW_range):\n\treturn imresize(image, HW_range, interp=\"nearest\")\n\ndef make_gray_image(image):\n\treturn rgb2gray(image)\n\ndef pre_proc(image):\n\ttemp_image = crop_image(image)\n\n\ttemp_image = make_gray_image(temp_image)\n\n\tfinal_image = resize_image(temp_image, (42, 42))\n\n\treturn final_image\n\ndef init_history(state):\n\tfor i in range(4):\n\t\thistory[:, :, i] = state\n\ndef add_to_history(new_state):\n\tfor i in range(3):\n\t\thistory[:, :,i] = history[:, :, i+1]\n\thistory[:, :, -1] = new_state\n\ndef get_next_history(new_state):\n\tnext_history = history\n\tfor i in range(3):\n\t\tnext_history[:, :, i] = next_history[:, :, i+1]\n\tnext_history[:, :, -1] = new_state\n\treturn next_history\n\n\ndef reshape_history(history):\n\treturn np.reshape(history, [-1, 42, 42, 4])\n\nclass DQN:\n\tdef __init__(self, session, name):\n\t\tself.session = session\n\t\tself.input_size = [42,42,4]\n\t\tself.output_size = 3\n\t\tself.name = name\n\n\t\tself._build_network()\n\t\n\tdef _build_network(self):\n\t\twith tf.variable_scope(self.name):\n\t\t\tself.X = tf.placeholder(shape=[None,42,42,4], dtype=tf.float32,name=\"input_x\")\n\n\t\t\tW1 = tf.Variable(tf.random_normal([4,4,4,32], stddev=0.01))\n\t\t\tL1 = tf.nn.conv2d(self.X, W1, strides=[1,2,2,1], padding='VALID')\n\t\t\tL1 = tf.nn.relu(L1)\n\t\t\tL1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n\t\t\tL1_flat = tf.reshape(L1, [-1,10*10*32])\n\n\t\t\tW2 = tf.get_variable(\"W2\", shape=[10*10*32, 318],\n\t\t\t\t\tinitializer=tf.contrib.layers.xavier_initializer())\n\t\t\tb2 = tf.Variable(tf.random_normal([318]))\n\t\t\tL2 = tf.nn.relu(tf.matmul(L1_flat, W2) + b2)\n\n\t\t\tW3 = tf.get_variable(\"W3\", shape=[318, 3],\n\t\t\t\t\tinitializer=tf.contrib.layers.xavier_initializer())\n\t\t\tself.Qpred = tf.matmul(L2, W3)\n\t\t\tself.Y = tf.placeholder(shape=[None, output_size], dtype=tf.float32)\n\n\t\t\tself.loss = tf.reduce_sum(tf.square(self.Y-self.Qpred))\n\t\t\tself.train = tf.train.AdamOptimizer(learning_rate = 0.001).minimize(self.loss)\n\n\tdef predict(self, history):\n\t\treturn self.session.run(self.Qpred, feed_dict={self.X: reshape_history(history)})\n\n\tdef update(self, x_stack, y_stack):\n\t\tfeed = {\n\t\t\tself.X: x_stack,\n\t\t\tself.Y: y_stack\n\t\t}\n\t\treturn self.session.run([self.loss, self.train], feed)\n\ndef get_copy_var_ops(*, dest_scope_name=\"target\", src_scope_name=\"main\"):\n\top_holder = []\n\n\tsrc_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,\n\t\tscope=src_scope_name)\n\tdest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,\n\t\tscope=dest_scope_name)\n\n\tfor src_var, dest_var in zip(src_vars, dest_vars):\n\t\top_holder.append(dest_var.assign(src_var.value()))\n\n\treturn op_holder\n\n\ndef simple_replay_train(mainDQN, targetDQN, train_batch):\n\tstate_array = np.array([x[0] for x in train_batch])\n\taction_array = np.array([x[1] for x in train_batch])\n\treward_array = np.array([x[2] for x in train_batch])\n\tnext_state_array = np.array([x[3] for x in train_batch])\n\tdone_array = np.array([x[4] for x in train_batch])\n\n\tX_batch = state_array\n\n\tY_batch = mainDQN.predict(state_array)\n\t\n\tfor i in range(len(train_batch)):\n\t\tif done_array[i] == True:\n\t\t\tY_batch[i, action_array[i]] = reward_array[i]\n\t\telse:\n\t\t\tY_batch[i, action_array[i]] = reward_array[i] + dis*np.max(targetDQN.predict(next_state_array[i]))\n\t\n\tloss, _ = mainDQN.update(X_batch, Y_batch)\n\n\treturn loss\n\ndef main():\n\treplay_buffer = deque(maxlen=REPLAY_MEMORY)\n\tlast_100_game_reward = deque(maxlen=100)\n\n\twith tf.Session() as sess:\n\t\tmainDQN = DQN(sess, 'main')\n\t\ttargetDQN = DQN(sess, 'target')\n\n\t\tsess.run(tf.global_variables_initializer())\n\n\t\tcopy_ops = get_copy_var_ops(dest_scope_name=\"target\",\n\t\t\t\t\t\t\t\t\tsrc_scope_name=\"main\")\n\n\t\tsess.run(copy_ops)\n\t\t\n\t\tfor i in range(MAX_EPISODE):\n\t\t\te = 1./ ((i/500)+1.)\n\t\t\tdone = False\n\t\t\tstate = env.reset()\n\t\t\tx = pre_proc(state)\n\t\t\tinit_history(x)\n\n\t\t\tstep_count = 0\n\t\t\treward_sum = 0\n\n\t\t\twhile not done:\n\t\t\t\tif np.random.rand(1) < e:\n\t\t\t\t\taction = np.random.randint(3)\n\t\t\t\telse:\n\t\t\t\t\taction = np.argmax(mainDQN.predict(history))\n\n\t\t\t\tnext_state, reward, done, info = env.step(action+1)\n\n\t\t\t\tif info['ale.lives'] < 5:\n\t\t\t\t\tdone = True\n\n\t\t\t\tif done:\n\t\t\t\t\treward = -100\n\t\t\t\t\n\t\t\t\tnext_x = pre_proc(next_state)\n\t\t\t\tnext_history = get_next_history(next_x)\n\n\t\t\t\treplay_buffer.append((history, action, reward, next_history, done))\n\t\t\t\tif len(replay_buffer) > REPLAY_MEMORY:\n\t\t\t\t\treplay_buffer.popleft()\n\n\t\t\t\tstate = next_state\n\t\t\t\tx = pre_proc(state)\n\t\t\t\tadd_to_history(x)\n\n\t\t\t\tstep_count += 1\n\t\t\t\tif i % 20 == 0 and i > 50000:\n\t\t\t\t\tenv.render()\n\n\n\t\t\tif step_count > 10000:\n\t\t\t\tpass\n\t\t\t\tbreak\n\n\t\t\tif i % 20 == 0 and i != 0 and i != 10:\n\t\t\t\tfor j in range(50):\n\t\t\t\t\tminibatch = random.sample(replay_buffer, 10)\n\t\t\t\t\tloss = simple_replay_train(mainDQN, targetDQN, minibatch)\n\t\t\t\tif i % 1000 == 0:\n\t\t\t\t\tprint(\"Episode: {}, Loss: {}\".format(i, loss))\n\n\t\t\tif i % 20 == 0:\n\t\t\t\tsess.run(copy_ops)\n\n\t\tbot_play(mainDQN)\n\ndef bot_play(mainDQN, env = env):\t\n\tstate = env.reset()\n\treward_sum = 0\n\tx = pre_proc(state)\n\tinit_history(x)\n\tenv.step(1)\n\twhile True:\n\t\tenv.render()\n\n\t\tQs = mainDQN.predict(history)\n\t\taction = np.argmax(Qs)\n\n\t\tstate, reward, done, info = env.step(action+1)\n\t\treward_sum += reward\n\t\tx = pre_proc(state)\n\t\tadd_to_history(x)\n\n\t\tif info['ale.lives'] < 5:\n\t\t\tdone = True\n\n\t\tif done:\n\t\t\tprint(\"Total score: {}\".format(reward_sum))\n\t\t\tbreak\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"SangHoon-Joo/Breakout_DQN","sub_path":"breakout_test.py","file_name":"breakout_test.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25881580742","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport pandas as pd \nimport time\n\ndriver = webdriver.Chrome(executable_path=\"F:\\chromedriver_win32\\chromedriver.exe\")\ndriver.implicitly_wait(30)\ndriver.maximize_window()\ndriver.get(\"https://summerofcode.withgoogle.com/programs/2022/organizations\")\nfields = driver.find_elements(by= By.XPATH, value= \"//mat-chip\")\ntypes=[]\nnames=[]\ntopics= []\ntechnologies=[]\n \nfor field in fields:\n if(field.text == \"All\"): \n continue\n driver.execute_script(\"window.scrollTo(0, 0)\")\n time.sleep(3)\n field.click()\n time.sleep(3)\n driver.execute_script(\"window.scrollTo(0, 900)\")\n time.sleep(3)\n\n\n\n driver.find_element(by=By.XPATH, value = \"//div[@class='mat-form-field-flex ng-tns-c87-2']\").click()\n numbers= driver.find_element(by= By.XPATH, value = \"//mat-option[@id='mat-option-3']\").click()\n orgs = driver.find_elements(by= By.XPATH, value = \"//div[@class='name']\")\n links=driver.find_elements(by=By.XPATH, value = \"//a[@class='content']\")\n\n i = 0\n h=850\n\n for org in orgs:\n names.append(org.text)\n if (i%3==0) and (i!=0) :\n h+=290 \n driver.execute_script(\"window.scrollTo(0, \"+str(h)+\")\")\n time.sleep(0.5)\n\n if (i==66):\n h-=150\n driver.execute_script(\"window.scrollTo(0, \"+str(h)+\")\")\n time.sleep(1)\n\n types.append(field.text)\n \n \n links[i].click()\n window2=driver.window_handles[1]\n window1=driver.window_handles[0]\n driver.switch_to.window(window2)\n TechContent = driver.find_element(by= By.XPATH, value = \"//div[@class='tech__content']\")\n topic = driver.find_element(by= By.XPATH, value = \"//div[@class='topics__content']\")\n topics.append(topic.text)\n technologies.append(TechContent.text)\n driver.close()\n driver.switch_to.window(window1)\n i+=1\ntime.sleep(5)\ndriver.close()\n\nprint(len(types))\nprint(len(names))\n \ndf = pd.DataFrame({'Field': types, 'Name of organisation':names, 'Tech Stack':technologies, 'Topics':topics})\ndf.to_csv('GSOC.csv', index=False)\nprint(df)\n\n","repo_name":"RudranshGoel/PClub-secy-recruitment","sub_path":"pclub.py","file_name":"pclub.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38235292756","text":"from pprint import pformat\n\nfrom django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponseRedirect\n\nfrom django.urls import reverse\n\nfrom django_tables2 import RequestConfig\nfrom .models import WikiUrlLog\nfrom .tables import WikiUrlLogTable, WikiLinkTable\n# from .filters import WikiUrlLogFilter\nfrom .logger import logger\nfrom .services import fetch_wiki, parse_wiki, save_wiki\n\n\ndef index(request):\n qs = WikiUrlLog.objects.all()\n table = WikiUrlLogTable(qs)\n RequestConfig(request, paginate={\"per_page\": 10}).configure(table)\n return render(request, \"index.html\", {\"table\": table})\n\n\ndef wikipedia_search(request):\n if request.method == \"GET\":\n logger.debug(pformat(request.GET))\n if \"query\" not in request.GET:\n logger.error(\"mandatory query param\")\n else:\n if len(request.GET.get(\"query\")):\n query = request.GET.get(\"query\")\n retpage = fetch_wiki(query)\n retdata = None\n if retpage:\n retdata = parse_wiki(retpage)\n save_wiki(request.build_absolute_uri(), query, retdata)\n return HttpResponseRedirect(reverse(\"wikiindex\"))\n\n\ndef wikilog_details(request, id):\n obj = get_object_or_404(WikiUrlLog, pk=id)\n table = WikiLinkTable(obj.wikilink_set.all())\n RequestConfig(request, paginate={\"per_page\": 10}).configure(table)\n return render(\n request, \"wikilog_details.html\", {\"wiki\": obj, \"links\": table}\n )\n","repo_name":"pahpa/django_study1","sub_path":"wikisearch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4014656911","text":"import pandas as pd\n\n\ndef init_mc_level_change_log_xxx():\n \"\"\"\n 2022-01-19\n 处理em等级初始化数据\n :return:\n \"\"\"\n path = '/Users/lhq/Downloads/lgm_init_uat_output_smalldata.sql'\n f = open(path, 'r')\n origin_datas = f.readlines()\n datas = list(map(lambda v: str(v).rstrip(';;\\n').split('VALUES'), origin_datas))\n print(datas)\n df = pd.DataFrame(datas, columns=['insert', 'values'])\n df_agg = df.groupby(by='insert', as_index=False).agg(list)\n df_agg['values'] = df_agg['values'].map(lambda v: ','.join(v))\n # print('\\n')\n # info(df_agg.iloc[:3])\n # return\n df_agg['sql'] = df_agg.apply(lambda v: '{} values {};'.format(v['insert'], v['values']), axis=1)\n # x = df_agg['sql'].iloc[:3]\n df_agg['sql'].to_csv('/Users/lhq/Downloads/lgm_init_uat_output_smalldata_ok.csv', index=False)\n\n\nif __name__ == '__main__':\n init_mc_level_change_log_xxx()\n","repo_name":"2424055216/memberlevellog","sub_path":"te4.py","file_name":"te4.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31578406159","text":"from .item import Item\nfrom oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401\nfrom oci.decorators import init_model_state_from_kwargs\n\n\n@init_model_state_from_kwargs\nclass ActivityItem(Item):\n \"\"\"\n Details about the ActivityItem object.\n \"\"\"\n\n #: A constant which can be used with the activity_type property of a ActivityItem.\n #: This constant has a value of \"NOTES\"\n ACTIVITY_TYPE_NOTES = \"NOTES\"\n\n #: A constant which can be used with the activity_type property of a ActivityItem.\n #: This constant has a value of \"PROBLEM_DESCRIPTION\"\n ACTIVITY_TYPE_PROBLEM_DESCRIPTION = \"PROBLEM_DESCRIPTION\"\n\n #: A constant which can be used with the activity_type property of a ActivityItem.\n #: This constant has a value of \"UPDATE\"\n ACTIVITY_TYPE_UPDATE = \"UPDATE\"\n\n #: A constant which can be used with the activity_type property of a ActivityItem.\n #: This constant has a value of \"CLOSE\"\n ACTIVITY_TYPE_CLOSE = \"CLOSE\"\n\n #: A constant which can be used with the activity_type property of a ActivityItem.\n #: This constant has a value of \"REOPEN\"\n ACTIVITY_TYPE_REOPEN = \"REOPEN\"\n\n #: A constant which can be used with the activity_author property of a ActivityItem.\n #: This constant has a value of \"CUSTOMER\"\n ACTIVITY_AUTHOR_CUSTOMER = \"CUSTOMER\"\n\n #: A constant which can be used with the activity_author property of a ActivityItem.\n #: This constant has a value of \"ORACLE\"\n ACTIVITY_AUTHOR_ORACLE = \"ORACLE\"\n\n #: A constant which can be used with the item_type property of a ActivityItem.\n #: This constant has a value of \"ATTACHMENTS\"\n ITEM_TYPE_ATTACHMENTS = \"ATTACHMENTS\"\n\n #: A constant which can be used with the item_type property of a ActivityItem.\n #: This constant has a value of \"COMMENTS\"\n ITEM_TYPE_COMMENTS = \"COMMENTS\"\n\n #: A constant which can be used with the item_status property of a ActivityItem.\n #: This constant has a value of \"PROCESSING\"\n ITEM_STATUS_PROCESSING = \"PROCESSING\"\n\n #: A constant which can be used with the item_status property of a ActivityItem.\n #: This constant has a value of \"ATTACHED\"\n ITEM_STATUS_ATTACHED = \"ATTACHED\"\n\n #: A constant which can be used with the item_status property of a ActivityItem.\n #: This constant has a value of \"REMOVED\"\n ITEM_STATUS_REMOVED = \"REMOVED\"\n\n #: A constant which can be used with the item_status property of a ActivityItem.\n #: This constant has a value of \"FAILED\"\n ITEM_STATUS_FAILED = \"FAILED\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new ActivityItem object with values from keyword arguments. The default value of the :py:attr:`~oci.cims.models.ActivityItem.type` attribute\n of this class is ``activity`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param item_key:\n The value to assign to the item_key property of this ActivityItem.\n :type item_key: str\n\n :param name:\n The value to assign to the name property of this ActivityItem.\n :type name: str\n\n :param type:\n The value to assign to the type property of this ActivityItem.\n :type type: str\n\n :param category:\n The value to assign to the category property of this ActivityItem.\n :type category: oci.cims.models.Category\n\n :param sub_category:\n The value to assign to the sub_category property of this ActivityItem.\n :type sub_category: oci.cims.models.SubCategory\n\n :param issue_type:\n The value to assign to the issue_type property of this ActivityItem.\n :type issue_type: oci.cims.models.IssueType\n\n :param comments:\n The value to assign to the comments property of this ActivityItem.\n :type comments: str\n\n :param time_created:\n The value to assign to the time_created property of this ActivityItem.\n :type time_created: int\n\n :param time_updated:\n The value to assign to the time_updated property of this ActivityItem.\n :type time_updated: int\n\n :param activity_type:\n The value to assign to the activity_type property of this ActivityItem.\n Allowed values for this property are: \"NOTES\", \"PROBLEM_DESCRIPTION\", \"UPDATE\", \"CLOSE\", \"REOPEN\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type activity_type: str\n\n :param activity_author:\n The value to assign to the activity_author property of this ActivityItem.\n Allowed values for this property are: \"CUSTOMER\", \"ORACLE\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type activity_author: str\n\n :param item_type:\n The value to assign to the item_type property of this ActivityItem.\n Allowed values for this property are: \"ATTACHMENTS\", \"COMMENTS\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type item_type: str\n\n :param item_status:\n The value to assign to the item_status property of this ActivityItem.\n Allowed values for this property are: \"PROCESSING\", \"ATTACHED\", \"REMOVED\", \"FAILED\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type item_status: str\n\n \"\"\"\n self.swagger_types = {\n 'item_key': 'str',\n 'name': 'str',\n 'type': 'str',\n 'category': 'Category',\n 'sub_category': 'SubCategory',\n 'issue_type': 'IssueType',\n 'comments': 'str',\n 'time_created': 'int',\n 'time_updated': 'int',\n 'activity_type': 'str',\n 'activity_author': 'str',\n 'item_type': 'str',\n 'item_status': 'str'\n }\n\n self.attribute_map = {\n 'item_key': 'itemKey',\n 'name': 'name',\n 'type': 'type',\n 'category': 'category',\n 'sub_category': 'subCategory',\n 'issue_type': 'issueType',\n 'comments': 'comments',\n 'time_created': 'timeCreated',\n 'time_updated': 'timeUpdated',\n 'activity_type': 'activityType',\n 'activity_author': 'activityAuthor',\n 'item_type': 'itemType',\n 'item_status': 'itemStatus'\n }\n\n self._item_key = None\n self._name = None\n self._type = None\n self._category = None\n self._sub_category = None\n self._issue_type = None\n self._comments = None\n self._time_created = None\n self._time_updated = None\n self._activity_type = None\n self._activity_author = None\n self._item_type = None\n self._item_status = None\n self._type = 'activity'\n\n @property\n def comments(self):\n \"\"\"\n **[Required]** Gets the comments of this ActivityItem.\n Comments added with the activity on the support ticket.\n\n\n :return: The comments of this ActivityItem.\n :rtype: str\n \"\"\"\n return self._comments\n\n @comments.setter\n def comments(self, comments):\n \"\"\"\n Sets the comments of this ActivityItem.\n Comments added with the activity on the support ticket.\n\n\n :param comments: The comments of this ActivityItem.\n :type: str\n \"\"\"\n self._comments = comments\n\n @property\n def time_created(self):\n \"\"\"\n **[Required]** Gets the time_created of this ActivityItem.\n The time when the activity was created, in milliseconds since epoch time.\n\n\n :return: The time_created of this ActivityItem.\n :rtype: int\n \"\"\"\n return self._time_created\n\n @time_created.setter\n def time_created(self, time_created):\n \"\"\"\n Sets the time_created of this ActivityItem.\n The time when the activity was created, in milliseconds since epoch time.\n\n\n :param time_created: The time_created of this ActivityItem.\n :type: int\n \"\"\"\n self._time_created = time_created\n\n @property\n def time_updated(self):\n \"\"\"\n **[Required]** Gets the time_updated of this ActivityItem.\n The time when the activity was updated, in milliseconds since epoch time.\n\n\n :return: The time_updated of this ActivityItem.\n :rtype: int\n \"\"\"\n return self._time_updated\n\n @time_updated.setter\n def time_updated(self, time_updated):\n \"\"\"\n Sets the time_updated of this ActivityItem.\n The time when the activity was updated, in milliseconds since epoch time.\n\n\n :param time_updated: The time_updated of this ActivityItem.\n :type: int\n \"\"\"\n self._time_updated = time_updated\n\n @property\n def activity_type(self):\n \"\"\"\n **[Required]** Gets the activity_type of this ActivityItem.\n The type of activity occuring on the support ticket.\n\n Allowed values for this property are: \"NOTES\", \"PROBLEM_DESCRIPTION\", \"UPDATE\", \"CLOSE\", \"REOPEN\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The activity_type of this ActivityItem.\n :rtype: str\n \"\"\"\n return self._activity_type\n\n @activity_type.setter\n def activity_type(self, activity_type):\n \"\"\"\n Sets the activity_type of this ActivityItem.\n The type of activity occuring on the support ticket.\n\n\n :param activity_type: The activity_type of this ActivityItem.\n :type: str\n \"\"\"\n allowed_values = [\"NOTES\", \"PROBLEM_DESCRIPTION\", \"UPDATE\", \"CLOSE\", \"REOPEN\"]\n if not value_allowed_none_or_none_sentinel(activity_type, allowed_values):\n activity_type = 'UNKNOWN_ENUM_VALUE'\n self._activity_type = activity_type\n\n @property\n def activity_author(self):\n \"\"\"\n **[Required]** Gets the activity_author of this ActivityItem.\n Allowed values for this property are: \"CUSTOMER\", \"ORACLE\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The activity_author of this ActivityItem.\n :rtype: str\n \"\"\"\n return self._activity_author\n\n @activity_author.setter\n def activity_author(self, activity_author):\n \"\"\"\n Sets the activity_author of this ActivityItem.\n\n :param activity_author: The activity_author of this ActivityItem.\n :type: str\n \"\"\"\n allowed_values = [\"CUSTOMER\", \"ORACLE\"]\n if not value_allowed_none_or_none_sentinel(activity_author, allowed_values):\n activity_author = 'UNKNOWN_ENUM_VALUE'\n self._activity_author = activity_author\n\n @property\n def item_type(self):\n \"\"\"\n Gets the item_type of this ActivityItem.\n Allowed values for this property are: \"ATTACHMENTS\", \"COMMENTS\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The item_type of this ActivityItem.\n :rtype: str\n \"\"\"\n return self._item_type\n\n @item_type.setter\n def item_type(self, item_type):\n \"\"\"\n Sets the item_type of this ActivityItem.\n\n :param item_type: The item_type of this ActivityItem.\n :type: str\n \"\"\"\n allowed_values = [\"ATTACHMENTS\", \"COMMENTS\"]\n if not value_allowed_none_or_none_sentinel(item_type, allowed_values):\n item_type = 'UNKNOWN_ENUM_VALUE'\n self._item_type = item_type\n\n @property\n def item_status(self):\n \"\"\"\n Gets the item_status of this ActivityItem.\n Who updates the activity on the support ticket.\n\n Allowed values for this property are: \"PROCESSING\", \"ATTACHED\", \"REMOVED\", \"FAILED\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The item_status of this ActivityItem.\n :rtype: str\n \"\"\"\n return self._item_status\n\n @item_status.setter\n def item_status(self, item_status):\n \"\"\"\n Sets the item_status of this ActivityItem.\n Who updates the activity on the support ticket.\n\n\n :param item_status: The item_status of this ActivityItem.\n :type: str\n \"\"\"\n allowed_values = [\"PROCESSING\", \"ATTACHED\", \"REMOVED\", \"FAILED\"]\n if not value_allowed_none_or_none_sentinel(item_status, allowed_values):\n item_status = 'UNKNOWN_ENUM_VALUE'\n self._item_status = item_status\n\n def __repr__(self):\n return formatted_flat_dict(self)\n\n def __eq__(self, other):\n if other is None:\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/cims/models/activity_item.py","file_name":"activity_item.py","file_ext":"py","file_size_in_byte":13231,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"6032896659","text":"from random import randint\n\nsoma = 1 \nnum = randint(0,10)\n\nchance = int(input('Sorteamos um número entre 0 e 10, se você acertar ganhará aulas com o professor Nevado.\\nQual seu palpite? '))\n\nwhile chance != num:\n chance = int(input('Seu palpite foi errado, tente outro número. '))\n soma += 1\n\nprint(f'Parabéns o número era {num}.\\nVocê fez {soma} tentativas.')","repo_name":"fillipekill/exercicios-python","sub_path":"ex 53.py","file_name":"ex 53.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16129330062","text":"r\"\"\"\nSpin-weighted spherical harmonics `{}_s Y_l^m(\\theta,\\phi)`\n\n\"\"\"\n#******************************************************************************\n# Copyright (C) 2018 Eric Gourgoulhon \n#\n# Distributed under the terms of the GNU General Public License (GPL)\n# as published by the Free Software Foundation; either version 2 of\n# the License, or (at your option) any later version.\n# http://www.gnu.org/licenses/\n#******************************************************************************\n\nfrom sage.rings.integer_ring import ZZ\nfrom sage.rings.real_double import RDF\nfrom sage.rings.real_mpfr import RealField_class\nfrom sage.functions.other import binomial, factorial, sqrt\nfrom sage.functions.log import exp\nfrom sage.functions.trig import cos, sin\nfrom sage.symbolic.constants import pi, I\nfrom sage.symbolic.expression import Expression\n\n_cached_functions = {}\n_cached_values = {}\n\ndef _compute_sw_spherical_harm(s, l, m, theta, phi, condon_shortley=True,\n numerical=None):\n r\"\"\"\n Compute the spin-weighted spherical harmonic of spin weight ``s`` and\n indices ``(l,m)`` as a callable symbolic expression in (theta,phi)\n\n INPUT:\n\n - ``s`` -- integer; the spin weight\n - ``l`` -- non-negative integer; the harmonic degree\n - ``m`` -- integer within the range ``[-l, l]``; the azimuthal number\n - ``theta`` -- colatitude angle\n - ``phi`` -- azimuthal angle\n - ``condon_shortley`` -- (default: ``True``) determines whether the\n Condon-Shortley phase of `(-1)^m` is taken into account (see below)\n - ``numerical`` -- (default: ``None``) determines whether a symbolic or\n a numerical computation of a given type is performed; allowed values are\n\n - ``None``: a symbolic computation is performed\n - ``RDF``: Sage's machine double precision floating-point numbers\n (``RealDoubleField``)\n - ``RealField(n)``, where ``n`` is a number of bits: Sage's\n floating-point numbers with an arbitrary precision; note that ``RR`` is\n a shortcut for ``RealField(53)``.\n - ``float``: Python's floating-point numbers\n\n\n OUTPUT:\n\n - `{}_s Y_l^m(\\theta,\\phi)` either\n\n - as a symbolic expression if ``numerical`` is ``None``\n - or a pair of floating-point numbers, each of them being of the type\n corresponding to ``numerical`` and representing respectively the\n real and imaginary parts of `{}_s Y_l^m(\\theta,\\phi)`\n\n ALGORITHM:\n\n The spin-weighted spherical harmonic is evaluated according to Eq. (3.1)\n of J. N. Golberg et al., J. Math. Phys. **8**, 2155 (1967)\n [:doi:`10.1063/1.1705135`], with an extra `(-1)^m` factor (the so-called\n *Condon-Shortley phase*) if ``condon_shortley`` is ``True``, the actual\n formula being then the one given in\n :wikipedia:`Spin-weighted_spherical_harmonics#Calculating`\n\n TESTS::\n\n sage: from kerrgeodesic_gw.spin_weighted_spherical_harm import _compute_sw_spherical_harm\n sage: theta, phi = var(\"theta phi\")\n sage: _compute_sw_spherical_harm(-2, 2, 1, theta, phi)\n 1/4*(sqrt(5)*cos(theta) + sqrt(5))*e^(I*phi)*sin(theta)/sqrt(pi)\n\n \"\"\"\n if abs(s)>l:\n return ZZ(0)\n if abs(theta) < 1.e-6: # TODO: fix the treatment of small theta values\n if theta < 0: # possibly with exact formula for theta=0\n theta = -1.e-6 #\n else: #\n theta = 1.e-6 #\n cott2 = cos(theta/2)/sin(theta/2)\n res = 0\n for r in range(l-s+1):\n res += (-1)**(l-r-s) * (binomial(l-s, r) * binomial(l+s, r+s-m)\n * cott2**(2*r+s-m))\n res *= sin(theta/2)**(2*l)\n ff = factorial(l+m)*factorial(l-m)*(2*l+1) / (factorial(l+s)*factorial(l-s))\n if numerical:\n pre = sqrt(numerical(ff)/numerical(pi))/2\n else:\n pre = sqrt(ff)/(2*sqrt(pi))\n res *= pre\n if condon_shortley:\n res *= (-1)**m\n if numerical:\n return (numerical(res*cos(m*phi)), numerical(res*sin(m*phi)))\n # Symbolic case:\n res = res.simplify_full()\n res = res.reduce_trig() # get rid of cos(theta/2) and sin(theta/2)\n res = res.simplify_trig() # further trigonometric simplifications\n res *= exp(I*m*phi)\n return res\n\n\ndef spin_weighted_spherical_harmonic(s, l, m, theta, phi,\n condon_shortley=True, cached=True,\n numerical=None):\n r\"\"\"\n Return the spin-weighted spherical harmonic of spin weight ``s`` and\n indices ``(l,m)``.\n\n INPUT:\n\n - ``s`` -- integer; the spin weight\n - ``l`` -- non-negative integer; the harmonic degree\n - ``m`` -- integer within the range ``[-l, l]``; the azimuthal number\n - ``theta`` -- colatitude angle\n - ``phi`` -- azimuthal angle\n - ``condon_shortley`` -- (default: ``True``) determines whether the\n Condon-Shortley phase of `(-1)^m` is taken into account (see below)\n - ``cached`` -- (default: ``True``) determines whether the result shall be\n cached; setting ``cached`` to ``False`` forces a new computation, without\n caching the result\n - ``numerical`` -- (default: ``None``) determines whether a symbolic or\n a numerical computation of a given type is performed; allowed values are\n\n - ``None``: the type of computation is deduced from the type of ``theta``\n - ``RDF``: Sage's machine double precision floating-point numbers\n (``RealDoubleField``)\n - ``RealField(n)``, where ``n`` is a number of bits: Sage's\n floating-point numbers with an arbitrary precision; note that ``RR`` is\n a shortcut for ``RealField(53)``.\n - ``float``: Python's floating-point numbers\n\n OUTPUT:\n\n - the value of `{}_s Y_l^m(\\theta,\\phi)`, either as a symbolic expression\n or as floating-point complex number of the type determined by\n ``numerical``\n\n ALGORITHM:\n\n The spin-weighted spherical harmonic is evaluated according to Eq. (3.1)\n of J. N. Golberg et al., J. Math. Phys. **8**, 2155 (1967)\n [:doi:`10.1063/1.1705135`], with an extra `(-1)^m` factor (the so-called\n *Condon-Shortley phase*) if ``condon_shortley`` is ``True``, the actual\n formula being then the one given in\n :wikipedia:`Spin-weighted_spherical_harmonics#Calculating`\n\n EXAMPLES::\n\n sage: from kerrgeodesic_gw import spin_weighted_spherical_harmonic\n sage: theta, phi = var('theta phi')\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, theta, phi)\n 1/4*(sqrt(5)*cos(theta) + sqrt(5))*e^(I*phi)*sin(theta)/sqrt(pi)\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, theta, phi,\n ....: condon_shortley=False)\n -1/4*(sqrt(5)*cos(theta) + sqrt(5))*e^(I*phi)*sin(theta)/sqrt(pi)\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, pi/3, pi/4)\n (3/32*I + 3/32)*sqrt(5)*sqrt(3)*sqrt(2)/sqrt(pi)\n\n\n Evaluation as floating-point numbers: the type of the output is deduced\n from the input::\n\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, 1.0, 2.0) # tol 1.0e-13\n -0.170114676286891 + 0.371707349012686*I\n sage: parent(_)\n Complex Field with 53 bits of precision\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, RDF(2.0), RDF(3.0)) # tol 1.0e-13\n -0.16576451879564585 + 0.023629159118690464*I\n sage: parent(_)\n Complex Double Field\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, float(3.0), float(4.0)) # tol 1.0e-13\n (-0.0002911423884400524-0.00033709085352998027j)\n sage: parent(_)\n \n\n Computation with arbitrary precision are possible (here 100 bits)::\n\n sage: R100 = RealField(100); R100\n Real Field with 100 bits of precision\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, R100(1.5), R100(2.0)) # tol 1.0e-28\n -0.14018136537676185317636108802 + 0.30630187143465275236861476906*I\n\n Even when the entry is symbolic, numerical evaluation can be enforced via\n the argument ``numerical``. For instance, setting ``numerical`` to ``RDF``\n (SageMath's Real Double Field)::\n\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, pi/3, pi/4, numerical=RDF) # tol 1.0e-13\n 0.2897056515173923 + 0.28970565151739225*I\n sage: parent(_)\n Complex Double Field\n\n One can also use ``numerical=RR`` (SageMath's Real Field with precision set\n to 53 bits)::\n\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, pi/3, pi/4, numerical=RR) # tol 1.0e-13\n 0.289705651517392 + 0.289705651517392*I\n sage: parent(_)\n Complex Field with 53 bits of precision\n\n Another option is to use Python floats::\n\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, pi/3, pi/4, numerical=float) # tol 1.0e-13\n (0.28970565151739225+0.2897056515173922j)\n sage: parent(_)\n \n\n One can go beyond double precision, for instance using 100 bits of\n precision::\n\n sage: spin_weighted_spherical_harmonic(-2, 2, 1, pi/3, pi/4,\n ....: numerical=RealField(100)) # tol 1.0e-28\n 0.28970565151739218525664455148 + 0.28970565151739218525664455148*I\n sage: parent(_)\n Complex Field with 100 bits of precision\n\n \"\"\"\n global _cached_functions, _cached_values\n s = ZZ(s) # ensure that we are dealing with Sage integers\n l = ZZ(l)\n m = ZZ(m)\n if abs(s)>l:\n return ZZ(0)\n if (isinstance(theta, Expression) and theta.variables() == (theta,) and\n isinstance(phi, Expression) and phi.variables() == (phi,)):\n # Evaluation as a symbolic function\n if cached:\n param = (s, l, m, condon_shortley)\n if param not in _cached_functions:\n _cached_functions[param] = _compute_sw_spherical_harm(s, l, m,\n theta, phi, condon_shortley=condon_shortley,\n numerical=None).function(theta, phi)\n return _cached_functions[param](theta, phi)\n return _compute_sw_spherical_harm(s, l, m, theta, phi,\n condon_shortley=condon_shortley,\n numerical=None)\n # Numerical or symbolic evaluation\n param = (s, l, m, theta, phi, condon_shortley, str(numerical))\n if not cached or param not in _cached_values:\n # a new computation is required\n if numerical:\n # theta and phi are enforced to be of the type defined by numerical\n theta = numerical(theta)\n phi = numerical(phi)\n else:\n # the type of computation is deduced from that of theta\n if type(theta) is float:\n numerical = float\n elif (theta.parent() is RDF or\n isinstance(theta.parent(), RealField_class)):\n numerical = theta.parent()\n res = _compute_sw_spherical_harm(s, l, m, theta, phi,\n condon_shortley=condon_shortley,\n numerical=numerical)\n if numerical is RDF or isinstance(numerical, RealField_class):\n res = numerical.complex_field()(res)\n elif numerical is float:\n res = complex(*res)\n if cached:\n _cached_values[param] = res\n return res\n return _cached_values[param]\n","repo_name":"BlackHolePerturbationToolkit/kerrgeodesic_gw","sub_path":"kerrgeodesic_gw/spin_weighted_spherical_harm.py","file_name":"spin_weighted_spherical_harm.py","file_ext":"py","file_size_in_byte":11484,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"18904861215","text":"from __future__ import print_function\n\nfrom network.manager.networkManager import NetworkManager, NetworkCallback\nfrom network.exceptions.networkManager import NetworkManagerException\nfrom clusterServer.packetHandling.packetHandler import ClusterServerPacketHandler\nfrom clusterServer.packetHandling.packet_t import CLUSTER_SERVER_PACKET_T as PACKET_T\nfrom time import sleep\n\nclass TesterCallback(NetworkCallback):\n def __init__(self, clusterServerPacketHandler):\n self.__repositoryPacketHandler = clusterServerPacketHandler\n \n def processPacket(self, packet):\n data = self.__repositoryPacketHandler.readPacket(packet)\n if (data[\"packet_type\"] == PACKET_T.VM_SERVER_REGISTRATION_ERROR) :\n print(\"Virtual machine server registration error\")\n print(\"\\tReason: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.VM_SERVERS_STATUS_DATA or data[\"packet_type\"] == PACKET_T.VM_DISTRIBUTION_DATA or\n data[\"packet_type\"] == PACKET_T.VM_SERVERS_RESOURCE_USAGE) :\n print(\"Virtual machine servers' current status\")\n print(\"\\tSegment \" + str(data[\"Segment\"]) + \" of \" + str(data[\"SequenceSize\"]))\n for row in data[\"Data\"] :\n print(row)\n elif (data[\"packet_type\"] == PACKET_T.VM_SERVER_BOOTUP_ERROR):\n print(\"Virtual machine server bootup error\")\n print(\"\\tReason: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.VM_SERVER_UNREGISTRATION_ERROR):\n print(\"Virtual machine server unregistration error\")\n print(\"\\tReason: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.VM_SERVER_SHUTDOWN_ERROR):\n print(\"Virtual machine server shutdown error\")\n print(\"\\tReason: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.VM_BOOT_FAILURE):\n print(\"Virtual machine boot failure\")\n print(\"\\tReason: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.VM_CONNECTION_DATA) :\n print(\"Virtual machine connection data\")\n print(\"\\tVNC server IP address: \" + data[\"VNCServerIPAddress\"])\n print(\"\\tVNC server port: \" + str(data[\"VNCServerPort\"]))\n print(\"\\tVNC server password: \" + data[\"VNCServerPassword\"])\n elif (data[\"packet_type\"] == PACKET_T.ACTIVE_VM_VNC_DATA) :\n print(\"VNC connection data\")\n print(\"\\tSegment \" + str(data[\"Segment\"]) + \" of \" + str(data[\"SequenceSize\"]))\n print(\"\\tVNC server IP address: \" + data[\"VMServerIP\"])\n print(\"\\t\" + str(data[\"Data\"]))\n elif (data[\"packet_type\"] == PACKET_T.DOMAIN_DESTRUCTION_ERROR) :\n print(\"Domain destruction error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.VM_SERVER_CONFIGURATION_CHANGE_ERROR) :\n print(\"Virtual machine configuration change error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.REPOSITORY_STATUS):\n print(\"Image repository status: {0} KB free, {1} KB in use, {2}\".format(data[\"FreeDiskSpace\"], data[\"AvailableDiskSpace\"],\n data[\"RepositoryStatus\"]))\n elif (data[\"packet_type\"] == PACKET_T.IMAGE_DEPLOYMENT_ERROR):\n print(\"Image deployment error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.DELETE_IMAGE_FROM_SERVER_ERROR):\n print(\"Image deletion error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.IMAGE_CREATION_ERROR):\n print(\"Image creation error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.IMAGE_EDITION_ERROR):\n print(\"Image edition error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.DELETE_IMAGE_FROM_INFRASTRUCTURE_ERROR):\n print(\"Image deletion error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.AUTO_DEPLOY_ERROR):\n print(\"Image auto-deployment error: \" + str(data[\"ErrorDescription\"]))\n elif (data[\"packet_type\"] == PACKET_T.COMMAND_EXECUTED):\n print(\"The cluster server says: command executed successfully\")\n\ndef printLogo():\n print('\\t _____ _____ _ _ ')\n print('\\t / ____| / ____| | | |')\n print('\\t | | _ _ __ _ _ __ _ _ ___| | | | ___ _ _ __| |')\n print('\\t | | | | | |/ _` | \\'_ \\| | | / __| | | |/ _ \\| | | |/ _` |')\n print('\\t | |___| |_| | (_| | | | | |_| \\__ \\ |____| | (_) | |_| | (_| |')\n print('\\t \\_____\\__, |\\__, |_| |_|\\__,_|___/\\_____|_|\\___/ \\__,_|\\__,_|')\n print('\\t __/ | __/ | ')\n print('\\t |___/ |___/ ')\n print()\n \ndef process_command(tokens, networkManager, pHandler, ip_address, port):\n if (len(tokens) == 0) :\n return False\n try :\n command = tokens.pop(0)\n if (command == \"registerVMServer\") :\n ip = tokens.pop(0)\n serverPort = int(tokens.pop(0))\n name = tokens.pop(0)\n isEditionServer = tokens.pop(0) == \"True\"\n p = pHandler.createVMServerRegistrationPacket(ip, serverPort, name, isEditionServer, '')\n networkManager.sendPacket(ip_address, port, p)\n return False \n elif (command == \"obtainVMServerConfiguration\") :\n p = pHandler.createDataRequestPacket(PACKET_T.QUERY_VM_SERVERS_STATUS)\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"obtainVMDistributionData\") :\n p = pHandler.createDataRequestPacket(PACKET_T.QUERY_VM_DISTRIBUTION)\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"obtainVMServerResourceUsage\"):\n p = pHandler.createDataRequestPacket(PACKET_T.QUERY_VM_SERVERS_RESOURCE_USAGE)\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"unregisterVMServer\") :\n p = pHandler.createVMServerUnregistrationOrShutdownPacket(tokens.pop(0), bool(tokens.pop(0)), True, \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"shutdownVMServer\") :\n p = pHandler.createVMServerUnregistrationOrShutdownPacket(tokens.pop(0), bool(tokens.pop(0)), False, \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"bootUpVMServer\") :\n p = pHandler.createVMServerBootPacket(tokens.pop(0), \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"bootUpVM\") :\n p = pHandler.createVMBootRequestPacket(int(tokens.pop(0)), int(tokens.pop(0)), tokens.pop(0))\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"changeVMServerConfiguration\") :\n p = pHandler.createVMServerConfigurationChangePacket(tokens.pop(0), tokens.pop(0), tokens.pop(0), \n int(tokens.pop(0)), tokens.pop(0) == \"True\", '')\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"halt\") :\n p = pHandler.createHaltPacket(True)\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"obtainActiveVMsVNCData\") :\n p = pHandler.createDataRequestPacket(PACKET_T.QUERY_ACTIVE_VM_VNC_DATA)\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"destroyDomain\") :\n p = pHandler.createDomainDestructionPacket(tokens.pop(0), \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"rebootDomain\") :\n p = pHandler.createDomainRebootPacket(tokens.pop(0), \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"obtainImageRepositoryStatus\") :\n p = pHandler.createDataRequestPacket(PACKET_T.QUERY_REPOSITORY_STATUS)\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"deployImage\"):\n p = pHandler.createImageDeploymentPacket(PACKET_T.DEPLOY_IMAGE, tokens.pop(0), int(tokens.pop(0)), \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"deleteImageFromServer\"):\n p = pHandler.createImageDeploymentPacket(PACKET_T.DELETE_IMAGE_FROM_SERVER, tokens.pop(0), int(tokens.pop(0)), \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"createImage\") :\n p = pHandler.createImageEditionPacket(PACKET_T.CREATE_IMAGE, int(tokens.pop(0)), 1, \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"editImage\") :\n p = pHandler.createImageEditionPacket(PACKET_T.EDIT_IMAGE, int(tokens.pop(0)), 1, \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"deleteImageFromInfrastructure\") :\n p = pHandler.createFullImageDeletionPacket(int(tokens.pop(0)), \"\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"deployEditedImage\") :\n p = pHandler.createAutoDeployPacket(int(tokens.pop(0)), -1, \"Auto-deploy\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"autoDeployImage\") :\n p = pHandler.createAutoDeployPacket(int(tokens.pop(0)), int(tokens.pop(0)), \"Auto-deploy\")\n networkManager.sendPacket(ip_address, port, p)\n elif (command == \"quit\") :\n return True\n elif (command == \"help\") :\n displayHelpMessage()\n return False\n except Exception as e:\n print(e) \n print(\"Error: invalid argument\")\n displayHelpMessage()\n \ndef displayHelpMessage():\n print(\"Usage: \")\n print(\"=====\")\n print(\"\\tregisterVMServer : registers a virtual machine server\")\n print(\"\\tobtainVMServerConfiguration: prints all the virtual machine server's status\")\n print(\"\\tobtainVMDistributionData: prints the active virtual machines' distribution data\")\n print(\"\\tobtainVMServerResourceUsage: prints the active virtual machine server's resource usage\") \n print(\"\\tobtainActiveVMsVNCData: prints the active virtual machines' VNC connection data\") \n print(\"\\tobtainImageRepositoryStatus: prints the image repository status\")\n print(\"\\tunregisterVMServer : unregisters a virtual machine server\")\n print(\"\\tshutdownVMServer : shuts down a virtual machine server\") \n print(\"\\tbootUpVMServer : boots up a virtual machine server\")\n print(\"\\tchangeVMServerConfiguration :\")\n print(\"\\t\\tchanges a virtual machine server's configuration\")\n print(\"\\tHalt: shuts down a virtual machine server\") \n print(\"\\tbootUpVM : boots up a virtual machine\")\n print(\"\\tdestroyDomain : destroys a virtual machine\")\n print(\"\\trebootDomain : reboots a virtual machine\")\n print(\"\\tdeployImage : deploys an image on a virtual machine server\")\n print(\"\\tdeleteImageFromServer : deletes an image on a virtual machine server\")\n print(\"\\tcreateImage : creates a new image\")\n print(\"\\teditImage : edits an image\")\n print(\"\\tdeleteImageFromInfrastructure : deletes an image from the whole infrastructure\")\n print(\"\\tdeployEditedImage : updates an edited image on all the virtual machine servers\")\n print(\"\\tautoDeployImage : performs an auto-deployment operation\")\n print(\"\\tquit: closes this application\")\n print(\"\\thelp: prints this help message\")\n\nif __name__ == \"__main__\" :\n print('*' * 80)\n print('*' * 80)\n printLogo()\n print('Cluster Server tester')\n print('Version 7.0')\n print('*' * 80)\n print('*' * 80)\n print()\n networkManager = NetworkManager(\".\")\n networkManager.startNetworkService()\n pHandler = ClusterServerPacketHandler(networkManager)\n ip_address = raw_input(\"Cluster server IP address: \")\n port = raw_input(\"Cluster server control connection port: \")\n try :\n port = int(port)\n networkManager.connectTo(ip_address, port, 10, TesterCallback(pHandler), True)\n while not networkManager.isConnectionReady(ip_address, port) :\n sleep(0.1)\n end = False\n while not end :\n command = raw_input('> ')\n tokens = command.split()\n end = process_command(tokens, networkManager, pHandler, ip_address, port)\n \n except NetworkManagerException as e:\n print(\"Error: \" + e.message)\n networkManager.stopNetworkService()","repo_name":"lbarriosh/cygnus-cloud","sub_path":"src/Infraestructura/testing/clusterServerTester.py","file_name":"clusterServerTester.py","file_ext":"py","file_size_in_byte":13039,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"40371405703","text":"\ndef nextDay(year, month, day):\n if day < 30:\n return year, month, day + 1\n else:\n if month == 12:\n return year + 1, 1, 1\n else:\n return year, month + 1, 1\n \ndef daysBetweenDates(year1, month1, day1, year2, month2, day2):\n start = year1, month1, day1\n end = year2,month2,day2\n\n # Check Validation\n # Assume Eache month has 30 days\n if(not isDateBefore(start,end)):\n return \"AssertionError\"\n\n days = 0\n start = nextDay(year1, month1, day1)\n while( isDateBefore(start, end) ):\n days+=1\n start = nextDay(start[0],start[1],start[2])\n\n return days\n \n\n\ndef isDateBefore(start, end):\n return start <= end\n \n\ndef test():\n test_cases = [((2012,10,30,2012,10,30),0), \n ((2012,1,1,2013,1,1),360),\n ((2012,9,1,2012,9,4),3),\n ((2013,1,1,1999,12,31), \"AssertionError\")]\n \n for (args, answer) in test_cases:\n try:\n result = daysBetweenDates(*args)\n if result != answer:\n print(\"Test with data:\", args, \"failed\")\n else:\n print(\"Test case passed!\")\n except AssertionError:\n if answer == \"AssertionError\":\n print(\"Nice job! Test case {0} correctly raises AssertionError!\\n\".format(args))\n else:\n print(\"Check your work! Test case {0} should not raise AssertionError!\\n\".format(args)) \n\n\ntest()\n \n","repo_name":"AbbasMustafa/DataStructure-Algorithm","sub_path":"Day 3/dateValidation.py","file_name":"dateValidation.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6213000227","text":"import os\nimport pygame as pg\nfrom abc import ABC, abstractmethod\n\nkeybinding = { # 键盘绑定\n 'action': pg.K_s, # 行动键\n 'jump': pg.K_SPACE, # 跳跃\n 'left': pg.K_LEFT, # 左跑\n 'right': pg.K_RIGHT, # 右跑\n 'down': pg.K_DOWN # 下蹲\n}\n\nclass State(): # 状态类\n def __init__(self):\n self.start_time = 0.0\n self.current_time = 0.0\n self.done = False # 状态结束为否\n self.next = None # 下一个状态为空\n self.persist = {} # 传递数据为空字典\n\n @abstractmethod\n def startup(self, current_time, persist): # 状态开始\n '''abstract method'''\n\n def cleanup(self): # 状态结束清空\n self.done = False\n return self.persist\n\n @abstractmethod\n def update(self, surface, keys, current_time): # 状态运行过程中的数据更新:界面,键,当前时间\n '''abstract method'''\n\nclass Control(): # 控制类\n def __init__(self):\n self.screen = pg.display.get_surface() # 获取当前显示的 Surface 对象\n self.done = False\n self.clock = pg.time.Clock() # python时间性能测量:time.Clock():测量程序运行的cpu时间\n self.fps = 60 # 帧频率为60\n self.current_time = 0.0\n self.keys = pg.key.get_pressed() # 获取键盘上所有按键的状态\n self.state_dict = {} # 状态字典\n self.state_name = None\n self.state = None\n\n def setup_states(self, state_dict, start_state): # 设置状态\n self.state_dict = state_dict\n self.state_name = start_state\n self.state = self.state_dict[self.state_name]\n\n def update(self): # 更新状态时间\n self.current_time = pg.time.get_ticks() # 获取以毫秒为时间间隔的时间\n if self.state.done: # 如果状态结束为真\n self.flip_state() # 跳状态\n self.state.update(self.screen, self.keys, self.current_time) # 更新状态数据\n\n def flip_state(self): # 跳状态\n previous, self.state_name = self.state_name, self.state.next # 之前的状态名,下一个状态名\n persist = self.state.cleanup()\n self.state = self.state_dict[self.state_name]\n self.state.startup(self.current_time, persist)\n\n def event_loop(self): # 事件循环\n for event in pg.event.get(): # 在游戏循环中监听事件\n if event.type == pg.QUIT: # 如果事件类型为用户按下关闭按钮\n self.done = True # 状态结束为真\n elif event.type == pg.KEYDOWN: # 键盘被按下\n self.keys = pg.key.get_pressed() # 获取键盘上所有的按键状态\n elif event.type == pg.KEYUP: # 键盘被放开\n self.keys = pg.key.get_pressed()\n\n def main(self): # 主函数\n while not self.done: # 状态结束不为真时\n self.event_loop() # 循环监听事件\n self.update() # 更新状态时间\n pg.display.update() # 更新部分界面显示信息\n self.clock.tick(self.fps) # 设置游戏的帧频, 帧率可以理解为游戏在一秒钟内进行多少次画面刷新。\n\ndef get_image(sheet, x, y, width, height, colorkey, scale): # 获取图像\n image = pg.Surface([width, height]) # 设置pygame的界面大小\n rect = image.get_rect() # 处理矩形图像的方法\n\n image.blit(sheet, (0, 0), (x, y, width, height)) # 将一个图像(Surface 对象)绘制到另一个图像上方\n image.set_colorkey(colorkey)\n image = pg.transform.scale(image, # 图像大小的缩放\n (int(rect.width*scale),\n int(rect.height*scale)))\n return image\n\ndef load_all_gfx(directory, colorkey=(255,0,255), accept=('.png', '.jpg', '.bmp', '.gif')): # 加载文件夹中的图片\n graphics = {} # 图标字典\n for pic in os.listdir(directory): # os.listdir():返回文件夹中的文件\n name, ext = os.path.splitext(pic) # 分离文件名与扩展名\n if ext.lower() in accept: # Python判断一个文件夹内哪些文件是accept扩展名中的图片实例\n img = pg.image.load(os.path.join(directory, pic)) # os.path.join()函数:连接两个或更多的路径名组件 pygame.image.load()从文件加载新图片。\n if img.get_alpha(): # 如果获取到了图像的透明度\n img = img.convert_alpha() # 保留图像的透明部分\n else:\n img = img.convert() # 将图像转化为surface对象\n img.set_colorkey(colorkey) # 设置透明颜色键,与colorkey颜色相同的任何像素都是透明的\n graphics[name] = img # 图像列表\n return graphics\n","repo_name":"KittyGao-Cui/supermario2","sub_path":"source/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70057810726","text":"import sys\nimport mariadb\nfrom django.db import connection\n\ndef dictfetchall(cursor):\n \"Return all rows from a cursor as a dict\"\n columns = [col[0] for col in cursor.description]\n return [\n dict(zip(columns, row))\n for row in cursor.fetchall()\n ]\n\ndef AllReview(c_id):\n try:\n cur = connection.cursor()\n use_db_query = \"use oosooDB\"\n select_query = f\"SELECT * FROM contents_review WHERE c_id = '{c_id}' ORDER BY _like DESC\"\n\n cur.execute(use_db_query)\n cur.execute(select_query)\n select_reviews = dictfetchall(cur)\n\n except mariadb.Error as e:\n print(f\"failed: Error connecting to Mariadb: {e}\")\n sys.exit(1)\n result = []\n\n connection.close()\n\n return select_reviews","repo_name":"kpuce2022CD/OOSOO","sub_path":"Backend/django/api/User/AllReview.py","file_name":"AllReview.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"37019574071","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\shared\\mapView\\mapViewConst.py\r\nfrom eve.client.script.ui.shared.maps.mapcommon import STARMODE_SECURITY\r\nUNIVERSE_SCALE = 1.5e-13\r\nSOLARSYSTEM_SCALE = 1e-10\r\nSTAR_SIZE = 60.0\r\nMAX_MARKER_DISTANCE = 220000.0\r\nMIN_CAMERA_DISTANCE = 10.0\r\nMAX_CAMERA_DISTANCE = 200000.0\r\nMIN_CAMERA_DISTANCE_SOLARSYSTEMVIEW = 1.0\r\nMAX_CAMERA_DISTANCE_SOLARSYSTEMVIEW = 2500.0\r\nJUMPLINE_BASE_WIDTH = 2.5\r\nAUTOPILOT_LINE_TICKSIZE = const.AU * 10000 * UNIVERSE_SCALE\r\nAUTOPILOT_LINE_ANIM_SPEED = 3.0\r\nAUTOPILOT_LINE_WIDTH = JUMPLINE_BASE_WIDTH * 2\r\nCONSTELLATION_LINE_TICKSIZE = const.AU * 5000 * UNIVERSE_SCALE\r\nREGION_LINE_TICKSIZE = const.AU * 10000 * UNIVERSE_SCALE\r\nAUDIO_SOLARSYSTEM_DISTANCE = 10.0\r\nAUDIO_CONSTELLATION_DISTANCE = 50.0\r\nSETTING_PREFIX = 'mapview1'\r\nVIEWMODE_LAYOUT_SETTINGS = SETTING_PREFIX + '_majorlayout'\r\nVIEWMODE_LAYOUT_SOLARSYSTEM = 0\r\nVIEWMODE_LAYOUT_CONSTELLATIONS = 1\r\nVIEWMODE_LAYOUT_REGIONS = 2\r\nVIEWMODE_LAYOUT_DEFAULT = VIEWMODE_LAYOUT_SOLARSYSTEM\r\nVIEWMODE_LINES_SETTINGS = SETTING_PREFIX + '_lines'\r\nVIEWMODE_LINES_NONE = 3\r\nVIEWMODE_LINES_ALL = 4\r\nVIEWMODE_LINES_SELECTION = 5\r\nVIEWMODE_LINES_SELECTION_REGION = 6\r\nVIEWMODE_LINES_SELECTION_REGION_NEIGHBOURS = 7\r\nVIEWMODE_LINES_DEFAULT = VIEWMODE_LINES_ALL\r\nVIEWMODE_LINES_SHOW_ALLIANCE_SETTINGS = SETTING_PREFIX + '_show_alliance_lines'\r\nVIEWMODE_LINES_SHOW_ALLIANCE_DEFAULT = True\r\nVIEWMODE_LAYOUT_SHOW_ABSTRACT_SETTINGS = SETTING_PREFIX + '_layout'\r\nVIEWMODE_LAYOUT_SHOW_ABSTRACT_DEFAULT = False\r\nVIEWMODE_COLOR_SETTINGS = SETTING_PREFIX + '_colormode'\r\nVIEWMODE_COLOR_DEFAULT = STARMODE_SECURITY\r\nVIEWMODE_COLOR_RECENT = SETTING_PREFIX + '_recent_colormode'\r\nVIEWMODE_COLOR_RECENT_DEFAULT = [VIEWMODE_COLOR_DEFAULT]\r\nVIEWMODE_COLOR_RECENT_MAX = 5\r\nVIEWMODE_MARKERS_SETTINGS = SETTING_PREFIX + '_systemmap_markers'\r\nMARKERS_OPTION_PERSONAL_LOCATION = 'personal_location'\r\nMARKERS_OPTION_CORPORATION_LOCATION = 'corporation_location'\r\nVIEWMODE_MARKERS_OPTIONS_CUSTOM = [MARKERS_OPTION_PERSONAL_LOCATION, MARKERS_OPTION_CORPORATION_LOCATION]\r\nVIEWMODE_MARKERS_CUSTOM_LABELS = {MARKERS_OPTION_PERSONAL_LOCATION: 'UI/PeopleAndPlaces/PersonalLocations',\r\n MARKERS_OPTION_CORPORATION_LOCATION: 'UI/PeopleAndPlaces/CorporationLocations'}\r\nVIEWMODE_MARKERS_OPTIONS = [const.groupScannerProbe,\r\n const.groupPlanet,\r\n const.groupMoon,\r\n const.groupStation,\r\n const.groupAsteroidBelt,\r\n const.groupBeacon,\r\n const.groupSatellite,\r\n const.groupStargate,\r\n const.groupSovereigntyClaimMarkers,\r\n const.groupSun]\r\nVIEWMODE_MARKERS_DEFAULT = VIEWMODE_MARKERS_OPTIONS + VIEWMODE_MARKERS_OPTIONS_CUSTOM\r\nVIEWMODE_MARKERS_OVERLAP_SORT_ORDER = [const.groupStargate,\r\n const.groupAsteroidBelt,\r\n const.groupStation,\r\n const.groupScannerProbe,\r\n const.groupPlanet,\r\n const.groupMoon,\r\n const.groupBeacon,\r\n const.groupSatellite,\r\n const.groupSovereigntyClaimMarkers,\r\n const.groupSun]\r\nDEFAULT_MAPVIEW_SETTINGS = {VIEWMODE_LAYOUT_SETTINGS: VIEWMODE_LAYOUT_DEFAULT,\r\n VIEWMODE_COLOR_SETTINGS: VIEWMODE_COLOR_DEFAULT,\r\n VIEWMODE_COLOR_RECENT: VIEWMODE_COLOR_RECENT_DEFAULT,\r\n VIEWMODE_LAYOUT_SHOW_ABSTRACT_SETTINGS: VIEWMODE_LAYOUT_SHOW_ABSTRACT_DEFAULT,\r\n VIEWMODE_LINES_SETTINGS: VIEWMODE_LINES_DEFAULT,\r\n VIEWMODE_LINES_SHOW_ALLIANCE_SETTINGS: VIEWMODE_LINES_SHOW_ALLIANCE_DEFAULT,\r\n VIEWMODE_MARKERS_SETTINGS: VIEWMODE_MARKERS_DEFAULT}\r\nVIEWMODE_FOCUS_SELF = 'focus_self'\r\nMARKERID_MYPOS = 1\r\nMARKERID_MYHOME = 2\r\nMARKERID_BOOKMARK = 3\r\nMARKERID_ROUTE = 4\r\nMARKERID_SCANRESULT = 5\r\nMARKERID_SOLARSYSTEM_CELESTIAL = 6\r\nMARKERID_PROBE = 7\r\nMARKERID_SCANRESULT_OVERLAP_SORT_ORDER = 0\r\nMARKERID_MYPOS_OVERLAP_SORT_ORDER = 1\r\nMARKERID_MYHOME_OVERLAP_SORT_ORDER = 2\r\nMARKER_TYPES = (MARKERID_MYPOS,\r\n MARKERID_BOOKMARK,\r\n MARKERID_ROUTE,\r\n MARKERID_SOLARSYSTEM_CELESTIAL,\r\n MARKERID_MYHOME,\r\n MARKERID_PROBE,\r\n MARKERID_SCANRESULT)\r\nMARKER_POINT_LEFT = 0\r\nMARKER_POINT_TOP = 1\r\nMARKER_POINT_RIGHT = 2\r\nMARKER_POINT_BOTTOM = 3\r\nJUMPBRIDGE_COLOR = (0.0, 1.0, 0.0, 1.0)\r\nJUMPBRIDGE_CURVE_SCALE = 0.5\r\nJUMPBRIDGE_TYPE = 4\r\nMAPVIEW_CAMERA_SETTINGS = SETTING_PREFIX + '_camera'\r\nMAPVIEW_PRIMARY_ID = 'primary'\r\nMAPVIEW_PRIMARY_OVERLAY_ID = 'primary_overlay'\r\nMAPVIEW_SOLARSYSTEM_ID = 'solarsystem'\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/eve/client/script/ui/shared/mapView/mapViewConst.py","file_name":"mapViewConst.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"26645457347","text":"import numpy as np\nfrom scipy.stats import pearsonr\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nimport pickle, time, plac, string, collections, operator\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nfrom word2sent_v1 import scoring_function_v1\nfrom word2sent_v2 import scoring_function_v2\nfrom word2sent_v3 import scoring_function_v3\nimport process_data\n\ndef get_correlation(word_embeddings, words, test_file, scoring_function):\n \"\"\"\n Testing the model on the given test file and producing the evaluation results with the Pearson's Coefficent and MSE.\n :param word_embeddings: a file contains all word vectors of the words in the vocabulary, one word embedding per line.\n :param words: a file contains all words in the corpus, one word per line.\n :param test_file: a test dataset.\n :param scoring_function: no weighting scheme scoring function (V1).\n :return: the Pearson's Coefficent and MSE\n \"\"\"\n print(\"evaluate with the model {}\\n\".format(str(scoring_function).split('_')[2]))\n test_file = open(test_file)\n lines = test_file.readlines()\n golds = []\n preds = []\n index = []\n idx = 0\n for num, i in enumerate(lines):\n if num % 100 == 0:\n print('{} lines have been proceeded.\\n'.format(num))\n i = i.split(\"\\t\")\n sent1 = i[0].translate(None, string.punctuation)\n sent2 = i[1].translate(None, string.punctuation)\n score = float(i[2])\n seq1, seq2 = process_data.getSeqs(sent1, sent2, words)\n id1, m1 = process_data.prepare_data(seq1)\n id2, m2 = process_data.prepare_data(seq2)\n uni_pairs_id = process_data.unigram_pairs(id1, id2)\n sentence_score = scoring_function(word_embeddings, uni_pairs_id)\n golds.append(score)\n preds.append(sentence_score)\n index.append(idx)\n idx += 1\n golds = np.asarray(golds)\n preds = np.asarray(preds)\n MSE = sqrt(mean_squared_error(golds, preds))\n return pearsonr(preds, golds)[0], MSE\n\ndef get_correlation_weighted(word_embeddings, words, weight4ind, test_file, scoring_function):\n \"\"\"\n Testing the model on the given test file and producing the evaluation results with the Pearson's Coefficent and MSE.\n :param word_embeddings: a file contains all word vectors of the words in the vocabulary, one word embedding per line.\n :param words: a file contains all words in the corpus, one word per line.\n :param weight4ind: a file indicates the weight of the word according to the index of the word.\n :param test_file: a test dataset.\n :param scoring_function: with weighting scheme scoring function (V2 & V3).\n :return: the Pearson's Coefficent and MSE\n \"\"\"\n print(\"evaluate with the model {}\\n\".format(str(scoring_function).split('_')[2]))\n test_file = open(test_file)\n lines = test_file.readlines()\n golds = []\n preds = []\n index = []\n idx = 0\n for num, i in enumerate(lines):\n if num % 100 == 0:\n print('{} lines have been proceeded.\\n'.format(num))\n i = i.split(\"\\t\")\n sent1 = i[0].translate(None, string.punctuation)\n sent2 = i[1].translate(None, string.punctuation)\n score = float(i[2])\n seq1, seq2 = process_data.getSeqs(sent1, sent2, words)\n id1, m1 = process_data.prepare_data(seq1)\n id2, m2 = process_data.prepare_data(seq2)\n weight1 = process_data.seq2weight(id1, m1, weight4ind)\n weight2 = process_data.seq2weight(id2, m2, weight4ind)\n uni_pairs_id = process_data.unigram_pairs(id1, id2)\n uni_pairs_weight = process_data.unigram_pairs(weight1, weight2)\n sentence_score = scoring_function(word_embeddings, uni_pairs_id, uni_pairs_weight)\n golds.append(score)\n preds.append(sentence_score)\n index.append(idx)\n idx += 1\n golds = np.asarray(golds)\n preds = np.asarray(preds)\n MSE = sqrt(mean_squared_error(golds, preds))\n return pearsonr(preds, golds)[0], MSE\n\n\ndef main():\n print('evaluation starts.')\n # Step 1: Choosing the vocabulary and the word embeddings file.\n path4words = '/shared/data_WordSentenceVector/model_lawinsider_full/lawinsider_full_tagged_OnlyWord/words_beagle'\n # path4words = '/shared/data_WordSentenceVector/model_wiki_glove/SentenceVector/words_glove'\n # path4words = '/shared/data_WordSentenceVector/model_fasttext_cc/SentenceVector/words_ft_cc'\n path4emb = '/shared/data_WordSentenceVector/model_lawinsider_full/lawinsider_full_tagged_OnlyWord/vectors_beagle'\n # path4emb = '/shared/data_WordSentenceVector/model_wiki_glove/SentenceVector/vectors_glove'\n # path4emb = '/shared/data_WordSentenceVector/model_fasttext_cc/SentenceVector/vectors_ft_cc'\n path4weight = '/shared/data_WordSentenceVector/model_lawinsider_full/lawinsider_full_tagged_OnlyWord/weight4ind_weightpara_1E-03'\n # path4weight = '/shared/data_WordSentenceVector/model_wiki_glove/SentenceVector/weight4ind_glove_1e-03'\n # path4weight = '/shared/data_WordSentenceVector/model_fasttext_cc/SentenceVector/weight4ind_weightpara_1E-03'\n\n # Step 2: Loading the vocabulary and the word embeddings file.\n print(\"loading words file from {}\".format(path4words.split('/')[3]))\n words = pickle.load(open(path4words, 'rb'))\n print(\"loading word embeddings file from {}\".format(path4emb.split('/')[3]))\n word_embeddings = pickle.load(open(path4emb, 'rb'))\n print(\"loading weight4ind file from {}\".format(path4weight.split('/')[3]))\n weight4ind = pickle.load(open(path4weight, 'rb'))\n\n # Step 3: Creating a dictionary to find scoring function and its string\n func_dictionary = {'scoring_function_v1': scoring_function_v1,\n 'scoring_function_v2': scoring_function_v2,\n 'scoring_function_v3': scoring_function_v3,\n }\n # Step 4: Adding all test files into a list\n test_folder = './eval_data/'\n test_list = [join(test_folder, f) for f in listdir(test_folder) if isfile(join(test_folder, f))]\n\n # Step 5: Preparing to write the processing information and the evaluation results to a .txt file.\n f = open(\"overall_result.txt\", 'w')\n f.write(\"loading words file from {}\\n\".format(path4words.split('/')[3]))\n f.write(\"loading word embeddings file from {}\\n\".format(path4emb.split('/')[3]))\n f.write(\"loading weight4ind file from {}\\n\".format(path4weight.split('/')[3]))\n for tf in test_list:\n f.write(\"test file is {}\\n\".format(str(tf)))\n sf = 'scoring_function_v1'\n pearson, MSE = get_correlation(word_embeddings, words, tf, func_dictionary[sf])\n f.write(\"evaluate with the model {}\\n\".format(str(sf).split('_')[2]))\n f.write('pearson is {} and MSE is {}\\n'.format(pearson, MSE))\n for i in (7,8):\n sf = 'scoring_function_v' + str(i)\n pearson, MSE = get_correlation_weighted(word_embeddings, words, weight4ind, tf, func_dictionary[sf])\n f.write(\"evaluate with the model {}\\n\".format(str(sf).split('_')[2]))\n f.write('pearson is {} and MSE is {}\\n'.format(pearson, MSE))\n\nif __name__ == '__main__':\n plac.call(main)\n","repo_name":"YingWang-Clare/Word2Sent","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":7166,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"41778875488","text":"import json\n\nimport boto3\n\n\ndef lambda_handler(event, context):\n payload = json.loads(event[\"body\"])\n\n SFN = boto3.client(\"stepfunctions\")\n # 対象のStep Functionsと同じアカウント同じリージョンにあると仮定している\n # なので「おおむね」動く\n\n res = SFN.describe_execution(executionArn=payload[\"executionArn\"])\n # print(res)\n return {\n \"statusCode\": 200,\n \"body\": json.dumps(\n {\"status\": res[\"status\"], \"output\": json.loads(res.get(\"output\", \"{}\"))}\n ),\n }\n","repo_name":"heiwa4126/sam-stepfunctions-apigw","sub_path":"src/result/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5814818357","text":"class Solution(object):\n def findAnagrams(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: List[int]\n \"\"\"\n result = []\n \n cnt = [0] * 26\n for c in p:\n cnt[ord(c) - ord('a')] += 1\n left, right = 0, 0 #####left, right pointer\n while right < len(s):\n cnt[ord(s[right]) - ord('a')] -= 1\n while left <= right and cnt[ord(s[right]) - ord('a')] < 0: #####while if!!\n cnt[ord(s[left]) - ord('a')] += 1\n left += 1\n if right - left + 1 == len(p):\n result.append(left)\n right += 1\n return result\n\n \n","repo_name":"shaniavina/Leetcode_Python","sub_path":"find_all_anagrams_in_a_string.py","file_name":"find_all_anagrams_in_a_string.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71656547365","text":"from brewapp import manager\nfrom model import *\nfrom util import *\nfrom brewapp import app\nfrom flask import request\nfrom flask_restless.helpers import to_dict\nfrom flask import Response\n\n@brewinit()\ndef init():\n manager.create_api(RecipeBooks, methods=['GET', 'POST', 'DELETE', 'PUT'])\n manager.create_api(RecipeBookSteps, methods=['GET', 'POST', 'DELETE', 'PUT'])\n\n@app.route('/api/recipe_books/load/', methods=['POST'])\ndef loadRecipe(id):\n\n Step.query.delete()\n db.session.commit()\n\n recipe = RecipeBooks.query.get(id);\n\n for a in recipe.steps:\n s = Step(name=a.name, order=a.order, timer=a.timer, temp=a.temp, type=a.type, state=\"I\", kettleid=a.kettleid)\n db.session.add(s)\n db.session.commit()\n\n setBrewName(recipe.name)\n return ('',204)\n\n@app.route('/api/recipe_books/export')\ndef export_book():\n r = RecipeBooks.query.all()\n ar = []\n for t in r:\n ar.append(to_dict(t, deep={'steps': []}))\n\n return Response(json.dumps(ar),\n mimetype='application/json',\n headers={'Content-Disposition':'attachment;filename=CraftBeerPI_RecipeBook.json'})\n\n\n\n@app.route('/api/recipe_books/save', methods=['POST'])\ndef save_book():\n data =request.get_json()\n\n recipie = RecipeBooks.query.filter_by(name=data[\"name\"]).first()\n\n if(recipie != None):\n db.session.delete(recipie)\n db.session.commit()\n\n s = Step.query.all()\n steps = []\n for a in s:\n steps.append(RecipeBookSteps(name=a.name, order=a.order, timer=a.timer, temp=a.temp, type=a.type, kettleid=a.kettleid))\n\n rb = RecipeBooks(name=data[\"name\"], steps=steps)\n db.session.add(rb)\n db.session.commit()\n return ('',204)\n\n\ndef hallo():\n pass\n\ndef setBrewName(name):\n config = Config.query.get(\"BREWNAME\");\n\n if(config == None):\n config = Config()\n config.name = \"BREWNAME\"\n config.value = name\n\n else:\n config.value = name\n\n db.session.add(config)\n db.session.commit()\n","repo_name":"craftbeerpi/craftbeerpi","sub_path":"brewapp/base/recipebook.py","file_name":"recipebook.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","stars":591,"dataset":"github-code","pt":"52"} +{"seq_id":"38960804592","text":"from numpy import full\r\nfrom pyparsing import col\r\nimport streamlit as st\r\nimport requests\r\nfrom bs4 import BeautifulSoup as BS\r\nimport pandas as pd\r\nimport random\r\nimport math\r\n\r\nfrom config import sources, columns, email_source, DOCTORS_PER_PAGE\r\nimport generate\r\n\r\n@st.cache\r\ndef parse_specializations():\r\n request = requests.get(sources['МОСГОРМЕД'])\r\n html = BS(request.content, 'html.parser')\r\n result = []\r\n\r\n items = html.select('.speciality-home-list > .speciality-home-one')\r\n if len(items) > 0:\r\n for element in items:\r\n num_entries = element.select('.speciality-number-home-wrap > span')[0].get_text(strip=True)\r\n if num_entries == \"0\":\r\n continue\r\n data = element.select('.dotted > a')[0]\r\n result.append(\r\n {\r\n 'spec': data.get_text(strip=True),\r\n 'href': data['href'],\r\n 'count': int(num_entries)\r\n }\r\n )\r\n \r\n return result\r\n\r\ndef parse_doctors(items, samples):\r\n data = {'Имя': [], 'Фамилия': [], 'Отчество': [], 'Должность': [], 'Стаж': []}\r\n while len(data['Имя']) != samples:\r\n item = items[random.randint(0, len(items) - 1)]\r\n\r\n if item['count'] > DOCTORS_PER_PAGE:\r\n page = random.randint(1, math.ceil(item['count'] // DOCTORS_PER_PAGE))\r\n else:\r\n page = 1\r\n \r\n request = requests.get(item['href'] + f'page/{page}')\r\n html = BS(request.content, 'html.parser')\r\n element = html.select('div.th-poststwo.th-postslist.taxonomy-speciality > article')\r\n if len(element) == 0:\r\n continue\r\n num_elements = len(element) - 1 if len(element) > 1 else 1\r\n element = element[random.randint(0, num_elements)]\r\n\r\n fullname = element.select('.zagdoc')[0].get_text(strip=True).split()\r\n experience = int(element.select('.expicience')[0].get_text(strip=True).split()[1])\r\n\r\n if (\r\n len(fullname) != 3 or\r\n fullname[1] in data['Имя'] and \r\n fullname[0] in data['Фамилия'] and \r\n fullname[2] in data['Отчество'] and \r\n experience in data['Стаж']\r\n ):\r\n continue\r\n \r\n data['Имя'].append(fullname[1])\r\n data['Фамилия'].append(fullname[0])\r\n data['Отчество'].append(fullname[2])\r\n data['Должность'].append(item['spec'])\r\n data['Стаж'].append(experience)\r\n \r\n return data\r\n\r\ndef parse_emails(samples):\r\n request = requests.get(email_source)\r\n html = BS(request.content, 'html.parser')\r\n result = []\r\n\r\n element = html.select('.entry-content > p')[2]\r\n for email in element.select('a'):\r\n result.append(email.get_text(strip=True))\r\n\r\n random.shuffle(result)\r\n result = list(set(result))\r\n \r\n return result[:samples]\r\n\r\ndef create_doctor_table(info, samples, output_format):\r\n with st.spinner('Считываем данные докторов...'):\r\n data = parse_doctors(info['specs'], samples=samples)\r\n \r\n days = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']\r\n day = 0\r\n with st.spinner('Генерируем расписание...'):\r\n for i in info['weekday']:\r\n data[days[day]] = generate.generate_schedule(samples=samples, is_working=i)\r\n day += 1\r\n\r\n with st.spinner('Генерируем номера телефонов...'):\r\n data['Номер телефона'] = generate.generate_phone(samples=samples)\r\n\r\n with st.spinner('Считываем адреса электронных почт...'):\r\n data['Email'] = parse_emails(samples)\r\n\r\n with st.spinner('Генерируем номера клиник...'):\r\n data['Клиники'] = generate.generate_clinics(samples, info['clinics_from'], info['clinics_to'])\r\n\r\n with st.spinner('Генерируем номера мед-лицензий...'):\r\n data['Номер медицинской лицензии'] = generate.generate_med_license(samples)\r\n\r\n with st.spinner('Генерируем сроки действия мед-лицензий...'):\r\n data['Срок действия'] = generate.generate_end_term(samples)\r\n\r\n data['id[pk]'] = list(range(1, samples + 1))\r\n\r\n table = pd.DataFrame(data, columns=columns)\r\n\r\n return table\r\n","repo_name":"Neko-Nika/Medical-Parsing","sub_path":"parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33859510201","text":"import requests as req\nfrom bs4 import BeautifulSoup\nimport ast\nimport time\nfrom webapp_stores.db_functions import save_data_product\n\n\nfull_randevu_man = ['https://www.rendez-vous.ru/catalog/male/',\n 'https://www.rendez-vous.ru/catalog/bags_male/',\n 'https://www.rendez-vous.ru/catalog/muzhskaya_odezhda/',\n 'https://www.rendez-vous.ru/catalog/accessories_male/']\nfull_randevu_women = ['https://www.rendez-vous.ru/catalog/female/',\n 'https://www.rendez-vous.ru/catalog/bags_female/',\n 'https://www.rendez-vous.ru/catalog/zhenskaya_odezhda/',\n 'https://www.rendez-vous.ru/catalog/accessories_female/']\nfull_randevu_chaildren = ['https://www.rendez-vous.ru/catalog/girls/',\n 'https://www.rendez-vous.ru/catalog/boys/']\nfull_randevu_unisex = ['https://www.rendez-vous.ru/catalog/tools/']\n\n\n\ndef get_html(url):\n try:\n result = req.get(url)\n result.raise_for_status()\n return result.text\n except(req.RequestException, ValueError):\n print('Сетевая ошибка')\n return False\n\ndef get_store_randevu(url):\n html = get_html(url)\n if html:\n soup = BeautifulSoup(html, 'html.parser')\n try:\n url_store = url\n image = soup.find('div', class_='item-info').find('div', class_='carousel-image-list').find('img')[\n 'data-src']\n\n code = \\\n ast.literal_eval(soup.find('button', class_='btn-block btn-primary btn')['data-productinfo'])[\n 'name']\n\n # price = ast.literal_eval(soup.find('button', class_='btn-block btn-primary btn')['data-productinfo'])[\n # 'priceFromCart']\n\n brand = ast.literal_eval(soup.find('button', class_='btn-block btn-primary btn')['data-productinfo'])[\n 'brand']\n color = ast.literal_eval(soup.find('button', class_='btn-block btn-primary btn')['data-productinfo'])[\n 'variant']\n category_detailed = \\\n ast.literal_eval(soup.find('button', class_='btn-block btn-primary btn')['data-productinfo'])[\n 'category'].split(\n '/')[0]\n category = soup.find('div', class_='breadcrumbs').find_all('li')[1].find('a').text\n\n # sizes\n try:\n sizes = soup.find('ul', class_='form-select-list scrollbar scrollbar-y').find_all('li')\n sizes_available = []\n for size in sizes:\n sizes_available.append(size.text.strip())\n except:\n sizes_available = ['one-size']\n\n dict = {'code': code, 'brand': brand, 'color': color,\n 'category_detailed': category_detailed, 'category': category, 'image': image,\n 'sizes': sizes_available, 'url': url_store}\n # print(dict)\n return dict\n\n # if the product is not available in the store\n except:\n # what should we do?\n print('Товар не доступен')\n\n\ndef pages_in_category(url):\n html = get_html(url)\n if html:\n soup = BeautifulSoup(html, 'html.parser')\n number_of_pages = int(soup.find('ul', class_='pagination').find_all('li', class_='page')[-1].get_text())\n return number_of_pages\n\n\n# Парсит линки всех товаров все товары\ndef get_full_randevu(full_randevu_man,full_randevu_women,full_randevu_chaildren,full_randevu_unisex):\n full_randevu = full_randevu_man + full_randevu_women + full_randevu_chaildren+full_randevu_unisex\n for category in full_randevu:\n pages = pages_in_category(url = category)\n # print(pages)\n for pa in range(1, pages + 1):\n final_link = category + 'page/' + str(pa) + '/'\n randevuze_product_collection(final_link)\n print(final_link)\n\ndef prod_url(product):\n url = 'https://www.rendez-vous.ru/' + product.find('a')['href']\n return url\n\ndef prod_category(product_randevoyz_all):\n product_category = product_randevoyz_all['category']\n product_category_clear = ((product_category).split('/'))[0]\n return product_category_clear\n\ndef prod_discount(product):\n product_discount = str(('').join((product.find('span', class_=\"item-price-value\").get_text()).split()))\n return product_discount\n\ndef prod_store():\n return 'Рандеву'\n\ndef product_name(product):\n name =((product.find('div', class_=\"item-name\")).text).strip()\n return name\n\n\n\ndef dict_cliner(product_randevoyz_all):\n try:\n if 'dimension5' in product_randevoyz_all:\n del product_randevoyz_all['dimension5']\n if 'position' in product_randevoyz_all:\n del product_randevoyz_all['position']\n if 'variant' in product_randevoyz_all:\n del product_randevoyz_all['variant']\n return product_randevoyz_all\n except(KeyError):\n return product_randevoyz_all\n\ndef product_gender(final_link):\n category = final_link.split('page/')\n if category[0] in full_randevu_man:\n return 'Man'\n elif category[0] in full_randevu_women:\n return 'Woman'\n elif category[0] in full_randevu_chaildren:\n return 'Children'\n else:\n return 'Unisex'\n\n\ndef randevuze_product_collection(final_link):\n html = get_html(url=final_link)\n if html:\n soup = BeautifulSoup(html, 'html.parser')\n product_all = soup.find('ul', class_=\"list-items list-items-catalog list-view-1 js-list-items\").\\\n find_all('li', class_=\"item\")\n for product in product_all:\n # print(product)\n try:\n product_randevoyz_all = ast.literal_eval(product['data-productinfo'])\n product_randevoyz = dict_cliner(product_randevoyz_all)\n product_url = prod_url(product)\n product_randevoyz['category'] = prod_category(product_randevoyz_all)\n current_product = get_store_randevu(url = product_url)\n product_randevoyz['name'] = product_name(product)\n # print(current_product)\n product_randevoyz['product_store'] = prod_store()\n product_randevoyz['color'] = current_product['color']\n product_randevoyz['category'] = current_product['category']\n product_randevoyz['category_detailed'] = current_product['category_detailed']\n product_randevoyz['product_url'] = product_url\n product_randevoyz['size'] = str(current_product['sizes'])\n product_randevoyz['product_image'] = current_product['image']\n product_randevoyz['product_discount'] = prod_discount(product)\n product_randevoyz['gender'] = product_gender(final_link)\n print(product_randevoyz)\n time.sleep(3.0)\n save_data_product(product_randevoyz)\n except(KeyError, TypeError):\n continue\n\n\nif __name__ == '__main__':\n get_full_randevu(full_randevu_man,full_randevu_women,full_randevu_chaildren,full_randevu_unisex)\n","repo_name":"FlyOn21/project_store_find","sub_path":"delete/all_product_randevuze.py","file_name":"all_product_randevuze.py","file_ext":"py","file_size_in_byte":7180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15357351172","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path('', home, name='home'),\n path('categoria/', categoria_add, name='add_categoria'),\n path('sitio/', sitio_add, name='add_sitio'),\n path('categoria/', categoria_list, name='lista_categoria'),\n path('sitio//', sitio, name='sitio'),\n]\n","repo_name":"KevinFernandoVidal/reto6","sub_path":"apps/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74532180005","text":"class Button():\n def __init__(self, image, pos, text, font, color):\n self.image = image\n self.x = pos[0]\n self.y = pos[1]\n self.font = font\n self.color = color\n self.input_text = text\n \n self.text = self.font.render(self.input_text, True, self.color)\n \n self.image = self.text\n self.rect = self.image.get_rect(center = (self.x, self.y))\n\n def update(self, screen):\n if self.image is not None:\n screen.blit(self.image, self.rect)\n screen.blit(self.text, self.text_rect)\n\n def check_input(self, position):\n if position[0] in range(self.rext.left, self.rect.right) and position[1] in range(self.rect.top, selft.rect.bottom):\n return True\n return False\n\n","repo_name":"ForTheDeusVult/Tetris-NEA","sub_path":"Tetris/Button.py","file_name":"Button.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27245163166","text":"################################################################################\n#Michael Guerzhoy and Davi Frossard, 2016\n#AlexNet implementation in TensorFlow, with weights\n#Details: \n#http://www.cs.toronto.edu/~guerzhoy/tf_alexnet/\n#\n#With code from https://github.com/ethereon/caffe-tensorflow\n#Model from https://github.com/BVLC/caffe/tree/master/models/bvlc_alexnet\n#Weights from Caffe converted using https://github.com/ethereon/caffe-tensorflow\n#\n#\n################################################################################\n\nfrom numpy import *\nimport os\n#from pylab import *\nimport numpy as np\n#import matplotlib.pyplot as plt\n#import matplotlib.cbook as cbook\nimport time\nfrom scipy.misc import imread\nfrom scipy.misc import imresize\nimport matplotlib.image as mpimg\nfrom scipy.ndimage import filters\nimport urllib\nfrom numpy import random\nimport scipy.misc\n\nimport tensorflow as tf\n\nfrom caffe_classes import class_names\n\ntrain_x = zeros((1, 227,227,3)).astype(float32)\ntrain_y = zeros((1, 1000))\nxdim = train_x.shape[1:]\nydim = train_y.shape[1]\n\n\n\n################################################################################\n#Read Image, and change to BGR\n\n\nim1 = (imread(\"normalized_jellyfish.jpg\")[:,:,:3]).astype(float32)\nim1 = im1 - mean(im1)\nim1[:, :, 0], im1[:, :, 2] = im1[:, :, 2], im1[:, :, 0]\n\n################################################################################\n\n# (self.feed('data')\n# .conv(11, 11, 96, 4, 4, padding='VALID', name='conv1')\n# .lrn(2, 2e-05, 0.75, name='norm1')\n# .max_pool(3, 3, 2, 2, padding='VALID', name='pool1')\n# .conv(5, 5, 256, 1, 1, group=2, name='conv2')\n# .lrn(2, 2e-05, 0.75, name='norm2')\n# .max_pool(3, 3, 2, 2, padding='VALID', name='pool2')\n# .conv(3, 3, 384, 1, 1, name='conv3')\n# .conv(3, 3, 384, 1, 1, group=2, name='conv4')\n# .conv(3, 3, 256, 1, 1, group=2, name='conv5')\n# .fc(4096, name='fc6')\n# .fc(4096, name='fc7')\n# .fc(1000, relu=False, name='fc8')\n# .softmax(name='prob'))\n\n#In Python 3.5, change this to:\nnet_data = load(open(\"bvlc_alexnet.npy\", \"rb\"), encoding=\"latin1\").item()\n#net_data = load(\"bvlc_alexnet.npy\").item()\n\ndef conv(input, kernel, biases, k_h, k_w, c_o, s_h, s_w, padding=\"VALID\", group=1):\n '''From https://github.com/ethereon/caffe-tensorflow\n '''\n c_i = input.get_shape()[-1]\n assert c_i%group==0\n assert c_o%group==0\n convolve = lambda i, k: tf.nn.conv2d(i, k, [1, s_h, s_w, 1], padding=padding)\n \n \n if group==1:\n conv = convolve(input, kernel)\n else:\n input_groups = tf.split(input, group, 3) #tf.split(3, group, input)\n kernel_groups = tf.split(kernel, group, 3) #tf.split(3, group, kernel) \n output_groups = [convolve(i, k) for i,k in zip(input_groups, kernel_groups)]\n conv = tf.concat(output_groups, 3) #tf.concat(3, output_groups)\n return tf.reshape(tf.nn.bias_add(conv, biases), [-1]+conv.get_shape().as_list()[1:])\n\n\n\n#x = tf.placeholder(tf.float32, (None,) + xdim)\ninput_image = np.zeros([1,227,227,3])\ninput_image[0]=im1\ninput_var = tf.Variable(input_image.astype(np.float32))\n\n\n\n\n#conv1\n#conv(11, 11, 96, 4, 4, padding='VALID', name='conv1')\nk_h = 11; k_w = 11; c_o = 96; s_h = 4; s_w = 4\nconv1W = tf.constant(net_data[\"conv1\"][0])\nconv1b = tf.constant(net_data[\"conv1\"][1])\nconv1_in = conv(input_var, conv1W, conv1b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=1)\nconv1 = tf.nn.relu(conv1_in)\n\n\n#lrn1\n#lrn(2, 2e-05, 0.75, name='norm1')\nradius = 2; alpha = 2e-05; beta = 0.75; bias = 1.0\nlrn1 = tf.nn.local_response_normalization(conv1,\n depth_radius=radius,\n alpha=alpha,\n beta=beta,\n bias=bias)\n\n\n#maxpool1\n#max_pool(3, 3, 2, 2, padding='VALID', name='pool1')\nk_h = 3; k_w = 3; s_h = 2; s_w = 2; padding = 'VALID'\nmaxpool1 = tf.nn.max_pool(lrn1, ksize=[1, k_h, k_w, 1], strides=[1, s_h, s_w, 1], padding=padding)\n\n\n#conv2\n#conv(5, 5, 256, 1, 1, group=2, name='conv2')\nk_h = 5; k_w = 5; c_o = 256; s_h = 1; s_w = 1; group = 2\nconv2W = tf.constant(net_data[\"conv2\"][0])\nconv2b = tf.constant(net_data[\"conv2\"][1])\nconv2_in = conv(maxpool1, conv2W, conv2b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\nconv2 = tf.nn.relu(conv2_in)\n\n\n#lrn2\n#lrn(2, 2e-05, 0.75, name='norm2')\nradius = 2; alpha = 2e-05; beta = 0.75; bias = 1.0\nlrn2 = tf.nn.local_response_normalization(conv2,\n depth_radius=radius,\n alpha=alpha,\n beta=beta,\n bias=bias)\n\n#maxpool2\n#max_pool(3, 3, 2, 2, padding='VALID', name='pool2') \nk_h = 3; k_w = 3; s_h = 2; s_w = 2; padding = 'VALID'\nmaxpool2 = tf.nn.max_pool(lrn2, ksize=[1, k_h, k_w, 1], strides=[1, s_h, s_w, 1], padding=padding)\n\n#conv3\n#conv(3, 3, 384, 1, 1, name='conv3')\nk_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 1\nconv3W = tf.constant(net_data[\"conv3\"][0])\nconv3b = tf.constant(net_data[\"conv3\"][1])\nconv3_in = conv(maxpool2, conv3W, conv3b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\nconv3 = tf.nn.relu(conv3_in)\n\n#conv4\n#conv(3, 3, 384, 1, 1, group=2, name='conv4')\nk_h = 3; k_w = 3; c_o = 384; s_h = 1; s_w = 1; group = 2\nconv4W = tf.constant(net_data[\"conv4\"][0])\nconv4b = tf.constant(net_data[\"conv4\"][1])\nconv4_in = conv(conv3, conv4W, conv4b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\nconv4 = tf.nn.relu(conv4_in)\n\n\n#conv5\n#conv(3, 3, 256, 1, 1, group=2, name='conv5')\nk_h = 3; k_w = 3; c_o = 256; s_h = 1; s_w = 1; group = 2\nconv5W = tf.constant(net_data[\"conv5\"][0])\nconv5b = tf.constant(net_data[\"conv5\"][1])\nconv5_in = conv(conv4, conv5W, conv5b, k_h, k_w, c_o, s_h, s_w, padding=\"SAME\", group=group)\nconv5 = tf.nn.relu(conv5_in)\n\n#maxpool5\n#max_pool(3, 3, 2, 2, padding='VALID', name='pool5')\nk_h = 3; k_w = 3; s_h = 2; s_w = 2; padding = 'VALID'\nmaxpool5 = tf.nn.max_pool(conv5, ksize=[1, k_h, k_w, 1], strides=[1, s_h, s_w, 1], padding=padding)\n\n#fc6\n#fc(4096, name='fc6')\nfc6W = tf.constant(net_data[\"fc6\"][0])\nfc6b = tf.constant(net_data[\"fc6\"][1])\nfc6 = tf.nn.relu_layer(tf.reshape(maxpool5, [-1, int(prod(maxpool5.get_shape()[1:]))]), fc6W, fc6b)\n\n#fc7\n#fc(4096, name='fc7')\nfc7W = tf.constant(net_data[\"fc7\"][0])\nfc7b = tf.constant(net_data[\"fc7\"][1])\nfc7 = tf.nn.relu_layer(fc6, fc7W, fc7b)\n\n#fc8\n#fc(1000, relu=False, name='fc8')\nfc8W = tf.constant(net_data[\"fc8\"][0])\nfc8b = tf.constant(net_data[\"fc8\"][1])\nfc8 = tf.nn.xw_plus_b(fc7, fc8W, fc8b)\n\n\n#prob\n#softmax(name='prob'))\nprob = tf.nn.softmax(fc8)\n\ninit = tf.initialize_all_variables()\n\n\n########################################################\n\n#\n#\n# Here we take a picture of jellyfish , and trying to let the CNN recognize it as a Mink (small Mammal)\n# we start by initialize the input of the model to be a jellyfish image, and configure the input image to\n# be a variable\n# then in change_class function, train the model (change the input image)\n# so we get high probability of mink image, while remaining close to jellyfish image (regularization)\n#\n# we want to minimize: - (mink_prob*500000) + regularization\n# (the constant obtained by traying multiple values, and 500000 leads to the best results)\n#\n\n\n\nSTEPS_NUM = 50000\n\n\ndef change_class():\n\n\n #set mink_prob to the ptobability of the input image to be a mink picture\n mink_index = 357\n mink_prob = prob[0, mink_index]\n\n # im1 is a jellyfish picture\n im = im1 - mean(im1)\n im[:, :, 0], im1[:, :, 2] = im1[:, :, 2], im1[:, :, 0]\n\n\n optimizer = tf.train.GradientDescentOptimizer(0.2)\n # save the image close to jellyfish image\n regularization = tf.norm(input_var-im)\n # train to get high probablity of mink , while remaining close to jellyfish image\n train = optimizer.minimize( - (mink_prob*500000) + regularization)\n sess = tf.Session()\n sess.run(init)\n max = 0\n image = None\n\n for step in range(STEPS_NUM):\n sess.run(train)\n current_prob = sess.run(mink_prob)\n\n # when the neuron's value is maximal, save the input image\n if current_prob > max:\n image = sess.run(input_var)\n max = current_prob\n if step%100 == 99:\n print(\"step: \", step, \" mink prob: \", '{0:.10f}'.format(current_prob ) , \" regularization: \", sess.run(regularization))\n\n\n\n scipy.misc.imsave(\"new_jellyfish.jpg\", image[0])\n\n\n\nchange_class()\n\n\n","repo_name":"daniellehs/huji","sub_path":"Intro to NeuralNetworks (67103)/ex2 - Visualizing And Fooling CNNs/code/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":8693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24862248190","text":"# Ch5Ex123.py\r\n# Author: Parshwa Patil\r\n# ThePythonWorkbook Solutions\r\n# Exercise No. 123\r\n# Title: Infix to Postfix\r\n\r\nfrom Ch5Ex122 import mathTokenizer\r\nfrom Ch4Ex090 import isInteger\r\nfrom Ch4Ex091 import precedence\r\n\r\ndef infixToPostfix(tokenList):\r\n\tops = []\r\n\tpostfix = []\r\n\r\n\tfor token in tokenList:\r\n\t\tif isInteger(token): postfix.append(token)\r\n\t\tif token in ['+', '-', '*', '/', '^']:\r\n\t\t\twhile len(ops) > 0 and ops[len(ops) - 1] != '(' \\\r\n\t\t\t\tand precedence(token) < precedence(ops[len(ops) - 1]):\r\n\t\t\t\tpostfix.append(ops.pop())\r\n\t\t\tops.append(token)\r\n\t\tif token == '(': ops.append(token)\r\n\t\tif token == ')':\r\n\t\t\twhile ops[len(ops) - 1] != '(': postfix.append(ops.pop())\r\n\t\t\tops.pop()\r\n\r\n\twhile len(ops) > 0: postfix.append(ops.pop())\r\n\r\n\treturn postfix\r\n\r\ndef main():\r\n\texpr = input(\"Enter expression: \")\r\n\ttokenList = mathTokenizer(expr)\r\n\tprint(infixToPostfix(tokenList))\r\n\r\nif __name__ == \"__main__\": main()","repo_name":"Parshwa-P3/ThePythonWorkbook-Solutions","sub_path":"Solutions/Ch5Ex123.py","file_name":"Ch5Ex123.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30760167431","text":"s=input()\nl=[]\n\nfor i in s:\n l.append(i)\n\nsl=[]\nr=int(input())\n\nno_val=r+(r-2) \nno_col=(len(l)//no_val)\nextra=len(l)-no_col*no_val\n\n# print(s,l)\nno_col=no_col+1\n# print(len(l),no_val,no_col,extra)\n\nfor i in range(0,no_col):\n sl.append(l[(no_val*i):(i+1)*no_val])\n# print(sl)\n\nfor i in range(r):\n for j in sl:\n if len(j)>i+1:\n if i==0 :\n print(j[i],end='')\n elif i==(r-1):\n print(j[no_val//2],end='')\n else:\n print(j[i],j[no_val-i],sep='',end='')\n elif len(j)==i+1:\n print(j[i],end='')\n \n","repo_name":"kishorekumarcodingmart/Intern","sub_path":"Day 4 26.7.2022/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17142219880","text":"# %%\nimport chess\n\nmove_list = [\n 'p E2 E4', 'p E7 E5',\n 'q D1 F3', 'n G8 F6',\n 'b F1 C4', 'p C7 C6',\n 'n G1 H3', 'b F8 C5',\n 'k E1 G1', 'q D8 E7',\n 'exit'\n]\n\ndef main():\n\n print(\n 'CHESS!!! - by SankE\\nFor additional help, enter \"help\" as a move\\n'\n )\n game, board = chess.Game().new_game()\n \n run = True\n i = 0\n while run:\n # print(f'Insert a move. {chess.game.turn} plays.')\n # move_str = input('(EXAMPLE: To move a pawn from E2 to E4, type: \"p E2 E4\")')\n\n print(f'Insert a move. {\"White\" if game.wTurn else \"Black\"} plays.')\n print('(EXAMPLE: To move a pawn from E2 to E4, type: \"p E2 E4\")\\n')\n move_str = move_list[i]\n\n if move_str.lower() == 'exit': break\n \n success, output = chess.move_parser(move_str)\n i += 1\n\n print(game)\n input('Game finished. Press ENTER to exit.\\n')\n\nif __name__ == '__main__':\n main()\n\n# %%\n","repo_name":"SankE342/python-chess","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"9664867322","text":"\n# Build with `python setup.py sdist --dist-dir ./export/tarball`\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\nimport sys\nfrom glob import glob\nimport py2exe\nplatform = \"unknown\"\n\n\n# Append long description from README.md\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\n# Create data files list\ndata_files = []\nfor ext in (\"*.html\", \"*.css\", \"*.svg\", \"*.png\", \"*.js\", \"*.eot\", \"*.ttf\", \"*.woff\", \"*.woff2\", \"*.sh\", \"*.desktop\"):\n data_files.extend(glob(f\"backdriveb2/**/{ext}\", recursive=True))\n\n# Create install require list\ninstall_requires = [\n \"pywebview==3.4\",\n \"b2sdk==1.6.0\",\n \"wcmatch==8.1.2\"\n]\n\n\n# Append platform specific dependencies\nif sys.platform == \"win32\" or sys.platform == \"cygwin\":\n platform = \"windows\"\n install_requires += [\n \"cefpython3==66.1\"\n ]\n\nelif sys.platform == \"linux\":\n platform = \"linux\"\n install_requires += [\n \"gobject==0.1.0\",\n \"PyGObject==3.40.1\"\n ]\n\n\nsetup(\n name=f\"backdriveb2_{platform}\",\n version=\"0.1.31\",\n author=\"Joffrey Bienvenu\",\n author_email=\"joffreybvn@gmail.com\",\n description=\"Cross-platform user-friendly client for BackBlaze B2\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Joffreybvn/backdriveb2\",\n license=\"MIT\",\n project_urls={\n \"Bug Tracker\": \"https://github.com/Joffreybvn/backdriveb2/issues\",\n },\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n packages=find_packages(include=[\"backdriveb2\", \"backdriveb2.*\"]),\n data_files=[(\".\", data_files)],\n include_package_data=True,\n python_requires=\">=3.6\",\n install_requires=install_requires,\n\n # Py2EXE windows export\n console=['./backdriveb2/main.py'],\n options={\n \"py2exe\": {\n \"optimize\": 2,\n \"includes\": [\"backdriveb2.api\"] # List of all the modules you want to import\n }\n }\n)\n","repo_name":"Joffreybvn/backdriveb2","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27343953416","text":"preg=input(\"Ejecutar el programa? (S/N)\\n\")\ncifrada = []\ncifrada2 = []\ncifrada3 = []\ndescifrada = []\ncont=0\nwhile preg==\"s\" or preg==\"S\":\n\tcond=input(\"Elija: 1. Introducir 2. Cifrar 3. Descifrar 4. LIMPIAR LISTAS 5. Imprimir 6. Salir\\n\")\n\tif cond == \"1\":\n\t\tpalabra=input(\"Introduzca el texto: \\n\") # Se introduce la palabra, ya sea sin cifrar o cifrada\n\telif cond == \"2\": \n\t\tfor x in palabra:\n\t\t\tcif=ord(x)+1 \t\t# Se cifra la palabra introducida en el cond==1\n\t\t\tcifrada.append(cif)\n\t\tfor x in cifrada:\n\t\t\tdes=chr(x)\n\t\t\tcifrada2.append(des)\n\telif cond == \"3\":\n\t\tfor x in cifrada2:\n\t\t\tcif=ord(x)-1 \t\t# Se descifra la palabra introducida en el cond==1\n\t\t\tcifrada3.append(cif)\n\t\tfor x in cifrada3:\n\t\t\tdes=chr(x)\t\t\t# Se convierte en texto la palabra descrifrada\n\t\t\tdescifrada.append(des)\n\telif cond == \"4\": # En este paso se limpian las listas, necesario para descifrar varias palabras\n\t\tcifrada = []\n\t\tcifrada2 = []\n\t\tcifrada3 = []\n\t\tdescifrada = []\n\telif cond == \"5\":\n\t\tpreg2=0\n\t\twhile preg2<3:\n\t\t\tpreg2=int(input(\"Opciones: 1. Texto cifrado 2. Texto descrifrado 3. Salir\\n\"))\n\t\t\tif preg2 == 1:\n\t\t\t\tres = ''.join(cifrada2) # Se imprime la lista cifrada\n\t\t\t\tprint(res)\n\t\t\t\tprint(\"\\nAcuerdese de limpiar las listas si va a cifrar o descifrar varias palabras\")\n\t\t\telif preg2 == 2:\n\t\t\t\tres = ''.join(descifrada) # Se imprime la lista descifrada\n\t\t\t\tprint(res)\n\t\t\t\tprint(\"\\nAcuerdese de limpiar las listas si va a cifrar o descifrar varias palabras\")\n\telse:\n\t\tbreak","repo_name":"rodolz/uip-prog3","sub_path":"Parciales/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24078662128","text":"#!/usr/bin/env python3\n\n\"\"\"\nAuthor: Agnes Szwarczynska; ass122@ic.ac.uk\nDate: 16th Nov 2022\nDescription: Visualising Lotka-Voltera model with various parametres\n\"\"\"\n\n__author__ = \"Agnes Szwarczynska (ass122@ic.ac.uk)\"\n__date__ = \"16th Nov 2022\"\n\n\n###Imports\nimport numpy as np\nimport scipy as sc\nfrom scipy import stats\nfrom scipy import integrate\nimport matplotlib.pylab as p\nimport sys\n\n###\n\ndef run(argv):\n \"\"\"This is the main entry point of the programme.\"\"\"\n ###Defining a function\n def dCR_dt(pops, t =0): \n R = pops[0]\n C = pops[1]\n dRdt = r * R *(1 - R/K) - a * R * C\n dCdt = -z * C + e * a * R * C\n \n return np.array([dRdt, dCdt])\n\n type(dCR_dt)\n\n ###Assigning variables\n\n if len(sys.argv) != 6:\n print(\"Insufficient number of arguments provided. Running the script with default parametres\")\n r = 1.0\n a = 0.9 \n z = 0.5\n e = 0.5\n K = 20\n \n else:\n r = float(sys.argv[1])\n a = float(sys.argv[2])\n z = float(sys.argv[3])\n e = float(sys.argv[4])\n K = float(sys.argv[5])\n\n\n ###Defining a time vector\n t = np.linspace(0, 300, 4000)\n\n ###Set the initial conditions for the two populations \n R0 = 1\n C0 = 1\n RC0 = np.array([R0, C0])\n\n pops, infodict = integrate.odeint(dCR_dt, RC0, t, full_output=True)\n\n #pops\n\n ###Checking whether integration was successful\n type(infodict)\n infodict.keys()\n infodict['message']\n\n ###Plotting a figure\n f1 = p.figure()\n\n p.plot(t, pops[:,0], 'g-', label=\"Resource density\") \n p.plot(t, pops[:,1], 'b-', label=\"Consumer density\")\n p.grid()\n p.legend(loc=\"best\")\n p.xlabel(\"Time\")\n p.ylabel(\"Population\")\n p.title(\"Consumer-Resource population dynamics\")\n p.text(150, 1.15, f\"\\n r = {r}\\n a = {a}\\n z = {z}\\n e = {e}\\n K = {K}\", fontsize=12)\n #p.text(180, 6, f\"K prey = {pops[-1][0]}\", fontsize=12)\n #p.show()\n\n f2 = p.figure()\n\n p.plot(pops[:,0], pops[:,1], 'r-') \n p.grid()\n p.legend(loc=\"best\")\n p.xlabel(\"Resource density\")\n p.ylabel(\"Consumer density\")\n p.title(\"Consumer-Resource population dynamics\")\n p.text(1.2, 1, f\"\\n r = {r}\\n a = {a}\\n z = {z}\\n e = {e}\\n K = {K}\", fontsize=12)\n #p.show()\n\n ###Saving the plot\n\n f1.savefig(\"../results/LV2_model_1.pdf\")\n f2.savefig(\"../results/LV2_model_2.pdf\")\n\n #Printing final prey and predator densities\n print(f\"The final prey density is {pops[-1][0]}.\\nThe final predator density is {pops[-1][1]}\")\n\n ###If the script is run by itself\n\nif __name__ == \"__main__\":\n import sys\n run(sys.argv)","repo_name":"AgaSz22/CMEECourseWork","sub_path":"week7/code/LV2.py","file_name":"LV2.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31003639417","text":"\nimport django_filters\nfrom .models import Client\n#from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker\nfrom django.db import models\nfrom django import forms\n#import datetime\n\n\nclass ClientFilter(django_filters.FilterSet):\n\n date_lte = django_filters.DateTimeFilter(field_name='date_ajout', \n lookup_expr='gte' , \n label='Date debut' , \n widget=forms.DateTimeInput(attrs={'class': 'form-control flatpickr', 'placeholder':'Date de debut'})\n )\n \n date_gte = django_filters.DateTimeFilter(field_name='date_ajout', \n lookup_expr='lte' , \n label='Date fin' , \n widget=forms.DateTimeInput(attrs={'class': 'form-control flatpickr', 'placeholder':'Date de fin'})\n )\n nom = django_filters.CharFilter(label='Nom', \n lookup_expr='icontains',\n widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Nom'})\n )\n cni = django_filters.CharFilter(label='CNI', \n lookup_expr='icontains',\n widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'CNI'})\n )\n telephone = django_filters.CharFilter(label='Telephone', \n lookup_expr='icontains',\n widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Telephone'})\n )\n \n\n class Meta :\n model = Client\n fields = ['nom', 'cni','telephone']","repo_name":"raoulalobo/mark_1","sub_path":"clients/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11959189837","text":"from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.svm import SVC\nimport pandas as pd\nfrom joblib import dump\n\nbreast_cancer_detection = pd.read_csv('datasets/dataR2.csv')\nX = breast_cancer_detection[['Age', 'BMI', 'Glucose', 'Insulin',\n 'HOMA','Leptin', 'Adiponectin', 'Resistin', 'MCP.1']]\ny = breast_cancer_detection['Classification']\nscaler = MinMaxScaler()\nscaler.fit(X)\nscaler.transform(X)\nmodel = SVC()\nmodel.fit(X, y)\ndump(model, 'models/cancer_classification.joblib')\n\n\ncancer_stage = pd.read_csv('datasets/breast-cancer-wisconsin.csv')\ncancer_stage_X = cancer_stage[['ClumpThickness', ' UniformityofCellSize', 'UniformityCellShape',\n 'MarginalAdhesion', 'SingleEpithelialCellSize', 'BareNuclei',\n 'BlandChromatin', 'NormalNucleoli', 'Mitoses']]\ncancer_stage_y = cancer_stage[' Class']\nfrom sklearn.tree import DecisionTreeClassifier\ndtc = DecisionTreeClassifier()\ndtc.fit(cancer_stage_X, cancer_stage_y)\ndump(dtc, 'models/cancer_stage.joblib')\n\n\nfrom sklearn.ensemble import RandomForestRegressor\ninsurance_data = pd.read_csv('datasets/policy.csv')\ninsurance_data_X = insurance_data[['age', 'incomepm', 'cancerstages', 'Smoking']]\ninsurance_data_y = insurance_data['insurance']\nrfr = RandomForestRegressor()\nrfr.fit(insurance_data_X, insurance_data_y)\ndump(rfr, 'models/insurance_claiming.joblib')","repo_name":"kanuarj/CancerPredictionMechanism","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11957444115","text":"__author__ = 'dieter'\n\nimport time\nimport sys\nimport os\nimport os.path\nimport shutil\nimport math\nimport glob\nimport inspect\nfrom PIL import ImageOps\nfrom PIL import Image\nfrom PIL import ImageFilter\nimport scipy.interpolate\nimport numpy\nfrom matplotlib import pyplot\nimport library.Rotate\nimport Vicon\nimport multiprocessing as mp\n\n\ndef vars2dict(var_list=[], values=locals()):\n result = {}\n if var_list == []: var_list = values.keys()\n for x in var_list:\n value = values[x]\n if type(value).__name__ not in ['module', 'function']: result[x] = value\n return result\n\ndef try2float(value):\n if type(value) == bool: return value\n try:\n value = float(value)\n return value\n except:\n return value\n\ndef print_dict(dictionary, current_depth=0, line_break='
'):\n txt = ''\n for key, value in dictionary.iteritems():\n if isinstance(value, dict):\n txt += (current_depth + 1) * '*' + str(key) + line_break\n depth = current_depth + 1\n txt += print_dict(value, depth)\n else:\n txt += (current_depth + 1) * '>' + str(key) + '=' + str(value) + line_break\n return txt\n\ndef is_between(point, point1, point2, delta=0.5):\n f = interpolate_path(point1, point2, 0, 1)\n xi = arange(0, 1, 0.05)\n line = f(xi)\n distances = distance2points(point, line)\n min_distance = numpy.min(distances)\n if min_distance < delta: return True\n return False\n\n\n# def sigmoid(x, threshold=0.25, slope=10):\n# value = 1 / (1 + numpy.exp(- slope * (x - threshold)))\n# return value\n\ndef sigmoid(x, threshold=1, slope=5):\n value = 1 / (1 + numpy.exp(- slope * (x - threshold)))\n return value\n\n\ndef is_array(variable):\n return isinstance(variable, numpy.ndarray)\n\n\ndef set_numpy_style():\n numpy.set_printoptions(precision=3, suppress=True, linewidth=200)\n\n\ndef wrap360(angles):\n array_input = is_array(angles)\n if not array_input: angles = numpy.array([angles])\n positive_input = angles > 0\n angles = numpy.mod(angles, 360)\n zeros = angles == 0\n selected = numpy.minimum(positive_input, zeros)\n angles[selected] = 360\n return angles\n\n\ndef wrap180(angles):\n array_input = is_array(angles)\n if not array_input: angles = numpy.array([angles])\n c1 = angles < -180\n c2 = angles > 180\n c = numpy.maximum(c1, c2)\n angles[c] = wrap360(angles[c] + 180) - 180\n return angles\n\n\ndef make_experiment_tree(session_path):\n empty_folder(session_path)\n empty_folder(session_path + '/plots')\n empty_folder(session_path + '/plots/ROBOT')\n empty_folder(session_path + '/plots/HUMAN_A')\n empty_folder(session_path + '/plots/HUMAN_B')\n empty_folder(session_path + '/images')\n empty_folder(session_path + '/matfiles')\n empty_folder(session_path + '/code')\n empty_folder(session_path + '/logs')\n\n\ndef make_grid_list(x_range, y_range):\n x_range, y_range = numpy.meshgrid(x_range, y_range)\n x_range = x_range.flatten()\n y_range = y_range.flatten()\n positions = numpy.vstack((x_range, y_range))\n positions = positions.transpose()\n return positions\n\n\ndef rotate_around_point(vector, point, alpha):\n vector = numpy.hstack((vector, 0))\n point = numpy.hstack((point, 0))\n vector = vector - point\n new, matrix = Rotate.rotate_z(alpha, vector)\n new = new + point\n new = numpy.asarray(new)\n new = new.flatten()\n return new[0:2]\n\n\ndef unique_rows(data):\n data = numpy.ascontiguousarray(data)\n data = data.round(decimals=3)\n n_cols = data.shape[1]\n dtype = data.dtype.descr * n_cols\n struct = data.view(dtype)\n uniq = numpy.unique(struct)\n uniq = uniq.view(data.dtype).reshape(-1, n_cols)\n return uniq\n\n\ndef get_perimeter(points, n=10):\n start = points[0, :]\n points = numpy.vstack((points, start))\n x_points = points[:, 0]\n y_points = points[:, 1]\n indices = range(0, len(x_points))\n indices_interpolate = numpy.linspace(0, max(indices), len(indices) * n)\n f_x = scipy.interpolate.interp1d(indices, x_points)\n f_y = scipy.interpolate.interp1d(indices, y_points)\n f_xi = f_x(indices_interpolate)\n f_yi = f_y(indices_interpolate)\n perimeter = numpy.vstack((f_xi, f_yi, f_yi * 0))\n perimeter = perimeter.transpose()\n perimeter = unique_rows(perimeter)\n return perimeter\n\n\ndef add_border(image, color, size=100):\n result = ImageOps.crop(image, border=size)\n result = ImageOps.expand(result, border=size, fill=color)\n return result\n\n\ndef replace_color(image, color_in, color_out, threshold=100, do_plot=False):\n im = numpy.array(image, dtype=numpy.float)\n\n d0 = color_in[0] - im[:, :, 0]\n d1 = color_in[1] - im[:, :, 1]\n d2 = color_in[2] - im[:, :, 2]\n d = d0 ** 2 + d1 ** 2 + d2 ** 2\n d = numpy.sqrt(d)\n\n foreground = numpy.ones_like(im)\n im[d < threshold] = numpy.array(color_out)\n foreground[d < threshold] = numpy.array([0, 0, 0])\n im = numpy.array(numpy.round(im), dtype=numpy.uint8)\n if do_plot:\n pyplot.close('all')\n pyplot.subplot(221)\n pyplot.hist(d.flatten(), bins=100)\n pyplot.subplot(222)\n pyplot.imshow(im)\n pyplot.subplot(223)\n pyplot.imshow(foreground)\n\n return im\n\n\ndef remove_background(im_file, threshold=100, do_plot=False):\n im = Image.open(im_file)\n im = im.filter(ImageFilter.MedianFilter(3))\n im = numpy.array(im, dtype=numpy.float)\n\n median = numpy.median(im, axis=(0, 1))\n\n d0 = median[0] - im[:, :, 0]\n d1 = median[1] - im[:, :, 1]\n d2 = median[2] - im[:, :, 2]\n d = d0 ** 2 + d1 ** 2 + d2 ** 2\n d = numpy.sqrt(d)\n\n foreground = numpy.ones_like(im)\n im[d < threshold] = numpy.array([0, 0, 0])\n foreground[d < threshold] = numpy.array([0, 0, 0])\n im = numpy.array(numpy.round(im), dtype=numpy.uint8)\n if do_plot:\n pyplot.close('all')\n pyplot.subplot(221)\n pyplot.hist(d.flatten(), bins=100)\n pyplot.subplot(222)\n pyplot.imshow(im)\n pyplot.subplot(223)\n pyplot.imshow(foreground)\n\n return im, foreground, median\n\n\ndef composite_image(files, threshold=80, color=False, skip=1):\n im_file = files[0]\n image, foreground, median = remove_background(im_file, threshold)\n shape = image.shape\n if not color: color = (int(median[0]), int(median[1]), int(median[2]))\n image_shape = (int(shape[1]), int(shape[0]))\n composite = Image.new(\"RGB\", image_shape, color)\n composite = numpy.array(numpy.round(composite), dtype=numpy.uint8)\n number_of_files = len(files)\n indices = range(0, number_of_files, skip)\n for file_index in indices:\n file_name = files[file_index]\n print(file_name)\n image, foreground, median = remove_background(file_name, threshold)\n composite[foreground > 0] = image[foreground > 0]\n composite = Image.fromarray(composite)\n return composite, median\n\n\ndef copy_python_files(target):\n files = glob.glob('*.py')\n for f in files:\n #print(f, '>'),\n src = os.path.join(os.getcwd(), f)\n tgt = target + '/' + f\n #print src, '>', tgt\n shutil.copy(src, tgt)\n\n\ndef copy_library(target):\n src = 'library'\n try:\n shutil.copytree(src, target)\n # Directories are the same\n except shutil.Error as e:\n print('Directory not copied. Error: %s' % e)\n # Any error saying that the directory doesn't exist\n except OSError as e:\n print('Directory not copied. Error: %s' % e)\n\n\ndef scale(x, minimum=0, maximum=1):\n x = x.astype(float)\n x = x + numpy.min(x.flatten())\n max_val = numpy.max(x.flatten())\n if max_val == 0: return x * 0\n x = x / max_val\n r = maximum - minimum\n x = x * r\n x = x + minimum\n return x\n\n\ndef arange(start, stop, step):\n var = stop - start\n nr_steps = float(var) / float(step)\n nr_steps = int(math.ceil(nr_steps))\n r = numpy.linspace(start, stop, nr_steps)\n return r\n\n\ndef closest(x, array):\n if not is_array(array): array = numpy.array(array)\n distance = numpy.abs(array - x)\n min_index = numpy.argmin(distance)\n found = array[min_index]\n return found, min_index\n\nclosest(9,[1,2,4,10])\n\n\ndef empty_folder(folder):\n if os.path.exists(folder): shutil.rmtree(folder)\n os.makedirs(folder)\n\n\ndef list2txt(lst, sep=','):\n text = ''\n for x in lst: text += str(x) + sep\n text = text.rstrip(sep)\n return text\n\n\ndef interpolate_path(p1, p2, t1, t2, n=None):\n p1 = p1.flatten()\n p2 = p2.flatten()\n plus_inf = 9999999\n min_inf = -9999999\n if t1 > t2: x = numpy.hstack((plus_inf, t1, t2, min_inf))\n if t2 >= t1: x = numpy.hstack((min_inf, t1, t2, plus_inf))\n y = numpy.vstack((p1, p1, p2, p2))\n f = scipy.interpolate.interp1d(x, y, axis=0)\n f.range = numpy.array([t1, t2])\n if n is None: return f\n xi = numpy.linspace(t1, t2, n)\n interpolated = f(xi)\n return interpolated\n\n\ndef interpolate_winding_path(path, t, ti=None):\n x = path[:, 0]\n y = path[:, 1]\n fill_value_x = (x[0], x[-1])\n fill_value_y = (y[0], y[-1])\n fx = scipy.interpolate.interp1d(t, x, axis=0, fill_value=fill_value_x, bounds_error=False)\n fy = scipy.interpolate.interp1d(t, y, axis=0, fill_value=fill_value_y, bounds_error=False)\n if len(ti) == 1: ti = numpy.linspace(min(t), max(t), ti)\n xi = fx(ti)\n yi = fy(ti)\n pathi = numpy.vstack((xi, yi))\n pathi = numpy.transpose(pathi)\n return pathi\n\n\ndef distance2points(ref_point, points):\n if type(ref_point) == list:ref_point = numpy.array(ref_point)\n if type(points) == list:points = numpy.array(points)\n ref_point = ref_point.flatten()\n points = numpy.asmatrix(points)\n ref_point = numpy.asmatrix(ref_point)\n number = points.shape[0]\n ref_point = numpy.tile(ref_point, (number, 1))\n delta = points - ref_point\n distances = numpy.linalg.norm(delta, axis=1)\n distances = numpy.asarray(distances)\n distances = distances.flatten()\n return distances\n\n\ndef minmax(array):\n mn = numpy.min(array)\n mx = numpy.max(array)\n return [mn, mx]\n\n\ndef perpendicular_distance(p0, p1, p2):\n # gives the perpendicular distance from point 0 to the line defined by p1-p2\n x0 = p0[0]\n x1 = p1[0]\n x2 = p2[0]\n\n y0 = p0[1]\n y1 = p1[1]\n y2 = p2[1]\n\n a = numpy.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1)\n b = numpy.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)\n result = a / b\n return result\n\n\ndef num2str(number, digits=3):\n if isinstance(number, basestring): return str(number)\n stg = '{0:.' + str(digits) + 'f}'\n return stg.format(number)\n\n\ndef my_regression(x, y):\n x = x.flatten()\n y = y.flatten()\n x = x - numpy.min(x)\n delta_x = numpy.diff(x)\n delta_y = numpy.diff(y)\n slope = delta_y / delta_x\n slope = numpy.mean(slope)\n mn_x = numpy.mean(x)\n mn_y = numpy.mean(y)\n intercept = mn_y - slope * mn_x\n return intercept, slope\n\n\nclass Logger(object):#modified from Dieter's original to create separate log files for each part of the code\n def __init__(self, name, filename=\"_Log.txt\"):\n self.terminal = sys.stdout\n self.name = name\n self.filename = name + filename\n\n def write(self, text):\n asc_time = time.asctime()\n screen_message = self.name.ljust(20) + '> ' + text + '\\n'\n log_message = [asc_time, self.name, text]\n log_message = list2txt(log_message, ';') + '\\n'\n self.terminal.write(screen_message)\n log = open(self.filename, \"a\")\n log.write(log_message)\n log.close()\n\n\ndef angle_vectors(a, b):\n noise_a = numpy.random.rand(a.shape[0]) * 0.001\n noise_b = numpy.random.rand(b.shape[0]) * 0.001\n a_norm = numpy.linalg.norm(a + noise_a)\n b_norm = numpy.linalg.norm(b + noise_b)\n a = a / a_norm\n b = b / b_norm\n p = numpy.dot(a, b)\n angle = numpy.arccos(p)\n angle = numpy.rad2deg(angle)\n return angle\n\n\ndef normalize(a):\n a_norm = numpy.linalg.norm(a)\n if a_norm == 0: return a * 0\n normalized = a / a_norm\n return normalized\n\n\ndef normalize_array(a):\n a_norm = numpy.linalg.norm(a, axis=1)\n a_norm_mat = numpy.tile(a_norm, (a.shape[1], 1))\n a_norm_mat = numpy.transpose(a_norm_mat)\n normalized = a / a_norm_mat\n is_zero = a_norm == 0\n normalized[is_zero, :] = 0\n return normalized\n\n\ndef remove_stable(path):\n try:\n os.remove(path)\n except:\n print('Could not remove: ' + path)\n\n\ndef padd_int(x, n=3):\n x = str(int(x))\n return x.zfill(n)\n\nclass Tracker():\n def __init__(self, tracked_obj, virtual_obj, shared_d_p, shared_d_v, shared_d_r, shared_d_s):\n self.shared_d_p = shared_d_p\n self.shared_d_v = shared_d_v\n self.shared_d_r = shared_d_r\n self.shared_d_s = shared_d_s\n self.tracked_obj = tracked_obj\n self.virtual_obj = virtual_obj\n self.end_flag = mp.Event()\n self.all_objects = tracked_obj[:] + virtual_obj.keys()\n\n \n self.client_process = mp.Process(target=self.tracker_client)#, args=(plan,))\n self.client_process.start()\n \n def get_position(self, key):\n return self.shared_d_p[key]\n\n def get_rotation(self, key):\n return self.shared_d_r[key]\n\n def get_velocity(self,key):\n return self.shared_d_v[key]\n\n def get_speed(self,key):\n return self.shared_d_s[key]\n\n def enquire(self, key):\n data = {'velocity': self.shared_d_v[key], 'position': self.shared_d_p[key], 'rotation': self.shared_d_r[key], 'speed': self.shared_d_s[key]}\n return data\n\n def stop(self):\n self.end_flag.set()\n\n \n def tracker_client(self):\n Tracker = Vicon.Tracker(self.tracked_obj, self.virtual_obj, 'Vicon')\n while not self.end_flag.is_set():\n #fill the dictionary\n for tracked_object in self.all_objects:\n tracker_data = Tracker.enquire(tracked_object)\n self.shared_d_p[tracked_object] = tracker_data['position']\n self.shared_d_v[tracked_object] = tracker_data['velocity']\n self.shared_d_s[tracked_object] = tracker_data['speed']\n self.shared_d_r[tracked_object] = tracker_data['rotation']\n \n Tracker.stop()\n \n","repo_name":"VerifiableAutonomy/EthicalNao","sub_path":"library/Utilities.py","file_name":"Utilities.py","file_ext":"py","file_size_in_byte":14241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42011267194","text":"from project.factory.database import Database\nfrom project.factory.validation import Validator\nfrom project.factory.response import ResponseMessage\nfrom project.algorithm.machineModel import MachineModel\n\nimport pandas as pd\n\n\nclass Predict(object):\n def __init__(self):\n self.validator = Validator()\n self.db = Database()\n self.machine_model = MachineModel()\n\n self.collection_name = \"predict_result\"\n\n self.fields = {\n \"input_text\": \"string\",\n \"result_prediction\": \"string\",\n \"created\": \"datetime\",\n \"updated\": \"datetime\",\n }\n\n self.create_required_fields = [\"input_text\",\"result_prediction\"]\n\n # Fields optional for CREATE\n self.create_optional_fields = [\"input_text \",\"result_prediction\"]\n\n # Fields required for UPDATE\n self.update_required_fields = [\"input_text \",\"result_prediction\"]\n\n # Fields optional for UPDATE\n self.update_optional_fields = [\"input_text \",\"result_prediction\"]\n\n def classify(self, input_text):\n cleaned_text = self.machine_model.clean_text(input_text)\n series_text = pd.Series(cleaned_text)\n preprocessed_text = series_text.apply(self.machine_model.preprocess_tweet)\n vectorized_text = self.machine_model.TFIDFVector.transform(preprocessed_text.astype(\"U\"))\n result_test = self.machine_model.ModelML.predict(vectorized_text)\n final_result = self.machine_model.difine_result(result_test)\n return final_result\n \n def create(self, predict):\n # Validator will throw error if invalid\n print(predict)\n validated = self.validator.validateTypes(predict, self.fields)\n if validated:\n err = self.validator.validate(predict, self.fields, self.create_required_fields, self.create_optional_fields)\n if err is None:\n res = self.db.insert(predict, self.collection_name)\n return ResponseMessage(res, \"Data validated\").send()\n else:\n return ResponseMessage(err, \"Data required is missing\").send()\n\n else:\n return ResponseMessage(validated, \"Data type is missing\").send()\n\n def find(self, predict): # find all\n return self.db.find(predict, self.collection_name)\n\n def find_by_id(self, id):\n return self.db.find_by_id(id, self.collection_name)\n\n def update(self, id, predict):\n self.validator.validate(predict, self.fields, self.update_required_fields, self.update_optional_fields)\n return self.db.update(id, predict,self.collection_name)\n\n def delete(self, id):\n return self.db.delete(id, self.collection_name)\n","repo_name":"rhmnarief/cyberbullying-api","sub_path":"project/models/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38789500003","text":"from PyQt5.QtWidgets import QWidget\nfrom base_pyinstall_window import Ui_Form\nfrom PyQt5.QtWidgets import QApplication,QFileDialog\n\nfrom PyQt5.QtCore import pyqtSlot\nimport sys\n\nimport threading\nimport subprocess\ntry :\n import PyInstaller\nexcept ModuleNotFoundError:\n print('未下载Pyinstaller,无法打包')\n exit()\nclass pyinstall_window(QWidget,Ui_Form):\n def __init__(self,execute_path) -> None:\n super(pyinstall_window,self).__init__()\n self.executable_path=execute_path\n self.setupUi(self)\n self.input_file_pushButton.clicked.connect(self.open_input_file)\n self.output_pushButton.clicked.connect(self.open_output_dir)\n self.icon_pushButton.clicked.connect(self.open_icon_file)\n self.start_pushButton.clicked.connect(self.export_exe)\n self.signle_exe_radioButton.setChecked(True)\n self.with_consoleradioButton.setChecked(True)\n\n @pyqtSlot()\n def open_input_file(self):\n file_path=QFileDialog.getOpenFileName(filter=\"*.py\")[0]\n if file_path!='':\n self.input_file_path.setText(file_path)\n\n @pyqtSlot()\n def open_output_dir(self):\n dir_path=QFileDialog.getExistingDirectory(self, '打开文件夹','./')\n if dir_path!='':\n self.output_path.setText(dir_path)\n\n @pyqtSlot()\n def open_icon_file(self):\n icon_path=QFileDialog.getOpenFileName(filter=\"*.ico\")[0]\n if icon_path!='':\n self.icon_path.setText(icon_path)\n\n @pyqtSlot()\n def export_exe(self):\n self.console_flag=None\n self.dir_flag=None\n if self.with_consoleradioButton.isChecked():\n self.console_flag='--console'\n else :\n self.console_flag='--windowed'\n\n if self.signle_exe_radioButton.isChecked():\n self.dir_flag='--onefile'\n else:\n self.dir_flag='--onedir'\n package_thread=threading.Thread(target=self.thread_package)\n package_thread.start()\n # print(self.executable_path)\n \n # with open(\"./log/{}.log\".format(time.strftime(\"%Y_%m_%d_%H_%M_%S\", time.localtime())),\"w\",encoding=\"gbk\")as f:\n # f.write(p.stdout)\n \n # PyInstaller.__main__.run([self.console_flag,self.dir_flag,'--noconfirm','--distpath={}'.format(self.output_path.text()),'--icon={}'.format(self.icon_path.text()),self.input_file_path.text()])\n def thread_package(self):\n subprocess.run(args=[self.executable_path, \"-m\", \"PyInstaller\",self.console_flag,self.dir_flag,'--noconfirm','--distpath={}'.format(self.output_path.text()),'--icon={}'.format(self.icon_path.text()),self.input_file_path.text()],encoding=\"gbk\",stdout=subprocess.PIPE)\n\n\nif __name__==\"__main__\":\n app = QApplication(sys.argv)\n ui = pyinstall_window(sys.executable)\n ui.show()\n sys.exit(app.exec_())\n","repo_name":"JerryVan22/package_management","sub_path":"pyinstall_window.py","file_name":"pyinstall_window.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44233777473","text":"import os, sys, ast, random, logging\nimport argparse\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import WeightedRandomSampler\n\nfrom transformers import get_linear_schedule_with_warmup\n\nfrom util.config import *\nfrom util.processor import _adjust_encoder\nfrom util.trainer import train, eval\nfrom util.common import _update_cfgs, param_reader, write_json, read_json, gen_mdl, gen_clf, _handle_model, save_model, load_model, seqmatch, mltl2entlmnt, entlmnt2mltl\n\nglobal FILE_DIR, DATA_PATH, args\nFILE_DIR = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))\nDATA_PATH = os.path.join(os.path.expanduser('~'), 'data', 'bionlp')\nargs = {}\n\n\ndef classify(dev_id=None):\n config_updates = dict([(k, v) for k, v in args.__dict__.items() if not k.startswith('_') and k not in set(['model', 'cfg']) and v is not None and not callable(v)])\n config_updates.update({**args.cfg, **{'wsdir':FILE_DIR}})\n config = SimpleConfig.from_file_importmap(args.cfg.setdefault('config', 'config.json'), pkl_fpath=None, import_lib=True, updates=config_updates)\n # Prepare model related meta data\n mdl_name = config.model\n pr = param_reader(os.path.join(FILE_DIR, 'etc', '%s.yaml' % config.common_cfg.setdefault('mdl_cfg', 'mdlcfg')))\n params = pr('LM', config.lm_params) if mdl_name != 'none' else {}\n use_gpu = dev_id is not None\n tokenizer = config.tknzr.from_pretrained(params['pretrained_vocab_path'] if 'pretrained_vocab_path' in params else config.lm_mdl_name) if config.tknzr else {}\n _adjust_encoder(tokenizer, config)\n\n # Prepare task related meta data.\n task_path, task_type, task_dstype, task_cols, task_trsfm, task_extparms = config.input if config.input and os.path.isdir(os.path.join(DATA_PATH, config.input)) else config.task_path, config.task_type, config.task_ds, config.task_col, config.task_trsfm, config.task_ext_params\n ds_kwargs = config.ds_kwargs\n\n # Prepare data\n if (not config.distrb or config.distrb and hvd.rank() == 0): logging.info('Dataset path: %s' % os.path.join(DATA_PATH, task_path))\n train_ds = task_dstype(os.path.join(DATA_PATH, task_path, 'train.%s' % config.fmt), tokenizer, config, **ds_kwargs)\n # Calculate the class weights if needed\n lb_trsfm = [x['get_lb'] for x in task_trsfm[1] if 'get_lb' in x]\n if (not config.weight_class or task_type == 'sentsim'):\n class_count = None\n elif len(lb_trsfm) > 0:\n lb_df = train_ds.df[task_cols['y']].apply(lb_trsfm[0])\n class_count = np.array([[1 if lb in y else 0 for lb in train_ds.binlb.keys()] for y in lb_df]).sum(axis=0)\n else:\n lb_df = train_ds.df[task_cols['y']]\n binlb = task_extparms['binlb'] if 'binlb' in task_extparms and type(task_extparms['binlb']) is not str else train_ds.binlb\n class_count = lb_df.value_counts()[binlb.keys()].values\n if (class_count is None):\n class_weights = None\n sampler = None\n else:\n class_weights = torch.Tensor(1.0 / class_count)\n class_weights /= class_weights.sum()\n class_weights *= (args.clswfac[min(len(args.clswfac)-1, 1)] if type(args.clswfac) is list else args.clswfac)\n sampler = None # WeightedRandomSampler does not work in new version\n # sampler = WeightedRandomSampler(weights=class_weights, num_samples=config.bsize, replacement=True)\n if not config.distrb and type(dev_id) is list: class_weights = class_weights.repeat(len(dev_id))\n\n # Partition dataset among workers using DistributedSampler\n if config.distrb: sampler = torch.utils.data.distributed.DistributedSampler(train_ds, num_replicas=hvd.size(), rank=hvd.rank())\n\n train_loader = DataLoader(train_ds, batch_size=config.bsize, shuffle=sampler is None and config.droplast, sampler=sampler, num_workers=config.np, drop_last=config.droplast)\n\n # Classifier\n if (not config.distrb or config.distrb and hvd.rank() == 0):\n logging.info('Language model input fields: %s' % config.input_keys)\n logging.info('Classifier hyper-parameters: %s' % config.clf_ext_params)\n logging.info('Classifier task-related parameters: %s' % task_extparms['mdlaware'])\n if (config.resume):\n # Load model\n clf, prv_optimizer, resume, chckpnt = load_model(config.resume)\n if config.refresh:\n logging.info('Refreshing and saving the model with newest code...')\n try:\n if (not config.distrb or config.distrb and hvd.rank() == 0):\n save_model(clf, prv_optimizer, '%s_%s.pth' % (config.task, config.model))\n except Exception as e:\n logging.warning(e)\n # Update parameters\n clf.update_params(task_params=task_extparms['mdlaware'], **config.clf_ext_params)\n if (use_gpu): clf = _handle_model(clf, dev_id=dev_id, distrb=config.distrb)\n # Construct optimizer\n optmzr_cls = config.optmzr if config.optmzr else (torch.optim.Adam, {}, None)\n optimizer = optmzr_cls[0](clf.parameters(), lr=config.lr, weight_decay=config.wdecay, **optmzr_cls[1]) if config.optim == 'adam' else torch.optim.SGD(clf.parameters(), lr=config.lr, momentum=0.9)\n if prv_optimizer: optimizer.load_state_dict(prv_optimizer.state_dict())\n training_steps = int(len(train_ds) / config.bsize) if hasattr(train_ds, '__len__') else config.trainsteps\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(config.wrmprop*training_steps), num_training_steps=training_steps) if not config.noschdlr and len(optmzr_cls) > 2 and optmzr_cls[2] and optmzr_cls[2] == 'linwarm' else None\n if (not config.distrb or config.distrb and hvd.rank() == 0): logging.info((optimizer, scheduler))\n else:\n # Build model\n lm_model, lm_config = gen_mdl(config, use_gpu=use_gpu, distrb=config.distrb, dev_id=dev_id)\n clf = gen_clf(config, lm_model, lm_config, num_lbs=len(train_ds.binlb) if train_ds.binlb else 1, mlt_trnsfmr=True if task_type in ['entlmnt', 'sentsim'] and task_extparms['mdlaware'].setdefault('sentsim_func', None) is not None else False, task_params=task_extparms['mdlaware'], binlb=train_ds.binlb, binlbr=train_ds.binlbr, use_gpu=use_gpu, distrb=config.distrb, dev_id=dev_id, **config.clf_ext_params)\n optmzr_cls = config.optmzr if config.optmzr else (torch.optim.Adam, {}, None)\n optimizer = optmzr_cls[0](clf.parameters(), lr=config.lr, weight_decay=config.wdecay, **optmzr_cls[1]) if config.optim == 'adam' else torch.optim.SGD(clf.parameters(), lr=config.lr, momentum=0.9)\n training_steps = int(len(train_ds) / config.bsize) if hasattr(train_ds, '__len__') else config.trainsteps\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=config.wrmprop, num_training_steps=training_steps) if not config.noschdlr and len(optmzr_cls) > 2 and optmzr_cls[2] and optmzr_cls[2] == 'linwarm' else None\n if (not config.distrb or config.distrb and hvd.rank() == 0): logging.info((optimizer, scheduler))\n\n if config.verbose: logging.debug(config.__dict__)\n\n if config.distrb:\n # Add Horovod Distributed Optimizer\n optimizer = hvd.DistributedOptimizer(optimizer, named_parameters=clf.named_parameters())\n # Broadcast parameters from rank 0 to all other processes.\n hvd.broadcast_parameters(clf.state_dict(), root_rank=0)\n hvd.broadcast_optimizer_state(optimizer, root_rank=0)\n\n # Training\n train(clf, optimizer, train_loader, config, scheduler, weights=class_weights, lmcoef=config.lmcoef, clipmaxn=config.clipmaxn, epochs=config.epochs, earlystop=config.earlystop, earlystop_delta=config.es_delta, earlystop_patience=config.es_patience, use_gpu=use_gpu, devq=dev_id, distrb=config.distrb, resume=resume if config.resume else {})\n\n if config.distrb:\n if hvd.rank() == 0:\n clf = _handle_model(clf, dev_id=dev_id, distrb=False)\n else:\n return\n\n if config.noeval: return\n dev_ds = task_dstype(os.path.join(DATA_PATH, task_path, 'dev.%s' % config.fmt), tokenizer, config, binlb=task_extparms['binlb'] if 'binlb' in task_extparms and type(task_extparms['binlb']) is not str else train_ds.binlb, **ds_kwargs)\n dev_loader = DataLoader(dev_ds, batch_size=config.bsize, shuffle=False, num_workers=config.np)\n test_ds = task_dstype(os.path.join(DATA_PATH, task_path, 'test.%s' % config.fmt), tokenizer, config, binlb=task_extparms['binlb'] if 'binlb' in task_extparms and type(task_extparms['binlb']) is not str else train_ds.binlb, **ds_kwargs)\n test_loader = DataLoader(test_ds, batch_size=config.bsize, shuffle=False, num_workers=config.np)\n logging.debug(('binlb', train_ds.binlb, dev_ds.binlb, test_ds.binlb))\n\n # Evaluation\n eval(clf, dev_loader, config, ds_name='dev', use_gpu=use_gpu, devq=dev_id, distrb=config.distrb, ignored_label=task_extparms.setdefault('ignored_label', None))\n if config.traindev: train(clf, optimizer, dev_loader, config, scheduler=scheduler, weights=class_weights, lmcoef=config.lmcoef, clipmaxn=config.clipmaxn, epochs=config.epochs, earlystop=config.earlystop, earlystop_delta=config.es_delta, earlystop_patience=config.es_patience, use_gpu=use_gpu, devq=dev_id, distrb=config.distrb)\n eval(clf, test_loader, config, ds_name='test', use_gpu=use_gpu, devq=dev_id, distrb=config.distrb, ignored_label=task_extparms.setdefault('ignored_label', None))\n\n\ndef rerank(dev_id=None):\n print('### Re-rank Mode ###')\n orig_task = args.task\n args.task = '%s_entilement' % orig_task\n config_updates = dict([(k, v) for k, v in args.__dict__.items() if not k.startswith('_') and k not in set(['model', 'cfg']) and v is not None and not callable(v)])\n config_updates.update({**args.cfg, **{'wsdir':FILE_DIR}})\n config = SimpleConfig.from_file_importmap(args.cfg.setdefault('config', 'config.json'), pkl_fpath=None, import_lib=True, updates=config_updates)\n # Prepare model related meta data\n mdl_name = config.model\n pr = param_reader(os.path.join(FILE_DIR, 'etc', '%s.yaml' % config.common_cfg.setdefault('mdl_cfg', 'mdlcfg')))\n params = pr('LM', config.lm_params) if mdl_name != 'none' else {}\n use_gpu = dev_id is not None\n encode_func = config.encode_func\n tokenizer = config.tknzr.from_pretrained(params['pretrained_vocab_path'] if 'pretrained_vocab_path' in params else config.lm_mdl_name) if config.tknzr else None\n # Prepare task related meta data.\n task_path, task_type, task_dstype, task_cols, task_trsfm, task_extparms = config.input if config.input and os.path.isdir(os.path.join(DATA_PATH, config.input)) else config.task_path, config.task_type, config.task_ds, config.task_col, config.task_trsfm, config.task_ext_params\n ds_kwargs = config.ds_kwargs\n config.input = '%s_entlmnt.csv' % orig_task\n onto_dict = pd.read_csv(config.onto, sep='\\t', index_col='id', encoding='utf-8')\n mltl2entlmnt(config.prvres if config.prvres and os.path.exists(config.prvres) else os.path.join(DATA_PATH, config.task_path, 'test.%s' % config.fmt), onto_dict, out_fpath=config.input, sent_mode=config.sent)\n\n if config.verbose: logging.debug(config.__dict__)\n\n # Load model\n clf, prv_optimizer, resume, chckpnt = load_model(config.resume)\n if config.refresh:\n print('Refreshing and saving the model with newest code...')\n try:\n save_model(clf, prv_optimizer, '%s_%s.pth' % (config.task, config.model))\n except Exception as e:\n print(e)\n # Update parameters\n clf.update_params(task_params=task_extparms['mdlaware'], **config.clf_ext_params)\n if (use_gpu): clf = _handle_model(clf, dev_id=dev_id, distrb=config.distrb)\n optmzr_cls = config.optmzr if config.optmzr else (torch.optim.Adam, {}, None)\n optimizer = optmzr_cls[0](clf.parameters(), lr=config.lr, weight_decay=config.wdecay, **optmzr_cls[1]) if config.optim == 'adam' else torch.optim.SGD(clf.parameters(), lr=config.lr, momentum=0.9)\n if prv_optimizer: optimizer.load_state_dict(prv_optimizer.state_dict())\n\n # Prepare test set\n test_ds = task_dstype(config.input, tokenizer, config, ds_name='test', binlb=task_extparms['binlb'] if 'binlb' in task_extparms and type(task_extparms['binlb']) is not str else clf.binlb, **ds_kwargs)\n test_loader = DataLoader(test_ds, batch_size=config.bsize, shuffle=False, num_workers=config.np)\n\n # Evaluation\n if config.traindev:\n dev_ds = task_dstype(config.input, tokenizer, config, ds_name='dev', binlb=task_extparms['binlb'] if 'binlb' in task_extparms and type(task_extparms['binlb']) is not str else clf.binlb, **ds_kwargs)\n training_steps = int(len(dev_ds) / config.bsize) if hasattr(dev_ds, '__len__') else config.trainsteps\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=config.wrmprop, num_training_steps=training_steps) if not config.noschdlr and len(optmzr_cls) > 2 and optmzr_cls[2] and optmzr_cls[2] == 'linwarm' else None\n if (not config.distrb or config.distrb and hvd.rank() == 0): print((optimizer, scheduler))\n dev_loader = DataLoader(dev_ds, batch_size=config.bsize, shuffle=False, num_workers=config.np)\n eval(clf, dev_loader, config, ds_name='dev', use_gpu=use_gpu, devq=dev_id, distrb=config.distrb, ignored_label=task_extparms.setdefault('ignored_label', None))\n train(clf, optimizer, dev_loader, config, scheduler, weights=config.class_weights, lmcoef=config.lmcoef, clipmaxn=config.clipmaxn, epochs=config.epochs, earlystop=config.earlystop, earlystop_delta=config.es_delta, earlystop_patience=config.es_patience, use_gpu=use_gpu, devq=dev_id, distrb=config.distrb, resume=resume if config.resume else {})\n eval(clf, test_loader, config, ds_name='test', use_gpu=use_gpu, devq=dev_id, distrb=config.distrb, ignored_label=task_extparms.setdefault('ignored_label', None))\n os.rename('pred_test.csv', '%s_entlmnt_pred.csv' % orig_task)\n ref_df = pd.read_csv(config.prvres if config.prvres and os.path.exists(config.prvres) else os.path.join(DATA_PATH, config.task_path, 'test.%s' % config.fmt), sep='\\t', dtype={'id':object}, encoding='utf-8')\n entlmnt2mltl('%s_entlmnt_pred.csv' % orig_task, ref_df, onto_dict, out_fpath='%s_rerank_pred_test.csv' % orig_task, idx_num_underline=NUM_UNDERLINE_IN_ORIG[orig_task])\n\n\ndef main():\n predefined_tasks = ['biolarkgsc', 'copd', 'biolarkgsc_entilement', 'copd_entilement', 'hpo_entilement']\n if any(args.task == t for t in ['biolarkgsc_entilement', 'copd_entilement', 'hpo_entilement']):\n if args.method != 'train' or args.method != 'fine-tune':\n print('Running in training mode instead ...')\n main_func = classify\n elif any(args.task == t for t in ['biolarkgsc', 'copd']):\n if args.method != 'rerank':\n print('Running in re-ranking mode instead ...')\n main_func = rerank\n else:\n print('Please select the task among: %s' % predefined_tasks)\n return\n\n if (args.distrb or args.devq):\n main_func(args.devq if len(args.devq) > 1 else args.devq[0])\n else:\n main_func(None) # CPU\n\n\nif __name__ == '__main__':\n # Parse commandline arguments\n parser = argparse.ArgumentParser(description='Train or evaluate the re-ranking model.')\n parser.add_argument('-p', '--pid', default=0, action='store', type=int, dest='pid', help='indicate the process ID')\n parser.add_argument('-n', '--np', default=1, action='store', type=int, dest='np', help='indicate the number of processes used for training')\n parser.add_argument('-j', '--epochs', default=1, action='store', type=int, dest='epochs', help='indicate the epoch used in deep learning')\n parser.add_argument('-z', '--bsize', default=64, action='store', type=int, dest='bsize', help='indicate the batch size used in deep learning')\n parser.add_argument('-g', '--gpunum', default=1, action='store', type=int, dest='gpunum', help='indicate the gpu device number')\n parser.add_argument('-q', '--gpuq', dest='gpuq', help='prefered gpu device queue [template: DEVICE_ID1,DEVICE_ID2,...,DEVICE_IDn]')\n parser.add_argument('--gpumem', default=0.5, action='store', type=float, dest='gpumem', help='indicate the per process gpu memory fraction')\n parser.add_argument('--distrb', default=False, action='store_true', dest='distrb', help='whether to distribute data over multiple devices')\n parser.add_argument('--distbknd', default='nccl', action='store', dest='distbknd', help='distribute framework backend')\n parser.add_argument('--disturl', default='env://', action='store', dest='disturl', help='distribute framework url')\n parser.add_argument('--traindev', default=False, action='store_true', help='whether to use dev dataset for training')\n parser.add_argument('--noeval', default=False, action='store_true', help='whether to train only')\n parser.add_argument('--noschdlr', default=False, action='store_true', help='force to not use scheduler whatever the default setting is')\n parser.add_argument('--maxlen', default=128, action='store', type=int, dest='maxlen', help='indicate the maximum sequence length for each samples')\n parser.add_argument('--maxtrial', default=50, action='store', type=int, dest='maxtrial', help='maximum time to try')\n parser.add_argument('--droplast', default=False, action='store_true', help='whether to drop the last incompleted batch')\n parser.add_argument('--weight_class', default=False, action='store_true', help='whether to drop the last incompleted batch')\n parser.add_argument('--clswfac', default='1', type=str, help='whether to drop the last incompleted batch')\n parser.add_argument('--bert_outlayer', default='-1', type=str, dest='output_layer', help='indicate which layer to be the output of BERT model')\n parser.add_argument('--resume', action='store', dest='resume', help='resume training model file')\n parser.add_argument('--refresh', default=False, action='store_true', dest='refresh', help='refresh the trained model with newest code')\n parser.add_argument('--onto', help='ontology data')\n parser.add_argument('--pred', help='prediction file')\n parser.add_argument('--sent', default=False, action='store_true', dest='sent', help='whether to use location of labels to split the text into sentences')\n parser.add_argument('--datapath', help='location of dataset')\n parser.add_argument('-i', '--input', help='input dataset')\n parser.add_argument('--prvres', help='previous results for re-ranking')\n parser.add_argument('-u', '--task', default='hpo_entilement', type=str, dest='task', help='the task name [default: %default]')\n parser.add_argument('--model', default='bert', type=str, dest='model', help='the model to be validated')\n parser.add_argument('--encoder', dest='encoder', help='the encoder to be used after the language model: pool, s2v or s2s')\n parser.add_argument('--pretrained', dest='pretrained', help='pretrained model file')\n parser.add_argument('--seed', help='manually set the random seed')\n parser.add_argument('-c', '--cfg', help='config string used to update the settings, format: {\\'param_name1\\':param_value1[, \\'param_name1\\':param_value1]}')\n parser.add_argument('-m', '--method', default='rerank', help='main method to run')\n parser.add_argument('-v', '--verbose', default=False, action='store_true', dest='verbose', help='display detailed information')\n args = parser.parse_args()\n\n # Logging setting\n logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, format='%(asctime)s %(levelname)s %(message)s')\n\n # Update config\n global_vars = globals()\n cfg_kwargs = {} if args.cfg is None else ast.literal_eval(args.cfg)\n args.cfg = cfg_kwargs\n _update_cfgs(global_vars, cfg_kwargs)\n\n # GPU setting\n if (args.gpuq is not None and not args.gpuq.strip().isspace()):\n args.gpuq = list(range(torch.cuda.device_count())) if (args.gpuq == 'auto' or args.gpuq == 'all') else [int(x) for x in args.gpuq.split(',') if x]\n elif (args.gpunum > 0):\n args.gpuq = list(range(args.gpunum))\n else:\n args.gpuq = []\n if (args.gpuq and args.gpunum > 0):\n if args.verbose: os.environ['CUDA_LAUNCH_BLOCKING'] = '1'\n os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(os.environ['CUDA_VISIBLE_DEVICES'].split(',')[:args.gpunum]) if 'CUDA_VISIBLE_DEVICES' in os.environ and not os.environ['CUDA_VISIBLE_DEVICES'].isspace() else ','.join(map(str, args.gpuq[:args.gpunum]))\n setattr(args, 'devq', list(range(torch.cuda.device_count())))\n else:\n setattr(args, 'devq', None)\n if args.distrb:\n import horovod.torch as hvd\n hvd.init()\n DATA_PATH = os.path.join('/', 'data', 'bionlp')\n torch.cuda.set_device(hvd.local_rank())\n\n # Process config\n if args.datapath is not None: DATA_PATH = args.datapath\n\n # Random seed setting\n if args.seed is not None:\n np.random.seed(args.seed)\n torch.cuda.manual_seed(args.seed)\n\n # Format some arguments\n args.output_layer = list(map(int, args.output_layer.split(',')))\n args.output_layer = args.output_layer[0] if len(args.output_layer) == 1 else args.output_layer\n args.clswfac = list(map(float, args.clswfac.split(','))) if ',' in args.clswfac else float(args.clswfac)\n\n main()\n","repo_name":"ncbi-nlp/PhenoRerank","sub_path":"rerank.py","file_name":"rerank.py","file_ext":"py","file_size_in_byte":21326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29120176734","text":"class BinaryTreeNode(object):\n #initial values for value,left and right\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n\n# inserting a new node in the binary tree\ndef insert(tree, item):\n # if no initial element in the tree\n if tree == None:\n tree = BinaryTreeNode(item)\n else:\n if (item < tree.value):\n # if left branch of the tree is empty\n if (tree.left == None):\n tree.left = BinaryTreeNode(item)\n else:\n insert(tree.left, item)\n else:\n # if right branch of the tree is empty\n if (tree.right == None):\n tree.right = BinaryTreeNode(item)\n else:\n insert(tree.right, item)\n return tree\n\n# funtion for the inorder traversal of the binary tree\ndef in_order_traversal(tree,a):\n if (tree.left != None):\n in_order_traversal(tree.left,a)\n a.append(tree.value)\n if (tree.right != None):\n in_order_traversal(tree.right,a)\n\n\ndef tree_sort(x):\n # root node\n t = insert(None, x[0]);\n # inserting all elements in the binary tree\n for i in x[1:]:\n insert(t,i)\n # the results of the inorder traversal of a binary tree is a sorted\n a = []\n in_order_traversal(t,a)\n return a\n\n","repo_name":"my-first-pr/hacktoberfest-2018","sub_path":"code/tree_sort.py","file_name":"tree_sort.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"52"} +{"seq_id":"5081508220","text":"from unittest import mock\r\n\r\nimport pytest\r\n\r\nfrom pystripe.utils import StripeAPI\r\nfrom pystripe import utils\r\n\r\n\r\nclass MockRequest(object):\r\n def __init__(self, response, **kwargs):\r\n self.response = response\r\n self.overwrite = True\r\n if kwargs.get(\"overwrite\"):\r\n self.overwrite = True\r\n self.status_code = kwargs.get(\"status_code\", 200)\r\n\r\n @classmethod\r\n def raise_for_status(cls):\r\n pass\r\n\r\n def json(self):\r\n if self.overwrite:\r\n return self.response\r\n return {\"data\": self.response}\r\n\r\n\r\n@pytest.fixture\r\ndef stripe_api():\r\n return StripeAPI(\r\n public_key=\"public_key\",\r\n secret_key=\"secret_key\",\r\n webhook_secret=\"webhook_secret\",\r\n )\r\n\r\n\r\n@pytest.fixture\r\ndef headers(stripe_api: utils.StripeAPI):\r\n return {\r\n \"Authorization\": \"Bearer {}\".format(stripe_api.secret_key),\r\n \"Content-Type\": \"application/json\",\r\n }\r\n\r\n\r\n@pytest.fixture\r\ndef get_request(mocker):\r\n def _get_request(*args, **kwargs):\r\n side_effect = kwargs.pop(\"side_effect\", None)\r\n mock_get = mocker.patch(\"requests.get\")\r\n if side_effect:\r\n mock_get.side_effect = [MockRequest(x) for x in side_effect]\r\n else:\r\n mock_get.return_value = MockRequest(*args, **kwargs)\r\n return mock_get\r\n\r\n return _get_request\r\n\r\n\r\n@pytest.fixture\r\ndef post_request(mocker):\r\n def _post_request(*args, **kwargs):\r\n side_effect = kwargs.pop(\"side_effect\", None)\r\n mock_post = mocker.patch(\"requests.post\")\r\n if side_effect:\r\n mock_post.side_effect = [MockRequest(x) for x in side_effect]\r\n else:\r\n mock_post.return_value = MockRequest(*args, **kwargs)\r\n return mock_post\r\n\r\n return _post_request\r\n\r\n\r\n@pytest.fixture\r\ndef put_request(mocker):\r\n def _put_request(*args, **kwargs):\r\n mock_post = mocker.patch(\"requests.put\")\r\n mock_post.return_value = MockRequest(*args, **kwargs)\r\n return mock_post\r\n\r\n return _put_request\r\n\r\n\r\n@pytest.fixture\r\ndef mock_assertion(headers, stripe_api: utils.StripeAPI):\r\n def _mock_assertion(mock_call, path, **kwargs):\r\n side_effect = kwargs.pop(\"stripe_apiside_effect\", None)\r\n url = \"{}{}\".format(stripe_api.base_url, path)\r\n if side_effect:\r\n mock_calls = [mock.call(url, headers=headers, **x) for x in side_effect]\r\n mock_call.assert_has_calls(mock_calls, any_order=True)\r\n else:\r\n mock_call.assert_called_once_with(url, headers=headers, **kwargs)\r\n\r\n return _mock_assertion\r\n","repo_name":"gbozee/pystripe","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21208725163","text":"#klampt wrappper\nfrom klampt.math import vectorops as vo\nimport numpy as np\nimport math\nimport pydrake as pd\nfrom pydrake.attic.multibody.rigid_body_tree import RigidBodyTree\nfrom pydrake.autodiffutils import AutoDiffXd as AD\n\nclass robosimian_drake:\n\tdef __init__(self,dt = 0.01):\n\t\tpath = \"data/robosimian_caesar_new_pinnochio.urdf\"\n\t\tself.tree = RigidBodyTree(path)\n\n\tdef get_world(self):\n\t\treturn self.world_all_active\n\n\tdef set_q_2D(self,q):\n\t\t\"\"\"\n\t\tParameters:\n\t\t--------------\n\t\tq: n*1 column vector; 2D numpy array\n\t\t\"\"\"\n\t\t# assert len(q) == 15 , \"wrong length for q\"\n\t\tq_to_be_set = [0.0]*self.N_of_joints_3D\n\t\tfor (i,j) in zip(self.joint_indices_3D,self.joint_indices_2D):\n\t\t\tq_to_be_set[i] = q[j,0]\n\t\t#print(q_to_be_set,len(q_to_be_set))\n\t\tself.robot_all_active.setConfig(q_to_be_set)\n\n\t\treturn np.array(q_to_be_set)[np.newaxis].T\n\n\tdef set_q_dot_2D(self,q_dot):\n\t\t# assert len(q_dot) == 15 , \"wrong length for q\"\n\t\tq_dot_to_be_set = [0.0]*self.N_of_joints_3D\n\t\tfor (i,j) in zip(self.joint_indices_3D,self.joint_indices_2D):\n\t\t\tq_dot_to_be_set[i] = q_dot[j,0]\n\t\t#print(q_dot_to_be_set, len(q_dot_to_be_set))\n\t\tself.robot_all_active.setVelocity(q_dot_to_be_set)\n\n\t\treturn np.array(q_dot_to_be_set)[np.newaxis].T\n\n\tdef set_q_2D_(self,q):\n\t\t\"\"\"\n\t\tParameters:\n\t\t--------------\n\t\tq: 1D numpy array\n\t\t\"\"\"\n\t\t# assert len(q) == 15 , \"wrong length for q\"\n\t\tq_to_be_set = [0.0]*self.N_of_joints_3D\n\t\tfor (i,j) in zip(self.joint_indices_3D,self.joint_indices_2D):\n\t\t\tq_to_be_set[i] = float(q[j])\n\t\t#print(q_to_be_set,len(q_to_be_set))\n\t\tself.robot_all_active.setConfig(q_to_be_set)\n\n\t\treturn np.array(q_to_be_set)[np.newaxis].T\n\n\tdef set_q_dot_2D_(self,q_dot):\n\t\t\"\"\"\n\t\tParameters:\n\t\t--------------\n\t\tq: 1D numpy array\n\t\t\"\"\"\n\t\t# assert len(q_dot) == 15 , \"wrong length for q\"\n\t\tq_dot_to_be_set = [0.0]*self.N_of_joints_3D\n\t\tfor (i,j) in zip(self.joint_indices_3D,self.joint_indices_2D):\n\t\t\tq_dot_to_be_set[i] = float(q_dot[j])\n\t\t#print(q_dot_to_be_set, len(q_dot_to_be_set))\n\t\tself.robot_all_active.setVelocity(q_dot_to_be_set)\n\n\t\treturn np.array(q_dot_to_be_set)[np.newaxis].T\n\n\n\tdef get_mass_matrix(self):\n\t\tm_3D = self.robot_all_active.getMassMatrix()\n\t\tm = []\n\t\tfor i in self.joint_indices_3D:\n\t\t\trow = []\n\t\t\tfor j in self.joint_indices_3D:\n\t\t\t\trow.append(m_3D[i][j]) \n\t\t\tm.append(row)\n\t\treturn m\n\n\n\tdef compute_CD(self,u,gravity = (0,0,-9.81)):\n\t\t\"\"\" Compute the dynamics of the 2D robot, given by matrices C and D.\n\t\tacceleration = C + D*contact_wrench \n\n\t\tParameters:\n\t\t------------\n\t\tu a numpy array\n\t\t\n\t\tReturns:\n\t\t------------\n\t\tC,D: numpy array nx1 2D arrays...\n\t\t\"\"\"\n\t\tu = self.u_2D_to_3D(u) #u is a 1D numpy array\n\t\tB_inv = np.array(self.robot_all_active.getMassMatrixInv())\n\t\tI = np.eye(38)\n\t\ta_from_u = np.array(self.robot_all_active.accelFromTorques(u))\n\t\tK = np.subtract(I,np.dot(B_inv,np.dot(self.F.T,np.dot(np.linalg.inv(np.dot(self.F,np.dot(B_inv,self.F.T))),self.F))))\n\t\tG = np.array(self.robot_all_active.getGravityForces(gravity))\n\t\ta = np.dot(K,a_from_u.T)\n\t\tC = np.subtract(a,np.dot(K,np.dot(B_inv,G)))\n\t\t# print(self.robot_all_active.getConfig())\n\t\t# print(self.robot_all_active.getVelocity())\n\t\t#print('a',C)\n\t\t#print('C',C)\n\n\t\tself._clean_vector(C)\n\t\tJ1 = np.array(self.robot_all_active.link(13).getJacobian((0.075,0,0)))\n\t\tJ2 = np.array(self.robot_all_active.link(21).getJacobian((0.075,0,0)))\n\t\tJ3 = np.array(self.robot_all_active.link(29).getJacobian((0.075,0,0)))\n\t\tJ4 = np.array(self.robot_all_active.link(37).getJacobian((0.075,0,0)))\n\t\tJ1 = J1[[3,5,1],:] #orientation jacobian is stacked upon position\n\t\tJ2 = J2[[3,5,1],:]\n\t\tJ3 = J3[[3,5,1],:]\n\t\tJ4 = J4[[3,5,1],:]\n\t\tJ = np.vstack((J1,np.vstack((J2,np.vstack((J3,J4))))))\n\t\tD = np.dot(K,np.dot(B_inv,J.T))\n\n\t\tC = C[np.newaxis].T\n\t\treturn C[self.joint_indices_3D,:],D[self.joint_indices_3D,:]\n\n\nif __name__==\"__main__\":\n\trobot = robosimian_drake()\n\t#robot.set_generalized_q([0]*15)\n\t#robot.compute_CD(np.zeros((12,1)))\n","repo_name":"yifanzhu95/TOGM","sub_path":"robosimian_drake_wrapper.py","file_name":"robosimian_drake_wrapper.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"32346748261","text":"# Input\n\n# The input is composed of two lines. The first line contains a single positive integer n\n# (1≤n≤100) that specifies the number of temperatures collected by the University of Chicago Weather Service. The second line contains n temperatures, each separated by a single space. Each temperature is represented by an integer t (−1000000≤t≤1000000\n\n# )\n# Output\n\n# You must print a single integer: the number of temperatures strictly less than zero.\n\n\nimport sys\n\nn = sys.stdin.readline()\nt = sys.stdin.readline()\n\ncount_neg_values = 0\n\nfor v in t.split(\" \"):\n if int(v) < 0:\n count_neg_values = count_neg_values + 1\n\nprint(count_neg_values)","repo_name":"dkfrankandersen/kattis","sub_path":"problems/cold/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2439228817","text":"import pytest\nfrom .shared import CLICommon\n\nclass T_IntraCmdConflicts(CLICommon):\n # Reuse the same conflicts as python plugin. Only change should be the processed command\n\n cmd = CLICommon.app_cmds.intra_cmd_conflicts\n conflicts = CLICommon.python_plugin.get_intra_cmd_conflicts_list(cmd)\n\n @classmethod\n def setup_class(cls):\n cls.cmd_help = cls.cmd.get_help_msg()\n cls.cmd_conflicts = cls.cmd_help.logged_errors\n\n @classmethod\n def teardown_class(cls):\n delattr(cls, \"cmd_help\")\n delattr(cls, \"cmd_conflicts\")\n\n def test_help_msg(self):\n # Check help message\n cmd = self.cmd\n help = self.cmd_help\n print(self.cmd_help.text)\n help.assert_args(cmd.arg0, cmd.arg1, cmd.arg2)\n help.assert_opts(\n cmd.arg_clash,\n cmd.intra_opt_conflicts,\n \"help\",\n cmd.inter_opt_conflicts,\n \"m\", \"nt\",\n cmd.opt,\n cmd.reserved_prefix_in_ln_lna,\n \"t\", \"v\", \"vk\",\n )\n help.assert_subcmds(cmd.conflicts_subc, \"help\")\n\n assert help.aux_exts == None\n assert help.pl_exts == None\n assert help.app_exts == False\n\n def test_conflicts_during_cmd_building(self):\n for c in reversed(self.conflicts):\n m = self.cmd_conflicts.pop()\n assert self.err_msgs.to_conflict_msg(self.cmd, c) in m\n\n def test_all_error_messages_checked(self):\n assert len(self.cmd_conflicts) == 0\n\n def test_cmd_conflicts_resolve_correctly(self):\n cmd = self.cmd\n out = cmd.run(\n \"0\", \"1\", \"2\",\n \"--opt\", \"--opt0\",\n \"--arg0\", \"--arg1\",\n \"--ext_opt_lna\",\n \"--intra_opt_cons\", \"-c\", \"-e\",\n \"-d\",\n )\n cmd.assert_args(\n out,\n (cmd.arg0, \"0\"),\n (cmd.arg1, \"1\"),\n (cmd.arg2, \"2\"),\n (cmd.opt, 2),\n (cmd.arg_clash, 2),\n (cmd.reserved_prefix_in_ln_lna, 1),\n (cmd.intra_opt_conflicts, 3),\n (cmd.inter_opt_conflicts, 1),\n )\n\n def test_subc_help_msg(self):\n # Check help message\n cmd = self.cmd.conflicts_subc\n help = cmd.get_help_msg()\n\n help.assert_args(cmd.arg0, cmd.sub_arg_1)\n help.assert_opts(\n \"help\",\n cmd.inter_subc_conflicts,\n cmd.intra_subc_lna_iln_conflict,\n \"m\", \"nt\",\n cmd.opt,\n cmd.intra_subc_conflicts,\n \"t\", \"v\", \"vk\",\n )\n help.assert_subcmds(None)\n\n assert help.aux_exts == None\n assert help.pl_exts == None\n assert help.app_exts == False\n\n def test_cmd_subc_conflicts_resolve_correctly(self):\n cmd = self.cmd.conflicts_subc\n out = cmd.run(\n \"a\", \"b\",\n \"--opt\", \"--subc_opt\",\n \"--intra_subc_conflicts\", \"-r\",\n \"--intra_subc_lna_iln_conflict\",\n \"--inter_subc_conflicts\"\n )\n cmd.assert_args(\n out,\n (cmd.arg0, \"a\"),\n (cmd.sub_arg_1, \"b\"),\n (cmd.opt, 2),\n (cmd.intra_subc_conflicts, 2),\n (cmd.intra_subc_lna_iln_conflict, 1),\n (cmd.inter_subc_conflicts, 1),\n )\n\n","repo_name":"Origen-SDK/o2","sub_path":"test_apps/python_app/tests/cli/tests__intra_cmd_conflicts.py","file_name":"tests__intra_cmd_conflicts.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"37059079587","text":"import re\nimport numpy as np\nimport json\nimport pandas as pd\nimport time\nimport os\nimport glob\nimport argparse\n# import openpyxl for xls writer\n\ndef read_json_to_df(file_path):\n\t# df = pd.read_json(path_or_buf=file_path,orient='records',lines=True)\n\tdf = pd.read_json(path_or_buf=file_path,orient='records')\n\treturn df\n\ndef read_df_pickle(file_path):\n\tdf = pd.read_pickle(path=file_path)\n\treturn df\n\ndef get_column_stats(df,column_name,to_dict = False):\n\tif to_dict:\n\t\treturn df[column_name].value_counts().to_dict()\n\telse: \n\t\treturn df[column_name].value_counts()\n\ndef main(args):\n\t# Stats\n\t# stats_file_pkl = 'stats_df_all.pkl'\n\tstats_df = read_df_pickle(args.stats_file_pkl)\n\tstats_describe = stats_df.describe()\n\tstats_sum = pd.DataFrame(stats_df.sum(numeric_only=True))\n\tstats_sum.columns = ['total']\n\ttotal_turns = stats_sum.at['total_turns','total'] # Value \n\tstats_sum['percent'] = stats_sum/total_turns*100\n\tstats_sum['percent'] = stats_sum['percent'].astype(int)\n\t# System utterances\n\t# sys_file_pkl = 'combined_df_sys.json'\n\twriter = pd.ExcelWriter(args.output_file_path)\n\tstats_describe.to_excel(writer, sheet_name='Stats_desc')\n\tstats_sum.to_excel(writer, sheet_name='Stats_sum')\n\n\tsys_df = read_df_pickle(args.sys_file_pkl)\n\tsys_df = sys_df.loc[sys_df['is_nlg']>0]\n\tsys_df_numeric = sys_df.loc[sys_df['is_nlg']>0][['state', 'num_chars','num_sent', 'num_words']]\t\n\tsys_df_describe = sys_df_numeric.groupby('state').describe()\n\tunique_nlg = sys_df.groupby(['state']).nlg.nunique().to_frame()\n\tunique_nlg.columns = ['total']\n\t# states = get_column_stats(sys_df, 'state').to_frame()\n\t# Num unique\n\tnum_unique_states = sys_df['state'].nunique()\n\tnum_unique_type = sys_df['type'].nunique()\n\tprint(\"Sys Unique states\" + str(num_unique_states))\n\tprint(\"Sys Unique type\" + str(num_unique_states))\n\tnlg_state_table = sys_df.groupby(['state','nlg']).size().sort_values(ascending=False).to_frame()\n\tnlg_state_table.columns = ['count']\n\tlargest_nlg = nlg_state_table.groupby(['state'])['count'].nlargest(10)\n\n\tsys_df_describe.to_excel(writer, sheet_name='Sys_describe')\n\tunique_nlg.to_excel(writer, sheet_name='Sys_unique_count_nlg')\n\tlargest_nlg.to_excel(writer, sheet_name='Sys_state_nlg')\n\n\t# User utterances\n\t# user_file_pkl = 'combined_df_user.json'\n\tuser_df = read_df_pickle(args.user_file_pkl)\n\tuser_df = user_df.loc[user_df['is_nlg']>0]\n\tuser_df_numeric = user_df.loc[user_df['is_nlg']>0][['state', 'num_chars','num_sent', 'num_words']]\t\n\tuser_df_describe = user_df_numeric.groupby('state').describe()\n\tunique_nlg_user = user_df.groupby(['state']).nlg.nunique().to_frame()\n\tunique_nlg_user.columns = ['total']\n\t# states = get_column_stats(sys_df, 'state').to_frame()\n\t# Num unique\n\tnum_unique_states = user_df['state'].nunique()\n\tnum_unique_type = user_df['type'].nunique()\n\tprint(\"User Unique states\" + str(num_unique_states))\n\tprint(\"User Unique type\" + str(num_unique_states))\n\tnlg_state_table = user_df.groupby(['state','nlg']).size().sort_values(ascending=False).to_frame()\n\tnlg_state_table.columns = ['count']\n\tlargest_nlg_user = nlg_state_table.groupby(['state'])['count'].nlargest(10)\n\n\tuser_df_describe.to_excel(writer, sheet_name='User_describe')\n\tunique_nlg_user.to_excel(writer, sheet_name='User_unique_count_nlg')\n\tlargest_nlg_user.to_excel(writer, sheet_name='User_state_nlg')\n\twriter.save()\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-user_file_pkl', help='User file path')\n\tparser.add_argument('-sys_file_pkl', help='Sys file path')\n\tparser.add_argument('-stats_file_pkl', help='Output file path')\n\tparser.add_argument('-output_file_path', help='Output file path')\n\targs = parser.parse_args()\n\tmain(args)\n","repo_name":"shubhamagarwal92/mmd","sub_path":"data_analysis/read_combine_df.py","file_name":"read_combine_df.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"52"} +{"seq_id":"13089893765","text":"import gdb\nimport re\n\n\"\"\"GDB commands for working with xmethods.\"\"\"\n\n\ndef validate_xm_regexp(part_name, regexp):\n try:\n return re.compile(regexp)\n except SyntaxError:\n raise SyntaxError(\"Invalid %s regexp: %s\", part_name, regexp)\n\n\ndef parse_xm_command_args(arg):\n \"\"\"Parses the arguments passed to a xmethod command.\n\n Arguments:\n arg: The argument string passed to a xmethod command.\n\n Returns:\n A 3-tuple: (,\n ,\n )\n \"\"\"\n argv = gdb.string_to_argv(arg)\n argc = len(argv)\n if argc > 2:\n raise SyntaxError(\"Too many arguments to command.\")\n locus_regexp = \"\"\n matcher_name_regexp = \"\"\n xm_name_regexp = None\n if argc >= 1:\n locus_regexp = argv[0]\n if argc == 2:\n parts = argv[1].split(\";\", 1)\n matcher_name_regexp = parts[0]\n if len(parts) > 1:\n xm_name_regexp = parts[1]\n if xm_name_regexp:\n name_re = validate_xm_regexp(\"xmethod name\", xm_name_regexp)\n else:\n name_re = None\n return (validate_xm_regexp(\"locus\", locus_regexp),\n validate_xm_regexp(\"matcher name\", matcher_name_regexp),\n name_re)\n\n\ndef get_global_method_matchers(locus_re, matcher_re):\n \"\"\"Returns a dict of matching globally registered xmethods.\n\n Arguments:\n locus_re: Even though only globally registered xmethods are\n looked up, they will be looked up only if 'global' matches\n LOCUS_RE.\n matcher_re: The regular expression matching the names of xmethods.\n\n Returns:\n A dict of matching globally registered xmethod matchers. The only\n key in the dict will be 'global'.\n \"\"\"\n locus_str = \"global\"\n xm_dict = { locus_str: [] }\n if locus_re.match(\"global\"):\n xm_dict[locus_str].extend(\n [m for m in gdb.xmethods if matcher_re.match(m.name)])\n return xm_dict\n\n\ndef get_method_matchers_in_loci(loci, locus_re, matcher_re):\n \"\"\"Returns a dict of matching registered xmethods in the LOCI.\n\n Arguments:\n loci: The list of loci to lookup matching xmethods in.\n locus_re: If a locus is an objfile, then xmethod matchers will be\n looked up in it only if its filename matches the regular\n expression LOCUS_RE. If a locus is the current progspace,\n then xmethod matchers will be looked up in it only if the\n string \"progspace\" matches LOCUS_RE.\n matcher_re: The regular expression to match the xmethod matcher\n names.\n\n Returns:\n A dict of matching xmethod matchers. The keys of the dict are the\n filenames of the loci the xmethod matchers belong to.\n \"\"\"\n xm_dict = {}\n for locus in loci:\n if isinstance(locus, gdb.Progspace):\n if not locus_re.match('progspace'):\n continue\n locus_type = \"progspace\"\n else:\n if not locus_re.match(locus.filename):\n continue\n locus_type = \"objfile\"\n locus_str = \"%s %s\" % (locus_type, locus.filename)\n xm_dict[locus_str] = [\n m for m in locus.xmethods if matcher_re.match(m.name)]\n return xm_dict\n\n\ndef print_xm_info(xm_dict, name_re):\n \"\"\"Print a dictionary of xmethods.\"\"\"\n def get_status_string(m):\n if not m.enabled:\n return \" [disabled]\"\n else:\n return \"\"\n\n if not xm_dict:\n return\n for locus_str in xm_dict:\n if not xm_dict[locus_str]:\n continue\n print (\"Xmethods in %s:\" % locus_str)\n for matcher in xm_dict[locus_str]:\n print (\" %s%s\" % (matcher.name, get_status_string(matcher)))\n if not matcher.methods:\n continue\n for m in matcher.methods:\n if name_re is None or name_re.match(m.name):\n print (\" %s%s\" % (m.name, get_status_string(m)))\n\n\ndef set_xm_status1(xm_dict, name_re, status):\n \"\"\"Set the status (enabled/disabled) of a dictionary of xmethods.\"\"\"\n for locus_str, matchers in xm_dict.items():\n for matcher in matchers:\n if not name_re:\n # If the name regex is missing, then set the status of the\n # matcher and move on.\n matcher.enabled = status\n continue\n if not matcher.methods:\n # The methods attribute could be None. Move on.\n continue\n for m in matcher.methods:\n if name_re.match(m.name):\n m.enabled = status\n\n\ndef set_xm_status(arg, status):\n \"\"\"Set the status (enabled/disabled) of xmethods matching ARG.\n This is a helper function for enable/disable commands. ARG is the\n argument string passed to the commands.\n \"\"\"\n locus_re, matcher_re, name_re = parse_xm_command_args(arg)\n set_xm_status1(get_global_method_matchers(locus_re, matcher_re), name_re,\n status)\n set_xm_status1(\n get_method_matchers_in_loci(\n [gdb.current_progspace()], locus_re, matcher_re),\n name_re,\n status)\n set_xm_status1(\n get_method_matchers_in_loci(gdb.objfiles(), locus_re, matcher_re),\n name_re,\n status)\n\n\nclass InfoXMethod(gdb.Command):\n \"\"\"GDB command to list registered xmethod matchers.\n\n Usage: info xmethod [locus-regexp [name-regexp]]\n\n LOCUS-REGEXP is a regular expression matching the location of the\n xmethod matchers. If it is omitted, all registered xmethod matchers\n from all loci are listed. A locus could be 'global', a regular expression\n matching the current program space's filename, or a regular expression\n matching filenames of objfiles. Locus could be 'progspace' to specify that\n only xmethods from the current progspace should be listed.\n\n NAME-REGEXP is a regular expression matching the names of xmethod\n matchers. If this omitted for a specified locus, then all registered\n xmethods in the locus are listed. To list only a certain xmethods\n managed by a single matcher, the name regexp can be specified as\n matcher-name-regexp;xmethod-name-regexp.\n \"\"\"\n\n def __init__(self):\n super(InfoXMethod, self).__init__(\"info xmethod\",\n gdb.COMMAND_DATA)\n\n def invoke(self, arg, from_tty):\n locus_re, matcher_re, name_re = parse_xm_command_args(arg)\n print_xm_info(get_global_method_matchers(locus_re, matcher_re),\n name_re)\n print_xm_info(\n get_method_matchers_in_loci(\n [gdb.current_progspace()], locus_re, matcher_re),\n name_re)\n print_xm_info(\n get_method_matchers_in_loci(gdb.objfiles(), locus_re, matcher_re),\n name_re)\n\n\nclass EnableXMethod(gdb.Command):\n \"\"\"GDB command to enable a specified (group of) xmethod(s).\n\n Usage: enable xmethod [locus-regexp [name-regexp]]\n\n LOCUS-REGEXP is a regular expression matching the location of the\n xmethod matchers. If it is omitted, all registered xmethods matchers\n from all loci are enabled. A locus could be 'global', a regular expression\n matching the current program space's filename, or a regular expression\n matching filenames of objfiles. Locus could be 'progspace' to specify that\n only xmethods from the current progspace should be enabled.\n\n NAME-REGEXP is a regular expression matching the names of xmethods\n within a given locus. If this omitted for a specified locus, then all\n registered xmethod matchers in the locus are enabled. To enable only\n a certain xmethods managed by a single matcher, the name regexp can be\n specified as matcher-name-regexp;xmethod-name-regexp.\n \"\"\"\n\n def __init__(self):\n super(EnableXMethod, self).__init__(\"enable xmethod\",\n gdb.COMMAND_DATA)\n\n def invoke(self, arg, from_tty):\n set_xm_status(arg, True)\n\n\nclass DisableXMethod(gdb.Command):\n \"\"\"GDB command to disable a specified (group of) xmethod(s).\n\n Usage: disable xmethod [locus-regexp [name-regexp]]\n\n LOCUS-REGEXP is a regular expression matching the location of the\n xmethod matchers. If it is omitted, all registered xmethod matchers\n from all loci are disabled. A locus could be 'global', a regular\n expression matching the current program space's filename, or a regular\n expression filenames of objfiles. Locus could be 'progspace' to specify\n that only xmethods from the current progspace should be disabled.\n\n NAME-REGEXP is a regular expression matching the names of xmethods\n within a given locus. If this omitted for a specified locus, then all\n registered xmethod matchers in the locus are disabled. To disable\n only a certain xmethods managed by a single matcher, the name regexp\n can be specified as matcher-name-regexp;xmethod-name-regexp.\n \"\"\"\n\n def __init__(self):\n super(DisableXMethod, self).__init__(\"disable xmethod\",\n gdb.COMMAND_DATA)\n\n def invoke(self, arg, from_tty):\n set_xm_status(arg, False)\n\n\ndef register_xmethod_commands():\n \"\"\"Installs the xmethod commands.\"\"\"\n InfoXMethod()\n EnableXMethod()\n DisableXMethod()\n\n\nregister_xmethod_commands()\n","repo_name":"kiwibrowser/src","sub_path":"third_party/android_ndk/prebuilt/linux-x86_64/share/gdb/python/gdb/command/xmethods.py","file_name":"xmethods.py","file_ext":"py","file_size_in_byte":9482,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"42839781806","text":"# Clock Angles\n\nimport re\n\n\ndef angles(times):\n total = 0\n pattern = re.compile(r\"([0-2][0-9]):([0-5][0-9])\")\n for time in times:\n match = pattern.match(time)\n if not match:\n total -= 100\n continue\n h, m = map(int, match.groups())\n if not (0 <= h < 24):\n total -= 100\n continue\n if not (0 <= m < 60):\n total -= 100\n continue\n\n h = (h % 12) + (m * (1 / 60))\n m = m / 5\n if h <= m:\n total += (m - h) * 30\n else:\n total += (12 - (h - m)) * 30\n return total\n\n\nimport pytest\n\n\ndef test():\n result = angles([\"12:00\", \"17:30\", \"blabla\", \"20:21\", \"26:88\"])\n assert result == pytest.approx(50.5)\n","repo_name":"stsewd/devsucodejam-2019","sub_path":"06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"72879388324","text":"import re\n\ntext = input().upper()\nword = input().upper()\n\nregex = r\"\\b\" + word + r\"\\b\"\npattern = re.compile(regex)\nmatches = re.finditer(pattern, text)\n\nresult = 0\nfor match in matches:\n result += 1\n\nprint(result)\n","repo_name":"Dan-Mihaylov/Software-Uni-Courses","sub_path":"Fundamentals/11_regex_exercises/03_find_occurrences_of_word_in_sentence.py","file_name":"03_find_occurrences_of_word_in_sentence.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1548071992","text":"import sqlite3\r\nfrom employee import Employee\r\n\r\nconn = sqlite3.connect(\"employee2.db\")\r\n\r\nc = conn.cursor()\r\n\r\n# c.execute(\"\"\"CREATE TABLE employee(first_name text, last_name text, pay integer)\"\"\")\r\n\r\ndef insert_emp(emp):\r\n with conn:\r\n c.execute(\"INSERT INTO employee VALUES (:first, :last, :pay)\", {'first': emp.first, 'last': emp.last, 'pay': emp.pay})\r\n\r\ndef get_emp_by_name(lastname):\r\n c.execute(\"SELECT * FROM employee WHERE last_name=:last\", {'last': lastname})\r\n return c.fetchall()\r\n\r\ndef update_pay(emp, pay):\r\n with conn:\r\n c.execute(\"\"\"UPDATE employee SET pay = :pay\r\n WHERE first_name = :first AND last_name = :last\"\"\",\r\n {'first': emp.first, 'last': emp.last, 'pay': pay})\r\n\r\ndef remove_emp(emp):\r\n with conn:\r\n c.execute(\"DELETE FROM employee WHERE first_name = :first AND last_name = :last\",\r\n {'first': emp.first, 'last': emp.last})\r\n\r\n\r\nemp_1 = Employee(\"Prakhar\", \"Kumar\", \"50000\")\r\nemp_2 = Employee(\"Yush\", \"Kumar\", \"60000\")\r\nemp_3 = Employee(\"Joe\", \"Doe\", \"70000\")\r\nemp_4 = Employee(\"Jane\", \"Doe\", \"80000\")\r\n\r\ninsert_emp(emp_1)\r\ninsert_emp(emp_2)\r\ninsert_emp(emp_3)\r\ninsert_emp(emp_4)\r\n\r\nemps = get_emp_by_name('Kumar')\r\nprint(emps)\r\n\r\nconn.close()","repo_name":"Pyk017/Python","sub_path":"SQLite/sqlite2.py","file_name":"sqlite2.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"33658392167","text":"from pynput.mouse import Button, Controller\nimport time\nmouse = Controller()\n\nfrom pynput import keyboard\n\ndef on_press(key):\n while True:\n mouse.click(Button.left, 1)\n time.sleep(1)\n if key == keyboard.Key.esc:\n break\n\n\ndef on_release(key):\n if key == keyboard.Key.shift_r:\n return False\n\n# Collect events until released\nwith keyboard.Listener(\n on_press=on_press,\n on_release=on_release) as listener:\n listener.join()\n","repo_name":"thomaslworley/python","sub_path":"autoclicker.py","file_name":"autoclicker.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6204730990","text":"from torch import nn\nimport torch\nimport torch.nn.functional as F\n\n\n# Simple LeAE that suppose Grad-CAM\nclass LeAE(nn.Module):\n def __init__(self):\n super(LeAE, self).__init__()\n\n self.conv1 = nn.Conv2d(1, 6, 5, stride=1, padding=2)\n self.pool1 = nn.AvgPool2d(2, 2)\n\n self.conv2 = nn.Conv2d(6, 16, 5, stride=1)\n self.pool2 = nn.AvgPool2d(2, 2)\n\n self.conv3 = nn.ConvTranspose2d(16, 16, 2, stride=2)\n self.conv4 = nn.ConvTranspose2d(16, 6, 5, stride=1)\n self.conv5 = nn.ConvTranspose2d(6, 1, 4, stride=2, padding=1)\n\n self.gradients = None\n\n def activation_hook(self, grad):\n self.gradients = grad\n\n def forward(self, x):\n res = dict()\n res['c1'] = F.relu(self.conv1(x))\n res['p1'] = self.pool1(res['c1'])\n res['c2'] = F.relu(self.conv2(res['p1']))\n res['c2'].register_hook(self.activation_hook)\n res['p2'] = self.pool2(res['c2'])\n\n res['c3'] = F.relu(self.conv3(res['p2']))\n res['c4'] = F.relu(self.conv4(res['c3']))\n res['rec'] = torch.tanh(self.conv5(res['c4']))\n return res\n\n def get_activations_gradient(self):\n return self.gradients\n\n\nclass LeClassifier(nn.Module):\n def __init__(self):\n super(LeClassifier, self).__init__()\n self.classifier = nn.Sequential(\n nn.Linear(400, 200),\n nn.ReLU(),\n nn.Linear(200, 100),\n nn.ReLU(),\n nn.Linear(100, 10)\n )\n\n def forward(self, x):\n return self.classifier(x)\n\n\nclass LeDiscriminator(nn.Module):\n def __init__(self):\n super(LeDiscriminator, self).__init__()\n self.net = nn.Sequential(\n nn.Conv2d(1, 64, 4, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(64, 128, 4, stride=2, padding=1),\n nn.InstanceNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 256, 4, stride=2, padding=1),\n nn.InstanceNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(256, 2, 3, stride=1)\n )\n\n self.gradient = None\n\n def activation_hook(self, grad):\n self.gradient = grad\n\n def forward(self, x):\n res = self.net(x)\n res.register_hook(self.activation_hook)\n return res.view(-1, 2)\n\n def get_activations_gradient(self):\n return self.gradient\n","repo_name":"voidstrike/Attension_Grad_CAM","sub_path":"model/LeAE.py","file_name":"LeAE.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42908296194","text":"from django.apps import apps\nCliente = apps.get_model('clients', 'Cliente')\n\ndef get_client_by_idfiscal(id_fiscal):\n try:\n client = Cliente.objects.get(ID_fiscal=id_fiscal)\n except Cliente.DoesNotExist:\n context = {\n 'error':True,\n 'message_error': \"Client doesn't exist. please Sign Up\"\n }\n else :\n context = {\n 'error':False,\n 'client': client\n }\n return context ","repo_name":"jhoncortez/django_heroku_project","sub_path":"authentication/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36885738674","text":"# Monte-Carlo Algorithm visualisation\n\n# Imports:\nimport os\nimport random\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport matplotlib.animation as animation\nimport csv\n\n\n# Functions:\ndef calc_pi(points):\n counter = 0\n total_points = points\n ratio = 0\n x = 0\n y = 0\n pi = 0\n\n for i in range(0, total_points):\n x = random.random()\n y = random.random()\n if x ** 2 + y ** 2 <= 1:\n counter += 1\n ratio = counter / total_points\n\n ratio = counter / total_points\n pi = ratio * 4\n return pi\n\n\ndef get_csv(amount_of_iterations):\n results = []\n for i in range(1, amount_of_iterations):\n results.append(calc_pi(i))\n\n np.savetxt('data10k.csv', results, delimiter=',')\n\n\ndef visualize_static():\n my_data = pd.read_csv('data.csv')\n plt.plot(my_data)\n pi = plt.axhline(y=3.14159)\n pi.set_color('red')\n plt.show()\n\nget_csv(10000)\n#visualize_static()\n","repo_name":"No1Cheats/MCA-visualisation","sub_path":"venv/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5080972905","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef selu(x, a =1.67326, l =1.0507):\n y_list = []\n for x in x:\n if x >= 0:\n y = l * x\n if x < 0:\n y = l * a * (np.exp(x) - 1)\n y_list.append(y)\n return y_list\n\n\nx = np.arange(-5, 5, 0.1)\ny = selu(x)\n\nplt.plot(x, y)\nplt.grid()\nplt.show()\n","repo_name":"jsja22/study","sub_path":"keras2/keras72_3_selu.py","file_name":"keras72_3_selu.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19659825848","text":"import marshmallow_dataclass as mad\nimport marshmallow as ma\n\n\nclass Scaffold:\n \"\"\"Common behavior shared between Sparrow and Blueprint\n \"\"\"\n\n @classmethod\n def _data_clz_to_schema(cls, data_clz, base_schema=ma.Schema):\n if issubclass(data_clz, ma.Schema) or isinstance(data_clz, ma.Schema):\n # data_clz is schema\n schema = data_clz\n else:\n # data_clz is object\n schema = mad.class_schema(data_clz, base_schema)\n return schema\n","repo_name":"Sparrow-Microservice/sparrow-flask","sub_path":"sparrow_flask/base/scaffold.py","file_name":"scaffold.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23910773754","text":"import nltk\r\n\r\nfrom nltk.corpus import stopwords\r\nimport pandas as pd\r\nstopwords_english = stopwords.words('english')\r\n\r\ndef format_sentence(sent):\r\n return ({word: True for word in nltk.word_tokenize(sent)})\r\nposdataset= pd.read_csv(\"Positive_words.csv\")\r\nnegdataset=[\"worst\",\"poor\",\"bad\",\"pathetic\",\"poor\"]\r\nflag=False\r\nreview=input(\"Enter the product review\")\r\nif(\"not\" in review):\r\n flag=True\r\nprint(review)\r\ndata=nltk.word_tokenize(review)\r\nprint(data)\r\n\r\nall_words_without_stopwords = [word for word in data if word not in stopwords_english]\r\nprint(all_words_without_stopwords)\r\nprocessedreview=\"\"\r\nfor word in all_words_without_stopwords:\r\n processedreview=processedreview+word+\" \"\r\nprint(processedreview)\r\n\r\npos=[]\r\nfor word in posdataset:\r\n pos.append([format_sentence(word), 'positive'])\r\nprint (pos)\r\n\r\nneg = []\r\nfor word in negdataset:\r\n neg.append([format_sentence(word), 'negative'])\r\nprint (neg)\r\n\r\ntraining = pos[:int((.8)*len(pos))] + neg[:int((.8)*len(neg))]\r\ntest = pos[int((.8)*len(pos)):] + neg[int((.8)*len(neg)):]\r\n\r\nfrom nltk.classify import NaiveBayesClassifier\r\nclassifier = NaiveBayesClassifier.train(training)\r\nclassifier.show_most_informative_features()\r\n\r\nresult=classifier.classify(format_sentence(processedreview))\r\n\r\nif(flag):\r\n if(result==\"positive\"):\r\n result=\"negative\"\r\n elif(result==\"negative\"):\r\n result=\"positive\"\r\n\r\nprint(\"The analysis of\",review,\" is \",result)\r\n\r\n# is of the on am was not for to of\r\n\r\n# good bad nice worst beautiful\r\n","repo_name":"rohit-kadam-hub/Embedded_internship","sub_path":"reviews_nltk.py","file_name":"reviews_nltk.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33994392001","text":"\"\"\"\n1000-digit Fibonacci number\nProblem 25\n\nThe Fibonacci sequence is defined by the recurrence relation:\n\n Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.\n\nHence the first 12 terms will be:\n\n F1 = 1\n F2 = 1\n F3 = 2\n F4 = 3\n F5 = 5\n F6 = 8\n F7 = 13\n F8 = 21\n F9 = 34\n F10 = 55\n F11 = 89\n F12 = 144\n\nThe 12th term, F12, is the first term to contain three digits.\n\nWhat is the index of the first term in the Fibonacci sequence to contain 1000 digits?\n\"\"\"\n\nfrom mathext import fibonacci_series\n\n\ndef attempt(*, limit=3):\n \"\"\"This straight forward attempt is useful up to approximately index 1000.\n Above this index, it tends to become annoyingly slow.\n\n The implementation builds on a generator enumerating all Fibonacci numbers to infinity.\n \"\"\"\n for index, f in enumerate(fibonacci_series(), 1):\n if not (len(str(f)) < limit):\n print('Solution =', index)\n break\n\n\nif __name__ == '__main__':\n import time\n start = time.time()\n attempt(limit=1000)\n print('Elapsed:', time.time() - start, 'seconds')\n\n# last line of code\n","repo_name":"techrabbit58/ProjectEuler","sub_path":"problem_0025.py","file_name":"problem_0025.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37170222315","text":"\"\"\"\n\"\"\"\nimport os\nimport csv\nimport io\nimport sys\nfrom pathlib import Path, PosixPath\nfrom contextlib import contextmanager\nimport subprocess as sp\nimport time\nimport gspread\nimport random\nimport logging\nimport logging.handlers\nfrom fnmatch import fnmatch\n\nlogger = logging.getLogger(__name__)\n\ndef init_logging(logfile):\n \"\"\"Sets up logging to logfile and log level, with a mirror of the output going to stderr\"\"\"\n\n # Format for logging to file\n formatter = logging.Formatter(fmt=\"{levelname:8} {asctime} {message}\", style='{')\n\n formatter.converter=time.gmtime\n formatter.default_msec_format = \"%s.%03d\"\n\n # Configure a file handler to write detailed information to the log file\n file_handler = logging.handlers.WatchedFileHandler(logfile)\n file_handler.setLevel(\"DEBUG\")\n file_handler.setFormatter(formatter)\n\n # Setup a basic formatter for output to stderr\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(\"INFO\")\n stream_handler.setFormatter(logging.Formatter())\n\n logging.basicConfig(handlers=[stream_handler, file_handler], force=True, level=\"DEBUG\")\n\ndef signal_proof_sleep(seconds):\n # I've noticed the time.sleep() function doesn't alway sleep as long as I want. My theory,\n # based on the docs, is that some network errors contacting S3/Google Drive cause a signal\n # which raises an exception. In any event this code make sure that the retries sleep for\n # the desired # of seconds.\n start_time = time.time()\n current_time = start_time\n while current_time < start_time + seconds:\n time.sleep(1)\n current_time = time.time()\n\n\ndef retry_gspread_call(func, retry_delays = [30, 60, 60, 90], retry_jitter=5):\n\n for i in range(len(retry_delays)+1):\n try:\n return func()\n except gspread.exceptions.APIError as e:\n if i == len(retry_delays):\n # We've passed the max # of retries, re-reaise the exception\n raise\n except:\n # an exception type we don't want to retry\n raise\n \n # A failure happened, sleep before retrying\n signal_proof_sleep(retry_delays[i] + random.randrange(1, retry_jitter+1))\n\n\n@contextmanager\ndef lock_workqueue(work_queue_file):\n \"\"\"\n Open the work queue with a file lock to prevent race conditions between pods running in parallel.\n This function can be used as a context manager, keeping the file locked within a \"with\" block.\n\n Args:\n work_queue_file(str or pathlib.Path): The full path to the work queue file.\n\n Returns:\n file-like object For the work queue file.\n\n \"\"\"\n fd = os.open(work_queue_file, os.O_RDWR)\n # The documentation is unclear if this can return -1 like the underlying C call, so I test for it\n if fd == -1:\n raise RuntimeError(\"Failed to open file\")\n\n # Lock the file\n os.lockf(fd, os.F_LOCK, 0)\n\n # Return a nice file like object to wrap the file descriptor\n file_object_wrapper = open(fd, \"r+\", closefd=False)\n try:\n yield file_object_wrapper\n finally:\n # Presumably the file object's close would also release the lock, but I didn't trust it so \n # I closed it and the file descriptor separately\n file_object_wrapper.close()\n os.close(fd)\n\n\ndef update_gsheet_status(args, dataset, status):\n # Note need to retry Google API calls due to rate limits\n source_spreadsheet, source_worksheet = args.gsheet.split('/')\n\n # Allow specifying the column to store status in in the worksheet name\n status_col = \"B\"\n if \"@\" in source_worksheet:\n source_worksheet, status_col = source_worksheet.split('@')\n\n # This relies on a service account json\n account = retry_gspread_call(lambda: gspread.service_account(filename=args.google_creds))\n\n # Get the spreadsheet from Google sheets\n spreadsheet = retry_gspread_call(lambda: account.open(source_spreadsheet))\n\n # Get the worksheet\n worksheet = retry_gspread_call(lambda: spreadsheet.worksheet(source_worksheet))\n\n work_queue = retry_gspread_call(lambda: worksheet.col_values(1))\n\n if len(work_queue) > 1:\n found = False\n for i in range(0, len(work_queue)):\n if work_queue[i].strip() == dataset:\n logger.info(f\"Updating {dataset} status with {status}\")\n retry_gspread_call(lambda: worksheet.update(f\"{status_col}{i+1}\", status))\n found = True\n break\n if not found:\n logger.error(args, f\"Did not find {dataset} to update status!\")\n else:\n logger.error(args, f\"Could not update {dataset}, spreadsheet is empty!\")\n\ndef claim_dataset(args, my_pod):\n\n dataset = None\n\n with lock_workqueue(args.work_queue) as wq_file:\n csv_reader = csv.reader(wq_file)\n rows = []\n found=False \n for row in csv_reader:\n rows.append(row)\n if not found and row[1] == 'IN QUEUE':\n row[1] = my_pod\n dataset = row[0]\n found = True\n\n if found:\n # Rewrite the work queue file with the new info\n wq_file.truncate(0)\n wq_file.seek(0,io.SEEK_SET)\n csv_writer = csv.writer(wq_file)\n csv_writer.writerows(rows)\n\n # Update the scorecard. This is done within the lock on the work queue\n # To prevent against race conditions accessing it\n update_gsheet_status(args, dataset, \"In Progress: \" + my_pod)\n logger.info(f\"Pod: {my_pod} has claimed dataset {dataset}\")\n else:\n logger.info(\"Work Queue is empty\")\n\n return dataset\n\ndef run_script(command, return_output=False, save_output=None, log_output=False):\n logger.debug(f\"Running: '{' '.join(command)}'\")\n\n if save_output is not None:\n with open(save_output, \"w\") as f:\n cp = sp.run(command, stdout=f, stderr=sp.STDOUT, encoding='UTF-8', errors='replace')\n\n elif return_output or log_output: \n cp = sp.run(command, stdout=sp.PIPE, stderr=sp.STDOUT, encoding='UTF-8', errors='replace')\n\n if cp.returncode == 0:\n if log_output:\n for line in cp.stdout.splitlines():\n logger.info(line)\n if return_output:\n return cp.stdout.splitlines()\n else:\n cp = sp.run(command)\n\n if cp.returncode != 0:\n if log_output:\n logger.error(f\"Failed to run {command[0]}, return code: {cp.returncode}.\")\n if cp.stdout is not None and len(cp.stdout) != 0:\n for line in cp.stdout.splitlines():\n logger.error(line)\n else:\n logger.error(f\"No output from {command[0]}\")\n \n raise RuntimeError(f\"Failed to run '{' '.join(command)}', return code: {cp.returncode}.\")\n\ndef update_dataset_status(args, dataset, status):\n\n with lock_workqueue(args.work_queue) as wq_file:\n csv_reader = csv.reader(wq_file)\n rows = []\n found=False \n for row in csv_reader:\n rows.append(row)\n if not found and row[0] == dataset:\n row[1] = status\n found = True\n\n if found:\n wq_file.truncate(0)\n wq_file.seek(0,io.SEEK_SET)\n csv_writer = csv.writer(wq_file)\n csv_writer.writerows(rows)\n\n try:\n update_gsheet_status(args, dataset, status)\n except Exception as e:\n logger.error(f\"Failed to update scorecard work queue status for {dataset}.\", exc_info=True)\n\nclass RClonePath():\n def __init__(self, rclone_conf, service, *path_components):\n self.service=service\n if service not in ['s3', 'gdrive']:\n raise ValueError(f\"Unknown service {service}\")\n self.rclone_config = rclone_conf\n\n self.path = Path(*path_components)\n\n def ls(self, recursive=False):\n paths_to_search = [self.path]\n combined_results = []\n while len(paths_to_search) != 0:\n path = paths_to_search.pop()\n results = run_script([\"rclone\", '--config', self.rclone_config, 'lsf', self.service + \":\" + str(path)], return_output=True)\n for result in results: \n if recursive and result.endswith(\"/\"):\n paths_to_search.append(path / result)\n combined_results.append(RClonePath(self.rclone_config, self.service, path, result))\n return combined_results\n\n def glob(self, pattern):\n return [rp for rp in self.ls(False) if fnmatch(rp.path.name, pattern)]\n\n def rglob(self, pattern):\n return [rp for rp in self.ls(True) if fnmatch(rp.path.name, pattern)]\n\n def _copy(self, source, dest):\n # Run rclone copy with nice looking progress\n run_script([\"rclone\", '--config', self.rclone_config, 'copy', '-P', '--stats-one-line', '--stats', '60s', '--stats-unit', 'bits', '--retries-sleep', '60s', str(source), str(dest)])\n\n def unlink(self):\n run_script([\"rclone\", '--config', self.rclone_config, 'delete', str(self)], log_output=True)\n\n def download(self, dest): \n logger.info(f\"Downloading {self} to {dest}\")\n self._copy(self, dest)\n\n def upload(self, source):\n logger.info(f\"Uploading {source} to {self}\")\n self._copy(source, self)\n\n def sync_from(self, path):\n logger.info(f\"Syncing {self} from {path}\")\n run_script([\"rclone\", '--config', self.rclone_config, 'sync', '-P', '--stats-one-line', '--stats', '60s', '--stats-unit', 'bits', str(path), str(self)], log_output=True) \n\n def __str__(self):\n return f\"{self.service}:{self.path}\"\n \n def __truediv__(self, other):\n if isinstance(other, RClonePath):\n if self.rclone_config != other.rclone_config:\n raise ValueError(\"Cannot combine rclone paths with different configurations.\")\n if self.service != other.service:\n raise ValueError(\"Cannot combine rclone paths from different services.\")\n\n return RClonePath(self.rclone_config, self.service, self.path, other.path)\n else:\n return RClonePath(self.rclone_config, self.service, self.path, other)\n\ndef backup_task_log(log_manager, backup_loc):\n # Cleanup the local task log\n try:\n log_manager.close()\n try:\n backup_loc.upload(log_manager.logfile)\n except Exception as e:\n logger.error(\"Failed to backup task logs\", exc_info=True)\n log_manager.clear()\n log_manager.open()\n except Exception as e:\n logger.error(\"Failed to clean up and re-initialize task logs.\", exc_info=True)\n # Treat an inability to access/clean up logs as fatal\n return\n\n\ndef run_task_on_queue(args, task):\n\n try:\n my_pod = os.environ[\"POD_NAME\"]\n logger.info(f\"Started on pod {my_pod} and python {sys.implementation}\")\n\n dataset = claim_dataset(args, my_pod)\n\n if args.adap_root_dir is not None:\n root_dir = Path(args.adap_root_dir)\n else:\n root_dir = Path(\".\")\n except Exception as e:\n logger.error(f\"Failed initializing.\", exc_info=True)\n return\n\n # Go through the queue and run the task on each dataset\n while dataset is not None:\n status = 'COMPLETE'\n\n # Run the task\n try:\n status = task(args, dataset)\n except Exception as e:\n logger.error(f\"Failed processing {dataset}.\", exc_info=True)\n status = f'FAILED on {my_pod}'\n\n try:\n update_dataset_status(args, dataset, status)\n except Exception as e:\n logger.error(f\"Failed to update dataset status for {dataset} to {status}.\", exc_info=True)\n \n\n # Done with this dataset, move to the next\n try:\n dataset = claim_dataset(args, my_pod)\n except Exception as e:\n logger.error(\"Failed to claim dataset.\", exc_info=True)\n dataset = None\n\n\"\"\"\ndef run_task_on_queue(args, task, source_loc, dest_loc, backup_loc, cleanup, log_backup_loc=None):\n\n try:\n log_manager = LogManager(args.logfile)\n\n if log_backup_loc is None:\n log_backup_loc = backup_loc\n\n my_pod = os.environ[\"POD_NAME\"]\n logger.info(f\"Started on pod {my_pod} and python {sys.implementation}\")\n\n dataset = claim_dataset(args, my_pod)\n\n if args.adap_root_dir is not None:\n root_dir = Path(args.adap_root_dir)\n else:\n root_dir = Path(\".\")\n except Exception as e:\n logger.error(f\"Failed initializing.\", exc_info=True)\n return\n\n # Go through the queue and run the task on each dataset\n while dataset is not None:\n status = 'COMPLETE'\n\n downloaded_paths = []\n # Download data the task may need\n try:\n if source_loc is not None:\n downloaded_paths = source_loc.download(dataset)\n \n except Exception as e:\n logger.error(f\"Failed downloading source data for {dataset}.\", exc_info=True)\n status = 'FAILED'\n\n # Run the task\n if status != 'FAILED':\n try:\n status = task(args, dataset)\n except Exception as e:\n logger.error(f\"Failed processing {dataset}.\", exc_info=True)\n status = 'FAILED'\n\n # Cleanup old results, if needed\n if cleanup and dest_loc is not None:\n try:\n # Cleanup results from an old run\n dest_loc.cleanup(dataset)\n except Exception as e:\n logger.error(f\"Failed to cleanup old results for dataset{dataset}.\", exc_info=True)\n\n # Upload any results. We do this regardless of status because partial results can help debug\n # failures\n try: \n if dest_loc is not None:\n dest_loc.upload(dataset)\n except Exception as e:\n logger.error(f\"Failed uploading results for {dataset}.\", exc_info=True)\n status = 'FAILED'\n\n # Backup results\n try: \n if backup_loc is not None:\n backup_loc.upload(dataset)\n except Exception as e:\n logger.error(f\"Failed backup up results for {dataset}.\", exc_info=True)\n if status != 'FAILED':\n status = \"WARNING\"\n\n try:\n update_dataset_status(args, dataset, status)\n except Exception as e:\n logger.error(f\"Failed to update dataset status for {dataset} to {status}.\", exc_info=True)\n \n # Cleanup locally before moving to the next dataset\n try:\n for local_path in downloaded_paths:\n shutil.rmtree(Path(root_dir) / local_path)\n except Exception as e:\n logger.error(f\"Failed to clean up local storage for {dataset}.\")\n\n # Cleanup the local task log\n try:\n log_manager.close()\n try:\n log_backup_loc.upload_file(log_manager.logfile, Path(dataset, \"complete\"))\n except Exception as e:\n logger.error(\"Failed to backup task logs\", exc_info=True)\n log_manager.clear()\n log_manager.open()\n except Exception as e:\n logger.error(\"Failed to clean up and re-initialize task logs.\", exc_info=True)\n # Treat an inability to access/clean up logs as fatal\n return\n\n # Done with this dataset, move to the next\n try:\n dataset = claim_dataset(args, my_pod)\n except Exception as e:\n logger.error(\"Failed to claim dataset.\", exc_info=True)\n dataset = None\n\"\"\"","repo_name":"pypeit/adap","sub_path":"scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72645068325","text":"from manim import *\n\nclass ProblemText(Tex):\n def __init__(self, text, color = '#DBC9B8', **kwargs):\n super().__init__(text, color=color, tex_environment=r'\\begin{tabular}{p{15 cm}}', **kwargs)\n\n @staticmethod\n def create_title(text, **kwargs):\n return ProblemText(text, **kwargs)\n\n @staticmethod\n def create_header(text, font_size = 40, color = '#337357', **kwargs):\n return ProblemText(text, font_size=font_size, color=color, **kwargs)\n\n @staticmethod\n def create_statement(text, font_size = 30, **kwargs):\n return ProblemText(text, font_size=font_size, **kwargs)\n\n @staticmethod\n def create_constraints_list(constraints, color='#DBC9B8', font_size = 25, dot_scale_factor = 1, buff = 0.25, **kwargs):\n bulleted_list = BulletedList(\n *[c for c in constraints],\n color=color,\n font_size=font_size,\n dot_scale_factor=dot_scale_factor,\n buff=buff\n )\n for bullet in bulleted_list:\n bullet.set_color(color)\n return bulleted_list\n\n @staticmethod\n def create_constraints_table(constraints, explanations, color = '#DBC9B8'):\n row_list = []\n for constraint, explanation in zip(constraints, explanations):\n row_list.append(\n [\n ProblemText.create_statement(constraint),\n ProblemText.create_statement(explanation, fill_opacity=0)\n ]\n )\n table = MobjectTable(row_list,\n col_labels=[ProblemText.create_header('Constraint'),\n ProblemText.create_header('Explanation/Conclusion')],\n include_outer_lines=True,\n line_config={'color': color, 'stroke_width': 1.5}).scale(0.75)\n return table\n\n @staticmethod\n def create_key_points_table(points, explanations, color = '#DBC9B8'):\n row_list = []\n for point, explanation in zip(points, explanations):\n row_list.append(\n [\n ProblemText.create_statement(point),\n ProblemText.create_statement(explanation, fill_opacity=0)\n ]\n )\n table = MobjectTable(row_list,\n col_labels=[ProblemText.create_header('Key Point'),\n ProblemText.create_header('Explanation/Conclusion')],\n include_outer_lines=True,\n line_config={'color': color, 'stroke_width': 1.5}).scale(0.75)\n return table","repo_name":"Brandon-Hubacher/Code-Curator","sub_path":"src/leetcode/problem_text.py","file_name":"problem_text.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71656326884","text":"def change10(N):\n ans = 0\n for i,n in enumerate(N[::-1]):\n ans += int(n)*8**i\n return ans\ndef change9(N):\n N = int(N)\n ans = \"\"\n for i in range(20,-1,-1):\n tmp = N//9**i\n N -= tmp*9**i\n if tmp == 8:\n tmp = 5\n ans += str(tmp)\n return ans\nN, K = map(int,input().split())\nN = str(N)\nfor _ in range(K):\n N = change10(N)\n N = change9(N)\nprint(int(N))\n","repo_name":"mitu24472/Atcoder","sub_path":"Typical90/067.py","file_name":"067.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31054082296","text":"from __future__ import annotations\nfrom datetime import date, datetime\nimport pandas as pd\nfrom typing import List\nfrom NNTrade.common.candle_col_name import OPEN, CLOSE, HIGH, LOW, VOLUME\n\nclass CandleDto:\n def __init__(self, \n date_open: date, \n open: float, \n high: float,\n low:float,\n close: float, \n volume):\n self.date_open = date_open\n self.open = open\n self.high = high\n self.low = low\n self.close = close\n self.volume = volume\n\n @staticmethod\n def from_df(df:pd.DataFrame)-> List[CandleDto]:\n tmp_df = df.copy()\n tmp_df.index.name = \"date_open\"\n tmp_df = tmp_df.reset_index()\n return [CandleDto(date_open = kwargs['date_open'].date(), \n open = kwargs[OPEN],\n close= kwargs[CLOSE],\n high = kwargs[HIGH],\n low = kwargs[LOW],\n volume= kwargs[VOLUME]\n ) for kwargs in tmp_df.to_dict(orient='records')]\n\n def __eq__(self, other) -> bool:\n if not isinstance(other, CandleDto):\n return False\n return self.date_open == other.date_open and \\\n self.open == other.open and \\\n self.high == other.high and \\\n self.low == other.low and \\\n self.close == other.close and \\\n self.volume == other.volume\n\n\n","repo_name":"NNTrade/Yahoo-stock-quote-loader-srv","sub_path":"src/dto/candleDto.py","file_name":"candleDto.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70102437926","text":"import pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\n\n# Read the CSV file into a Pandas DataFrame\ndf = pd.read_csv(\"news.csv\", header=0)\n\n# Create a TfidfVectorizer object\nvectorizer = TfidfVectorizer()\n\n# Transform the text column into a sparse matrix of term frequencies\nX = vectorizer.fit_transform(df[\"text\"])\n\n# Create a LogisticRegression model\nmodel = LogisticRegression()\n\n# Train the model on the features and labels\nmodel.fit(X, df[\"label\"])\n\nprint(\"Accuracy: \" + str(model.score(X, df['label'])))\n\n# Define a function to classify news\ndef classify_news(text):\n # Convert the text to a sparse matrix of term frequencies\n X_new = vectorizer.transform([text])\n\n # Make a prediction using the trained model\n prediction = model.predict(X_new)[0]\n\n # Return the prediction\n return prediction\n\n\n# Open the text file in read mode\nwith open(\"article_the_onion.txt\", \"r\") as f:\n article_text = f.read()\n print(\"The Onion article: \" + classify_news(article_text))\n\nwith open(\"article_usa_today.txt\", \"r\") as f:\n article_text = f.read()\n print(\"USA Today article: \" + classify_news(article_text))\n","repo_name":"dbroemme/news-classifier","sub_path":"news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41440508366","text":"\"\"\"SubCategories filters.\"\"\"\n\n# Django forms\nfrom django import forms\n\n# Django Filters\nimport django_filters\nfrom django_filters import CharFilter\n\n# Models\nfrom apps.inventories.models import Category, SubCategory\n\nclass SubCategoryFilter(django_filters.FilterSet):\n\t\"\"\"SubCategory filter class.\"\"\"\n\n\tname = CharFilter(\n\t\tfield_name='name', \n\t\tlookup_expr='icontains', \n\t\twidget=forms.TextInput(attrs={'class': 'form-control', \n\t\t\t'placeholder': 'Nombre'}),\n\t)\n\n\tcategory = CharFilter(\n\t\tlabel='Categoría', \n\t\tfield_name='category__name', \n\t\tlookup_expr='icontains', \n\t\twidget=forms.TextInput(attrs={'class': 'form-control', \n\t\t\t'placeholder': 'Categoria'}),\n\t)\n\n\tclass Meta:\n\t\tmodel = SubCategory\n\t\tfields = ('name', 'category')\n","repo_name":"jorgesaw/kstore","sub_path":"apps/inventories/filters/subcategories.py","file_name":"subcategories.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3407505080","text":"from __future__ import division, absolute_import\nimport hashlib\nfrom urllib.parse import urlencode\n\nfrom django import template\nfrom django.utils.safestring import mark_safe\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom .. import settings as wooey_settings\n\n\nclass Library(template.Library):\n simple_assignment_tag = template.Library.simple_tag\n\n\nregister = Library()\n\n\n@register.simple_tag\ndef get_user_favorite_count(user, app, model):\n from ..models import Favorite\n\n ctype = ContentType.objects.get(app_label=app, model=model)\n # Return the current total number for UI updates\n favorites_count = Favorite.objects.filter(content_type=ctype, user=user).count()\n return str(favorites_count)\n\n\n@register.simple_assignment_tag\ndef get_wooey_setting(name):\n return getattr(wooey_settings, name, \"\")\n\n\n@register.filter\ndef divide(value, arg):\n try:\n return float(value) / float(arg)\n except ZeroDivisionError:\n return None\n\n\n@register.filter\ndef endswith(value, arg):\n return str(value).endswith(arg)\n\n\n@register.filter\ndef valid_user(obj, user):\n from ..backend import utils\n\n valid = utils.valid_user(obj, user)\n return True if valid.get(\"valid\") else valid.get(\"display\")\n\n\n@register.filter\ndef complete_job(status):\n from ..models import WooeyJob\n from celery import states\n\n return status in (WooeyJob.COMPLETED, states.REVOKED)\n\n\n@register.filter\ndef numericalign(s):\n \"\"\"\n Takes an input string of \"number units\" splits it\n and outputs it with each half wrapped in 50% width\n span. Has the effect of centering numbers on the unit part.\n :param s:\n :return: s\n \"\"\"\n number, units = s.split()\n return mark_safe(\n '%s %s'\n % (number, units)\n )\n\n\n@register.filter\ndef app_model_id(obj):\n \"\"\"\n Returns a app-model-id string for a given object\n :param obj:\n :return:\n \"\"\"\n ct = ContentType.objects.get_for_model(obj)\n\n return \"%s-%s-%s\" % (ct.app_label, ct.model, obj.id)\n\n\n@register.filter\ndef concat(arg1, arg2):\n \"\"\"concatenate arg1 & arg2\"\"\"\n return str(arg1) + str(arg2)\n\n\nclass GravatarUrlNode(template.Node):\n def __init__(self, email, size):\n self.email = template.Variable(email)\n self.size = template.Variable(size)\n\n def render(self, context):\n try:\n email = self.email.resolve(context)\n except template.VariableDoesNotExist:\n return \"\"\n\n try:\n size = self.size.resolve(context)\n except template.VariableDoesNotExist:\n return \"\"\n\n url = (\n \"http://www.gravatar.com/avatar/\"\n + hashlib.md5(email.lower().encode()).hexdigest()\n + \"?\"\n )\n url += urlencode({\"s\": str(size)})\n\n return url\n\n\n@register.tag\ndef gravatar(parser, token):\n try:\n tag_name, email, size = token.split_contents()\n\n except ValueError:\n raise template.TemplateSyntaxError(\n \"%r tag requires email and size arguments\" % token.contents.split()[0]\n )\n\n return GravatarUrlNode(email, size)\n\n\n@register.filter\ndef get_range(value):\n return range(int(value))\n\n\n@register.simple_assignment_tag(takes_context=True)\ndef absolute_url(context, url):\n request = context[\"request\"]\n return request.build_absolute_uri(url)\n","repo_name":"wooey/Wooey","sub_path":"wooey/templatetags/wooey_tags.py","file_name":"wooey_tags.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","stars":2006,"dataset":"github-code","pt":"52"} +{"seq_id":"14832607399","text":"'''\npython -m finetune.inference -N t5_small -M t5-small\n'''\n\nimport json\nimport random\nimport numpy as np\nfrom tqdm import tqdm\nimport GPUtil\nfrom threading import Thread\nimport time\nimport argparse\nimport re\nimport wandb, os\nfrom collections import defaultdict\nimport statistics\nimport pandas as pd\nimport torch\nfrom torch.utils.data import Dataset, TensorDataset, DataLoader\nfrom transformers import T5Tokenizer\nfrom transformers import BartTokenizer\n\nfrom utils.handle_data import RAW_DIR, save_csv\nfrom finetune import FinetuneTransformer\n\nos.environ['WANDB_NOTEBOOK_NAME'] = 'FinetuneTransformer'\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\n# %%\n# load dataset\ndef clean_str(text):\n # Replace double quotes with single quotes\n # Remove non breaking spaces (\\u00A0), etc\n text = re.sub(r\"\\s+\", \" \", text)\n\n return text.strip()\n\n\ndef get_parallel_corpus(json_data, filetype='train'):\n # hash stories and sections\n story, answer, question = [], [], []\n for data in json_data:\n story.append(data['content'])\n answer.append(data['answer'])\n question.append(data['question'])\n \n return story, answer, question\n\n# Constrcut transformer input \ndef construct_transformer_input(story, answer, choice=1):\n inps = []\n if choice == 1:\n prefix = 'Generate question from answer and story: '\n suffix = ''\n elif choice == 2:\n prefix = 'Generate question: '\n suffix = ''\n elif choice == 3:\n prefix = ''\n suffix = ''\n elif choice == 4:\n prefix = 'Generate question from answer and story: '\n suffix = '\\nThe question is:'\n for stry, ans in zip(story, answer):\n transformer_input = prefix + '\\nThe answer is ' + ans + '\\nThe story is ' + stry + suffix\n inps.append(transformer_input)\n return inps\n\n# Constrcut transformer input \ndef construct_transformer_input_newer(story, answer, choice=1):\n inps = []\n if choice == 1:\n prefix = 'Generate question from answer and context: '\n suffix = ''\n elif choice == 2:\n prefix = 'Generate question: '\n suffix = ''\n elif choice == 3:\n prefix = ''\n suffix = ''\n elif choice == 4:\n prefix = 'Generate question from answer and context: '\n suffix = '\\nThe question is:'\n for stry, ans in zip(story, answer):\n transformer_input = prefix + '\\nAnswer: ' + ans + '\\nContext: ' + stry + suffix\n inps.append(transformer_input)\n return inps\n\n# Constrcut transformer input \ndef construct_transformer_input_old_vary(story, answer, choice=1):\n inps = []\n if choice == 1:\n prefix = 'Generate question from context and answer: '\n suffix = ''\n elif choice == 2:\n prefix = 'Generate question: '\n suffix = ''\n elif choice == 3:\n prefix = ''\n suffix = ''\n elif choice == 4:\n prefix = 'Generate question from context and answer: '\n suffix = '\\nThe question is:'\n for stry, ans in zip(story, answer):\n transformer_input = prefix + '\\nContext: ' + stry + '\\nAnswer: ' + ans + suffix\n inps.append(transformer_input)\n return inps\n\n\n\n# Tokenization\ndef get_transformer_encoding(tokenizer, transformer_inputs, question, source_len=1024, tar_len=128):\n # tokenizer = T5Tokenizer.from_pretrained(model_name)\n max_source_length, max_target_length = source_len, tar_len\n\n inp_encoding = tokenizer(transformer_inputs, padding='longest', \n max_length=max_source_length,\n truncation=True,\n return_tensors=\"pt\"\n )\n input_ids, attention_mask = inp_encoding.input_ids, inp_encoding.attention_mask\n\n target_encoding = tokenizer(question, padding='longest', \n max_length=max_target_length,\n truncation=True,\n return_tensors=\"pt\"\n )\n labels = target_encoding.input_ids\n # 0 loss for pad tokens\n labels[labels == tokenizer.pad_token_id] = -100\n return input_ids, attention_mask, labels\n\nclass FairyDataset(Dataset):\n def __init__(self, input_ids, attn_masks, labels):\n self.input_ids = input_ids\n self.attn_masks = attn_masks\n self.labels = labels\n \n def __getitem__(self, index):\n x = self.input_ids[index]\n y = self.attn_masks[index]\n z = self.labels[index]\n \n return {'input_ids': x, 'attention_mask': y, 'labels':z}\n \n def __len__(self):\n return len(self.input_ids)\n\ndef get_dataloader(batch_size, dataset, datatype='train'):\n if type == 'train':\n return DataLoader(dataset=dataset, shuffle=True, batch_size = batch_size)\n else:\n return DataLoader(dataset=dataset, batch_size = batch_size)\n\n# Generate from saved model\ndef get_generation(model, val_dataloader, force_words_ids, decoding_strategy='B', num_beams=3, prob_p=0.9, temp=1, K=6, alpha=0.6, num_samples=10):\n val_outputs = []\n for batch in tqdm(val_dataloader):\n val_input_ids = batch['input_ids'].to(device)\n # TODO: Force ? to occur in the sentence\n if decoding_strategy == 'B': # Beam search\n generation = model.generate(val_input_ids, force_words_ids=force_words_ids, \n num_beams = num_beams, temperature=temp,\n max_new_tokens=64)\n elif decoding_strategy == 'N': # Nucleus Sampling\n generation = model.generate(val_input_ids, do_sample=True, max_new_tokens=64,\n top_p=prob_p, temperature=temp,\n num_return_sequences=num_samples)\n elif decoding_strategy == 'C': # Contrastive Decoding\n generation = model.generate(val_input_ids, do_sample=True, max_new_tokens=64,\n penalty_alpha=alpha, top_k=K,\n num_return_sequences=num_samples)\n\n else:\n generation = model.generate(val_input_ids, temperature=temp, max_new_tokens=64)\n for gen in generation:\n val_outputs.append(gen)\n return val_outputs\n\ndef get_preds(tokenizer, generated_tokens):\n # tokenizer = T5Tokenizer.from_pretrained(model_name)\n val_preds = []\n for inp in generated_tokens:\n sample = tokenizer.decode(inp, skip_special_tokens=True)\n val_preds.append(sample)\n return val_preds\n\nclass Monitor(Thread):\n def __init__(self, delay):\n super(Monitor, self).__init__()\n self.stopped = False\n self.delay = delay # Time between calls to GPUtil\n self.start()\n\n def run(self):\n while not self.stopped:\n GPUtil.showUtilization()\n time.sleep(self.delay)\n\n def stop(self):\n self.stopped = True\n\ndef set_seed(seed_val = 37):\n # setting the seed\n random.seed(seed_val)\n np.random.seed(seed_val)\n torch.manual_seed(seed_val)\n torch.cuda.manual_seed_all(seed_val)\n\ndef add_params():\n parser = argparse.ArgumentParser()\n parser.add_argument('-TGU', '--track_gpu_usage', action=argparse.BooleanOptionalAction, help='Track GPU Usage')\n parser.add_argument('-AVG', '--average_decoding', action=argparse.BooleanOptionalAction, help='Average Decoding')\n parser.add_argument('-Fold', '--fold_decoding', action=argparse.BooleanOptionalAction, help='Average Decoding')\n parser.add_argument('-FN', '--fold_number', type=int, default=0, help='Fold Number of validation set')\n parser.add_argument(\"-EFN\", \"--eval_filename\", type=str, default=\"test.json\", help=\"Evaluation filename\")\n parser.add_argument(\"-F\", \"--eval_folder\", type=str, default=\"FairytaleQA\", help=\"Evaluation Folder where output is saved (testset for testing on test set)\")\n parser.add_argument(\"-CF\", \"--checkpoint_folder\", type=str, default=\"Checkpoints_org\", help=\"Folder where the checkpoint is stored\")\n parser.add_argument(\"-B\", \"--batch_size\", type=int, default=8, help=\"Batch size for passing through the Transformer Model\")\n parser.add_argument(\"-MT\", \"--model_type\", type=str, default=\"t\", help=\"T for T5 and B for BART\")\n parser.add_argument(\"-MN\", \"--model_name\", default=\"t5-small\", help=\"Variant of the Transformer model for finetuning\")\n parser.add_argument(\"-N\", \"--run_name\", type=str, default=\"t5-small\", help=\"Name of the Run (Used in storing the model)\")\n parser.add_argument('-DS', '--decoding_strategy', type=str, default=\"G\", help='Specify the decoding strategy (B-Beam Search, N-Nucleus sampling, C - Contrsative, G-Greedy)')\n parser.add_argument(\"-PS\", \"--p_sampling\", type=float, default=0.9, help=\"Value of P used in the P-sampling\")\n parser.add_argument(\"-T\", \"--temperature\", type=float, default=1, help=\"Temperature for softmax decoding\")\n parser.add_argument(\"-K\", \"--top_K\", type=int, default=4, help=\"Value of K used for contrastive decoding\")\n parser.add_argument(\"-alpha\", \"--alpha\", type=float, default=0.6, help=\"Value of alpha used for contrastive decoding\")\n parser.add_argument(\"-NS\", \"--num_of_samples\", type=int, default=10, help=\"Number of samples to generate when using sampling\")\n parser.add_argument('-NB', '--num_of_beams', type=int, default=3, help=\"Number of beams for decoding\")\n parser.add_argument(\"-PC\", \"--prefix_choice\", type=int, default=1, help=\"Choice of prefix used for the input construction - 1, 2, 3\")\n params = parser.parse_args()\n \n return params\n\n# %%\nif __name__=='__main__':\n set_seed(seed_val = 37)\n\n args = add_params()\n\n test_file = os.path.join('./data', args.eval_folder, args.eval_filename)\n \n test_data = []\n with open(test_file, 'r') as infile:\n for i, line in enumerate(infile):\n json_dict = json.loads(line)\n json_dict['pairID'] = i+1\n test_data.append(json_dict)\n\n test_story, test_answer, test_question = get_parallel_corpus(test_data)\n\n # %%\n test_inps = construct_transformer_input_old_vary(test_story, test_answer, args.prefix_choice)\n\n if args.model_type == 'T':\n tokenizer = T5Tokenizer.from_pretrained(args.model_name)\n elif args.model_type == 'B':\n tokenizer = BartTokenizer.from_pretrained(args.model_name)\n else:\n print('Wrong model type - either T or B only')\n\n # %%\n test_input_ids, test_attention_mask, test_labels = get_transformer_encoding(tokenizer, test_inps, test_question)\n print('Tokenized Data!')\n\n # %%\n test_dataset = FairyDataset(test_input_ids, test_attention_mask, test_labels)\n print('Created Pytorch Dataset')\n\n # %%\n batch_size = args.batch_size\n test_dataloader = get_dataloader(batch_size, test_dataset, datatype='val')\n print('Loaded Dataloader!')\n\n # %%\n # Load the Generative Head \n # search for ckpt file\n search_dir = os.path.join('./finetune', args.checkpoint_folder, args.run_name)\n for file in os.listdir(search_dir):\n name, ext = os.path.splitext(file)\n if ext == '.ckpt':\n ckpt_file = os.path.join(search_dir, file)\n\n print('ckpt_file', ckpt_file)\n # model_pl = FinetuneTransformer(model_type = args.model_type, model_name = args.model_name)\n model = FinetuneTransformer.load_from_checkpoint(ckpt_file, model_type = args.model_type).model.to(device)\n print('Successfully loaded the saved checkpoint!')\n\n force_tokens = ['?']\n force_words_ids = tokenizer(force_tokens, add_special_tokens=False).input_ids\n\n # NOTE: Track GPU Utilization\n if args.track_gpu_usage:\n print('Tracking GPU Usage')\n monitor = Monitor(10)\n\n print('Begining Generation')\n val_outputs = get_generation(model, test_dataloader, force_words_ids, \n args.decoding_strategy, args.num_of_beams, \n args.p_sampling, args.temperature, \n args.top_K, args.alpha,\n args.num_of_samples)\n print('Done Generating!')\n\n print('Begining Decoding')\n val_preds = get_preds(tokenizer, val_outputs)\n print('Done Decoding!')\n\n val_df = pd.DataFrame(test_data)\n\n # NOTE: Saving val_preds\n if args.decoding_strategy == 'N':\n times = [args.num_of_samples for _ in range(len(val_df))]\n new_val_df = val_df.loc[val_df.index.repeat(times)].reset_index(drop=True)\n save_csv_name = 'nucleus_{:s}_{:.2f}_{:.2f}_{:d}'.format(args.run_name, args.p_sampling, args.temperature, args.num_of_samples)\n elif args.decoding_strategy == 'C':\n times = [args.num_of_samples for _ in range(len(val_df))]\n new_val_df = val_df.loc[val_df.index.repeat(times)].reset_index(drop=True)\n save_csv_name = 'contrastive_{:s}_{:d}_{:.2f}_{:d}'.format(args.run_name, args.top_K, args.alpha, args.num_of_samples)\n else:\n new_val_df = val_df\n save_csv_name = args.run_name\n\n # add generated question\n new_val_df['generated_question'] = val_preds\n\n output_path = os.path.join(RAW_DIR, \"results_org\")\n if args.eval_filename != 'test.json':\n save_csv_name = args.eval_filename.split('.')[0] + '_' + save_csv_name\n save_csv(new_val_df, save_csv_name, output_path)","repo_name":"umass-ml4ed/question-gen-aug-ranking","sub_path":"finetune/inference_org.py","file_name":"inference_org.py","file_ext":"py","file_size_in_byte":13250,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"21333481984","text":"import os as real_os\nimport mock\nfrom nose.tools import ok_, eq_, raises\n\nimport forge\nfrom forge import tests\nfrom forge import main, defaults\nfrom os import path\n\n@mock.patch('forge.main._setup_logging_to_stdout')\n@mock.patch('forge.main._setup_error_logging_to_file')\n@mock.patch('forge.main.logging')\ndef _logging_test(settings, level, logging, _setup_error_logging_to_file, _setup_logging_to_stdout):\n\tmain.setup_logging(settings)\n\n\t_setup_error_logging_to_file.assert_called_once_with()\n\t_setup_logging_to_stdout.assert_called_once_with(getattr(logging, level))\n\ndef test_verbose():\n\tsettings = dict(verbose = True)\n\t_logging_test(settings, 'DEBUG')\ndef test_quiet():\n\tsettings = dict(quiet = True)\n\t_logging_test(settings, 'WARNING')\ndef test_default():\n\tsettings = dict()\n\t_logging_test(settings, 'INFO')\n@raises(main.ArgumentError)\ndef test_both():\n\tsettings = dict(quiet = True, verbose = True)\n\t_logging_test(settings, 'DEBUG')\n\ngeneral_argparse = [\n\t(('-v', '--verbose'), {'action': 'store_true'}),\n\t(('-q', '--quiet'), {'action': 'store_true'}),\n\t(('--username', ), {'help': 'username used to login to the forge website'}),\n\t(('--password', ), {'help': 'password used to login to the forge website'}),\n]\n\nclass TestCreate(object):\n\t@mock.patch('forge.main.development_build')\n\t@mock.patch('forge.main.build_config')\n\t@mock.patch('forge.main.os')\n\t@mock.patch('forge.main.Remote')\n\t@mock.patch('forge.main.argparse')\n\t@mock.patch('forge.main.async.current_call')\n\tdef test_normal(self, current_call, argparse, Remote, mock_os,\n\t\t\tbuild_config, development_build):\n\t\tmock_os.sep = real_os.sep\n\t\tparser = argparse.ArgumentParser.return_value\n\t\tparser.parse_args.return_value.name = None\n\n\t\tmock_os.path.exists.return_value = False\n\n\t\tcall = current_call.return_value\n\t\tinput = 'user input'\n\t\tcall.wait_for_response.return_value = {'data': {'name': input}}\n\n\t\tremote = Remote.return_value\n\t\tbuild_config.load.return_value = tests.dummy_config()\n\n\t\tmain.create([])\n\n\t\tmock_os.path.exists.assert_called_once_with(defaults.SRC_DIR)\n\t\tremote.create.assert_called_once_with(input)\n\t\tremote.fetch_initial.assert_called_once_with(remote.create.return_value)\n\t\tdevelopment_build.assert_called_once_with([])\n\n\t@mock.patch('forge.main.os')\n\t@mock.patch('forge.main.Remote')\n\t@mock.patch('forge.main.argparse')\n\t@raises(forge.ForgeError)\n\tdef test_user_dir_there(self, argparse, Remote, mock_os):\n\t\tmock_os.sep = real_os.sep\n\t\tparser = argparse.ArgumentParser.return_value\n\t\tmock_os.path.exists.return_value = True\n\t\tmock_raw_input = mock.MagicMock()\n\t\tmock_raw_input.return_value = 'user input'\n\t\tremote = Remote.return_value\n\n\t\twith mock.patch('__builtin__.raw_input', new=mock_raw_input):\n\t\t\tmain.create([])\n\nclass TestRun(object):\n\t@mock.patch('forge.main.forge_build')\n\t@mock.patch('forge.main._assert_have_development_folder')\n\t@mock.patch('forge.main._assert_have_target_folder')\n\t@mock.patch('forge.main._assert_outside_of_forge_root', new=mock.Mock())\n\tdef test_not_android(self, _assert_have_target_folder, _assert_have_development_folder, build):\n\t\tmain.handle_secondary_options('run', ['firefox'])\n\t\tmain.run([])\n\n\t\tgenerate_dynamic = build.import_generate_dynamic.return_value\n\t\tgenerate_dynamic.customer_goals.run_app.assert_called_once()\n\nclass Test_AssertNotSubdirectoryOfForgeRoot(object):\n\t@raises(main.RunningInForgeRoot)\n\tdef test_raises_in_subdirectory(self):\n\t\tgetcwd = path.join(defaults.FORGE_ROOT, 'dummy')\n\t\tmain._assert_not_in_subdirectory_of_forge_root(getcwd)\n\n\tdef test_not_confused_by_similar_directory(self):\n\t\tgetcwd = path.join(defaults.FORGE_ROOT + '-app', 'dummy')\n\t\tmain._assert_not_in_subdirectory_of_forge_root(getcwd)\n\n\tdef test_ok_when_not_in_subdirectory(self):\n\t\tgetcwd = path.join('not','forge','tools', 'dummy')\n\t\tmain._assert_not_in_subdirectory_of_forge_root(getcwd)\n\nclass Test_AssertOutsideOfForgeRoot(object):\n\t@raises(main.RunningInForgeRoot)\n\tdef test_raises_exception_inside_forge_root(self):\n\t\tmain._assert_outside_of_forge_root(defaults.FORGE_ROOT)\n\n\tdef test_nothing_happens_outside_of_forge_root(self):\n\t\tmain._assert_outside_of_forge_root(path.join('some', 'other', 'dir'))\n\nclass TestBuild(object):\n\tdef _check_common_setup(self, parser, Remote):\n\t\tparser.parse_args.assert_called_once_with([])\n\t\targs = parser.parse_args.return_value\n\t\targs.quiet = False\n\t\tmain.setup_logging(args)\n\n\t\tRemote.assert_called_once_with(tests.dummy_config())\n\n\tdef _check_dev_setup(self, parser, Manager, Remote, Generate):\n\t\teq_(parser.add_argument.call_args_list,\n\t\t\t[\n\t\t\t\t(('-f', '--full'), {'action': 'store_true', 'help': 'Force a complete rebuild on the forge server'}),\n\t\t\t]\n\t\t)\n\n\t\tManager.assert_called_once_with(tests.dummy_config())\n\t\tGenerate.assert_called_once_with()\n\t\tself._check_common_setup(parser, Remote)\n\n\t@mock.patch('forge.main.build_config')\n\t@mock.patch('forge.main.os.path.isdir')\n\t@mock.patch('forge.main.argparse')\n\t@mock.patch('forge.main._assert_outside_of_forge_root', new=mock.Mock())\n\t@raises(forge.ForgeError)\n\tdef test_user_dir_not_there(self, argparse, isdir, build_config):\n\t\tisdir.return_value = False\n\t\tbuild_config.load.return_value = tests.dummy_config()\n\n\t\tmain.development_build([])\n\n\t\tisdir.assert_called_once_with(defaults.SRC_DIR)\n\t\tok_(not build_config.called)\n\n\n\t@mock.patch('forge.main.build_config')\n\t@mock.patch('forge.main.os.path.isdir')\n\t@mock.patch('forge.main.shutil')\n\t@mock.patch('forge.main.Generate')\n\t@mock.patch('forge.main.Remote')\n\t@mock.patch('forge.main.Manager')\n\t@mock.patch('forge.main.argparse')\n\t@mock.patch('forge.main._assert_outside_of_forge_root', new=mock.Mock())\n\tdef test_dev_no_conf_change(self, argparse, Manager, Remote, Generate, shutil, isdir, build_config):\n\t\tparser = argparse.ArgumentParser.return_value\n\t\targs = parser.parse_args.return_value\n\t\tManager.return_value.need_new_templates_for_config.return_value = False\n\t\tRemote.return_value.server_says_should_rebuild.return_value = dict(\n\t\t\tshould_rebuild = False,\n\t\t\treason = 'testing',\n\t\t\tstable_platform = 'v1.2',\n\t\t\tplatform_state = 'active',\n\t\t)\n\t\targs.full = False\n\t\tRemote.return_value._api_post.return_value = {\n\t\t\t\t\"config\": '{\"dummy_config\": true}',\n\t\t\t\t\"config_hash\": \"dummy config hash\",\n\t\t}\n\t\tbuild_config.load.return_value = tests.dummy_config()\n\t\tbuild_config.load_app.return_value = tests.dummy_app_config()\n\n\t\tmain.development_build([])\n\n\t\tManager.return_value.need_new_templates_for_config.assert_called_once_with()\n\t\teq_(shutil.rmtree.call_args_list, [\n\t\t\t(\n\t\t\t\t('development',),\n\t\t\t\t{'ignore_errors': True}\n\t\t\t),\n\t\t\t(\n\t\t\t\t(path.join('development', 'generate_dynamic'),),\n\t\t\t\t{'ignore_errors': True}\n\t\t\t)\n\t\t])\n\t\tshutil.copytree.assert_called_once_with(\".template\", \"development\")\n\t\tGenerate.return_value.all.assert_called_once_with('development',\n\t\t\t\tdefaults.SRC_DIR, extra_args=[],\n\t\t\t\tconfig={'config_hash': 'dummy config hash', u'dummy_config': True}\n\t\t)\n\n\t@mock.patch('forge.main.build_config')\n\t@mock.patch('forge.main.os.path.isdir')\n\t@mock.patch('forge.main.shutil')\n\t@mock.patch('forge.main.Generate')\n\t@mock.patch('forge.main.Remote')\n\t@mock.patch('forge.main.Manager')\n\t@mock.patch('forge.main.argparse')\n\t@mock.patch('forge.main._assert_outside_of_forge_root', new=mock.Mock())\n\tdef test_dev_conf_change(self, argparse, Manager, Remote, Generate, shutil, isdir, build_config):\n\t\tparser = argparse.ArgumentParser.return_value\n\t\targs = parser.parse_args.return_value\n\t\targs.full = False\n\t\tManager.return_value.need_new_templates_for_config.return_value = True\n\t\tRemote.return_value.server_says_should_rebuild.return_value = dict(\n\t\t\tshould_rebuild = False,\n\t\t\treason = 'testing',\n\t\t\tstable_platform = 'v1.2',\n\t\t\tplatform_state = 'active',\n\t\t)\n\t\tRemote.return_value.build.return_value = {\"id\": -1}\n\t\tRemote.return_value._api_post.return_value = {\n\t\t\t\t\"config\": '{\"dummy_config\": true}',\n\t\t\t\t\"config_hash\": \"dummy config hash\",\n\t\t}\n\t\tisdir.return_value = True\n\t\tbuild_config.load.return_value = tests.dummy_config()\n\t\tbuild_config.load_app.return_value = tests.dummy_app_config()\n\n\t\tmain.development_build([])\n\n\t\tManager.return_value.need_new_templates_for_config.assert_called_once_with()\n\t\tRemote.return_value.build.assert_called_once_with(development=True,\n\t\t\t\ttemplate_only=True, config={'dummy_config': True})\n\t\tManager.return_value.fetch_template_apps_and_instructions.assert_called_once_with(Remote.return_value.build.return_value)\n\n\t\teq_(shutil.rmtree.call_args_list, [\n\t\t\t(\n\t\t\t\t('development',),\n\t\t\t\t{'ignore_errors': True}\n\t\t\t),\n\t\t\t(\n\t\t\t\t(path.join('development', 'generate_dynamic'),),\n\t\t\t\t{'ignore_errors': True}\n\t\t\t)\n\t\t])\n\t\tshutil.copytree.assert_called_once_with(\".template\", 'development')\n\t\tGenerate.return_value.all.assert_called_once_with('development',\n\t\t\t\tdefaults.SRC_DIR, extra_args=[],\n\t\t\t\tconfig={'config_hash': 'dummy config hash', 'dummy_config': True}\n\t\t)\n\nclass TestMain(object):\n\t@mock.patch('forge.main._dispatch_command')\n\t@mock.patch('forge.main.argparse')\n\tdef test_if_using_deprecated_command_then_should_warn(self, argparse, dispatch):\n\t\targs = mock.Mock()\n\t\targs.command = 'create'\n\t\targparse.ArgumentParser.return_value.parse_known_args.return_value = (args, [])\n\n\t\tlog = mock.Mock()\n\t\twith mock.patch('forge.main.LOG', new=log):\n\t\t\tmain._using_deprecated_command('wm-create', 'forge create')\n\t\t\tmain.main()\n\t\tlog.warning.assert_called_with(\"Using wm-create which is now deprecated and will eventually be unsupported, instead, please use: 'forge create'\\n\\n\")\n","repo_name":"mobilipia/build-tools","sub_path":"forge/tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":9395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5932400855","text":"\"\"\"\nGiven two binary strings, return their sum\nhttps://leetcode.com/problems/add-binary/description/\n\"\"\"\n\n\ndef sum_of_binary(a, b):\n if a == '' or a == '0':\n return b\n if b == '' or b == '0':\n return a\n\n sum_value = ''\n last_a, last_b = len(a)-1, len(b)-1\n carry = 0\n\n while last_a >= 0 or last_b >= 0 or carry != 0:\n if last_a >= 0:\n carry += eval(a[last_a] + '-0') # or int(a[last_a])\n if last_b >= 0:\n carry += eval(b[last_b] + '-0') # or int(b[last_b])\n\n sum_value = str(carry % 2) + sum_value\n carry //= 2\n last_a -= 1\n last_b -= 1\n\n return sum_value\n\n\nif __name__ == \"__main__\":\n a = '111'\n b = '1011'\n print(sum_of_binary(a, b))\n","repo_name":"ravikailash/leetcode_solutions","sub_path":"add_binary_string.py","file_name":"add_binary_string.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34672280158","text":"from cmu_112_graphics import * #graphics package taken from class\nimport math, copy, random, projectionOperationsWithDrag, worldElements, BoidTest \n#from 15112 class website https://www.cs.cmu.edu/~112/notes/notes-graphics.html\n\ndef rgbString(r, g, b):\n return f'#{r:02x}{g:02x}{b:02x}'\n\ndef drawBackGround(canvas, app):\n r = 1\n b = 2*math.pi/600\n time = 50*math.cos(b*app.time)+50\n g = int(2.18804*time)\n b = int(2.18804*time + 35.15009)\n color = rgbString(r,g,b)\n canvas.create_rectangle(0,0, app.width, app.height, fill = color)\n if app.time != 0 and (app.time-200)%600 < 150: \n drawStars(canvas, app)\n\ndef drawStars(canvas, app):\n for star in app.stars:\n x, y= star[0], star[1]\n size = random.randrange(7, 21, 1)\n pixel = size/7\n hx1, hx2, hy1, hy2 = x-(size/2), x+(size/2), y-(pixel/2), y+(pixel/2)\n sx1, sx2, sy1, sy2 = x-(pixel*3/2), x+(pixel*3/2), y-(pixel*3/2), y+(pixel*3/2)\n vx1 = x-(pixel/2)\n vx2 = x+(pixel/2)\n vy1 = y-(pixel*9/2)\n vy2 = y+(pixel*9/2)\n canvas.create_rectangle(hx1, hy1, hx2, hy2, fill = \"white\", width = 0)\n canvas.create_rectangle(sx1, sy1, sx2, sy2, fill = \"white\", width = 0)\n canvas.create_rectangle(vx1, vy1, vx2, vy2, fill = \"white\", width = 0) \n\nclass Cloud(object):\n def __init__(self, x, y, size, color, smallSize, midSize):\n self.x = x\n self.y = y\n self.size = size\n self.color = color\n self.smallSize = smallSize\n self.midSize = midSize\n\n def drawCloud(self, canvas, app):\n #Big rect\n x, y = self.x, self.y\n size, smallSize, midSize = self.size, self.smallSize, self.midSize\n\n bx2, by2 = x+size, y+size\n #little left rectangle\n sx1, sy1 = x-smallSize, y+size-smallSize\n sx2, sy2 = x, by2\n #middle sized right rectangle\n mx1, my1 = bx2, y+size-midSize\n mx2, my2 = bx2+midSize, by2\n canvas.create_rectangle(x, y, bx2, by2, fill = self.color, width = 0)\n canvas.create_rectangle(sx1, sy1, sx2, sy2, fill = self.color, width = 0)\n canvas.create_rectangle(mx1, my1, mx2, my2, fill = self.color, width = 0) \n\n\n\n\n ","repo_name":"sophie006liu/15112finalProject","sub_path":"15112 Hw/DayNight.py","file_name":"DayNight.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74382695205","text":"import random\n\n\n\ndef play_game(\n p1_name: str,\n p2_name: str,\n p1_type: str = \"human\",\n p2_type: str = \"engine\",\n randomize_colors: bool = False,\n):\n \"\"\"Играем игру.\"\"\"\n if randomize_colors and random.random() < 0.5:\n p1_name, p1_type, p2_name, p2_type = p2_name, p2_type, p1_name, p1_type\n\n if p1_type == \"engine\":\n p1 = Eng\n\n\ndef main():\n ...\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Yamp/chess_explorer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37228772855","text":"from channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nfrom django.urls import re_path\nfrom core import consumers\n\nwebsocket_urlpatterns = [\n re_path(r'ws/notification$', consumers.NotificationConsumer),\n]\n\napplication = ProtocolTypeRouter({\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n websocket_urlpatterns\n )\n ),\n})","repo_name":"vhkreddy/server","sub_path":"adminserver/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71996051686","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nimport tensorflow as tf\n\nfrom tfsnippet.utils import (get_variables_as_dict,\n reopen_variable_scope,\n root_variable_scope,\n VarScopeObject,\n instance_reuse,\n is_tensorflow_version_higher_or_equal)\nfrom tests.helper import TestCase\n\n\nclass _VarScopeTestMixin:\n\n def _check_ns(self, ns, ns_name, op_name):\n self.assertEqual(ns, ns_name)\n self.assertEqual(tf.add(1, 2, name='op').name, op_name)\n\n def _check_vs(self, get_var_name, vs_name, vs_scope, var_name, op_name):\n vs = tf.get_variable_scope()\n self.assertEqual(vs.name, vs_name)\n self.assertEqual(vs.original_name_scope, vs_scope)\n self.assertEqual(tf.get_variable(get_var_name, shape=()).name, var_name)\n self.assertEqual(tf.add(1, 2, name='op').name, op_name)\n\n\nclass TensorFlowScopeTestCase(TestCase, _VarScopeTestMixin):\n\n def test_name_scope(self):\n with tf.name_scope(None) as root:\n self._check_ns(root, '', 'op:0')\n\n with tf.name_scope('a') as a:\n self._check_ns(a, 'a/', 'a/op:0')\n with tf.name_scope('') as ns:\n self._check_ns(ns, '', 'op_1:0')\n with tf.name_scope('a') as ns:\n self._check_ns(ns, 'a_1/', 'a_1/op:0')\n\n with tf.name_scope('b/c') as ns:\n self._check_ns(ns, 'b/c/', 'b/c/op:0')\n\n with tf.name_scope('b') as ns:\n self._check_ns(ns, 'b/', 'b/op:0')\n with tf.name_scope('c') as ns:\n self._check_ns(ns, 'b/c_1/', 'b/c_1/op:0')\n\n with tf.name_scope('b') as ns:\n self._check_ns(ns, 'b_1/', 'b_1/op:0')\n\n def test_variable_scope(self):\n root = tf.get_variable_scope()\n\n with tf.variable_scope(''):\n self._check_vs('v0', '', '', 'v0:0', 'op:0')\n\n with tf.variable_scope('a') as a:\n self._check_vs('v1', 'a', 'a/', 'a/v1:0', 'a/op:0')\n\n with tf.variable_scope('b'):\n self._check_vs('v2', 'a/b', 'a/b/', 'a/b/v2:0', 'a/b/op:0')\n\n with tf.variable_scope(a):\n # having the name scope 'a/b/a' is an absurd behavior\n # of `tf.variable_scope`, which we may not agree but\n # have to follow.\n self._check_vs('v3', 'a', 'a/', 'a/v3:0', 'a/b/a/op:0')\n\n with tf.variable_scope('b'):\n self._check_vs('v5', 'a/b', 'a/b_1/', 'a/b/v5:0',\n 'a/b_1/op:0')\n\n with tf.variable_scope('a/b'):\n self._check_vs('v9', 'a/b', 'a/b_2/', 'a/b/v9:0',\n 'a/b_2/op:0')\n\n with tf.variable_scope('a'):\n self._check_vs('v6', 'a', 'a_1/', 'a/v6:0', 'a_1/op:0')\n\n with tf.variable_scope('b'):\n self._check_vs('v7', 'a/b', 'a_1/b/', 'a/b/v7:0',\n 'a_1/b/op:0')\n\n with tf.variable_scope(None, default_name='b'):\n self._check_vs('v8', 'a/b_1', 'a_1/b_1/', 'a/b_1/v8:0',\n 'a_1/b_1/op:0')\n\n with tf.variable_scope(a):\n self._check_vs('v9', 'a', 'a/', 'a/v9:0', 'a_2/op:0')\n\n # test return to root scope\n with tf.variable_scope(root):\n self._check_vs('v10', '', '', 'v10:0', 'a_2/op_1:0')\n\n def test_reuse(self):\n root = tf.get_variable_scope()\n self.assertFalse(root.reuse)\n\n with tf.variable_scope('a', reuse=True) as a:\n self.assertTrue(a.reuse)\n\n with tf.variable_scope('b') as b:\n self.assertTrue(b.reuse)\n\n # TensorFlow >= 1.1.0 does not allow to cancel reuse flag\n if is_tensorflow_version_higher_or_equal('1.1.0'):\n with tf.variable_scope('b', reuse=False) as vs:\n self.assertTrue(vs.reuse)\n\n with tf.variable_scope(b, reuse=False) as vs:\n self.assertTrue(vs.reuse)\n\n # Reopen a stored variable scope will restore its reuse flag.\n with tf.variable_scope(root) as vs:\n self.assertFalse(vs.reuse)\n\n\nclass ReopenVariableScopeTestCase(TestCase, _VarScopeTestMixin):\n\n def test_basic(self):\n root = tf.get_variable_scope()\n\n with tf.variable_scope('a') as a:\n self._check_vs('v1', 'a', 'a/', 'a/v1:0', 'a/op:0')\n\n with reopen_variable_scope(root):\n self._check_vs('v2', '', '', 'v2:0', 'op:0')\n\n with reopen_variable_scope(a):\n self._check_vs('v3', 'a', 'a/', 'a/v3:0', 'a/op_1:0')\n\n with tf.variable_scope('a/b') as b:\n self._check_vs('v4', 'a/b', 'a/b/', 'a/b/v4:0', 'a/b/op:0')\n\n with reopen_variable_scope(root):\n self._check_vs('v5', '', '', 'v5:0', 'op_1:0')\n\n with reopen_variable_scope(a):\n self._check_vs('v6', 'a', 'a/', 'a/v6:0', 'a/op_2:0')\n\n with reopen_variable_scope(a):\n self._check_vs('v7', 'a', 'a/', 'a/v7:0', 'a/op_3:0')\n\n with reopen_variable_scope(b):\n self._check_vs('v8', 'a/b', 'a/b/', 'a/b/v8:0', 'a/b/op_1:0')\n\n\nclass RootVariableScopeTestCase(TestCase, _VarScopeTestMixin):\n\n def test_root_variable_scope(self):\n with root_variable_scope() as root:\n self._check_vs('v1', '', '', 'v1:0', 'op:0')\n with tf.variable_scope('a'):\n self._check_vs('v2', 'a', 'a/', 'a/v2:0', 'a/op:0')\n\n with root_variable_scope():\n self._check_vs('v3', '', '', 'v3:0', 'op_1:0')\n\n self._check_vs('v4', 'a', 'a/', 'a/v4:0', 'a/op_1:0')\n\n with root_variable_scope():\n self._check_vs('v5', '', '', 'v5:0', 'op_2:0')\n\n with tf.variable_scope('b'):\n with tf.variable_scope(root):\n self._check_vs('v6', '', '', 'v6:0', 'b/op:0')\n\n\nclass VarScopeObjectTestCase(TestCase):\n\n def test_VarScopeObject(self):\n class _VarScopeObject(VarScopeObject):\n @instance_reuse\n def f(self):\n return tf.get_variable('var', shape=()), tf.add(1, 2, name='op')\n\n o1 = _VarScopeObject(name='o')\n self.assertEqual(o1.name, 'o')\n self.assertEqual(o1.variable_scope.name, 'o')\n self.assertEqual(o1.variable_scope.original_name_scope, 'o/')\n var_1, op_1 = o1.f()\n self.assertEqual(var_1.name, 'o/f/var:0')\n self.assertEqual(op_1.name, 'o/f/op:0')\n\n with tf.variable_scope('child'):\n var_child, op_child = o1.f()\n self.assertIs(var_child, var_1)\n self.assertEqual(var_child.name, 'o/f/var:0')\n self.assertEqual(op_child.name, 'o/f_1/op:0')\n\n # test the second object with the same default name\n o2 = _VarScopeObject(name='o')\n self.assertEqual(o2.name, 'o')\n self.assertEqual(o2.variable_scope.name, 'o_1')\n self.assertEqual(o2.variable_scope.original_name_scope, 'o_1/')\n var_2, op_2 = o2.f()\n self.assertEqual(var_2.name, 'o_1/f/var:0')\n self.assertEqual(op_2.name, 'o_1/f/op:0')\n\n # test the third object with the same scope as o1\n o3 = _VarScopeObject(scope='o')\n self.assertIsNone(o3.name)\n self.assertEqual(o3.variable_scope.name, 'o')\n self.assertEqual(o3.variable_scope.original_name_scope, 'o_2/')\n var_3, op_3 = o3.f()\n self.assertEqual(var_3.name, 'o/f/var:0')\n self.assertEqual(op_3.name, 'o_2/f/op:0')\n\n # test the object under other scope\n with tf.variable_scope('c'):\n o4 = _VarScopeObject(name='o')\n self.assertEqual(o4.name, 'o')\n self.assertEqual(o4.variable_scope.name, 'c/o')\n self.assertEqual(o4.variable_scope.original_name_scope, 'c/o/')\n var_4, op_4 = o4.f()\n self.assertEqual(var_4.name, 'c/o/f/var:0')\n self.assertEqual(op_4.name, 'c/o/f/op:0')\n\n\nclass GetVariablesTestCase(TestCase):\n\n def test_get_variables_as_dict(self):\n GLOBAL_VARIABLES = tf.GraphKeys.GLOBAL_VARIABLES\n MODEL_VARIABLES = tf.GraphKeys.MODEL_VARIABLES\n LOCAL_VARIABLES = tf.GraphKeys.LOCAL_VARIABLES\n\n # create the variables to be checked\n a = tf.get_variable(\n 'a', shape=(), collections=[GLOBAL_VARIABLES, MODEL_VARIABLES])\n b = tf.get_variable(\n 'b', shape=(), collections=[GLOBAL_VARIABLES])\n c = tf.get_variable(\n 'c', shape=(), collections=[MODEL_VARIABLES])\n\n with tf.variable_scope('child') as child:\n child_a = tf.get_variable(\n 'a', shape=(),\n collections=[GLOBAL_VARIABLES, MODEL_VARIABLES])\n child_b = tf.get_variable(\n 'b', shape=(), collections=[GLOBAL_VARIABLES])\n child_c = tf.get_variable(\n 'c', shape=(), collections=[MODEL_VARIABLES])\n\n # test to get variables as dict\n self.assertEqual(\n get_variables_as_dict(),\n {'a': a, 'b': b, 'child/a': child_a, 'child/b': child_b}\n )\n self.assertEqual(\n get_variables_as_dict(collection=MODEL_VARIABLES),\n {'a': a, 'c': c, 'child/a': child_a, 'child/c': child_c}\n )\n self.assertEqual(\n get_variables_as_dict(collection=LOCAL_VARIABLES),\n {}\n )\n self.assertEqual(\n get_variables_as_dict(''),\n {'a': a, 'b': b, 'child/a': child_a, 'child/b': child_b}\n )\n self.assertEqual(\n get_variables_as_dict('child'),\n {'a': child_a, 'b': child_b}\n )\n self.assertEqual(\n get_variables_as_dict('child/'),\n {'a': child_a, 'b': child_b}\n )\n self.assertEqual(\n get_variables_as_dict(child),\n {'a': child_a, 'b': child_b}\n )\n self.assertEqual(\n get_variables_as_dict('child', collection=MODEL_VARIABLES),\n {'a': child_a, 'c': child_c}\n )\n self.assertEqual(\n get_variables_as_dict('child', collection=LOCAL_VARIABLES),\n {}\n )\n self.assertEqual(\n get_variables_as_dict('non_exist'),\n {}\n )\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"haowen-xu/tfsnippet-pre-alpha","sub_path":"tests/utils/test_scope.py","file_name":"test_scope.py","file_ext":"py","file_size_in_byte":10549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36033807432","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import AllowAny\nfrom django.core.exceptions import SuspiciousOperation\nfrom django.shortcuts import get_object_or_404\nfrom .models import *\nfrom django.http import HttpResponse\nimport uuid\nimport json\nfrom . import writecsv\nimport datetime\nimport ast\n\n\nclass ItemView(APIView):\n permission_classes = (AllowAny,)\n # Get Items\n\n def get(self, request):\n return Response(\n {\n 'unique_id': item.unique_id,\n 'pk': item.pk,\n 'name': item.name,\n 'tamil_name': item.tamil_name,\n 'price': str(item.price),\n 'total_price': str(item.total_price),\n 'subitems': [\n {\n 'name': subitem.name,\n 'price': str(subitem.price),\n 'quantity': subitem.quantity\n }\n for subitem in item.subitems.all()]\n }\n\n for item in Items.objects.all())\n # Post New Item\n\n def post(self, request):\n item = Items()\n item.name = request.POST.get('name')\n item.price = request.POST.get('price')\n item.total_price = request.POST.get('total_price')\n subs = request.POST.get('subitems')\n for i in subs:\n subitem = SubItems()\n subitem.name = i['name']\n subitem.price = i['price']\n subitem.quantity = i['quantity']\n item.subitems.add(subitem)\n subitem.save()\n item.save()\n return Response({})\n\n # Edit Existing Item\n def put(self, request):\n item = get_object_or_404(Items, pk=int(request.POST.get('pk')))\n item.name = request.POST.get('name')\n item.price = int(request.POST.get('price'))\n item.total_price = int(request.POST.get('total_price'))\n subs = request.POST.get('subitems')\n for i in subs:\n subitem = SubItems()\n subitem.name = i['name']\n subitem.price = int(i['price'])\n subitem.quantity = int(i['quantity'])\n item.subitems.add(subitem)\n subitem.save()\n item.save()\n\n return Response({})\n # Delete Item\n\n def patch(self, request):\n item = get_object_or_404(Items, pk=int(request.POST.get('pk')))\n item.delete()\n return Response({})\n\n\nclass OrderView(APIView):\n permission_classes = (AllowAny,)\n # View Order\n\n def get(self, request):\n return Response(\n {\n 'name': order.customer.name,\n 'invoice_no': order.invoice_no,\n 'phone_num': order.customer.phone_number,\n 'ordered_items': [\n {\n 'unique_id': item.item.unique_id,\n 'tamil_name': item.item.tamil_name,\n 'name': item.item.name,\n 'price': item.item.price,\n 'total_price': item.total_price,\n 'subitems': [\n {\n 'unique_id': subitem.unique_id,\n 'name': subitem.name,\n 'price': subitem.price,\n 'quantity': subitem.quantity\n }\n for subitem in item .item.subitems.all()],\n\n\n }\n for item in order.ordered_items.all()],\n 'session': order.session,\n 'total': order.total,\n 'paid_amount': order.paid_amount,\n 'paid': order.paid,\n 'returned_vessel': order.returned_vessel,\n 'balance': order.balance,\n 'date_placed': order.date_placed,\n 'date_of_delivery': order.date_of_delivery\n\n\n }\n for order in Order.objects.all())\n # Place New Order\n\n def post(self, request):\n print(request.POST)\n\n order = Order()\n order.invoice_no = request.POST.get('invoiceNo')\n customer = CustomerDetails()\n customer.u_id = uuid.uuid4()\n customer.phone_number = request.POST.get('phoneNum')\n customer.email = request.POST.get('email')\n customer.address = request.POST.get('address')\n customer.save()\n order.customer = customer\n\n items = json.loads(request.POST.get('items'))\n subitems = json.loads(request.POST.get('subitems'))\n\n print(subitems)\n for i, j in zip(items, subitems):\n # j=json.loads(j)\n\n item = get_object_or_404(Items, name=i['item'])\n subitem = get_object_or_404(SubItems, name=j['item'])\n subitem.quantity = j['quantity']\n subitem.price = j['rate']\n subitem.save()\n ordered_item = OrderItem()\n ordered_item.item = item\n ordered_item.quantity = int(i['quantity'])\n ordered_item.total_price = int(i['amount'])\n ordered_item.subitems = subitem\n ordered_item.save()\n order.advance = request.POST.get('adv')\n order.session = request.POST.get('session')\n order.total = int(request.POST.get('total'))\n order.date_of_delivery = request.POST.get('deliveryDate')\n order.paid_amount = int(request.POST.get('total'))\n order.paid = False\n order.balance = int(request.POST.get('total')) - \\\n int(request.POST.get('adv'))\n order.save()\n order.ordered_items.add(ordered_item)\n\n print(request.POST['adv'])\n\n writecsv.write_order_csv(\n {\n 'InvoiceNo': order.invoice_no,\n 'CustomerId': customer.u_id,\n 'CustomerName': customer.name,\n 'CustomerNumber': customer.phone_number,\n 'TotalAmount': order.total\n }\n )\n\n return Response()\n # Edit Order\n\n def put(self, request):\n order = get_object_or_404(\n Order, invoice_no=request.POST.get('invoiceNo'))\n customer = CustomerDetails()\n customer.u_id = uuid.uuid4()\n customer.phone_number = request.POST.get('phoneNum')\n customer.email = request.POST.get('email')\n customer.address = request.POST.get('address')\n customer.save()\n order.customer = customer\n items = list(request.POST.get('items'))\n for i in items:\n item = get_object_or_404(Items, name=i['name'])\n ordered_item = OrderItem()\n ordered_item.item = item\n ordered_item.quantity = int(request.POST.get('quantity'))\n ordered_item.total_price = int(request.POST.get('totalPrice'))\n order.ordered_items.add(ordered_item)\n ordered_item.save()\n order.adv = int(request.POST.get('adv'))\n order.session = int(request.POST.get('session'))\n order.total = int(request.POST.get('total'))\n order.date_of_delivery = request.POST.get('deliveryDate')\n order.save()\n return Response()\n # Delete Order\n\n def patch(self, request):\n order = get_object_or_404(\n Order, invoice_no=request.POST.get('invoice_no'))\n order.delete()\n return Response({})\n\n\nclass VesselView(APIView):\n # Get Vessels\n def get(self, request):\n return Response(\n\n {\n 'u_id': item.u_id,\n 'name': item.name\n }\n for item in Vessels.objects.all())\n\n # Add new Vessels\n def post(self, request):\n vessel = Vessels()\n vessel.name = request.POST.get('name')\n vessel.save()\n return Response({})\n # Edit Vessel\n\n def put(self, request):\n vessel = get_object_or_404(Vessels, u_id=request.POST.get('u_id'))\n vessel.name = request.POST.get('name')\n vessel.save()\n return Response({})\n # Delete Vessel\n\n def patch(self, request):\n vessel = get_object_or_404(Vessels, u_id=request.POST.get('u_id'))\n vessel.delete()\n return Response({})\n\n\nclass CustomerSearchView(APIView):\n # Get Customers\n def get(self, request):\n customers = CustomerDetails.objects.all()\n return Response(\n\n {\n 'u_id': customer.u_id,\n 'name': customer.name,\n 'phone_number': customer.phone_number,\n 'email': customer.email,\n 'address': customer.address\n\n\n }\n\n for customer in customers)\n # Add Customers\n\n def post(self, request):\n customer = CustomerDetails()\n customer.name = request.POST.get('name')\n customer.phone_number = request.POST.get('phone_number')\n customer.email = request.POST.get('email')\n customer.address = request.POST.get('address')\n customer.save()\n return Response({})\n # Edit Customers\n\n def put(self, request):\n customer = get_object_or_404(\n CustomerDetails, u_id=request.POST.get('u_id'))\n customer.name = request.POST.get('name')\n customer.phone_number = request.POST.get('phone_number')\n customer.email = request.POST.get('email')\n customer.address = request.POST.get('address')\n customer.save()\n return Response({})\n # Delete Customers\n\n def patch(self, request):\n customer = get_object_or_404(\n CustomerDetails, u_id=request.POST.get('u_id'))\n customer.delete()\n return Response({})\n\n\nclass DailyItemView(APIView):\n def get(self, request):\n today_items = {}\n orders = Order.objects.filter(date_of_delivery=datetime.date.today())\n for order in orders:\n for ort in order.ordered_items.all():\n if today_items.get(ort.item.name):\n today_items.get(ort.item.name)[\"quantity\"] += ort.quantity\n else:\n today_items[ort.item.name] = {\n \"tamil_name\": ort.item.tamil_name, \"quantity\": ort.quantity}\n print(today_items)\n return Response()\n\n\nclass DailySubItemView(APIView):\n def get(self, request):\n sub_items = []\n orders = DailySubItems.objects.filter(date=datetime.date.today())\n for order in orders:\n sub_item = SubItems.objects.get(unique_id=order.unique_id)\n data = {\n 'name': sub_item.tamil_name,\n 'quantity': order.quantity\n }\n sub_items.append(data)\n return Response(sub_items)\n\n\nclass SubItemsView(APIView):\n def get(self, request):\n return Response({\n\n 'unique_id': subitem.unique_id,\n 'title': subitem.name,\n 'rate': subitem.price,\n\n\n }for subitem in SubItems.objects.all())\n","repo_name":"vigneshwar221B/taj-backend","sub_path":"neworder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40134553894","text":"import flask\nfrom flask import render_template, redirect, url_for, request, session, g, flash\nfrom . import admin\nfrom app.models import *\nfrom app.exts import db\n\n#跳转到文章管理界面,查询所有用户\n@admin.route('/article')\ndef articlelist():\n articles = db.session.query(Article, User).filter(Article.userId == User.id).all()\n return render_template('admin/admin-article.html',articles = articles)\n\n#处理删除单个请求\n@admin.route('/article/delete', methods=['POST'])\ndef deletearticle():\n articleId = request.form['articleId']\n currentArticle = Article.query.filter_by(articleId=articleId).first()\n db.session.delete(currentArticle)\n db.session.commit()\n return redirect(url_for('admin.articlelist'))\n\n#处理批量删除\n@admin.route('/article/batchdelete', methods=['POST'])\ndef batchdeletearticle():\n articleIds = request.form['articleIds']\n aids = articleIds.split(',');\n for aid in aids:\n currentArticle = Article.query.filter_by(articleId=int(aid)).first()\n print(currentArticle)\n db.session.delete(currentArticle)\n db.session.commit()\n return redirect(url_for('admin.articlelist'))\n\n","repo_name":"StrongPosHao/ITC","sub_path":"app/admin/ArticleManage.py","file_name":"ArticleManage.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17453503992","text":"import tweepy\nimport sqlite3\nimport os\nimport requests\nimport json\nimport time\nfrom bs4 import BeautifulSoup\n\njsonFile = open(\"twitter_data.json\", \"r\")\ndata = json.load(jsonFile)\njsonFile.close()\n\n#Twitter account keys\nconsumerKey = data[\"consumer_key\"]\nconsumerSecret = data[\"consumer_secret\"]\naccessToken = data[\"access_token\"]\naccessTokenSecret = data[\"access_token_secret\"]\n\n#setting up tweepy api\nauth = tweepy.OAuthHandler(consumerKey, consumerSecret)\nauth.set_access_token(accessToken, accessTokenSecret)\napi = tweepy.API(auth) \n\n#functions that gets all retweets from account \"screenName\" and adds\n#them to DB\ndef getAllRetweets(screenName):\n allTweets = []\n \n newTweets = api.user_timeline(screen_name = screenName,count=200)\n allTweets.extend(newTweets)\n \n oldestTweet = allTweets[-1].id - 1\n \n while len(newTweets) > 0:\n print(\"getting tweets before %s\" % (oldestTweet))\n newTweets = api.user_timeline(screen_name = screenName, count = 200, max_id = oldestTweet)\n allTweets.extend(newTweets)\n oldestTweet = allTweets[-1].id - 1\n print(\"...%s tweets downloaded so far\" % (len(allTweets)))\n \n #transform the tweepy tweets into a 2D array that will populate the database\n dataTweets = []\n for tweet in allTweets:\n try:\n if(tweet.retweeted_status):\n dataTweets.append(getOriginalTime(tweet))\n except AttributeError:\n pass\n print(\"Found: %s retweets\" % len(dataTweets))\n insertTweetData(dataTweets)\n\n#gets the last \"count\" number of retweets from \"screenName\" and add them to DB\ndef getMostRecentRetweets(screenName, count):\n allTweets = []\n \n newTweets = api.user_timeline(screen_name = screenName,count=count)\n allTweets.extend(newTweets)\n \n dataTweets = []\n for tweet in allTweets:\n try:\n if(tweet.retweeted_status):\n dataTweets.append(getOriginalTime(tweet))\n except AttributeError:\n pass\n print(\"Found: %s retweets\" % len(dataTweets))\n insertTweetData(dataTweets)\n\n#If \"tweet\" is a retweet, returns the original day of the tweet, otherwise\n#returns normal tweet date\ndef getOriginalTime(tweet):\n if(tweet.retweeted):\n originaltTweet = api.get_status(tweet.id_str)\n return [originaltTweet.id_str, str(originaltTweet.retweeted_status.created_at)]\n else:\n return [tweet.id_str, str(tweet.created_at)]\n\n#Inserts tweet ID and date into DB\n#Won't duplicate insertions if tweet ID is already on DB\ndef insertTweetData(dataTweets):\n conn = sqlite3.connect('trumpgret.db')\n c = conn.cursor()\n\n for tweet in dataTweets:\n c.execute(\"INSERT OR IGNORE INTO tweets VALUES (?,?)\", tweet)\n\t\n conn.commit()\n conn.close()\n\n#Returns all tuples from table tweets\ndef getDBTweets():\n conn = sqlite3.connect('trumpgret.db')\n c = conn.cursor()\n\n c.execute('SELECT * FROM tweets')\n results = c.fetchall()\n\n conn.close()\n return results\n\n#Initializes the databse if it doesn't exist\ndef initDB():\n if not ([s for s in os.listdir(os.getcwd()) if \".db\" in s]):\n con = sqlite3.connect('trumpgret.db')\n cursor = con.cursor()\n \n cursor.execute('''CREATE TABLE IF NOT EXISTS tweets\n (id integer primary key, date text)''')\n con.close()\n \n#Returns total tweet count from Trump_Regrets directly from the website\ndef readTotalTweetValue():\n page = requests.get(\"https://twitter.com/Trump_Regrets\")\n soup = BeautifulSoup(page.content, 'html.parser')\n return soup.find_all(class_='ProfileNav-value')[0].text.replace(',', '')\n\n#Updates DB with latest tweets if total Tweet count is different from the one\n#saved in twitter_data.json\ndef updateTweetDB():\n jsonFile = open(\"twitter_data.json\", \"r\")\n data = json.load(jsonFile)\n jsonFile.close()\n newTweetsNumber = int(readTotalTweetValue()) - int(data[\"total_tweets\"])\n if(newTweetsNumber > 0):\n getMostRecentRetweets(\"Trump_Regrets\", newTweetsNumber)\n #Changing total_tweets and last_update in json\n data[\"total_tweets\"] = int(readTotalTweetValue())\n data[\"last_update\"] = time.strftime(\"%Y-%m-%d\")\n \n jsonFile = open(\"twitter_data.json\", \"w+\")\n jsonFile.write(json.dumps(data))\n jsonFile.close()\n return \"Saved %s tweets to database\" % newTweetsNumber\n else:\n return \"No new tweets\"\n\n#getAllRetweets(\"Trump_Regrets\")\ninitDB()\n#updateTweetDB()","repo_name":"araizaga-yael/trumpgret","sub_path":"trumpgret.py","file_name":"trumpgret.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19763455496","text":"from keras.callbacks import Callback\nimport tensorflow as tf\n\n\nclass TensorBoardStepCallback(Callback):\n \"\"\"Tensorboard basic visualizations by step.\n\n \"\"\"\n\n def __init__(self, log_dir, logging_per_steps=100, step=0):\n super().__init__()\n self.step = step\n self.logging_per_steps = logging_per_steps\n self.writer = tf.summary.FileWriter(log_dir)\n\n def on_batch_end(self, batch, logs=None):\n self.step += 1\n\n if self.step % self.logging_per_steps > 0:\n return\n\n for name, value in logs.items():\n if name in ['batch', 'size']:\n continue\n summary = tf.Summary()\n summary_value = summary.value.add()\n summary_value.simple_value = value.item()\n summary_value.tag = name\n self.writer.add_summary(summary, self.step)\n self.writer.flush()\n\n def close(self):\n self.writer.close()\n","repo_name":"mokemokechicken/reversi-alpha-zero","sub_path":"src/reversi_zero/lib/tensorboard_step_callback.py","file_name":"tensorboard_step_callback.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":658,"dataset":"github-code","pt":"52"} +{"seq_id":"43169788406","text":"from .SchoolGraph import SchoolGraph\nfrom .SchoolOrganize import SchoolOrganize\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\nclass SchoolData(SchoolOrganize, SchoolGraph):\n \"\"\"\n A class designed specifically to deal with this dataset. Mostly dedicated\n to calling methods upon creation to sort the data how I want.\n \"\"\"\n def __init__(self, df, figwidth, figheight,subset=False,**kwargs):\n \"\"\"\n Constructor method for SchoolData\n \"\"\"\n super().__init__(df,**kwargs)\n # A collection of columns that will be created and summed based on the\n # arguments sent into columnGenerator\n # IDEA: Will a list of dictionaries be faster than a nested dictionary\n # where the number representation doesn't matter\n if not subset:\n self.retail_read()\n self.metro_read()\n self.car_read()\n self._transform_data()\n self._calculate_in_need()\n\n def retail_read(self):\n \"\"\"\n Reads in Grocery Store Data and merges with dataset\n \"\"\"\n retail_food_df = pd.read_csv('Retail_Food_Stores.csv')\n\n retail_food_df['Establishment Type'] = [ i.strip() \\\n for i in retail_food_df['Establishment Type'] ]\n retail_zips = pd.DataFrame(retail_food_df[retail_food_df[\\\n 'Establishment Type'] == \\\n 'A'].groupby('Zip Code').count().loc[:,'County'])\n retail_zips = retail_zips.reset_index()\n retail_zips.columns = ['Zip', 'Grocery Store Count']\n\n self.df = pd.merge(self.df, retail_zips, on = 'Zip', how = 'left')\n\n del retail_food_df\n del retail_zips\n\n # Convert to integer values and fill empty values with 0\n self.df['Grocery Store Count'] = \\\n self.df['Grocery Store Count'].fillna(0)\n self.df['Grocery Store Count'] = \\\n self.df['Grocery Store Count'].astype(int)\n\n return\n\n def metro_read(self):\n \"\"\"\n Reads in Metro Distances data and merges with dataset\n \"\"\"\n # Computationally expensive, ran once and saved info\n # self._metro_read()\n # Reloads computed code and adds it to the dataframe\n metro_distance = pd.read_csv('Metro distances.csv')\n self.df['Closest Metro Station'] = metro_distance\n\n del metro_distance\n\n return\n\n def _metro_read(self):\n # Read in file\n metro_df = pd.read_csv('NYC_Transit_Subway_Entrance_And_Exit_Data.csv')\n\n # Create a tuple of co-ordinates to match the metro_df\n df['Coords'] = [(i,j) for i, j in zip(df['Latitude'], df['Longitude'])]\n\n # Read from bottom to top for most coherent explanation of the double\n # list comprehension\n # Creates a tuple out of the two float numbers in a\n # co-ordinate\n stations = [tuple([float(number) for number in group]) \\\n # Takes each string co-ordinate, and separates it into\n # two float numbers (in string form)\n for group in [s.strip(\"()\").split(\",\") \\\n # For each co-ordinate stored in the metro\n # dataframe\n for s in metro_df['Station Location']] ]\n\n def returnClosestStation(coords):\n closest = -1\n for station in stations:\n distance = coordsDistance( station, coords)\n if distance > closest:\n closest = distance\n return closest\n\n self.df['Closest Metro Station'] = \\\n self.df['Coords'].apply(returnClosestStation)\n\n del metro_df\n del stations\n\n self.df['Closest Metro Station'].to_csv(\\\n 'Metro distances.csv', index = False)\n\n def car_read(self):\n \"\"\"\n Reads in the car-accident data and merges with the dataset\n \"\"\"\n # Computationally expensive, ran once and saved info\n # self._car_read()\n # Reloads computed code and adds it to the dataframe\n car_crashes = pd.read_csv('Car Crash Count.csv')\n self.df['Car Crash Count'] = car_crashes\n del car_crashes\n\n def _car_read(self):\n crashes_df = pd.read_csv('nypd-motor-vehicle-collisions.csv')\n # Many zip code values weren't kept track of, most of these were considered less severe car accidents so I dropped\n # them all from the dataset\n crashes_df = pd.DataFrame(crashes_df.dropna(subset = \\\n ['ZIP CODE']).groupby('ZIP CODE').count()['TIME'])\n crashes_df = crashes_df.reset_index()\n crashes_df.columns = ['Zip', 'Car Crash Count']\n\n # Zip codes were not inputted well in this dataset, there were multiple formats for all zip codes, I went through a process\n # of converting from strings to floats or ints or just returned as an empty string to drop later.\n\n def convert(n):\n try:\n return(int(n))\n except:\n pass\n try:\n return(float(n))\n except:\n pass\n return(n.strip())\n\n crashes_df['Zip'] = crashes_df['Zip'].apply(convert)\n crashes_df = crashes_df[crashes_df['Zip'] != ''].astype(int)\n crashes_df = crashes_df.groupby('Zip').sum()\n self.df = pd.merge(self.df, crashes_df, on = 'Zip', how = 'left')\n\n del crashes_df\n\n self.df['Car Crash Count'].to_csv('Car Crash Count.csv', index = False)\n\n def _transform_data(self):\n \"\"\"\n A collection of methods and calls that re-structure the School data\n to be more organized\n \"\"\"\n self._rename_cols()\n self._type_correction()\n # Set to retain only unique items, filled with some base columns\n # I won't be using\n drop_cols = set(['Adjusted Grade', 'New?',\n 'Other Location Code in LCGMS',\n 'SED Code', 'Location Code',\n 'Address (Full)'])\n drop_cols = self._feature_engineering(drop_cols)\n # Make sure not to drop columns concerning all students\n drop_cols = [i for i in drop_cols if 'All Students' not in i]\n # Drop superfluous columns\n self.drop_cols(drop_cols)\n\n # Organize grades\n self._grade_combination()\n # Impute numerical columns\n self.dict_fun_run(self._impute_dict, self.imputer)\n # Impute categorical columns\n for col in self._cat_impute:\n self.cat_impute(col)\n # Create Boolean columns for different grades\n self._grade_bools()\n del self._impute_dict\n del self._cat_impute\n return\n\n def _rename_cols(self):\n \"\"\"\n Columns that require re-naming to match the pattern that is displayed\n in the majority of data\n \"\"\"\n self.df.rename(columns={\n 'Grade 3 Math - All Students tested':\n 'Grade 3 Math - All Students Tested'}, inplace=True)\n return\n\n def _type_correction(self):\n \"\"\"\n A function for all type corrections\n \"\"\"\n # Convert from dollars to a float\n self.df['School Income Estimate'] = \\\n self.df['School Income Estimate'].apply(self.dollarsToDigits)\n\n # Converts all object style percents to float style percents\n for col in self._perc_cols:\n self.df[col] = self.df[col].apply(self.percents_to_floats)\n\n # Convert column to type Boolean\n self.df['Community School?'] = self.df['Community School?'].map(\n {'Yes': 1, 'No': 0})\n\n return\n\n def _grade_combination(self):\n \"\"\"\n Sums all the like Grades 4 scores and stores it in a new total column\n\n :return: Nothing, all columns are assigned in the function\n \"\"\"\n cols = list(self.df.columns)\n for grade in range(3, 8 + 1):\n col_data = [i for i in cols if ('Grade ' + str(grade) in i) and\n ('All Students' in i) and\n ('Tested' not in i)]\n self.df['Grade ' + str(grade) + ' 4s Total'] = \\\n self.df[col_data].apply(sum, axis=1)\n col_data = [i for i in cols if ('Grade ' + str(grade) in i) and\n ('All Students' in i) and\n ('Tested' in i)]\n self.df['Grade ' + str(grade) + ' 4s Tested Total'] = \\\n self.df[col_data].apply(sum, axis=1)\n del cols\n return\n\n def _grade_bools(self):\n \"\"\"\n Create a boolean column for each possible grade\n \"\"\"\n grades = self.lol_to_set(col='Grades', splitby=',')\n\n for grade in grades:\n self.df[grade] = False\n\n for grade in grades:\n self.df.loc[self.df['Grades'].str.contains(grade), grade] = True\n return\n\n def _calculate_in_need(self):\n \"\"\"\n Calculates the In Need Score for schools, a weighted formula to\n determine what schools are in need of the new resources\n \"\"\"\n # Instantiate score column with 0, for lowest possible score\n self.df['In Need Score'] = 0\n # A nested dictionary to calculate weights and add to the In Need Score\n pre_dict = {\n 0: {'pre_col':'Economic Need Index', 'weight':0.75},\n 1: {'pre_col':'White Students %', 'invert':True, 'weight':0.80},\n 2: {'pre_col':'Asian / Pacific Islanders Students %',\n 'weight':0.40},\n 3: {'pre_col':'Multiracial Students %', 'weight':0.05},\n 4: {'pre_col':'Black Students %', 'weight':0.80},\n 5: {'pre_col':'Hispanic / Latino Students %', 'weight':0.60},\n 6: {'pre_col':'American Indian / Alaska Native Students %',\n 'weight':0.15},\n 7: {'pre_col':'Limited English Students %', 'weight':0.05},\n 8: {'pre_col':'Economically Disadvantaged Students %',\n 'weight':0.30},\n 9: {'pre_col':'Total 4 %', 'invert':True, 'weight':0.8},\n 10: {'pre_col':'Math Prop 4', 'invert':True, 'weight':0.6},\n 11: {'pre_col':'ELA Prop 4', 'invert':True, 'weight':0.6},\n 12: {'pre_col':'Percent of Students Chronically Absent',\n 'weight':0.25},\n 13: {'pre_col':'Nonreported Ethnicity %',\n 'weight':0.15},\n 14: {'pre_col':'Students Tested Total', 'invert':True,\n 'weight':0.15}\n }\n # Computes all straight-forward weighted scores\n self.dict_fun_run(pre_dict, self._in_need_calculate)\n\n # School Income Estimate fits outside of the nice loop structure\n # This is beacuse 0 indicates that they had no data for it, meaning it\n # has to be handled differently than all other columns\n self.subset_normalized_in_need(col='School Income Estimate',\n weight=0.30, col_greater_than=0.001, filter_greater_than=0.001,\n invert=True)\n # Bin columns from groupby calls\n bin_dict={\n 0:{'bin_col':'Total 4 % City Bin', 'lowest':0.30, 'low':0.20,\n 'medium':-0.40, 'high':-0.8},\n 1:{'bin_col':'School Income City Bin', 'lowest':0.20, 'low':0.10,\n 'medium':-0.40, 'high':-0.8},\n 2:{'bin_col':'ENI City Bin', 'lowest':0.20, 'low':0.10,\n 'medium':-0.40, 'high':-0.8},\n 3:{'bin_col':'School Income District Bin', 'lowest':0.20,\n 'low':0.10, 'medium':-0.40, 'high':-0.8},\n 4:{'bin_col':'Total 4 % District Bin', 'lowest':0.30, 'low':0.15,\n 'medium':-0.40, 'high':-0.8}\n }\n\n # Instantiate Classes in order to get their information\n self._init_cit()\n self._init_dis()\n\n self.dict_fun_run(bin_dict, self.iterate_bin_need)\n # Rating information and how it affects score\n rating_dict={\n 0:{'bin_col':'Rigorous Instruction Rating',\n 'not_meeting_target':0.75, 'approaching_target':0.55,\n 'meeting_target':-0.75, 'exceeding_target':-1},\n 1:{'bin_col':'Collaborative Teachers Rating',\n 'not_meeting_target':0.75, 'approaching_target':0.55,\n 'meeting_target':-0.75, 'exceeding_target':-1},\n 2:{'bin_col':'Supportive Environment Rating',\n 'not_meeting_target':0.75, 'approaching_target':0.55,\n 'meeting_target':-0.75, 'exceeding_target':-1},\n 3:{'bin_col':'Effective School Leadership Rating',\n 'not_meeting_target':0.5, 'approaching_target':0.25,\n 'meeting_target':-0.25, 'exceeding_target':-0.5},\n 4:{'bin_col':'Strong Family-Community Ties Rating',\n 'not_meeting_target':0.25, 'approaching_target':0.10,\n 'meeting_target':-0.10, 'exceeding_target':-0.25},\n 5:{'bin_col':'Trust Rating',\n 'not_meeting_target':0.25, 'approaching_target':0.10,\n 'meeting_target':-0.10, 'exceeding_target':-0.25},\n 6:{'bin_col':'Student Achievement Rating',\n 'not_meeting_target':0.75, 'approaching_target':0.55,\n 'meeting_target':-0.75, 'exceeding_target':-1}\n }\n\n self.dict_fun_run(rating_dict, self.iterate_bin_rating)\n\n # If the school offers a grade associated with SE or 6+\n grades_in_need = (self.df['SE'] == True) | (self.df['06'] == True) |\\\n (self.df['07'] == True) | (self.df['08'] == True) | \\\n (self.df['09'] == True) | (self.df['10'] == True) | \\\n (self.df['11'] == True) | (self.df['12'] == True)\n # Increase the In Need Score\n self.df.loc[grades_in_need, 'In Need Score'] += 0.5\n\n # Normalize the In Need Score column from 0 to 100\n self.df['In Need Score'] = self.normalize_column('In Need Score') * 100\n\n return\n\n def iterate_bin_need(self, bin_col, lowest, low, medium, high):\n \"\"\"\n Iterates through each row and and adds points to In Need Score. This is\n inefficient but it works\n \"\"\"\n for index, value in enumerate(self.df[bin_col]):\n self._bin_need_calculate(value, index, lowest, low, medium, high)\n\n def iterate_bin_rating(self, bin_col, not_meeting_target,\n approaching_target, meeting_target, exceeding_target):\n \"\"\"\n Iterates through each row and and adds points to In Need Score. This is\n inefficient but it works\n \"\"\"\n for index, value in enumerate(self.df[bin_col]):\n self._bin_rating_calculate(value, index, not_meeting_target,\n approaching_target, meeting_target, exceeding_target)\n\n def _bin_rating_calculate(self, value, index, not_meeting_target,\n approaching_target, meeting_target, exceeding_target):\n \"\"\"\n Compares the inputted value and adds points to In Need Score based on\n the variables\n \"\"\"\n if value=='Not Meeting Target':\n self.df.loc[index, 'In Need Score'] += not_meeting_target\n elif value=='Approaching Target':\n self.df.loc[index, 'In Need Score'] += approaching_target\n elif value=='Meeting Target':\n self.df.loc[index, 'In Need Score'] += meeting_target\n elif value=='Exceeding Target':\n self.df.loc[index, 'In Need Score'] += exceeding_target\n return\n\n def _bin_need_calculate(self, value, index, lowest, low, medium, high):\n \"\"\"\n Compares the inputted value and adds points to In Need Score based on\n the variables\n \"\"\"\n if value=='lowest':\n self.df.loc[index, 'In Need Score'] += lowest\n elif value=='low':\n self.df.loc[index, 'In Need Score'] += low\n elif value=='medium':\n self.df.loc[index, 'In Need Score'] += medium\n elif value=='high':\n self.df.loc[index, 'In Need Score'] += high\n return\n\n def _in_need_calculate(self, pre_col, weight, invert=False):\n normalized_values = self.normalize_column(pre_col, invert)\n self.df['In Need Score'] += normalized_values * weight\n return\n\n def subset_normalized_in_need(self, col, weight, col_greater_than=None,\n col_less_than=None, filter_greater_than=None,\n filter_less_than=None, invert=False):\n\n col_greater_than, col_less_than = self._set_greater_less_than(col,\n col_greater_than, col_less_than)\n\n subset_normalized = self.normalize_column_filter(col=col,\n greater_than=filter_greater_than, less_than=filter_less_than,\n invert=True)\n\n self.df.loc[(self.df[col] >= col_greater_than) & \\\n (self.df[col] <= col_less_than),'In Need Score'] += \\\n subset_normalized * weight\n\n return\n\n def _misc_features(self):\n \"\"\"\n A collection of operations to help readability and processing of data\n These fit outside the order of the logical feature engineering order,\n they are needed to be able to engineer the rest of the featuers.\n \"\"\"\n # Column needed for upcoming processing\n self.df['4 Tested Total'] = self.df['Math Tested 4s'] + \\\n self.df['ELA Tested 4s']\n column_4s = ['White Students Total',\n 'Asian / Pacific Islanders Students Total',\n 'Black Students Total',\n 'Hispanic / Latino Students Total',\n 'American Indian / Alaska Native Students Total',\n 'Multiracial Students Total']\n\n # Operations that fit outside the dictionaries for organization reasons\n self.df['Ethnicity Tested Total'] = \\\n self.df[column_4s].apply(sum, axis=1)\n self.df['Nonreported Ethnicity Total'] = \\\n self.df['4 Tested Total'] - self.df['Ethnicity Tested Total']\n self.df['Nonreported Ethnicity %'] = \\\n (self.df['Nonreported Ethnicity Total'] /\n self.df['4 Tested Total']).fillna(0)\n\n return\n\n def _feature_engineering(self, drop_cols):\n \"\"\"\n Organizes, cleans, and feature engineers columns for the data\n \"\"\"\n # Engineer all features that involve sums\n drop_cols = self._process_drop_features(self._sum_dict, drop_cols)\n\n # Help make the data more readable, must be called after sum features\n # but before division and bin features\n self._misc_features()\n\n # Engineer all features that involve division\n self.dict_fun_run(self._div_dict, self._column_div)\n # Engineer all features that involve bins (pd.cut)\n self.dict_fun_run(self._bin_dict, self._column_bin)\n\n del self._sum_dict\n del self._bin_dict\n del self._div_dict\n del self._perc_cols\n\n return drop_cols\n\n def _column_sum(self, **kwargs):\n \"\"\"\n Generates columns using column_generator, sums them, and assigns them\n to a new column\n\n :return: The list of columns that were summed based on the **kwargs\n arguments sent in\n \"\"\"\n col_data = self.column_generator(subject=kwargs['subject'],\n students=kwargs['students'],\n test=kwargs['test'])\n self.df[kwargs['new_col']] = self.df[col_data].apply(sum, axis=1)\n return(col_data)\n\n def _process_drop_features(self, dic, drop_cols):\n \"\"\"\n Processes all features that will also be added to a list of columns to\n drop from the dataset\n\n :param drop_cols: A set that will be updated with columns to drop\n :return: A set of columns\n \"\"\"\n\n for item in dic.items():\n drop_cols.update(self._column_sum(**item[1]))\n\n return drop_cols\n\n def column_generator(self, subject='both', students='All Students',\n test=False, grade=None):\n \"\"\"\n Generates a list of columns based on the input given\n\n :param subject: School subject, must be: 'both', 'Math', or 'Ela'\n :param students: Filters for the type of student, 'All Students' is\n default\n :param test: Also returns for columns that end in ' Tested' if True\n :return: A list of columns from the data\n\n >>> data.column_generator(test = True, subject = 'ELA')\n ['Grade 3 ELA - All Students Tested',\n 'Grade 4 ELA - All Students Tested',\n 'Grade 5 ELA - All Students Tested',\n 'Grade 6 ELA - All Students Tested',\n 'Grade 7 ELA - All Students Tested',\n 'Grade 8 ELA - All Students Tested']\n\n >>> data.column_generator(test = False, subject = 'Math')\n ['Grade 3 Math 4s - All Students',\n 'Grade 4 Math 4s - All Students',\n 'Grade 5 Math 4s - All Students',\n 'Grade 6 Math 4s - All Students',\n 'Grade 7 Math 4s - All Students',\n 'Grade 8 Math 4s - All Students']\n \"\"\"\n # Ensures subject is assigned correctly\n assert subject in ['both', 'Math', 'ELA'], ('Subject must be: both'\n 'Math, or ELA')\n\n if test:\n assert students == 'All Students', ('test Flag should only be set'\n 'true with All Students')\n students += ' Tested'\n else:\n students = '4s - ' + students\n\n # Stores a list of all the columns\n cols = list(self.df.columns)\n\n if subject == 'both':\n lst = [i for i in cols if students in i and\n ('ELA' in i or 'Math' in i)]\n elif subject == 'Math':\n lst = [i for i in cols if students in i and 'Math' in i]\n elif subject == 'ELA':\n lst = [i for i in cols if students in i and 'ELA' in i]\n\n if grade != None:\n assert grade >= 3 and grade <= 8\n lst = [i for i in lst if ('Grade ' + str(grade) in i)]\n\n return lst\n # else:\n # return -1 # An error has occurred\n","repo_name":"mwmcnall/Schools-In-Need","sub_path":"school_wdata/SchoolData.py","file_name":"SchoolData.py","file_ext":"py","file_size_in_byte":22209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21208913463","text":"import random,sys\n\nimported = True\ntry:\n import jieba\n import jieba.posseg as pseg\n jieba.setLogLevel(20)\nexcept ImportError:\n imported = False\n\n\ndef chaos (x, y, chaosrate):\n if random.random() > chaosrate:\n return x\n if x in {'[', ']'}:\n return ''\n if x in {','}:\n return '…'\n if x in { '!', '!',}:\n return '‼‼‼'\n if x in { '。'}:\n return '❗'\n if len(x) > 1 and random.random() < 0.1:\n if random.random() < 0.2:\n return f'{x[0]}…{x}'\n else:\n return f'{x[0]}~{x}'\n if len(x) > 1 and random.random() < 0.4:\n return f'{x[0]}♥{x}'\n if y == 'n' and random.random() < 0.1:\n if random.random() < 0.4:\n x = '⭕️' * len(x)\n else:\n x = '~' * len(x)\n return f'…{x}'\n if x in { '\\……n', '\\♥n'}:\n return '\\n'\n if x in { '…………'}:\n if random.random() < 0.3:\n return '……'\n else:\n if random.random() < 0.3:\n return '…'\n else:\n return '~'\n else:\n if y == 'n' and random.random() < 0.2:\n x = '⭕' * len(x)\n return f'…{x}'\n\n\ndef chs2yin(s, chaosrate =0.8):\n return ''.join(chaos (x, y, chaosrate) for x, y in pseg.cut(s))\n\nprint(chs2yin(sys.argv[1]))\n","repo_name":"YidaozhanYa/my-scripts","sub_path":"yinglish.py","file_name":"yinglish.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"5734898461","text":"\"\"\"\nentity_tag\n 0: B-GPE,\n 1: I-GPE,\n 2: B-PER,\n 3: I-PER,\n 4: B-DATE,\n 5: I-DATE,\n 6: B-ORG,\n 7: I-ORG,\n 8: B-CARDINAL,\n 9: I-CARDINAL,\n 10: B-NORP,\n 11: I-NORP,\n 12: B-LOC,\n 13: I-LOC,\n 14: B-TIME,\n 15: I-TIME,\n 16: B-FAC,\n 17: I-FAC,\n 18: B-MONEY,\n 19: I-MONEY,\n 20: B-ORDINAL,\n 21: I-ORDINAL,\n 22: B-EVENT,\n 23: I-EVENT,\n 24: B-WFA,\n 25: I-WFA,\n 26: B-QUANTITY,\n 27: I-QUANTITY,\n 28: B-PERCENT,\n 29: I-PERCENT,\n 30: B-LANGUAGE,\n 31: I-LANGUAGE,\n 32: B-PRODUCT,\n 33: I-PRODUCT,\n 34: B-LAW,\n 35: I-LAW,\n 36: O\n\"\"\"\nfrom ckiptagger import POS, NER\nimport pandas\n\nner_tag_binder = {'GPE': 0, 'PERSON': 2, 'DATE': 4, 'ORG': 6, 'CARDINAL': 8, 'NORP': 10, 'LOC': 12, 'TIME': 14,\n 'FAC': 16, 'MONEY': 18, 'ORDINAL': 20, 'EVENT': 22, 'WORK_OF_ART': 24, 'QUANTITY': 26, 'PERCENT': 28,\n 'LANGUAGE': 30, 'PRODUCT': 32, 'LAW': 34}\n\n\ndata = pandas.read_csv('../Datasets/self_create_datasets_with_diff_tags/Train_data_pos_tags.csv')['Paragraph'].tolist()\ntoken_data = pandas.read_csv('../Datasets/self_create_datasets_with_diff_tags/News_data_token.csv')['Paragraph'].tolist()\npos = POS('../Datasets/data')\nner = NER('../Datasets/data')\n\nfor ind, element in enumerate(data):\n pos_list = pos([element])\n ner_list = ner([element], pos_list)\n temp = [36 for i in range(len(element))]\n for index, el in enumerate(ner_list[0]):\n temp[el[0]] = ner_tag_binder[el[2]]\n for i in range(el[0] + 1, el[1]):\n temp[i] = ner_tag_binder[el[2]] + 1\n\n df = pandas.DataFrame({'Id': [ind], 'Tokens': [token_data[ind]], 'NER_tag': [temp.__str__()]})\n df.to_csv('../Datasets/Train_data_ner_tags.csv', encoding='utf-8', index_label=False, index=False,\n columns=df.keys(), header=False, mode='a')\n print(f'current running at index {ind}')\n","repo_name":"Revrs01/Named-Entity-Recognition","sub_path":"src/label_ner_tag.py","file_name":"label_ner_tag.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41251673149","text":"__author__ = 'maldevel'\n__español__ = 'cdamiangomez'\n\nfrom datetime import datetime\nimport os\nfrom termcolor import colored\nfrom sys import platform as _platform\n\n\nif _platform == 'win32':\n import colorama\n colorama.init()\n\ndef Red(value):\n return colored(value, 'red', attrs=['bold'])\n\ndef Green(value):\n return colored(value, 'green', attrs=['bold'])\n\n\nclass Logger:\n\n def __init__(self, nolog=False, verbose=False):\n self.NoLog = nolog\n self.Verbose = verbose\n\n\n def WriteLog(self, messagetype, message):\n filename = '{}.log'.format(datetime.strftime(datetime.now(), \"%Y%m%d\"))\n path = os.path.join('.', 'logs', filename)\n with open(path, 'a') as logFile:\n logFile.write('[{}] {} - {}\\n'.format(messagetype, datetime.strftime(datetime.now(), \"%Y-%m-%d %H:%M:%S\"), message))\n\n\n def PrintError(self, message):\n \"\"\"Mensaje de error de impresión / registro\"\"\"\n if not self.NoLog:\n self.WriteLog('ERROR', message)\n\n print('[{}] {}'.format(Red('ERROR'), message))\n\n\n def PrintResult(self, title, value):\n \"\"\"Imprimir resultado a terminal\"\"\"\n print('{}: {}'.format(title, Green(value)))\n\n\n def Print(self, message):\n \"\"\"Mensaje de información de impresión / registro\"\"\"\n if not self.NoLog:\n self.WriteLog('INFO', message)\n\n if self.Verbose:\n print('[{}] {}'.format(Green('**'), message))\n\n\n def PrintIPGeoLocation(self, ipGeoLocation):\n \"\"\"Imprimir información de geolocalización IP a la terminal\"\"\"\n self.PrintResult('\\nObjetivo', ipGeoLocation.Query)\n self.PrintResult('IP', ipGeoLocation.IP)\n self.PrintResult('ASN', ipGeoLocation.ASN)\n self.PrintResult('Ciudad', ipGeoLocation.City)\n self.PrintResult('País', ipGeoLocation.Country)\n self.PrintResult('Código País', ipGeoLocation.CountryCode)\n self.PrintResult('ISP', ipGeoLocation.ISP)\n self.PrintResult('Latitud', str(ipGeoLocation.Latitude))\n self.PrintResult('Longitud', str(ipGeoLocation.Longtitude))\n self.PrintResult('Organización', ipGeoLocation.Organization)\n self.PrintResult('Código Región', ipGeoLocation.Region)\n self.PrintResult('Nombre Región', ipGeoLocation.RegionName)\n self.PrintResult('Zona Horaria', ipGeoLocation.Timezone)\n self.PrintResult('Código Postal', ipGeoLocation.Zip)\n self.PrintResult('Google Maps', ipGeoLocation.GoogleMapsLink)\n print()\n #.encode('cp737', errors='replace').decode('cp737')\n","repo_name":"cdamiangomez-coder/IPGeoLocation_Spanish","sub_path":"core/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27244805490","text":"def slidingWindow(sequence, winSize, step=1):\n \"\"\"Returns a generator that will iterate through\n the defined chunks of input sequence. Input sequence\n must be iterable.\"\"\"\n\n # Verify the inputs\n try:\n it = iter(sequence)\n except TypeError:\n raise ValueError(\"sequence must be iterable.\")\n if not ((type(winSize) == type(0)) and (type(step) == type(0))):\n raise ValueError(\"type(winSize) and type(step) must be int.\")\n if step > winSize:\n raise ValueError(\"step must not be larger than winSize.\")\n if winSize > len(sequence):\n raise ValueError(\"winSize must not be larger than sequence length.\")\n\n # Pre-compute number of chunks to emit\n numOfChunks = ((len(sequence) - winSize) // step) + 1\n\n # Do the work\n for i in range(0, numOfChunks * step, step):\n yield sequence[i:i + winSize]\n\n\nfrom itertools import islice\n\n\ndef sliding_window(seq, n=4):\n if len(seq) < n:\n yield seq\n \"Returns a sliding window (of width n) over data from the iterable\"\n \" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... \"\n it = iter(seq)\n result = tuple(islice(it, n))\n if len(result) == n:\n yield result\n for elem in it:\n result = result[1:] + (elem,)\n yield result\n","repo_name":"AVakiliT/NLP-Classification-Benchmarks","sub_path":"new_utils.py","file_name":"new_utils.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42120142252","text":"import pygame as pg\r\nimport random\r\n\r\n# Инициализация pg\r\npg.init()\r\n\r\n# Размеры окна\r\nSCREEN_WIDTH = 900\r\nSCREEN_HEIGHT = 550\r\n\r\nICON_SIZE = 80\r\nPADDING = 5\r\n\r\nDOG_WIDTH = 310\r\nDOG_HEIGHT = 500\r\n\r\nDOG_Y = 100\r\n\r\nBUTTON_WIDTH = 200\r\nBUTTON_HEIGHT = 60\r\n\r\nMENU_NAV_XPAD = 90\r\nMENU_NAV_YPAD = 130\r\n\r\nfont = pg.font.Font(None, 40)\r\nfont_mini = pg.font.Font(None, 15)\r\n\r\n\r\ndef load_image(file, width, height):\r\n image = pg.image.load(file).convert_alpha()\r\n image = pg.transform.scale(image, (width, height))\r\n return image\r\n\r\n\r\ndef text_render(text):\r\n return font.render(str(text), True, \"black\")\r\n\r\n\r\nclass Item:\r\n def __init__(self, name, price, file):\r\n self.name = name\r\n self.price = price\r\n self.image = load_image(file, DOG_WIDTH // 1.7, DOG_HEIGHT // 1.7)\r\n self.is_using = False\r\n self.is_bought = False\r\n\r\n self.full_image = load_image(file, DOG_WIDTH, DOG_HEIGHT)\r\n\r\n\r\nclass ClothesMenu:\r\n def __init__(self, game):\r\n self.game = game\r\n self.menu_page = load_image(\"images/menu/menu_page.png\", SCREEN_WIDTH, SCREEN_HEIGHT)\r\n\r\n self.bottom_label_off = load_image(\"images/menu/bottom_label_off.png\", SCREEN_WIDTH, SCREEN_HEIGHT)\r\n self.bottom_label_on = load_image(\"images/menu/bottom_label_on.png\", SCREEN_WIDTH, SCREEN_HEIGHT)\r\n self.top_label_off = load_image(\"images/menu/top_label_off.png\", SCREEN_WIDTH, SCREEN_HEIGHT)\r\n self.top_label_on = load_image(\"images/menu/top_label_on.png\", SCREEN_WIDTH, SCREEN_HEIGHT)\r\n\r\n self.items = [Item(\"Синяя футболка\", 10, \"images/items/blue t-shirt.png\"),\r\n Item(\"Ботинки\", 50, \"images/items/boots.png\"),\r\n Item(\"Шляпа\", 50, \"images/items/hat.png\")]\r\n\r\n self.current_item = 0\r\n\r\n self.item_rect = self.items[0].image.get_rect()\r\n self.item_rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)\r\n\r\n self.next_button = Button(\"Вперёд\", SCREEN_WIDTH - MENU_NAV_XPAD - BUTTON_WIDTH, SCREEN_HEIGHT - MENU_NAV_YPAD,\r\n width=int(BUTTON_WIDTH // 1.2), height=int(BUTTON_HEIGHT // 1.2), func=self.to_next)\r\n\r\n self.previous_button = Button(\"Назад\", MENU_NAV_XPAD + 30, SCREEN_HEIGHT - MENU_NAV_YPAD,\r\n width=int(BUTTON_WIDTH // 1.2), height=int(BUTTON_HEIGHT // 1.2),\r\n func=self.to_previous)\r\n\r\n self.use_button = Button(\"Надеть\", MENU_NAV_XPAD + 30, SCREEN_HEIGHT - MENU_NAV_YPAD - 50 - PADDING,\r\n width=int(BUTTON_WIDTH // 1.2), height=int(BUTTON_HEIGHT // 1.2),\r\n func=self.use_item)\r\n\r\n self.buy_button = Button(\"Купить\", SCREEN_WIDTH // 2 - int(BUTTON_WIDTH // 1.5) // 2,\r\n SCREEN_HEIGHT // 2 + 95,\r\n width=int(BUTTON_WIDTH // 1.5), height=int(BUTTON_HEIGHT // 1.5),\r\n func=self.buy)\r\n\r\n self.price_text = text_render(self.items[self.current_item].price)\r\n self.price_text_rect = self.price_text.get_rect()\r\n self.price_text_rect.center = (SCREEN_WIDTH // 2, 180)\r\n\r\n self.name_text = text_render(self.items[self.current_item].name)\r\n self.name_text_rect = self.name_text.get_rect()\r\n self.name_text_rect.center = (SCREEN_WIDTH // 2, 120)\r\n\r\n self.use_text = text_render(\"Надето\")\r\n self.use_text_rect = self.use_text.get_rect()\r\n self.use_text_rect.midright = (SCREEN_WIDTH - 150, 130)\r\n\r\n self.buy_text = text_render(\"Куплено\")\r\n self.buy_text_rect = self.buy_text.get_rect()\r\n self.buy_text_rect.midright = (SCREEN_WIDTH - 140, 200)\r\n\r\n def update(self):\r\n self.next_button.update()\r\n self.previous_button.update()\r\n self.use_button.update()\r\n self.buy_button.update()\r\n\r\n def is_clicked(self, event):\r\n self.next_button.is_clicked(event)\r\n self.previous_button.is_clicked(event)\r\n self.use_button.is_clicked(event)\r\n self.buy_button.is_clicked(event)\r\n\r\n def to_next(self):\r\n if self.current_item != len(self.items) - 1:\r\n self.current_item += 1\r\n\r\n self.price_text = text_render(self.items[self.current_item].price)\r\n self.price_text_rect = self.price_text.get_rect()\r\n self.price_text_rect.center = (SCREEN_WIDTH // 2, 180)\r\n\r\n self.name_text = text_render(self.items[self.current_item].name)\r\n self.name_text_rect = self.name_text.get_rect()\r\n self.name_text_rect.center = (SCREEN_WIDTH // 2, 120)\r\n\r\n def to_previous(self):\r\n if self.current_item != 0:\r\n self.current_item -= 1\r\n\r\n self.price_text = text_render(self.items[self.current_item].price)\r\n self.price_text_rect = self.price_text.get_rect()\r\n self.price_text_rect.center = (SCREEN_WIDTH // 2, 180)\r\n\r\n self.name_text = text_render(self.items[self.current_item].name)\r\n self.name_text_rect = self.name_text.get_rect()\r\n self.name_text_rect.center = (SCREEN_WIDTH // 2, 120)\r\n\r\n def buy(self):\r\n if self.game.money >= self.items[self.current_item].price:\r\n self.game.money -= self.items[self.current_item].price\r\n self.items[self.current_item].is_bought = True\r\n\r\n def use_item(self):\r\n self.items[self.current_item].is_using = not self.items[self.current_item].is_using\r\n\r\n def draw(self, screen):\r\n screen.blit(self.menu_page, (0, 0))\r\n\r\n screen.blit(self.items[self.current_item].image, self.item_rect)\r\n\r\n if self.items[self.current_item].is_bought:\r\n screen.blit(self.bottom_label_on, (0, 0))\r\n else:\r\n screen.blit(self.bottom_label_off, (0, 0))\r\n if self.items[self.current_item].is_using:\r\n screen.blit(self.top_label_on, (0, 0))\r\n else:\r\n screen.blit(self.top_label_off, (0, 0))\r\n self.next_button.draw(screen)\r\n self.previous_button.draw(screen)\r\n self.use_button.draw(screen)\r\n self.buy_button.draw(screen)\r\n\r\n screen.blit(self.price_text, self.price_text_rect)\r\n screen.blit(self.name_text, self.name_text_rect)\r\n screen.blit(self.use_text, self.use_text_rect)\r\n screen.blit(self.buy_text, self.buy_text_rect)\r\n\r\n\r\nclass Button:\r\n def __init__(self, text, x, y, width=BUTTON_WIDTH, height=BUTTON_HEIGHT, text_font=font, func=None):\r\n self.func = func\r\n\r\n self.idle_image = load_image(\"images/button.png\", width, height)\r\n self.pressed_image = load_image(\"images/button_clicked.png\", width, height)\r\n self.image = self.idle_image\r\n self.rect = self.image.get_rect()\r\n self.rect.topleft = (x, y)\r\n\r\n self.text_font = text_font\r\n self.text = self.text_font.render(str(text), True, \"black\")\r\n self.text_rect = self.text.get_rect()\r\n self.text_rect.center = self.rect.center\r\n\r\n self.is_pressed = False\r\n\r\n def draw(self, screen):\r\n screen.blit(self.image, self.rect)\r\n screen.blit(self.text, self.text_rect)\r\n\r\n def update(self):\r\n mouse_pos = pg.mouse.get_pos()\r\n if self.rect.collidepoint(mouse_pos):\r\n if self.is_pressed:\r\n self.image = self.pressed_image\r\n else:\r\n self.image = self.idle_image\r\n\r\n def is_clicked(self, event):\r\n if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:\r\n if self.rect.collidepoint(event.pos):\r\n self.is_pressed = True\r\n self.func()\r\n elif event.type == pg.MOUSEBUTTONUP and event.button == 1:\r\n self.is_pressed = False\r\n\r\n\r\nclass Game:\r\n def __init__(self):\r\n\r\n # Создание окна\r\n self.screen = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\r\n pg.display.set_caption(\"Виртуальный питомец\")\r\n\r\n self.happiness = 100\r\n self.satiety = 100\r\n self.health = 100\r\n\r\n self.money = 10\r\n\r\n self.coins_per_second = 1\r\n self.costs_of_upgrade = {100: False, 1000: False, 5000: False, 10000: False}\r\n\r\n self.items_on = []\r\n\r\n self.mode = \"Main\"\r\n\r\n # Загрузка фона\r\n self.background = load_image(\"images/background.png\", SCREEN_WIDTH, SCREEN_HEIGHT)\r\n\r\n # Загрузка иконок\r\n self.happiness_image = load_image(\"images/happiness.png\", ICON_SIZE, ICON_SIZE)\r\n self.satiety_image = load_image(\"images/satiety.png\", ICON_SIZE, ICON_SIZE)\r\n self.health_image = load_image(\"images/health.png\", ICON_SIZE, ICON_SIZE)\r\n\r\n self.money_image = load_image(\"images/money.png\", ICON_SIZE, ICON_SIZE)\r\n\r\n # Загрузка изображений для собаки\r\n self.body = load_image(\"images/dog.png\", DOG_WIDTH, DOG_HEIGHT)\r\n\r\n # Создание кнопок\r\n button_x = SCREEN_WIDTH - BUTTON_WIDTH - PADDING\r\n\r\n self.eat_button = Button(\"Еда\", button_x, PADDING + ICON_SIZE)\r\n self.clothes_button = Button(\"Одежда\", button_x, PADDING * 2 + ICON_SIZE + BUTTON_HEIGHT,\r\n func=self.clothes_menu_on)\r\n self.play_button = Button(\"Игры\", button_x, PADDING * 3 + ICON_SIZE + BUTTON_HEIGHT * 2)\r\n\r\n self.upgrade_button = Button(\"Улучшить\", SCREEN_WIDTH - ICON_SIZE, 0,\r\n width=BUTTON_WIDTH // 3, height=BUTTON_HEIGHT // 3,\r\n text_font=font_mini, func=self.increase_money)\r\n\r\n self.buttons = [self.eat_button, self.clothes_button, self.play_button, self.upgrade_button]\r\n\r\n # Создание события для кликера\r\n self.INCREASE_COINS = pg.USEREVENT + 1\r\n pg.time.set_timer(self.INCREASE_COINS, 1000)\r\n\r\n self.clothes_menu = ClothesMenu(self)\r\n\r\n self.run()\r\n\r\n def clothes_menu_on(self):\r\n self.mode = \"Clothes menu\"\r\n\r\n def increase_money(self):\r\n for cost, check in self.costs_of_upgrade.items():\r\n if not check and self.money >= cost:\r\n self.coins_per_second += 1\r\n self.money -= cost\r\n self.costs_of_upgrade[cost] = True\r\n break\r\n\r\n def run(self):\r\n while True:\r\n self.event()\r\n self.update()\r\n self.draw()\r\n\r\n def event(self):\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT:\r\n pg.quit()\r\n exit()\r\n if event.type == pg.KEYDOWN:\r\n if event.key == pg.K_ESCAPE:\r\n self.mode = \"Main\"\r\n\r\n if event.type == self.INCREASE_COINS:\r\n self.money += self.coins_per_second\r\n\r\n if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:\r\n self.money += self.coins_per_second\r\n\r\n for button in self.buttons:\r\n button.is_clicked(event)\r\n\r\n\r\n def update(self):\r\n for button in self.buttons:\r\n button.update()\r\n self.clothes_menu.update()\r\n\r\n def draw(self):\r\n # Отрисовка интерфейса\r\n self.screen.blit(self.background, (0, 0))\r\n\r\n self.screen.blit(self.happiness_image, (PADDING, PADDING))\r\n self.screen.blit(self.satiety_image, (PADDING, PADDING * 2 + ICON_SIZE))\r\n self.screen.blit(self.health_image, (PADDING, PADDING * 3 + ICON_SIZE * 2))\r\n\r\n # Упростить размещение предметов относительно других\r\n self.screen.blit(text_render(self.happiness), (PADDING * 2 + ICON_SIZE, PADDING * 6))\r\n self.screen.blit(text_render(self.satiety), (PADDING * 2 + ICON_SIZE, PADDING * 7 + ICON_SIZE))\r\n self.screen.blit(text_render(self.health), (PADDING * 2 + ICON_SIZE, PADDING * 8 + ICON_SIZE * 2))\r\n\r\n self.screen.blit(self.money_image, (SCREEN_WIDTH - PADDING - ICON_SIZE, PADDING))\r\n self.screen.blit(text_render(self.money), (SCREEN_WIDTH - PADDING - ICON_SIZE - 40, PADDING * 6))\r\n\r\n # Отрисовка кнопок\r\n for button in self.buttons:\r\n button.draw(self.screen)\r\n\r\n # Отрисовка собаки\r\n self.screen.blit(self.body, (SCREEN_WIDTH // 2 - DOG_WIDTH // 2, DOG_Y))\r\n\r\n for item in self.clothes_menu.items:\r\n if item.is_using:\r\n self.screen.blit(item.full_image, (SCREEN_WIDTH // 2 - DOG_WIDTH // 2, DOG_Y))\r\n\r\n if self.mode == \"Clothes menu\":\r\n self.clothes_menu.draw(self.screen)\r\n\r\n pg.display.flip()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n Game()","repo_name":"SnaRad2020/v_pet","sub_path":"chernouick.py","file_name":"chernouick.py","file_ext":"py","file_size_in_byte":12847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37283880018","text":"#\n# @lc app=leetcode id=2231 lang=python3\n#\n# [2231] Largest Number After Digit Swaps by Parity\n#\n\n# @lc code=start\nimport heapq\n\nclass Solution:\n def largestInteger(self, num: int) -> int:\n odd, even = [], []\n\n nums = list(str(num))\n n = len(nums)\n\n for i in range(n):\n d = ord(nums[i]) - ord('0')\n if d % 2:\n heapq.heappush(odd, -d)\n else:\n heapq.heappush(even, -d)\n\n ans = 0\n for i in range(n):\n ans *= 10\n if int(nums[i]) % 2:\n ans -= heapq.heappop(odd)\n else:\n ans -= heapq.heappop(even)\n\n return ans\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"2231.largest-number-after-digit-swaps-by-parity.py","file_name":"2231.largest-number-after-digit-swaps-by-parity.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"71340158245","text":"from operator import le, truediv\nimport os, sys\nimport re\nfrom tkinter import W\n\ndef solve(data: str, target) -> bool:\n dp_array = [False] * (len(target) + 1)\n dp_array[len(target)] = True\n\n for i in range(len(target) - 1, -1, -1):\n for w in data:\n if i+len(w) <= len(target) and target[i:i+len(w)] == w:\n dp_array[i] = dp_array[i+len(w)]\n if dp_array[i]:\n break\n return dp_array[0]\n \n\nif __name__ == \"__main__\":\n sys.stdin = open('input.txt', 'r')\n sys.stdout = open('output.txt', 'w')\n target = str(input())\n data = list(map(str, input().split(' ')))\n print(solve(data, target))","repo_name":"daitoch/Leetcode-python","sub_path":"word_break.py","file_name":"word_break.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42135184820","text":"\"\"\"SensorSetManagerMDI class file.\"\"\"\n\nimport os\nimport dateutil.parser\n#pylint: disable=E0611\n#pylint: disable=E0401\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import QVBoxLayout, QTreeWidgetItem, QMessageBox\nfrom PyQt5.QtCore import Qt\nfrom gui.base_mdi import BaseMDI\nfrom gui.ui import SensorSetManagerMDIUi\nfrom gui.sensor_data_view_widget import SensorDataViewWidget\nfrom gui.time_control_widget import TimeControlWidget\nfrom gui.gui_utils import save_message_box, get_save_file, get_open_files\nfrom gui.plot.plot_data import PlotData\nfrom models.sensor_data import SENSORTYPES, SENSORTYPES_VALUES_SIZES\n#pylint: enable=E0401\n#pylint: enable=E0611\n\nclass SensorSetManagerMDI(BaseMDI):\n \"\"\"Main Window class\"\"\"\n\n ###############################################################################################\n # Init Method\n ###############################################################################################\n def __init__(self, sensor_set_data, working_dir=None, has_changes=False, parent=None):\n \"\"\"Init method\"\"\"\n BaseMDI.__init__(self, parent, SensorSetManagerMDIUi)\n\n self._sensor_set_data = sensor_set_data\n self._working_dir = working_dir\n self._has_changes = has_changes\n self._sensor_data_view_widget = None\n self._time_control_widget = None\n self._json_file = None\n\n self._configure_gui()\n self._fill_fields()\n self._make_connections()\n\n ###############################################################################################\n # Public Methods\n ###############################################################################################\n def get_title(self):\n \"\"\"Get window name\"\"\"\n title = self._sensor_set_data.data_id\n return title if not self._has_changes else title + '*'\n\n @staticmethod\n def get_icon():\n \"\"\"get icon\"\"\"\n return QIcon(':/icons/sensor_manager.png')\n\n def set_json_file(self, json_file):\n \"\"\"Set json file.\"\"\"\n self._json_file = json_file\n\n ###############################################################################################\n # Private Methods\n ###############################################################################################\n def _configure_gui(self):\n self.gui.verticalSplitter.setStretchFactor(0, 1)\n self.gui.verticalSplitter.setStretchFactor(1, 20)\n self.gui.optionsSplitter.setStretchFactor(0, 1)\n self.gui.optionsSplitter.setStretchFactor(1, 8)\n\n self._sensor_data_view_widget = SensorDataViewWidget()\n self._time_control_widget = TimeControlWidget()\n layout = QVBoxLayout()\n layout.addWidget(self._sensor_data_view_widget)\n layout.addWidget(self._time_control_widget)\n self.gui.dataVisualizationGroup.setLayout(layout)\n\n self._tree_parent_device = QTreeWidgetItem(self.gui.sensorDataTree)\n self._tree_parent_device.setExpanded(True)\n self._tree_parent_device.setFlags(Qt.ItemIsEnabled)\n self._refresh_tree_view()\n\n self._data_view_refresh()\n\n def _fill_fields(self):\n self.gui.dataIDField.setText(self._sensor_set_data.data_id)\n self.gui.deviceNameField.setText(self._sensor_set_data.device_name)\n self.gui.deviceLocationField.setText(self._sensor_set_data.device_location)\n device_type = self._sensor_set_data.device_type\n index = self.gui.deviceTypeList.findText(device_type, Qt.MatchFixedString)\n if index >= 0:\n self.gui.deviceTypeList.setCurrentIndex(index)\n\n def _make_connections(self):\n self.gui.dataIDField.textChanged.connect(self._data_id_field_changed)\n self.gui.deviceNameField.textChanged.connect(self._device_name_field_changed)\n self.gui.deviceLocationField.textChanged.connect(self._device_location_field_changed)\n self.gui.deviceTypeList.currentIndexChanged.connect(self._device_type_list_changed)\n self.gui.saveButton.clicked.connect(self._save_button_clicked)\n self.gui.addSensorButton.clicked.connect(self._add_sensor_button_clicked)\n self.gui.deleteSensorButton.clicked.connect(self._delete_sensor_button_clicked)\n self.gui.sensorDataTree.itemSelectionChanged.connect(self._sensor_tree_selection_changed)\n self._time_control_widget.time_updated.connect(self._time_updated)\n\n def _update_tree_view(self):\n self._tree_parent_device.setText(0, self._sensor_set_data.device_name)\n if self._sensor_set_data.device_type == 'smartphone':\n self._tree_parent_device.setIcon(0, QIcon(':/icons/smartphone.png'))\n if self._sensor_set_data.device_type == 'smartwatch':\n self._tree_parent_device.setIcon(0, QIcon(':/icons/smartwatch.png'))\n\n def _refresh_tree_view(self):\n self._update_tree_view()\n self._tree_parent_device.takeChildren()\n for sensor_data in self._sensor_set_data.sensors_data:\n child = QTreeWidgetItem(self._tree_parent_device)\n child_text = '{} ({} values)'.format(sensor_data.sensor_type, len(sensor_data.readings))\n child.setText(0, child_text)\n child.setText(1, sensor_data.sensor_type)\n child.setIcon(0, QIcon(':/icons/sensor.png'))\n\n def _save(self):\n if len(self._sensor_set_data.sensors_data) == 0:\n confirm_save = QMessageBox.warning(self, \"Alert\", \\\n \"This data does not have any sensor. Do you want save?\", \\\n QMessageBox.Ok | QMessageBox.Cancel)\n if confirm_save == QMessageBox.Cancel:\n return False\n\n if self._json_file is not None:\n self._sensor_set_data.save(self._json_file)\n self._has_changes = False\n else:\n suggestion = os.path.join(self._working_dir, self._sensor_set_data.data_id + '.json')\n json_file = get_save_file(self, 'Save file', \"JSON Files (*.json)\", suggestion)\n if json_file is None:\n return False\n self._sensor_set_data.save(json_file)\n self._json_file = json_file\n self._has_changes = False\n return True\n\n def _data_view_refresh(self):\n selected_itens = self.gui.sensorDataTree.selectedItems()\n if selected_itens:\n selected_plots_data = []\n selected_sensors_data = []\n for selected_item in selected_itens:\n sensor_type = selected_item.text(1)\n sensor_data = self._sensor_set_data.get_sensor_data(sensor_type)\n plot_data = self._make_plot_data(sensor_data)\n if plot_data is not None:\n selected_sensors_data.append(sensor_data)\n selected_plots_data.append(plot_data)\n start_time, _ = self._update_time_control(selected_sensors_data)\n self._time_control_widget.set_enable(True)\n self._time_control_widget.show()\n self._sensor_data_view_widget.clear()\n self._sensor_data_view_widget.add_plots_data(selected_plots_data)\n self._sensor_data_view_widget.update_central_time(start_time)\n self._sensor_data_view_widget.show()\n else:\n self._sensor_data_view_widget.hide()\n self._time_control_widget.set_enable(False)\n self._time_control_widget.hide()\n\n @staticmethod\n def _make_plot_data(sensor_data):\n \"\"\"make plot data\"\"\"\n readings = sensor_data.readings\n timestamps = None\n values = None\n if sensor_data.sensor_type in ('accelerometer', 'gyroscope', 'magnetometer'):\n timestamps, x_values, y_values, z_values = zip(*readings)\n values = {}\n values['x'] = x_values\n values['y'] = y_values\n values['z'] = z_values\n return PlotData(sensor_data.sensor_type, timestamps, values)\n elif sensor_data.sensor_type == 'barometer':\n timestamps, hpa_values = zip(*readings)\n values = {}\n values['hpa'] = hpa_values\n return PlotData(sensor_data.sensor_type, timestamps, values)\n else:\n return None\n\n\n\n\n def _update_time_control(self, selected_sensors_data):\n \"\"\"update time control\"\"\"\n starts = []\n ends = []\n intervals = []\n for sensor_data in selected_sensors_data:\n starts.append(sensor_data.start_time)\n ends.append(sensor_data.end_time)\n intervals.append(sensor_data.interval)\n start_time = min(starts) if starts else None\n end_time = max(ends) if ends else None\n interval = min(intervals) if intervals else None\n self._time_control_widget.set_control_values(start_time=start_time,\n end_time=end_time,\n interval=interval)\n return start_time, end_time\n\n ###############################################################################################\n # Private Slots\n ###############################################################################################\n def _data_id_field_changed(self, new_data_id):\n self._has_changes = True\n self._sensor_set_data.data_id = new_data_id\n self.title_updated.emit(self.get_title())\n self._update_tree_view()\n self.title_updated.emit(self.get_title())\n\n def _device_name_field_changed(self, new_device_name):\n self._has_changes = True\n self._sensor_set_data.device_name = new_device_name\n self._update_tree_view()\n self.title_updated.emit(self.get_title())\n\n def _device_location_field_changed(self, new_location_name):\n self._has_changes = True\n self._sensor_set_data.device_location = new_location_name\n self._update_tree_view()\n self.title_updated.emit(self.get_title())\n\n def _device_type_list_changed(self):\n self._has_changes = True\n self._sensor_set_data.device_type = self.gui.deviceTypeList.currentText()\n self._update_tree_view()\n self.title_updated.emit(self.get_title())\n\n def _save_button_clicked(self):\n self._save()\n self.title_updated.emit(self.get_title())\n\n def _add_sensor_button_clicked(self):\n sensor_data_files = get_open_files(self, 'Open Sensor Files', 'Text File (*.txt)')\n for sensor_data_file in sensor_data_files:\n sensor_type, readings = self._process_sensor_data_file(sensor_data_file)\n if self._sensor_set_data.has_sensor(sensor_type):\n QMessageBox.critical(self, \"Alert\", \\\n \"This sensor data already has the {} sensor\".format(sensor_type), \\\n QMessageBox.Ok)\n else:\n self._has_changes = True\n self._sensor_set_data.add_sensor_data(sensor_type, readings)\n self._refresh_tree_view()\n self.title_updated.emit(self.get_title())\n\n def _delete_sensor_button_clicked(self):\n confirm_delete = QMessageBox.warning(self, \"Alert\", \\\n \"Want to delete?\", QMessageBox.Ok | QMessageBox.Cancel)\n if confirm_delete == QMessageBox.Ok:\n selected_itens = self.gui.sensorDataTree.selectedItems()\n for item in selected_itens:\n self._has_changes = True\n self._sensor_set_data.remove_sensor_data(item.text(1))\n self._refresh_tree_view()\n self.title_updated.emit(self.get_title())\n\n def _sensor_tree_selection_changed(self):\n selected_itens = self.gui.sensorDataTree.selectedItems()\n if not selected_itens:\n self.gui.deleteSensorButton.setEnabled(False)\n else:\n self.gui.deleteSensorButton.setEnabled(True)\n self._data_view_refresh()\n\n def _time_updated(self, time):\n \"\"\"control current updated slot\"\"\"\n self._sensor_data_view_widget.update_central_time(time)\n\n\n\n ###############################################################################################\n # Protected auxiliar method\n ###############################################################################################\n def _process_sensor_data_file(self, sensor_data_file):\n \"\"\"process a text file with sensor data\"\"\"\n\n if not os.path.isfile(sensor_data_file):\n QMessageBox.critical(self, 'Error', 'File not found: {}', QMessageBox.Ok)\n\n sensor_type = None\n for s_type in SENSORTYPES:\n if s_type in sensor_data_file:\n sensor_type = s_type\n\n if sensor_type is None:\n QMessageBox.critical(self, 'Error', 'Invalid sensor type: {}', QMessageBox.Ok)\n return None, None\n\n readings = []\n for line in open(sensor_data_file):\n reading = line.split(';')\n if len(reading) != (SENSORTYPES_VALUES_SIZES[sensor_type] + 1):\n QMessageBox.critical(self, 'Error', 'Invalid sensor type: {}', QMessageBox.Ok)\n return None, None\n reading[0] = dateutil.parser.parse(reading[0])\n for idx in range(1, len(reading)):\n reading[idx] = float(reading[idx].replace(',', '.'))\n readings.append(reading)\n\n return sensor_type, readings\n\n ###############################################################################################\n # Override methods\n ###############################################################################################\n #pylint: disable=C0103\n def closeEvent(self, event):\n \"\"\"close event\"\"\"\n if not self._has_changes:\n event.accept()\n else:\n save_question = save_message_box(self)\n if save_question == QMessageBox.Save:\n if self._save():\n event.accept()\n else:\n event.ignore()\n elif save_question == QMessageBox.Cancel:\n event.ignore()\n elif save_question == QMessageBox.Discard:\n event.accept()\n #pylint: enable=C0103\n","repo_name":"acnazarejr/vsdt","sub_path":"src/gui/sensor_set_manager_mdi.py","file_name":"sensor_set_manager_mdi.py","file_ext":"py","file_size_in_byte":14179,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70562274404","text":"\r\nfrom agent import *\r\nfrom morpion import *\r\nimport morpion as mp\r\n\r\n\r\ndef main():\r\n\tgame = Morpion()\r\n\r\n\tx_player = Agent('X')\r\n\to_player = Agent('O')\r\n\r\n\tmp.play(game, x_player, o_player, print_game=True)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n\r\n","repo_name":"Viet281101/ITLMAU","sub_path":"Semestre_3_L2/Introduction_Intelligence_Artificielle_L2/TP3_Minimax_Morpion/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1636707487","text":"import sys\nimport coremltools as ct\nimport coremltools.proto.FeatureTypes_pb2 as ft\n\ndef update_multiarray_to_float32(feature):\n if feature.type.HasField(\"multiArrayType\"):\n feature.type.multiArrayType.dataType = ft.ArrayFeatureType.FLOAT32\n\nif len(sys.argv) != 3:\n print(\"USAGE: %s \" % sys.argv[0])\n sys.exit(1)\n\ninput_model_path = sys.argv[1]\noutput_model_path = sys.argv[2]\n\nspec = ct.utils.load_spec(input_model_path)\n\nfor feature in spec.description.input:\n update_multiarray_to_float32(feature)\n\nfor feature in spec.description.output:\n update_multiarray_to_float32(feature)\n\nct.utils.save_spec(spec, output_model_path)\n","repo_name":"hollance/coreml-survival-guide","sub_path":"Scripts/convert_multiarrays_to_floats.py","file_name":"convert_multiarrays_to_floats.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":233,"dataset":"github-code","pt":"52"} +{"seq_id":"13314651156","text":"# Names: Matthew Angelakos, Nicholas Weidman, Winston Lee\n# Pledge: I pledge my honor that I have abided by the Stevens Honor System.\n\n\nimport data_manager # all functions involing interaction with the database\nimport database_loader as db_load # load_database and save_database functions\nfrom sort import * # sort functions\n\n\ndef enter_preferences(database, username):\n \"\"\"Prompts the user to enter new liked artists, and replaces any previous preferences.\"\"\"\n liked_artists = []\n artist = input(\"Enter an artist that you like ( Enter to finish ): \")\n while artist != \"\":\n liked_artists.append(artist)\n artist = input(\"Enter an artist that you like ( Enter to finish ): \")\n data_manager.update_database(database, [username, liked_artists])\n\n\ndef get_recommendations(database, username):\n \"\"\"Prints recommended artists for the user based on their own preferences.\"\"\"\n recommendations = data_manager.findRecommendations(database, username)\n sort(recommendations)\n if len(recommendations) <= 0:\n print(\"No recommendations available at this time.\")\n else:\n for i in range(len(recommendations)):\n print(recommendations[i])\n\n\ndef show_most_popular(database):\n \"\"\"Most popular aritst based on the example using a database\"\"\"\n mostPopular = data_manager.mostPopular(database)\n if len(mostPopular) == 0:\n print(\"Sorry, no artists found.\")\n else:\n for artist in mostPopular:\n print(artist)\n\n\ndef how_most_popular(database):\n \"\"\"how many people like the most popular artists from a database\"\"\"\n data_manager.howPopular(database)\n\n\ndef user_most_likes(database):\n \"\"\"prints the user with the most liked artists, one per line and sorted if more than one\"\"\"\n data_manager.userMostLikes(database)\n\n\ndef delete_preferences(database, username):\n \"\"\"Prints the current users preferences on the screen and removes a\n preference depending on the user's input\"\"\"\n count = 1\n string = \"Which number would you like to remove? (Enter to cancel)\\n\"\n while count <= len(list(database[username])):\n string += (str(count) + \". \" + list(database[username])[count - 1]) + \"\\n\"\n count += 1\n delete = input(string)\n if delete.isnumeric() and int(delete) - 1 < len(database[username]) and int(delete) > 0:\n database[username] = database[username][0:int(delete) - 1] + database[username][int(delete):]\n print(\"Number \" + str(delete) + \" has been removed!\\n\")\n elif delete == \"\":\n print(\"Deletion Cancelled\\n\")\n else:\n print(\"Invalid choice!\\n\")\n\n\ndef show_preferences(database, username):\n \"\"\"Prints the current users preferences on the screen.\"\"\"\n count = 1\n string = \"Here are your current preferences:\\n\"\n while count <= len(list(database[username])):\n string += (str(count) + \". \" + list(database[username])[count - 1]) + \"\\n\"\n count += 1\n print(string)\n\n\ndef main():\n \"\"\"Main method for running the music recommender.\"\"\"\n # Loading data and user\n menu = \"Enter a letter to choose an option :\\n e - Enter preferences\\n r - Get recommendations\\n p - Show most \" \\\n \"popular artists\\n h - How popular is the most popular\\n m - Which user has the most likes\\n d - Delete \" \\\n \"Preferences\\n s - Show Preferences\\n q - Save and \" \\\n \"quit\\n \"\n filename = \"musicrecplus.txt\"\n database = db_load.load_database(filename)\n username = input(\"Enter your name ( put a $ symbol after your name if you wish your preferences to remain private \"\n \"): \")\n if username not in database:\n enter_preferences(database, username)\n\n # Menu\n print(menu)\n user_choice = input()\n while user_choice != \"q\":\n if user_choice == \"e\":\n enter_preferences(database, username)\n elif user_choice == \"r\":\n get_recommendations(database, username)\n elif user_choice == \"p\":\n show_most_popular(database)\n elif user_choice == \"h\":\n how_most_popular(database)\n elif user_choice == \"m\":\n user_most_likes(database)\n elif user_choice == \"d\":\n delete_preferences(database, username)\n elif user_choice == \"s\":\n show_preferences(database, username)\n else:\n print(\"Invalid choice!\\n\")\n print(menu)\n user_choice = input()\n\n # Save and quit\n db_load.save_database(database, filename)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Winner-exe/GroupProject","sub_path":"musicrecplus.py","file_name":"musicrecplus.py","file_ext":"py","file_size_in_byte":4518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33549102934","text":"\"\"\"\n计算最多有多少条线段重合, 线段两端都是整数, 且重合长度必须>=1\n\"\"\"\nimport sortedcontainers as stc\n\n\ndef max_line_cover_iter(lines: list[list[int]]) -> int:\n # min, max 第一条线段的起始位置与结束位置\n min_val = lines[0][0]\n max_val = lines[0][1]\n # 找到所有线段中最小的起始位置与最大的结束位置, 线段的范围\n for line in lines:\n min_val = min(min_val, line[0])\n max_val = max(max_val, line[1])\n ans = 0\n # 找到所有经过x.5的线段, 找到经过x.5最多的线段\n i = min_val + 0.5\n while i < max_val:\n cover = 0\n for line in lines:\n if line[0] < i < line[1]:\n cover += 1\n ans = max(ans, cover)\n i += 0.5\n return ans\n\n\ndef max_line_cover(lines: list[list[int]]) -> int:\n lines.sort()\n ans = 0\n # 新建一个小根堆\n s = stc.SortedList()\n for line in lines:\n # 若s还有值(里面的值代表之前线段的结尾), 且之前线段的结尾 <= 当前线段的起始位置, 自然不会重合, 弹出\n while s and s[0] <= line[0]:\n s.pop(0)\n # 将当前线段的结束位置加入\n s.add(line[1])\n # len(s) 计算以当前线段的起始位置开始有多少条线段穿过了它\n ans = max(ans, len(s))\n return ans\n\n\nif __name__ == '__main__':\n lines = [[1, 2], [2, 5], [1, 8], [6, 9], [6, 7], [5, 7], [3, 4]]\n print(max_line_cover_iter(lines.copy()))\n print(max_line_cover(lines.copy()))\n","repo_name":"LCW-QAQ/algorithme","sub_path":"src/binary_heap/max_line_cover.py","file_name":"max_line_cover.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10296073214","text":"import re\n\nfrom django.utils.translation import gettext_lazy\n\nfrom weblate.trans.autofixes.base import AutoFix\n\nQUOTE_PARAM = re.compile(r\"'(\\{[^}]+\\})'\")\nSINGLE_APO = re.compile(r\"'{1,3}\")\nDOUBLE_APO = re.compile(r\"'{4,}\")\nREPLACEMENT = \"__weblate:quote__\"\nREPLACE_STRING = rf\"{REPLACEMENT}\\1{REPLACEMENT}\"\n\n\nclass DoubleApostrophes(AutoFix):\n \"\"\"\n Ensures apostrophes are escaped in Java Properties MessageFormat string.\n\n - all apostrophes except ones around {} vars are doubled\n\n Note: This fix is not really generically applicable in all cases, that's\n why it's not enabled by default.\n \"\"\"\n\n fix_id = \"java-messageformat\"\n name = gettext_lazy(\"Apostrophes in Java MessageFormat\")\n\n def fix_single_target(self, target, source, unit):\n flags = unit.all_flags\n if (\"auto-java-messageformat\" not in flags or \"{0\" not in source) and (\n \"java-format\" not in flags\n ):\n return target, False\n # Split on apostrophe\n new = SINGLE_APO.sub(\n \"''\", DOUBLE_APO.sub(\"''''\", QUOTE_PARAM.sub(REPLACE_STRING, target))\n ).replace(REPLACEMENT, \"'\")\n return new, new != target\n","repo_name":"WeblateOrg/weblate","sub_path":"weblate/trans/autofixes/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":3905,"dataset":"github-code","pt":"52"} +{"seq_id":"36515497835","text":"import time \r\nimport os\r\nimport socket \r\nimport threading\r\nfrom queue import Queue\r\n### REMOTE MANAGEMENT SERVER ###\r\n\r\n# THREADING SETUP \r\nNUMBER_OF_THREADS = 2\r\nJOB_NUMBER = [1,2]\r\nqueue = Queue()\r\n# ARRAYS TO STORE CONNECTIONS AND ADDRESSES\r\nall_connections = []\r\nall_addresses = [] \r\n\r\n# CREATES SOCKET\r\ndef socket_create():\r\n try:\r\n global host\r\n global port\r\n global s\r\n host = socket.gethostname()\r\n port = 8080\r\n s = socket.socket()\r\n except socket.error as msg:\r\n print(\"Socket error: \" + str(msg))\r\n# BINDS SOCKET TO HOST AND PORT\r\ndef socket_bind():\r\n try:\r\n global host\r\n global port\r\n global s\r\n s.bind((host,port))\r\n s.listen(5)\r\n except socket.error as msg:\r\n print(\"Socket binding error: \" +str(msg))\r\n time.sleep(5)\r\n socket_bind()\r\n# ACCEPT CONNECTIONS - WIPES ARRAYS AND SETS UP CONNECTIONS - (Everytime file is ran the connections are wiped and set up again)\r\ndef accept_connections():\r\n for c in all_connections:\r\n c.close()\r\n del all_connections[:]\r\n del all_addresses[:]\r\n while 1:\r\n try:\r\n conn,address = s.accept()\r\n conn.setblocking(1)\r\n all_connections.append(conn)\r\n all_addresses.append(address)\r\n print(\"\\nConnection has been established! \" + address[0])\r\n except:\r\n print(\"Error accepting connections!\") \r\n \r\n \r\n \r\n# SHELL - EXECUTE COMMANDS\r\ndef shell():\r\n global prevselected\r\n while 1:\r\n cmd = input(host+'@ServerShell~# ')\r\n if cmd == 'list':\r\n list_connections()\r\n elif 'select' in cmd:\r\n conn = get_connection(cmd)\r\n prevselected = cmd #Stores the last selected client, can be used for more commands later on.\r\n if conn is not None:\r\n send_commands(conn)\r\n elif 'help' in cmd:\r\n print(\"\"\"\r\n list - To list all active connections\r\n select - To select a client to send commands to\r\n quit - To quit the server\r\n \"\"\")\r\n elif 'quit' in cmd:\r\n print(\"Server terminated.\")\r\n exit()\r\n else:\r\n print(\"\")\r\n print(\"Unknown Command...\")\r\n print(\"\")\r\n \r\n# 'LIST' FUNCTION - TO LIST ALL CONNECTIONS TO SERVER \r\ndef list_connections():\r\n showlist =\"\"\r\n for i, conn in enumerate(all_connections):\r\n try:\r\n conn.send(str.encode(':)')) #TESTS CONNECTION BY SENDING BYTES\r\n conn.recv(20480)\r\n except:\r\n del all_connections[i]\r\n del all_addresses[i]\r\n continue\r\n showlist += str(i) + ' ' + str(all_addresses[i][0]) + ' ' + str(all_addresses[i][1]) +'\\n'\r\n print('--------- CLIENTS --------- '+ '\\n' + showlist)\r\n \r\n# 'SELECT' FUNCTION - GETS CONNECTION WHEN SELECTING (I.E. 'SELECT 0')\r\ndef get_connection(cmd):\r\n try:\r\n connection = cmd.replace('select ' , '')\r\n connection = int(connection)\r\n conn = all_connections[connection]\r\n print(\"You have been connected to \" +str(all_addresses[connection][0]))\r\n print(str(all_addresses[connection][0]) + \"~> \", end=\"\")\r\n return conn\r\n except:\r\n print(\"Invalid selection\")\r\n return None\r\n# SENDS COMMANDS TO CLIENT, [CMDS when connected must have '#' before command.]\r\ndef send_commands(conn):\r\n while True:\r\n try:\r\n cmd = input()\r\n if len(str.encode(cmd)) > 0:\r\n conn.send(str.encode(cmd))\r\n client_response =str(conn.recv(20480),\"utf-8\")\r\n print(client_response, end=\"\")\r\n if cmd == '#quit':\r\n break\r\n\r\n elif cmd == '#help':\r\n print(\" \")\r\n print(\" \")\r\n print(\" \")\r\n print(\"#quit - To quit connection and return to server shell\")\r\n except:\r\n print(\"Connection has been lost !\")\r\n break\r\n \r\n# THREADING AND WORKERS\r\ndef create_workers():\r\n for _ in range(NUMBER_OF_THREADS):\r\n t = threading.Thread(target=work)\r\n t.daemon = True\r\n t.start()\r\n \r\ndef work():\r\n while True:\r\n x = queue.get()\r\n if x == 1:\r\n socket_create()\r\n socket_bind()\r\n accept_connections()\r\n if x == 2:\r\n shell()\r\n queue.task_done()\r\n \r\ndef create_jobs():\r\n for x in JOB_NUMBER:\r\n queue.put(x)\r\n queue.join()\r\n \r\n\r\n\r\ncreate_workers()\r\ncreate_jobs()\r\n\r\n","repo_name":"LorenzoEscobar/RemoteManagementTool","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44680707608","text":"import random\r\nfrom result_handler import result_handler\r\nfrom rolls import Roll\r\nfrom players import Player\r\nfrom print_output import print_header, print_round_count, print_choices, print_congratulations\r\nimport logbook\r\nimport sys\r\n\r\ngame_log = logbook.Logger('GAME_LOG')\r\n\r\n\r\ndef main():\r\n print_header()\r\n player1 = Player(Player.get_players_name())\r\n player2 = Player(Player.get_computer_name())\r\n rolls = Roll.build_the_three_rolls()\r\n game_loop(player1, player2, rolls)\r\n \r\n\r\ndef find_winner(player1, player2):\r\n if player1.current_score == 2:\r\n winner = player1.name\r\n if player2.current_score == 2:\r\n winner = player2.name\r\n return winner\r\n\r\n\r\ndef game_loop(player1, player2, rolls):\r\n game_log.info(f'Game started')\r\n count = 1\r\n player1.current_score = 0\r\n player2.current_score = 0\r\n while player1.current_score < 2 and player2.current_score < 2:\r\n print_round_count(count)\r\n game_log.info(f'Round {count}')\r\n\r\n# get rolls for current round\r\n player2.current_roll = random.choice(list(rolls.values()))\r\n player1.pick_current_roll(rolls)\r\n print_choices(player1, player2)\r\n game_log.info(f'Roll of {player1.name}: {player1.current_roll.name}')\r\n game_log.info(f'Roll of {player2.name}: {player2.current_roll.name}')\r\n\r\n# round results\r\n round_result = player1.current_roll.fight_against(player2.current_roll)\r\n result_handler.get(round_result)(player1, player2)\r\n game_log.info(f'{player1.name}: {round_result}')\r\n game_log.info(f'{player1.name}: {player1.current_score}')\r\n game_log.info(f'{player2.name}: {player2.current_score}')\r\n\r\n if round_result in ('win', 'lose'): count += 1\r\n\r\n winner = find_winner(player1, player2)\r\n print_congratulations(winner)\r\n game_log.info(f'Winner: {winner}')\r\n game_log.info(f'Game ended')\r\n\r\n\r\ndef init_logging(filename: str = None):\r\n level = logbook.TRACE\r\n\r\n if filename:\r\n logbook.TimedRotatingFileHandler(filename, level=level).push_application()\r\n else:\r\n logbook.StreamHandler(sys.stdout, level=level).push_application()\r\n\r\n msg = 'Logging initialized, level: {}, mode: {}'.format(level,\r\n \"stdout mode\" if not filename else 'file mode: ' + filename\r\n )\r\n logger = logbook.Logger('Startup')\r\n logger.notice(msg)\r\n\r\n\r\nif __name__ == '__main__':\r\n init_logging(r'log/game.log')\r\n main()\r\n","repo_name":"matthias-gass/rock-paper-scissors","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37611158868","text":"file = 'input.txt'\r\nf = open(file)\r\nstack = ['RPCDBG','HVG','NSQDJPM','PSLGDCNM','JBNCPFLS','QBDZVGTS','BZMHFTQ','CMDBF','FCQG']\r\nfor line in f:\r\n print(stack)\r\n line = line.strip()\r\n line = line.split(\" \")\r\n first_number = int(line[1])\r\n second_number = int(line[3])\r\n third_number = int(line[-1])\r\n print(first_number,second_number,third_number)\r\n print(stack)\r\n removed_element = stack.pop(second_number - 1) # wycinam caly index\r\n sliced_element = ''\r\n for x in range(-first_number,0):\r\n sliced_element = sliced_element + removed_element[x] # przygotowuje stringa do insertowania\r\n first_correct_element = removed_element[:-first_number] #wycinam je\r\n stack.insert(second_number - 1, first_correct_element) \r\n sec_removed_element = stack.pop(third_number - 1)\r\n stack.insert(third_number - 1, sec_removed_element + sliced_element) \r\n print(stack)\r\nprint(stack)","repo_name":"Skrilex19/advent-of-codde","sub_path":"day5/day5p2.py","file_name":"day5p2.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30867218754","text":"import matplotlib.pyplot as plt \r\n\r\n\r\ndimension = int(input(\"Que dimension desea ver su histograma?: \"))\r\n\r\ndistancias = [] # Crea una lista vacía para almacenar las distancias\r\n\r\n# Abre el archivo correspondiente basado en la dimensión ingresada\r\nwith open(f\"distancias_{dimension}.txt\", \"r\") as archivo:\r\n for linea in archivo: # Recorre cada línea del archivo\r\n distancia = float(linea.strip()) # Convierte la línea en un número flotante (distancia)\r\n distancias.append(distancia) # Agrega la distancia a la lista distancias\r\n\r\n# Genera el histograma de las distancias con 20 bins\r\nplt.hist(distancias, bins=20)\r\n\r\n\r\nplt.title(f\"Histograma de distancias (Dimensión : {dimension})\")\r\nplt.xlabel(\"Distancia\")\r\nplt.ylabel(\"Frecuencia\")\r\n\r\nplt.show()\r\n","repo_name":"SaulCondoriM/Laboratorio_1-La-maldicion-de-la-dimensionalidad","sub_path":"grafica.py","file_name":"grafica.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31362415475","text":"#!/usr/bin/python\r\n# -*- encoding=utf-8 -*-\r\nimport collections\r\nimport datetime\r\nimport io\r\nimport os\r\nimport re\r\nimport sys\r\nimport random\r\nimport yaml\r\n\r\npaylist = []\r\n\r\ntime_range = [\"20230401\", \"20230701\"] #左闭右开\r\n#sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\r\nSCHEMA = yaml.load(open('script/schema.yaml', encoding ='utf8'), Loader=yaml.FullLoader)\r\nalipay_input_schema = SCHEMA['alipay_input_schema']\r\nwechat_input_schema = SCHEMA['wechat_input_schema']\r\noutput_schema = SCHEMA['output_schema']\r\nlabel_dict = {sub_label: label for label, sub_labels in SCHEMA['label'].items() for sub_label in sub_labels}\r\n\r\nword2label = {}\r\nfor line in open('script/word2label.csv', encoding='gbk'):\r\n rows = line.strip().split(',')\r\n if len(rows) != 2: continue\r\n sub_label, word_list = rows\r\n for word in word_list.split('、'):\r\n if word in ('', ' '): continue\r\n word2label[word] = sub_label\r\n#print(word2label)\r\n\r\ndef auto_label(paylist):\r\n for item in paylist:\r\n #print(item)\r\n # 退款过滤\r\n if item['消费来源'] == '支付宝':\r\n # 支付宝\r\n if item['交易状态'] in ('交易关闭', '退款成功'):\r\n item['to_delete'] = 1\r\n elif item['交易状态'] == '交易成功' and item['成功退款'] != '0.00':\r\n item['商品名称'] += '原价{} 退款{}'.format(item['金额'], item['成功退款'])\r\n item['金额'] = float(item['金额']) - float(item['成功退款'])\r\n else:\r\n # 微信\r\n if '已全额退款' in item['交易状态']:\r\n item['to_delete'] = 1\r\n elif item['收/支'] == '收入' and '已退款' in item['交易状态']:\r\n item['to_delete'] = 1\r\n elif item['收/支'] == '支出' and '已退款' in item['交易状态']:\r\n refund = float(item['交易状态'].split('¥')[1].split(')')[0])\r\n item['商品名称'] += '原价{} 退款{}'.format(item['金额'], refund)\r\n item['金额'] = float(item['金额'].replace('¥','')) - refund\r\n # 花呗过滤\r\n if item['收/支'] == '不计收支' and item['交易对方'] in ('余额宝', '花呗' ,'花呗|信用购'):\r\n item['to_delete'] = 1\r\n\r\n # 自动打标\r\n if item['收/支'] == '收入':\r\n continue\r\n for info in [item['交易对方'], item['商品名称']]:\r\n for word, label in word2label.items():\r\n if word in info:\r\n item['子类型'] = word2label[word]\r\n break\r\n if item['子类型'] != 'other':\r\n break\r\n item['类型'] = label_dict[item['子类型']]\r\n\r\n # 字段清洗\r\n item['商品名称'] = item['商品名称'].replace('收款方备注:二维码收款', '')\r\n item['商品名称'] = item['商品名称'].replace('付款方留言:', '')\r\n item['商品名称'] = item['商品名称'].replace('转账备注', '')\r\n\r\n #专项聚合\r\n # 余额宝\r\n\r\n\r\n \r\ndef parse_concent(filename):\r\n crwod_source = '凡' if 'fan' in filename else '莹'\r\n if 'alipay' in filename:\r\n app_source = '支付宝'\r\n input_schema = alipay_input_schema\r\n encoding_type = 'gbk'\r\n elif 'wechat' in filename:\r\n app_source = '微信'\r\n input_schema = wechat_input_schema\r\n encoding_type = 'utf8'\r\n else:\r\n raise NameError(filename)\r\n \r\n for line in open(filename, encoding = encoding_type):\r\n #if len(line.rstrip('\\n').split(',')) < len(input_schema): continue\r\n item = collections.defaultdict(lambda: '-', zip(input_schema, line.rstrip('\\n').split(',')))\r\n # if not item['交易时间'].startswith('20'): continue\r\n for key in item:\r\n item[key] = item[key].strip()\r\n try:\r\n cur_time = datetime.datetime.strptime(item['交易时间'].strip(), '%Y-%m-%d %H:%M:%S')\r\n except:\r\n continue\r\n start_time = datetime.datetime.strptime(time_range[0], '%Y%m%d')\r\n end_time = datetime.datetime.strptime(time_range[1], '%Y%m%d')\r\n # 时间窗过滤\r\n if cur_time < start_time or cur_time > end_time:\r\n #print(cur_time)\r\n continue\r\n item['子类型'] = 'other'\r\n item['消费来源'] = app_source\r\n item['消费人员'] = crwod_source\r\n item['to_delete'] = 0\r\n paylist.append(item)\r\n\r\ndef gen():\r\n filename_list = ['input/alipay_fan.csv', 'input/wechat_fan.csv', 'input/alipay_ying.csv', 'input/wechat_ying.csv']\r\n # parse paylist\r\n for filename in filename_list:\r\n if os.path.isfile(filename):\r\n parse_concent(filename)\r\n else:\r\n raise NameError(filename)\r\n\r\n paylist.sort(key=lambda x: x['交易时间'])\r\n auto_label(paylist)\r\n\r\n ## output\r\n f_out = open('output_{}_{}.csv'.format(time_range[0], time_range[1]), 'w', encoding = 'gbk', errors='ignore')\r\n f_out.write('\\t'.join([k.strip() for k in output_schema]) + '\\n')\r\n for item in paylist:\r\n f_out.write('\\t'.join([str(item[k]) for k in output_schema]) + '\\n')\r\n f_out.close()\r\n print('gen_paylist successfully')\r\n\r\n\r\n \r\nif __name__ == \"__main__\":\r\n gen()\r\n","repo_name":"Heartloving/Codebook","sub_path":"bill/gen_paylist.py","file_name":"gen_paylist.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34751097154","text":"import numpy as np\nfrom numpy import random as rand\nimport matplotlib.pyplot as plt\n\ndef find_intersections(mAlist, sAlist, Alist):\n adjacency_matrix = np.zeros(shape=(len(mAlist), len(mAlist)))\n for mi in range(len(mAlist)):\n std = sAlist[mi]\n mean = mAlist[mi]\n for smi in range(len(mAlist)):\n substd = sAlist[smi]\n submean = mAlist[smi]\n if (mean + std < submean - substd) or (mean - std > submean + substd):\n adjacency_matrix[mi][smi] = Alist[smi]\n else:\n adjacency_matrix[mi][smi] = 0\n return adjacency_matrix\n\ndef find_variance(kwargs, A_v, R_v, F_v):\n to_find = \"variance\"\n followup_variance = kwargs[(kwargs.index(to_find) + len(to_find) + 1):].strip()\n if \"in\" in followup_variance:\n to_find = \"in\"\n followup_in = followup_variance[(followup_variance.index(to_find) + len(to_find) + 1):].strip()\n if \"A\" in followup_in:\n to_find = \"A\"\n followup = followup_in[(followup_in.index(to_find) + len(to_find) + 1):].strip().split(\" \")\n A_v = (True, np.float32(followup[0]))\n elif \"R\" in followup_in:\n to_find = \"R\"\n followup = followup_in[(followup_in.index(to_find) + len(to_find) + 1):].strip().split(\" \")\n R_v = (True, np.float32(followup[0]))\n elif \"F\" in followup_in:\n to_find = \"F\"\n followup = followup_in[(followup_in.index(to_find) + len(to_find) + 1):].strip().split(\" \")\n F_v = (True, np.float32(followup[0]))\n if \"variance\" in followup_variance:\n return find_variance(followup_variance, A_v, R_v, F_v)\n else:\n return A_v, R_v, F_v\n\ndef sim_adv(A, R, F, sim_times, C, kwargs=\"\"):\n loss = (False, 0, 0)\n gain = (False, 0, 0)\n A_v = (False, None, 0, 0)\n R_v = (False, None, 0, 0)\n F_v = (False, None, 0, 0)\n fragment_imp = (False, 0)\n if len(kwargs) > 0:\n past_kwargs = kwargs\n if \"loss\" in kwargs:\n to_find = \"loss\"\n followup = kwargs[(kwargs.index(to_find) + len(to_find) + 1):].strip().split(\" \")\n loss = (True, np.float32(followup[0]), np.float32(followup[1]))\n if \"gain\" in kwargs:\n to_find = \"gain\"\n followup = kwargs[(kwargs.index(to_find) + len(to_find) + 1):].strip().split(\" \")\n gain = (True, np.float32(followup[0]), np.float32(followup[1]))\n if \"fragment\" in kwargs:\n to_find = \"fragment\"\n followup = kwargs[(kwargs.index(to_find) + len(to_find) + 1):].strip().split(\" \")\n gain = (True, np.int32(followup[0]), np.float32(followup[1]))\n if \"variance\" in kwargs:\n if \"gain\" in kwargs:\n to_find = \"gain\"\n to_find_index = kwargs.index(to_find)\n kwargs = (kwargs[:to_find_index] + kwargs[(to_find_index + len(to_find)):]).strip()\n A_v, R_v, F_v = find_variance(kwargs, A_v, R_v, F_v)\n\n if A_v[0]:\n A += np.random.normal(0, np.sqrt(A_v[1]), 1)[0]\n if R_v[0]:\n R += np.random.normal(0, np.sqrt(R_v[1]), 1)[0]\n if F_v[0]:\n F += np.random.normal(0, np.sqrt(F_v[1]), 1)[0]\n\n T = A + 2 * F\n N = np.int32(np.ceil(C * T / R))\n\n hit_count_list = list()\n out_count_list = list()\n\n for _ in range(sim_times):\n hit_count = 0\n out_count = 0\n starting_points = list()\n\n if not fragment_imp[0]:\n for _ in range(N):\n if loss[0]:\n rand_int = np.random.uniform(0,1)\n if rand_int < 0.5:\n randres = np.floor(rand.uniform(0, A + np.int32(0.5 * F))) + loss[1]\n starting_points.append(randres if randres < A + 0.5 * F else 0)\n else:\n randres = np.floor(rand.uniform(0, A + np.int32(0.5 * F))) - loss[1]\n starting_points.append(randres if randres >= 0 else 0)\n if gain[0]:\n starting_points.append(np.floor(rand.uniform(gain[1], A + np.int32(0.5 * F)) - gain[1]))\n else:\n random_normal_values = np.random.normal(fragment_imp[1], np.sqrt(fragment_imp[2]), np.int32(N / 2))\n for index in range(N):\n random_index1 = np.floor(rand.uniform(0, A + np.int32(0.5 * F)))\n random_index2 = random_index1 + random_normal_values[index]\n starting_points.append(random_index1)\n starting_points.append(random_index2)\n\n A_lower = F\n A_upper = (A_lower - 0.25 * F) + A - 0.75 * F - R\n F_lower = 0\n F_lower_bound = F * 0.5\n F_upper = A_upper\n F_upper_bound = F_upper + F * 0.5\n\n for i in range(N):\n x = starting_points[i]\n if (F_lower <= x and F_lower_bound > x) or (F_upper < x and F_upper_bound >= x):\n hit_count += 1\n elif (A_lower <= x and A_upper >= x):\n out_count += 1\n\n hit_count_list.append(hit_count)\n out_count_list.append(out_count)\n\n sum_hit = 0\n sum_out = 0\n ratio_list = list()\n\n for i in range(sim_times):\n sum_hit += hit_count_list[i]\n sum_out += out_count_list[i]\n ratio_list.append(out_count_list[i] / hit_count_list[i])\n\n std_return = np.round(np.std(ratio_list), decimals=2)\n mean_return = np.round(np.mean(ratio_list), decimals=2)\n print(\"A=\" + str(A) + \", C=\" + str(C) + \", mean=\" + str(mean_return) + \", std=\" + str(std_return))\n return mean_return, std_return\n\nmlist = list()\nslist = list()\ntlist = list()\n\nmdict = {}\nsim_times = 40\n\nREAD_LENGTH = 100\nfragment_variance = 50\n\nClist = [70, 140, 355]\nAlist = np.arange(READ_LENGTH * 2, READ_LENGTH * 8)#[400, 550, 700]#[1000, 1500, 4000]#[1000, 1500, 2000]#[500, 750, 1000, 1250, 1500, 1750, 2000]\nfor C in Clist:\n mdict[C] = {}\n for A in Alist:\n mdict[C][A] = (0, 0)\n\nordered_mean = list()\nordered_t = list()\ntest_list = np.arange(READ_LENGTH, 250, fragment_variance)\niter = 0\n\nfor t in test_list:\n for A in Alist:\n cmean = 0\n for C in Clist:\n mean, std = sim_adv(A, READ_LENGTH, READ_LENGTH, sim_times, C, kwargs=\"fragment \" + str(t) + \" \" + str(fragment_variance))\n mdict[C][A] = (mean, std)\n cmean += mean\n cmean = np.round(cmean / len(Clist), decimals=2)\n ordered_mean.append(cmean)\n ordered_t.append(A)\n print(\"> Progress: \" + str(100 * np.round(iter / (len(test_list) * len(Alist)), decimals=2)) + \"%\")\n iter += 1\n\nfor index in range(len(Alist)):\n plt.scatter(test_list, ordered_mean[index::len(Alist)])\n\nplt.title(\"READ_LENGTH=\" + str(READ_LENGTH) + \" | \" + str(sim_times) + \" iterations per simulation\")\nplt.ylabel(\"X/Y ratio\")\nplt.xlabel(\"t value (the intermediate fragment length | std.dev=\" + str(np.round(np.sqrt(fragment_variance), decimals=2)) + \")\")\nplt.show()\n\n# Fragment size from left end to right end; read lengths [100, 150, 250]; separation of coverages; increase number of simulations to 100;\n# allow fragment length to be smaller than 2R; fragment lengths 400-700 (550~150);\n# Graph of paired reads with error bars; -> add regression line; regression on 95% confidence intervals\n# Describe simulations in text on a document\n# loss: losing data from re-mapping reads (chance of loss?)\n\n# ultimately: how different do ratios have to be so that you can tell that array length changed; can you tell the length of the array (good estimate)?\n# given the length of 1 array (for each array in a sample), compare it with the reference genome array/ratio: can you say whether or not they're different\n # can we say how many copies they have\n# TRID with the suffix _I are labeled indistinguishables; therefore, they may not have accurate read counts/whatever since they may map in a bunch of different places","repo_name":"mkorovkin2/tandem-rep-mkorovkin","sub_path":"deprecated/simulator2_analysis.py","file_name":"simulator2_analysis.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"15424038868","text":"import wx \nimport time \n\n\n# This is a test for a scrollable canvas, with some top and left sliding \n# sub-windows. Similar to the way a spreadsheet works... \n\nclass TriPaneWindow(wx.ScrolledWindow): \n \"\"\" \n This is the main frame holding the other windows and the top level of the \n application \n \"\"\" \n \n def __init__(self, *arguments, **keywords): \n \"\"\" \n Constructor \n \"\"\" \n wx.ScrolledWindow.__init__ (self, *arguments, **keywords) \n self.SetAutoLayout(True) \n self.SetSizer(self.buildSizer()) \n self.SetTargetWindow(self.mainPanel) \n self.SetScrollRate(20,20) \n\n #Events \n #wx.EVT_SIZE(self, self.OnSize) \n self.Bind(wx.EVT_SCROLLWIN, self.OnScrollWindowEvent) \n self.Bind(wx.EVT_LEFT_UP, self.OnClickEvent) \n \n def OnClickEvent(self, event): \n \"\"\" \n For Debug... \n \"\"\" \n print() \n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition())) \n print(\"Size \" + str(self.GetSize())) \n print(\"VirtualSize \" + str(self.GetVirtualSize())) \n event.Skip() \n \n \n def buildSizer(self): \n \"\"\" \n Create the 3 sub windows and the sizer that holds them together. \n \"\"\" \n #Create the panels \n self.topPanel = MyCanvas(self, wx.RED, 40,40, 'Top', True, False) \n self.leftPanel = MyCanvas(self, wx.GREEN, 80,80, 'Left', False, True) \n self.mainPanel = MyMainCanvas(self, wx.WHITE, 100,100, 'Main', True, True) \n self.mainPanel.topPanel = self.topPanel \n self.mainPanel.leftPanel = self.leftPanel \n self.topPanel.mainPanel = self.mainPanel\n self.leftPanel.mainPanel = self.mainPanel\n self.mainPanel.mainPanel = self.mainPanel\n self.topPanel.parentPanel = self\n self.leftPanel.parentPanel = self\n self.mainPanel.parentPanel = self\n \n #Create the sizer \n sizer = wx.FlexGridSizer(2,2,0,0) \n \n #Add the panels to the sizers \n sizer.Add((100,30), 0, wx.EXPAND) \n sizer.Add(self.topPanel, 0, wx.EXPAND) \n sizer.Add(self.leftPanel, 0, wx.EXPAND) \n sizer.Add(self.mainPanel, 0, wx.EXPAND) \n sizer.AddGrowableCol(1) \n sizer.AddGrowableRow(1) \n \n return sizer \n \n def SetCanvasSize(self, width, height): \n \"\"\" \n Set the size of the 3 panes as follow: \n - main = width, height \n - top = width, 40 \n - left = 80, height \n \"\"\" \n self.mainPanel.SetVirtualSize(wx.Size(width,height)) \n (w,h) = self.topPanel.GetSize() \n self.topPanel.SetVirtualSize(wx.Size(width,h)) \n (w,h) = self.leftPanel.GetSize() \n self.leftPanel.SetVirtualSize(wx.Size(w,height)) \n \n \n def OnScrollWindowEvent(self, event): \n \"\"\" \n OnScrollWindow Event Callback. This should let the main panel scroll in \n both direction but transmit the vertical scrolling to the left panel \n and the horizontal scrolling to the top window \n \"\"\"\n sx,sy = self.GetScrollPixelsPerUnit()\n if event.GetOrientation() == wx.HORIZONTAL:\n dx = event.GetPosition()\n dy = self.GetScrollPos(wx.VERTICAL)\n else:\n dx = self.GetScrollPos(wx.HORIZONTAL)\n dy = event.GetPosition()\n \n pos = (dx ,dy) \n print(\"scrolling...\" + str(pos) + str(event.GetPosition()))\n # self.mainPanel.Scroll(dx, dy) \n # self.topPanel.Scroll(dx, 0) \n # self.leftPanel.Scroll(0, dy) \n event.Skip() \n\n def OnSize(self, event ): \n \"\"\" \n OnSize event callback. Currently not used \n \"\"\" \n print(\"Size \" + str(self.GetSize())) \n print(\"VirtualSize \" + str(self.GetVirtualSize())) \n #self.Layout() \n\n\n\n\nclass MyCanvas(wx.ScrolledCanvas): \n \"\"\" \n Custom colored panel for testing \n \"\"\" \n def __init__(self, parent, colour, width, height, name = \"\", dx=True, dy=True): \n wx.ScrolledCanvas.__init__(self, parent, -1) \n self.SetBackgroundColour(colour) \n self.SetSize(wx.Size(width, height)) \n self.SetVirtualSize(wx.Size(width, height)) \n self.use_x = 1 if dx else 0\n self.use_y = 1 if dy else 0\n self.Bind(wx.EVT_LEFT_DOWN, self.OnClickEvent) \n self.Bind(wx.EVT_PAINT, self.OnPaint) \n self.Bind(wx.EVT_SIZE, self.on_size) \n \n # def OnPaint(self, event): \n # \"\"\" \n # OnPaint callback, redraws the window \n # \"\"\" \n \n # dc = wx.PaintDC(self) \n # self.parentPanel.PrepareDC(dc) \n # self.drawGrid(dc) \n\n def on_size(self, event ): \n \"\"\" \n OnSize event callback. Currently not used \n \"\"\" \n print(\"Size \" + str(self.GetSize())) \n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n size = self.GetSize()\n vsize = self.GetVirtualSize()\n if self.use_x and self.use_y:\n # main window, no adjustment\n pass\n elif self.use_x:\n # scrolls in X dir\n self.SetVirtualSize(vsize.x, size.y)\n else:\n self.SetVirtualSize(size.x, vsize.y)\n\n #self.Layout() \n\n def OnPaint(self, event):\n\n dc = wx.PaintDC(self)\n #self.parentPanel.PrepareDC(dc)\n size = self.GetVirtualSize()\n\n s = \"Size: %d x %d\"%(size.x, size.y)\n vbX, vbY = self.parentPanel.GetViewStart()\n posX, posY = self.parentPanel.CalcUnscrolledPosition (0, 0)\n vbX, vbY = vbX * self.use_x, vbY * self.use_y\n posX, posY = posX * self.use_x, posY * self.use_y\n # vbX, vbY = self.GetViewStart()\n # posX, posY = self.CalcUnscrolledPosition (0, 0) \n upd = wx.RegionIterator(self.GetUpdateRegion()) # get the update rect list\n r = []\n while upd.HaveRects():\n rect = upd.GetRect()\n\n # Repaint this rectangle\n #PaintRectangle(rect, dc)\n r.append(\"rect: %s\" % str(rect))\n upd.Next()\n print(s, (posX, posY), (vbX, vbY), \" \".join(r))\n dc.SetLogicalOrigin(posX, posY)\n\n dc.SetFont(wx.NORMAL_FONT)\n w, height = dc.GetTextExtent(s)\n height += 3\n dc.SetBrush(wx.WHITE_BRUSH)\n dc.SetPen(wx.WHITE_PEN)\n dc.DrawRectangle(0, 0, size.x, size.y)\n dc.SetPen(wx.LIGHT_GREY_PEN)\n dc.DrawLine(0, 0, size.x, size.y)\n dc.DrawLine(0, size.y, size.x, 0)\n dc.DrawText(s, (size.x-w)/2, (size.y-height*5)/2)\n\n if False:\n\n pi = self._mgr.GetPane(self)\n\n s = \"Layer: %d\"%pi.dock_layer\n w, h = dc.GetTextExtent(s)\n dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*1))\n\n s = \"Dock: %d Row: %d\"%(pi.dock_direction, pi.dock_row)\n w, h = dc.GetTextExtent(s)\n dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*2))\n\n s = \"Position: %d\"%pi.dock_pos\n w, h = dc.GetTextExtent(s)\n dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*3))\n\n s = \"Proportion: %d\"%pi.dock_proportion\n w, h = dc.GetTextExtent(s)\n dc.DrawText(s, (size.x-w)/2, ((size.y-(height*5))/2)+(height*4))\n\n # def OnPaint(self, event):\n # dc = wx.PaintDC(self)\n # self.parentPanel.PrepareDC(dc)\n # size = self.GetVirtualSize()\n # s = \"OnPaint: %s Size: %d x %d\"%(self.Name, size.x, size.y)\n # posX, posY = self.parentPanel.CalcUnscrolledPosition (0, 0) \n # print s, posX, posY\n\n # pen = wx.Pen(wx.BLACK, 5)\n # dc.SetPen(pen)\n\n # for y in range(10):\n # for x in range(10):\n # dc.DrawCircle(x*400+20, y*400+20, 200)\n\n # dc.DrawText('Right click and drag in the direction you want to scroll.',\n # 20, 20)\n # dc.DrawText('The distance from the start of the drag determines the speed.',\n # 20, 50)\n\n def drawGrid(self, dc): \n #Get the offset to the canvas origin \n posX, posY = self.parentPanel.CalcUnscrolledPosition (0, 0) \n \n #Calculate the region to update \n updateRegion = self.GetUpdateRegion() \n box = updateRegion.GetBox() \n width = box.width \n height = box.height \n startX = posX + box.x \n endX = startX + width \n startY = posY + box.y \n endY = startY + height \n\n #erase to the background color (for debug) \n if False: \n dc.SetLogicalFunction(wx.INVERT) \n dc.SetBrush(wx.WHITE_BRUSH) \n dc.SetPen(wx.WHITE_PEN) \n dc.DrawRectangle(startX, startY, width, height) \n time.sleep(0.1) \n dc.SetLogicalFunction(wx.INVERT) \n dc.DrawRectangle(startX, startY, width, height) \n \n data = (self,posX,posY,startX, startY, endX, endY) \n print('Painting \"%s\" pos=%s,%s start=%s,%s end=%s,%s' % data) \n\n \n sizeX = 20 #pixels \n sizeY = 20 #pixels \n \n #Draw Vertical Lines \n diff = startX % (sizeX * 4 ) \n if diff > 0: \n tick = startX - diff \n else: \n tick = startX \n\n nbTick = int((endX - tick) / sizeX) + 1 \n listX = [] \n dc.SetLogicalFunction(wx.AND) \n for i in range(0,nbTick): \n x = tick + int(i * sizeX) \n if i % 4 == 0: \n dc.SetPen(wx.MEDIUM_GREY_PEN) \n dc.DrawLine(x, startY, x, endY) \n listX.append(x) \n else: \n dc.SetPen(wx.LIGHT_GREY_PEN) \n dc.DrawLine(x, startY, x, endY) \n \n #Draw Horizontal Lines \n diff = startY % (sizeY * 4 ) \n if diff > 0: \n tick = startY - diff \n else: \n tick = startY \n\n nbTick = int((endY - tick) / sizeY) + 1 \n listY = [] \n dc.SetLogicalFunction(wx.AND) \n for i in range(0,nbTick): \n y = tick + int(i * sizeY) \n if i % 4 == 0: \n dc.SetPen(wx.MEDIUM_GREY_PEN) \n dc.DrawLine(startX, y, endX, y) \n listY.append(y) \n else: \n dc.SetPen(wx.LIGHT_GREY_PEN) \n dc.DrawLine(startX, y, endX, y) \n \n #draw the labels \n dc.SetPen(wx.BLACK_PEN) \n font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL) \n dc.SetFont(font) \n for x in listX: \n for y in listY: \n dc.DrawText( str( (x,y) ) , x + 1 , y ) \n \n \n def OnClickEvent(self, event): \n print() \n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition())) \n print(\"ViewStart \" + str(self.GetViewStart())) \n print(\"Size \" + str(self.GetSize())) \n print(\"VirtualSize \" + str(self.GetVirtualSize())) \n\n\nclass MyMainCanvas(MyCanvas): \n \"\"\" \n This is the main canvas area \n \"\"\" \n def __init__(self, *args, **keys): \n \"\"\" \n Constructor. \n \"\"\" \n MyCanvas.__init__(self, *args, **keys) \n #self.Bind(wx.EVT_SCROLLWIN, self.OnScrollWindowEvent) \n \n def OnScrollWindowEvent(self, event): \n \"\"\" \n OnScrollWindow Event Callback. This should let the main panel scroll in \n both direction but transmit the vertical scrolling to the left panel \n and the horizontal scrolling to the top window \n \"\"\" \n event.Skip() \n sx,sy = self.GetViewStart() \n dx = self.GetScrollPos(wx.HORIZONTAL) \n dy = self.GetScrollPos(wx.VERTICAL) \n self.topPanel.Scroll(- dx, 0) \n self.leftPanel.Scroll(0, -dy) \n print(\"scrolling viewStart=%s,%s scrollPos=%s,%s\" % (sx, sy, dx, dy)) \n\nclass MyApp(wx.App): \n \"\"\" \n Simple Application class for testing \n \"\"\" \n def OnInit(self): \n \"\"\" \n Initialize the Application \n \"\"\" \n #This is the frame as I want to use it, with a tri-pane scroll window \n #However, the information sent to the sub-window is incorrect, so the \n #OnPaint callback draws the wrong area on screen... \n id = wx.NewId() \n frame = wx.Frame(None, id, \"Test Tri-pane frame\" ) \n scroll = TriPaneWindow(frame, wx.NewId()) \n scroll.SetCanvasSize(3000, 1000) \n scroll.SetScrollRate(20,20) \n frame.Show() \n # self.SetTopWindow(frame) \n \n # # #This is the simple example, which scrolls correctly using the same \n # # #OnPaint code... \n # id = wx.NewId() \n # frame2 = wx.Frame(None, id, \"Test Simple Frame\" ) \n # simple = MyCanvas(frame2, wx.WHITE, 100,100) \n # simple.SetVirtualSize(wx.Size(1000,1000)) \n # simple.SetScrollRate(20,20) \n # frame2.Show() \n print(\"wx.VERSION = \" + wx.VERSION_STRING) \n return True \n \n#For testing \nif __name__ == '__main__': \n app = MyApp(False) \n app.MainLoop() \n","repo_name":"robmcmullen/wx4demos","sub_path":"scrolltarget-orig.py","file_name":"scrolltarget-orig.py","file_ext":"py","file_size_in_byte":13122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42111281478","text":"#!/usr/bin/env python3\n\n\nfrom sys import stdin\nimport argparse\nimport re\n\n\nUNITS = [\"k\", \"m\", \"g\", \"t\", \"p\"]\n\n\ndef col(val):\n ival = int(val)\n if ival <= 0:\n raise argparse.ArgumentTypeError(f\"{ val } is not a valid column value.\")\n return ival\n\n\nparser = argparse.ArgumentParser(description=\"Sum sizes.\")\nparser.add_argument(\n \"-b\", \"--useb\", help=\"print in B instead of iB\", action=\"store_true\"\n)\nparser.add_argument(\n \"-u\", \"--unitless\", help=\"total size is given unitless\", action=\"store_true\"\n)\nparser.add_argument(\n \"-f\",\n \"--figure\",\n help=\"significant figure count after the dot (default 2)\",\n type=int,\n)\nparser.add_argument(\n \"-c\",\n \"--column\",\n help=\"which column to consider as sizes (default 1)\",\n type=col,\n default=1,\n)\nparser.add_argument(\n \"-d\",\n \"--double-input\",\n help=\"use both stdin and files if present\",\n action=\"store_true\",\n)\nparser.add_argument(\n \"files\",\n help=\"paths to files that contain the sizes. files have precedence over stdin unless -d option is given\",\n nargs=\"*\",\n)\n\nargs = parser.parse_args()\n\n\ndef sumsize(sizes):\n s = 0\n\n pf = re.compile(r\"[k|M|G|T|P]?i?B\", re.IGNORECASE)\n ps = re.compile(r\"[0-9]+\\.?[0-9]*\")\n\n for i in sizes:\n _sizes = ps.findall(i)\n size = float(_sizes[0]) if isinstance(_sizes, list) and len(_sizes) else 0.0\n\n if size == 0:\n continue\n\n _factors = pf.findall(i)\n factor = (\n _factors[0].lower() if isinstance(_factors, list) and len(_factors) else \"B\"\n )\n\n m = 1\n c = 1024 if \"i\" in factor else 1000\n for k, w in enumerate(UNITS):\n if w in factor:\n m = c ** (k + 1)\n break\n\n s += size * m\n\n return s\n\n\ndef addsize(f):\n global size\n size += sumsize(formatinput(f.readlines()))\n\n\ndef formatsize(size, fig=2, useb=False, unitless=False):\n size = int(size)\n if unitless:\n return str(size)\n\n c = 1000 if useb else 1024\n for i, j in reversed(list(enumerate(UNITS))):\n m = size / (c ** (i + 1))\n if m > 1:\n f = f\"%.{fig}f\" % m\n return f\"{ f }{ j.upper() }{ '' if useb else 'i' }B\"\n return f\"{ size }B\"\n\n\nformatinput = lambda x: [re.split(\"\\s\", i)[args.column - 1] for i in x]\nsize = 0\n\nif not len(args.files) and stdin.isatty():\n exit(0)\n\nfor i in args.files:\n with open(i, \"r\") as f:\n addsize(f)\nif (not len(args.files) or args.double_input) and not stdin.isatty():\n addsize(stdin)\n\nfigure = args.figure if args.figure is not None else 2\n\nformattedSize = formatsize(size, fig=figure, useb=args.useb, unitless=args.unitless)\n\nprint(formattedSize)\n","repo_name":"XPhyro/sumsize","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14507924492","text":"# WIP\n\n'''\nDay: 23\nFile: crab_cups.py\nAuthor: Rishabh Ranjan\nLast Modified: 12/25/2020\n'''\n\ndef move_cups(cups, current_cup):\n # print(cups)\n cups_to_move = []\n for j in range(3):\n cups_to_move.append(cups.pop((cups.index(current_cup) + 1) % len(cups)))\n # print(cups_to_move)\n destination_cup = current_cup - 1 if current_cup > 1 else len(cups) + len(cups_to_move)\n while destination_cup in cups_to_move:\n destination_cup = destination_cup - 1 if destination_cup > 1 else len(cups) + len(cups_to_move)\n for cup in cups_to_move:\n cups.insert(cups.index(destination_cup) + 1, cup)\n destination_cup = cup\n return cups, cups[(cups.index(current_cup) + 1) % len(cups)]\n\ndef main():\n f = open('day_23_input.txt', 'r')\n cups = list(map(int, list(f.read())[:-1]))\n f.close()\n cups_2 = cups.copy()\n current_cup = cups[0]\n for i in range(100):\n cups, current_cup = move_cups(cups, current_cup)\n print(cups)\n for i in range(10, 1000001):\n cups_2.append(i)\n current_cup = cups_2[0]\n # print(cups_2)\n for i in range(10000000):\n if i % 1000 == 0:\n print(i)\n cups_2, current_cup = move_cups(cups_2, current_cup)\n print(cups_2[(cups_2.index(1) + 1) % len(cups_2)] * cups_2[(cups_2.index(1) + 2) % len(cups_2)])\n\nif __name__ == '__main__':\n main()\n","repo_name":"rranjan11/Advent-of-Code-2020","sub_path":"crab_cups.py","file_name":"crab_cups.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19688331778","text":"from datetime import date\n\n\ndef convert_date_to_check_is_past(birth_date):\n \"\"\"verification de la position de la date dans le temps\n si elle est dans le futur elle est rejetée\n \"\"\"\n # birth_date = date(2001, 10, 10)\n today = date.today()\n if today > birth_date:\n\n return True\n else:\n print(\n \"votre date anniversaire est dans le futur,\"\n + \"changez la date ou faites un saut dans le temps vers\",\n birth_date\n )\n return False\n","repo_name":"temisgiona/oc_v2_p4_chess_tournament","sub_path":"model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14447692607","text":"# util of file dispose\nimport numpy as np\n\n\n# read data from text\ndef read_data(filename):\n lines = []\n arff_file = open(filename, \"r\")\n for line in arff_file:\n if not (line.startswith(\"@\")):\n if not (line.startswith(\"%\")) and line.strip():\n arr = line.strip(\"\\n\").split(\",\")\n if \"?\" not in arr:\n lines.append(arr)\n lines = np.array(lines)\n m, n = lines.shape\n for i in range(n):\n column = list(lines[:, i])\n if not column[0].isdigit():\n elements = list(set(column))\n elements.sort()\n new_column = [elements.index(s) for s in column]\n lines[:, i] = np.array(new_column)\n else:\n new_column = [int(s) for s in column]\n lines[:, i] = np.array(new_column)\n return lines\n\n\nif __name__ == \"__main__\":\n print(read_data(\"../datasets/lung-cancer.data\"))\n print(read_data(\"../datasets/breast-cancer-wisconsin.data.txt\"))\n\n\n","repo_name":"zhengxiang1994/feature-selection","sub_path":"fs/fileUtil.py","file_name":"fileUtil.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10711209977","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import Select\nimport os\nimport glob\nimport zipfile\nfrom helper_fct import download_wait\n\n\npath = os.path.dirname(__file__)\ndata_path = os.path.join(path, \"..\", \"..\", \"data\")\ndownload_path = os.path.join(path, \"..\", \"..\", \"..\", \"Downloads\")\nurl = \"https://cdr.ffiec.gov/public/PWS/DownloadBulkData.aspx\"\nyear = \"2019\"\n\n# Initialize the browser and call the url\ndriver = webdriver.Chrome()\ndriver.get(url)\n\ntry:\n element = WebDriverWait(driver, 200).until(EC.presence_of_element_located((By.TAG_NAME, \"form\")))\n\n selectProduct = Select(driver.find_element_by_id(\"ListBox1\"))\n selectProduct.select_by_value(\"ReportingSeriesSubsetSchedulesFourPeriods\")\n\n selectYear = Select(driver.find_element_by_id(\"DatesDropDownList\"))\n selectYear.select_by_visible_text(year)\n\n driver.find_element_by_id(\"Download_0\").click()\n driver.implicitly_wait(download_wait(download_path, 40))\n\nfinally:\n driver.quit()\n\n# Get latest latest filename with path\nlist_of_files = glob.glob(os.path.join(download_path, \"*\"))\nlatest_file_path = max(list_of_files, key=os.path.getctime)\n\n# Extract the filename from path\nfile = os.path.basename(os.path.normpath(latest_file_path))\n\n# Create destination path to move the file\ndata_move_path = os.path.join(data_path, file)\n\n# Move the file from downloads directory to destination\nos.replace(latest_file_path, data_move_path)\n\n# Unzip downloaded file\nz = zipfile.ZipFile(data_move_path)\nz.extractall(os.path.join(data_move_path, \"..\", \"Call_Report_\"+year))\nz.close()\n\n# Delete zipped file\nos.remove(data_move_path)","repo_name":"kbelulip/data5-call_report","sub_path":"dev/download/bulk_download.py","file_name":"bulk_download.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38436892206","text":"from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: gcpubsub_facts\nversion_added: \"2.3\"\nshort_description: List Topics/Subscriptions and Messages from Google PubSub.\ndescription:\n - List Topics/Subscriptions from Google PubSub. Use the gcpubsub module for\n topic/subscription management.\n See U(https://cloud.google.com/pubsub/docs) for an overview.\nrequirements:\n - \"python >= 2.6\"\n - \"google-auth >= 0.5.0\"\n - \"google-cloud-pubsub >= 0.22.0\"\nnotes:\n - list state enables user to list topics or subscriptions in the project. See examples for details.\nauthor:\n - \"Tom Melendez (@supertom) \"\noptions:\n topic:\n description:\n - GCP pubsub topic name. Only the name, not the full path, is required.\n required: False\n view:\n description:\n - Choices are 'topics' or 'subscriptions'\n required: True\n state:\n description:\n - list is the only valid option.\n required: False\n'''\n\nEXAMPLES = '''\n## List all Topics in a project\ngcpubsub_facts:\n view: topics\n state: list\n\n## List all Subscriptions in a project\ngcpubsub_facts:\n view: subscriptions\n state: list\n\n## List all Subscriptions for a Topic in a project\ngcpubsub_facts:\n view: subscriptions\n topic: my-topic\n state: list\n'''\n\nRETURN = '''\nsubscriptions:\n description: List of subscriptions.\n returned: When view is set to subscriptions.\n type: list\n sample: [\"mysubscription\", \"mysubscription2\"]\ntopic:\n description: Name of topic. Used to filter subscriptions.\n returned: Always\n type: str\n sample: \"mytopic\"\ntopics:\n description: List of topics.\n returned: When view is set to topics.\n type: list\n sample: [\"mytopic\", \"mytopic2\"]\n'''\n\ntry:\n from ast import literal_eval\n HAS_PYTHON26 = True\nexcept ImportError:\n HAS_PYTHON26 = False\n\ntry:\n from google.cloud import pubsub\n HAS_GOOGLE_CLOUD_PUBSUB = True\nexcept ImportError as e:\n HAS_GOOGLE_CLOUD_PUBSUB = False\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.gcp import check_min_pkg_version, get_google_cloud_credentials\n\n\ndef list_func(data, member='name'):\n \"\"\"Used for state=list.\"\"\"\n return [getattr(x, member) for x in data]\n\n\ndef main():\n module = AnsibleModule(argument_spec=dict(\n view=dict(choices=['topics', 'subscriptions'], default='topics'),\n topic=dict(required=False),\n state=dict(choices=['list'], default='list'),\n service_account_email=dict(),\n credentials_file=dict(),\n project_id=dict(), ),)\n\n if not HAS_PYTHON26:\n module.fail_json(\n msg=\"GCE module requires python's 'ast' module, python v2.6+\")\n\n if not HAS_GOOGLE_CLOUD_PUBSUB:\n module.fail_json(msg=\"Please install google-cloud-pubsub library.\")\n\n CLIENT_MINIMUM_VERSION = '0.22.0'\n if not check_min_pkg_version('google-cloud-pubsub', CLIENT_MINIMUM_VERSION):\n module.fail_json(msg=\"Please install google-cloud-pubsub library version %s\" % CLIENT_MINIMUM_VERSION)\n\n mod_params = {}\n mod_params['state'] = module.params.get('state')\n mod_params['topic'] = module.params.get('topic')\n mod_params['view'] = module.params.get('view')\n\n creds, params = get_google_cloud_credentials(module)\n pubsub_client = pubsub.Client(project=params['project_id'], credentials=creds, use_gax=False)\n pubsub_client.user_agent = 'ansible-pubsub-0.1'\n\n json_output = {}\n if mod_params['view'] == 'topics':\n json_output['topics'] = list_func(pubsub_client.list_topics())\n elif mod_params['view'] == 'subscriptions':\n if mod_params['topic']:\n t = pubsub_client.topic(mod_params['topic'])\n json_output['subscriptions'] = list_func(t.list_subscriptions())\n else:\n json_output['subscriptions'] = list_func(pubsub_client.list_subscriptions())\n\n json_output['changed'] = False\n json_output.update(mod_params)\n module.exit_json(**json_output)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhxfei/My-Admin","sub_path":"env/lib/python3.5/site-packages/ansible/modules/cloud/google/gcpubsub_facts.py","file_name":"gcpubsub_facts.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"41689104894","text":"\"\"\"\nThis is the main file for the web application. \nIt contains the routes for the webpages and the functions that are\ncalled when the user visits a page.\n\"\"\"\nfrom flask import Flask, render_template ,redirect,make_response,request\nimport sso\nimport middleware\nfrom dataFormat import User\nfrom charts import load_chart\nfrom sso import db_data\n\napp = Flask(__name__)\napp.config['ENV'] = 'development'\napp.config['DEBUG'] = True\napp.config['TESTING'] = True\n\n@app.route(\"/\")\ndef home():\n \"\"\"Homepage the first page visited.\"\"\"\n uuid = sso.get_uuid_from_cookie()\n print(uuid)\n if uuid is None:\n return render_template('homepage.html')\n else:\n return redirect(\"/results\", code=302)\n\n@app.route(\"/PrivacyPolicy\")\ndef privacy():\n \"\"\"Privacy Policy page.\"\"\"\n return render_template('PrivacyPolicy.html')\n\n@app.route(\"/oauth/info\")\ndef oauth_info():\n \"\"\"Imformation about OAuth.\"\"\"\n return render_template('OAuthInfo.html')\n\n@app.route(\"/oauth/begin\")\ndef get_begin_oauth():\n \"\"\"Redirects to the OAuth page.\"\"\"\n return sso.get_begin_oauth()\n\n@app.route(\"/oauth/authorised\")\ndef get_authorised_oauth():\n \"\"\"Recieves the OAuth token and redirects to the results page.\"\"\"\n uuid = sso.get_authorised_oauth()\n response = redirect(\"/results\", code=302)\n response.set_cookie( \"uuid\",uuid )\n return response\n\n#TODO Remove this endpoint\n# @app.route(\"/oauth/endpoint\")\n# def get_endpoint():\n# \"\"\"A temporary page to test the OAuth endpoint.\"\"\"\n# uuid = sso.get_uuid_from_cookie()\n# assignments = sso.get_assignments(uuid)\n# member = sso.get_user_info(uuid)\n# user_submissions = sso.get_assignments(uuid)\n\n# print(\"print_debug\", middleware.get_data(uuid))\n\n# assignment_names = []\n# for item in assignments['enrolledAssignments']:\n# assignment_names.append(item['name'])\n# for item in assignments['historicAssignments']:\n# assignment_names.append(item['name'])\n\n# return render_template('assignments.html',\\\n# assignments=assignment_names,\\\n# member=member,\\\n# submissions=user_submissions)\n\n@app.route(\"/user/count\")\ndef get_user_count():\n \"\"\"Returns the number of users.\"\"\"\n userCount= sso.get_user_count()\n return render_template('userCount.html',userCount=userCount)\n\n@app.route(\"/oauth/tabula/events/\")\ndef get_upcoming_events():\n \"\"\"temporary page to test the upcoming events endpoint.\"\"\"\n return sso.get_upcoming_events()\n\n@app.route(\"/results\")\ndef loading():\n \"\"\"Renders the laodin page that calls /api/results.\"\"\"\n\n return render_template('loading.html')\n\n@app.route(\"/api/results\")\ndef render_results():\n \"\"\"The primary page of the web application.\"\"\"\n args = request.args.to_dict()\n share_code=args.get(\"ref\")\n is_shared = False\n uuid=None\n if share_code is not None:\n uuid = db_data.get_token_for_share_code(share_code)\n is_shared = True\n try:\n if not is_shared:\n uuid = sso.get_uuid_from_cookie()\n except TypeError:\n return redirect(\"/?error=true\", code=302)\n if uuid is None:\n response = redirect(\"/\", code=302) \n response.set_cookie( \"uuid\",\"clear\",expires=0 )\n return response\n user_data:User=middleware.convert_to_page(middleware.get_data(uuid))\n\n return render_template('Results.html',userData=user_data,isShared=is_shared)\n\n@app.route(\"/api/share\")\ndef get_share_link():\n \"\"\"Returns a share link.\"\"\"\n uuid = sso.get_uuid_from_cookie()\n if uuid is None:\n return redirect(\"/?error=true\", code=302) \n return middleware.get_share_link(uuid)\n\n@app.route(\"/charts/\")\ndef get_chart(chart_id:str):\n \"\"\"Returns a chart.\"\"\"\n image_bytes = load_chart(chart_id)\n response = make_response(image_bytes)\n response.headers.set('Content-Type', 'image/png')\n response.headers.set('Content-Disposition', 'attachment', filename=f'{chart_id}.png')\n return response\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"efbicief/warwick-wrapped","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"14345682514","text":"from copy import deepcopy\n\n\nclass Reasoner:\n\n def __init__(self, kb):\n self.kb = kb\n\n def forward_chain(self, query):\n truths = set()\n\n for atom in self.kb.atoms:\n truths.add(atom)\n print(\".\")\n listLength = len(truths)\n newListLength = 0\n\n while newListLength != listLength:\n listLength = len(truths)\n for head in self.kb.get_heads(truths):\n print(\".\")\n truths.add(head)\n newListLength = len(truths)\n if query in truths:\n return True\n else:\n return False\n\n def backward_chain(self, query):\n unproven = []\n proven = []\n\n unproven.append(query)\n while len(unproven) > 0:\n curr = unproven.pop()\n head = self.kb.get_heads(curr)\n if curr in self.kb.atoms: #checks if query is one of the atom variables\n proven.append(head)\n continue\n elif head in proven:\n continue\n else:\n counter = 1\n inCompound = False\n #Searches top down from compound props\n for head in self.kb.compound_props:\n print(\".\")\n if curr == head:\n inCompound = True\n for body in self.kb.get_bodies(curr):\n print(\".\")\n for i in body:\n print(\".\")\n unproven.append(i)\n else:\n if len(self.kb.compound_props) == counter and inCompound == False:\n return False\n counter += 1\n return True\n\n\nclass KB:\n\n def __init__(self):\n self.atoms = set() # set\n self.compound_props = {} # dictionary; head: list of bodies (sets)\n\n def get_bodies(self, head):\n return self.compound_props[head]\n\n def get_heads(self, antecedents):\n heads = set()\n for h, a_list in self.compound_props.items():\n for a in a_list:\n if a.issubset(antecedents):\n heads.add(h)\n break # no need to add the same head multiple times\n return heads\n\n def add_atom(self, atom):\n self.atoms.add(atom)\n\n def add_compound(self, head, body):\n if head in self.compound_props:\n self.compound_props[head].append(body)\n else:\n self.compound_props[head] = [body]\n\n\nif __name__ == '__main__':\n kb = KB()\n kb.add_atom(\"has_cat\")\n kb.add_atom(\"plays_guitar\")\n kb.add_atom(\"is_artist\")\n kb.add_atom(\"no_sneeze\")\n kb.add_compound(\"no_allergy\", {\"has_pet\", \"no_sneeze\"})\n kb.add_compound(\"has_pet\", {\"has_dog\"})\n kb.add_compound(\"has_pet\", {\"has_cat\"})\n kb.add_compound(\"has_pet\", {\"has_gerbil\"})\n kb.add_compound(\"allergy\", {\"has_pet\", \"sneezes\"})\n kb.add_compound(\"allergy\", {\"no_pet\"})\n kb.add_compound(\"is_musician\", {\"plays_guitar\"})\n\n reasoner = Reasoner(kb)\n\n\n print(reasoner.forward_chain(\"no_allergy\"))\n print(\"***********************************\")\n print(reasoner.backward_chain(\"no_allergy\"))\n\n print(reasoner.forward_chain(\"allergy\"))\n #print(\"***********************************\")\n #print(reasoner.backward_chain(\"allergy\"))\n\n print(reasoner.forward_chain(\"has_dog\"))\n #print(\"***********************************\")\n #print(reasoner.backward_chain(\"has_dog\"))\n\n print(reasoner.forward_chain(\"has_cat\"))\n #print(\"***********************************\")\n #print(reasoner.backward_chain(\"has_cat\"))\n\n # TODO: test forward and backward chaining here\n\n","repo_name":"eddie-droid/Reasoner","sub_path":"Reasoner.py","file_name":"Reasoner.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42429201904","text":"import torch\nfrom torchvision import transforms as T\nfrom dataset import PennFundanDataset\n\ndef get_data_loaders(root, batch_size, training=True):\n if training:\n transform = T.Compose([\n T.RandomHorizontalFlip(p=0.5),\n T.RandomRotation(degrees=(-30, 30)),\n # T.RandomResizedCrop(size=256, scale=(0.8, 1.0)),\n T.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2),\n T.Resize((256, 256)),\n T.ToTensor(),\n T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n else:\n transform = T.Compose([\n T.Resize((256, 256)),\n T.ToTensor(),\n ])\n \n train_dataset = PennFundanDataset(root, transform)\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size, training)\n \n return train_loader","repo_name":"jjlee6496/torch","sub_path":"Project1/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"634090781","text":"# initialization\r\nimport numpy as np\r\n\r\n# importing Qiskit\r\nfrom qiskit import IBMQ, Aer\r\nfrom qiskit.providers.ibmq import least_busy\r\nfrom qiskit import QuantumCircuit, assemble, transpile\r\n\r\n# import basic plot tools\r\nfrom qiskit.visualization import plot_histogram\r\nimport matplotlib.pyplot as plt\r\n\r\n# the demonstration of Deutsch-Jozsa Algorithm, including \r\n# (1) the constant oracle\r\n# (2) the balanced oracle\r\n# (3) the Deiutsch-Jozsa circuit\r\ndef dj_demonstrate(n):\r\n\r\n # build the const oracle with X gate at the last (n+1) qubit\r\n const_oracle = QuantumCircuit(n+1)\r\n output = np.random.randint(2)\r\n if output == 1:\r\n const_oracle.x(n)\r\n const_oracle.draw(output='mpl')\r\n plt.show()\r\n\r\n # build the balanced oracle \r\n balanced_oracle = QuantumCircuit(n+1)\r\n b_str = \"101\"\r\n # Place X-gates\r\n for qubit in range(len(b_str)):\r\n if b_str[qubit] == '1':\r\n balanced_oracle.x(qubit)\r\n balanced_oracle.draw(output='mpl')\r\n plt.show()\r\n # Use barrier as divider\r\n balanced_oracle.barrier()\r\n # Controlled-NOT gates\r\n for qubit in range(n):\r\n balanced_oracle.cx(qubit, n)\r\n balanced_oracle.barrier()\r\n balanced_oracle.draw(output='mpl')\r\n plt.show()\r\n # Place X-gates\r\n for qubit in range(len(b_str)):\r\n if b_str[qubit] == '1':\r\n balanced_oracle.x(qubit)\r\n # Show oracle\r\n balanced_oracle.draw(output='mpl')\r\n plt.show()\r\n\r\n # build the Deutsch-Jozsa circuit\r\n dj_circuit = QuantumCircuit(n+1, n)\r\n # Apply H-gates\r\n for qubit in range(n):\r\n dj_circuit.h(qubit)\r\n # Put qubit in state |->\r\n dj_circuit.x(n)\r\n dj_circuit.h(n)\r\n dj_circuit.draw(output='mpl')\r\n plt.show()\r\n # Add oracle\r\n dj_circuit += balanced_oracle\r\n dj_circuit.draw(output='mpl')\r\n plt.show()\r\n # Repeat H-gates\r\n for qubit in range(n):\r\n dj_circuit.h(qubit)\r\n dj_circuit.barrier()\r\n # Measure\r\n for i in range(n):\r\n dj_circuit.measure(i, i)\r\n # Display circuit\r\n dj_circuit.draw(output='mpl')\r\n plt.show()\r\n\r\n return dj_circuit\r\n\r\n# the oracle gate for Deutsch-Jozsa Algorithm to detect difference: case='balanced' or 'constant'\r\ndef dj_oracle(case, n):\r\n # We need to make a QuantumCircuit object to return\r\n # This circuit has n+1 qubits: the size of the input,\r\n # plus one output qubit\r\n oracle_qc = QuantumCircuit(n+1)\r\n \r\n # First, let's deal with the case in which oracle is balanced\r\n if case == \"balanced\":\r\n # First generate a random number that tells us which CNOTs to\r\n # wrap in X-gates:\r\n b = np.random.randint(1,2**n)\r\n # Next, format 'b' as a binary string of length 'n', padded with zeros:\r\n b_str = format(b, '0'+str(n)+'b')\r\n # Next, we place the first X-gates. Each digit in our binary string \r\n # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1\r\n # we apply an X-gate to that qubit:\r\n for qubit in range(len(b_str)):\r\n if b_str[qubit] == '1':\r\n oracle_qc.x(qubit)\r\n # Do the controlled-NOT gates for each qubit, using the output qubit \r\n # as the target:\r\n for qubit in range(n):\r\n oracle_qc.cx(qubit, n)\r\n # Next, place the final X-gates\r\n for qubit in range(len(b_str)):\r\n if b_str[qubit] == '1':\r\n oracle_qc.x(qubit)\r\n\r\n # Case in which oracle is constant\r\n if case == \"constant\":\r\n # First decide what the fixed output of the oracle will be\r\n # (either always 0 or always 1)\r\n output = np.random.randint(2)\r\n if output == 1:\r\n oracle_qc.x(n)\r\n \r\n oracle_gate = oracle_qc.to_gate()\r\n oracle_gate.name = case+\"_Oracle\" # To show when we display the circuit\r\n return oracle_gate\r\n\r\n# run the Deutsch-Jozsa circuit\r\ndef dj_algorithm(oracle, n):\r\n dj_circuit = QuantumCircuit(n+1, n)\r\n # Set up the output qubit:\r\n dj_circuit.x(n)\r\n dj_circuit.h(n)\r\n # And set up the input register:\r\n for qubit in range(n):\r\n dj_circuit.h(qubit)\r\n # Let's append the oracle gate to our circuit:\r\n dj_circuit.append(oracle, range(n+1))\r\n # Finally, perform the H-gates again and measure:\r\n for qubit in range(n):\r\n dj_circuit.h(qubit)\r\n \r\n for i in range(n):\r\n dj_circuit.measure(i, i)\r\n \r\n return dj_circuit\r\n\r\n\r\nif __name__=='__main__':\r\n n = 3\r\n demonstrate = 1\r\n if demonstrate:\r\n dj_circuit = dj_demonstrate(n)\r\n # use local simulator\r\n aer_sim = Aer.get_backend('aer_simulator')\r\n shots = 1024\r\n qobj = assemble(dj_circuit, aer_sim)\r\n results = aer_sim.run(qobj).result()\r\n answer = results.get_counts()\r\n plot_histogram(answer)\r\n plt.show()\r\n else:\r\n oracle_gate = dj_oracle('balanced', n)\r\n dj_circuit = dj_algorithm(oracle_gate, n)\r\n dj_circuit.draw(output='mpl')\r\n plt.show()\r\n\r\n aer_sim = Aer.get_backend('aer_simulator')\r\n transpiled_dj_circuit = transpile(dj_circuit, aer_sim)\r\n qobj = assemble(transpiled_dj_circuit)\r\n results = aer_sim.run(qobj).result()\r\n answer = results.get_counts()\r\n plot_histogram(answer)\r\n plt.show()\r\n\r\n \r\n","repo_name":"huwenqing0606/Quantum-Computing-using-Qiskit","sub_path":"DeutschJozsa.py","file_name":"DeutschJozsa.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6331365520","text":"# coding: utf-8\n\n\"\"\"\n Apteco API\n\n An API to allow access to Apteco Marketing Suite resources # noqa: E501\n\n The version of the OpenAPI document: v2\n Contact: support@apteco.com\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom apteco_api.configuration import Configuration\n\n\nclass DashboardItemPreviewData(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'dashboard_item_id': 'str',\n 'drill_down_level': 'int',\n 'sort_order': 'str',\n 'base_query': 'Query',\n 'data_specification': 'DashboardItemDataSpecification'\n }\n\n attribute_map = {\n 'dashboard_item_id': 'dashboardItemId',\n 'drill_down_level': 'drillDownLevel',\n 'sort_order': 'sortOrder',\n 'base_query': 'baseQuery',\n 'data_specification': 'dataSpecification'\n }\n\n def __init__(self, dashboard_item_id=None, drill_down_level=None, sort_order=None, base_query=None, data_specification=None, local_vars_configuration=None): # noqa: E501\n \"\"\"DashboardItemPreviewData - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._dashboard_item_id = None\n self._drill_down_level = None\n self._sort_order = None\n self._base_query = None\n self._data_specification = None\n self.discriminator = None\n\n self.dashboard_item_id = dashboard_item_id\n self.drill_down_level = drill_down_level\n self.sort_order = sort_order\n self.base_query = base_query\n if data_specification is not None:\n self.data_specification = data_specification\n\n @property\n def dashboard_item_id(self):\n \"\"\"Gets the dashboard_item_id of this DashboardItemPreviewData. # noqa: E501\n\n The id for this dashboard item # noqa: E501\n\n :return: The dashboard_item_id of this DashboardItemPreviewData. # noqa: E501\n :rtype: str\n \"\"\"\n return self._dashboard_item_id\n\n @dashboard_item_id.setter\n def dashboard_item_id(self, dashboard_item_id):\n \"\"\"Sets the dashboard_item_id of this DashboardItemPreviewData.\n\n The id for this dashboard item # noqa: E501\n\n :param dashboard_item_id: The dashboard_item_id of this DashboardItemPreviewData. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and dashboard_item_id is None: # noqa: E501\n raise ValueError(\"Invalid value for `dashboard_item_id`, must not be `None`\") # noqa: E501\n\n self._dashboard_item_id = dashboard_item_id\n\n @property\n def drill_down_level(self):\n \"\"\"Gets the drill_down_level of this DashboardItemPreviewData. # noqa: E501\n\n The drill down level for this dashboard item # noqa: E501\n\n :return: The drill_down_level of this DashboardItemPreviewData. # noqa: E501\n :rtype: int\n \"\"\"\n return self._drill_down_level\n\n @drill_down_level.setter\n def drill_down_level(self, drill_down_level):\n \"\"\"Sets the drill_down_level of this DashboardItemPreviewData.\n\n The drill down level for this dashboard item # noqa: E501\n\n :param drill_down_level: The drill_down_level of this DashboardItemPreviewData. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and drill_down_level is None: # noqa: E501\n raise ValueError(\"Invalid value for `drill_down_level`, must not be `None`\") # noqa: E501\n\n self._drill_down_level = drill_down_level\n\n @property\n def sort_order(self):\n \"\"\"Gets the sort_order of this DashboardItemPreviewData. # noqa: E501\n\n Whether the chart for the given drill down level should be sorted in it's natural order, by ascending or descending values # noqa: E501\n\n :return: The sort_order of this DashboardItemPreviewData. # noqa: E501\n :rtype: str\n \"\"\"\n return self._sort_order\n\n @sort_order.setter\n def sort_order(self, sort_order):\n \"\"\"Sets the sort_order of this DashboardItemPreviewData.\n\n Whether the chart for the given drill down level should be sorted in it's natural order, by ascending or descending values # noqa: E501\n\n :param sort_order: The sort_order of this DashboardItemPreviewData. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and sort_order is None: # noqa: E501\n raise ValueError(\"Invalid value for `sort_order`, must not be `None`\") # noqa: E501\n allowed_values = [\"Natural\", \"AscendingByValue\", \"DescendingByValue\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and sort_order not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `sort_order` ({0}), must be one of {1}\" # noqa: E501\n .format(sort_order, allowed_values)\n )\n\n self._sort_order = sort_order\n\n @property\n def base_query(self):\n \"\"\"Gets the base_query of this DashboardItemPreviewData. # noqa: E501\n\n\n :return: The base_query of this DashboardItemPreviewData. # noqa: E501\n :rtype: Query\n \"\"\"\n return self._base_query\n\n @base_query.setter\n def base_query(self, base_query):\n \"\"\"Sets the base_query of this DashboardItemPreviewData.\n\n\n :param base_query: The base_query of this DashboardItemPreviewData. # noqa: E501\n :type: Query\n \"\"\"\n if self.local_vars_configuration.client_side_validation and base_query is None: # noqa: E501\n raise ValueError(\"Invalid value for `base_query`, must not be `None`\") # noqa: E501\n\n self._base_query = base_query\n\n @property\n def data_specification(self):\n \"\"\"Gets the data_specification of this DashboardItemPreviewData. # noqa: E501\n\n\n :return: The data_specification of this DashboardItemPreviewData. # noqa: E501\n :rtype: DashboardItemDataSpecification\n \"\"\"\n return self._data_specification\n\n @data_specification.setter\n def data_specification(self, data_specification):\n \"\"\"Sets the data_specification of this DashboardItemPreviewData.\n\n\n :param data_specification: The data_specification of this DashboardItemPreviewData. # noqa: E501\n :type: DashboardItemDataSpecification\n \"\"\"\n\n self._data_specification = data_specification\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, DashboardItemPreviewData):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, DashboardItemPreviewData):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"Apteco/apteco-api","sub_path":"pkg/apteco_api/models/dashboard_item_preview_data.py","file_name":"dashboard_item_preview_data.py","file_ext":"py","file_size_in_byte":8507,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"12910040365","text":"import os\nimport sys\n\n# boto requires depot_tools/third_party be in the path. Use\n# src/build/find_depot_tools.py to add this directory.\nsys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,\n os.pardir, os.pardir, 'build'))\nimport find_depot_tools\nDEPOT_TOOLS_PATH = find_depot_tools.add_depot_tools_to_path()\nsys.path.append(os.path.join(os.path.abspath(DEPOT_TOOLS_PATH), 'third_party'))\nimport boto\n\nfrom ispy.common import cloud_bucket\n\n\nclass BotoCloudBucket(cloud_bucket.BaseCloudBucket):\n \"\"\"Interfaces with GS using the boto library.\"\"\"\n\n def __init__(self, key, secret, bucket_name):\n \"\"\"Initializes the bucket with a key, secret, and bucket_name.\n\n Args:\n key: the API key to access GS.\n secret: the API secret to access GS.\n bucket_name: the name of the bucket to connect to.\n \"\"\"\n uri = boto.storage_uri('', 'gs')\n conn = uri.connect(key, secret)\n self.bucket = conn.get_bucket(bucket_name)\n\n def _GetKey(self, path):\n key = boto.gs.key.Key(self.bucket)\n key.key = path\n return key\n\n # override\n def UploadFile(self, path, contents, content_type):\n key = self._GetKey(path)\n key.set_metadata('Content-Type', content_type)\n key.set_contents_from_string(contents)\n # Open permissions for the appengine account to read/write.\n key.add_email_grant('FULL_CONTROL',\n 'ispy.google.com@appspot.gserviceaccount.com')\n\n # override\n def DownloadFile(self, path):\n key = self._GetKey(path)\n if key.exists():\n return key.get_contents_as_string()\n else:\n raise cloud_bucket.FileNotFoundError\n\n # override\n def UpdateFile(self, path, contents):\n key = self._GetKey(path)\n if key.exists():\n key.set_contents_from_string(contents)\n else:\n raise cloud_bucket.FileNotFoundError\n\n # override\n def RemoveFile(self, path):\n key = self._GetKey(path)\n key.delete()\n\n # override\n def FileExists(self, path):\n key = self._GetKey(path)\n return key.exists()\n\n # override\n def GetImageURL(self, path):\n key = self._GetKey(path)\n if key.exists():\n # Corrects a bug in boto that incorrectly generates a url\n # to a resource in Google Cloud Storage.\n return key.generate_url(3600).replace('AWSAccessKeyId', 'GoogleAccessId')\n else:\n raise cloud_bucket.FileNotFoundError(path)\n\n # override\n def GetAllPaths(self, prefix):\n return (key.key for key in self.bucket.get_all_keys(prefix=prefix))\n","repo_name":"kiwibrowser/src","sub_path":"chrome/test/ispy/client/boto_bucket.py","file_name":"boto_bucket.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"41571818118","text":"currency = str(input(\"Vložte druh meny (USD alebo EUR)\"))\n\n\ndef eur2usd():\n usd = eurToUsd * 1.19\n return usd\n\n\ndef usd2eur():\n eur = usdToEur * 0.84\n return eur\n\n\nif currency == \"EUR\" or currency == \"eur\":\n eurToUsd = float(input(\"vložte hodnotu €\"))\n print(eurToUsd, \"€ =\", eur2usd(), \"$\")\nelif currency == \"USD\" or currency == \"usd\":\n usdToEur = float(input(\"vložte hodnotu €\"))\n print(usdToEur, \"$ =\", usd2eur(), \"€\")\nelse:\n print(\"ZADANÁ NESPRÁVNA HODNOTA\")\n \n","repo_name":"tomassabol/python-SEN5","sub_path":"mena.py","file_name":"mena.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33322109891","text":"import pyautogui as pg\nimport numpy as np\nimport time\n\n#grid = [[3, 0, 6, 5, 0, 8, 4, 0, 0],\n# [5, 2, 0, 0, 0, 0, 0, 0, 0],\n# [0, 8, 7, 0, 0, 0, 0, 3, 1],\n# [0, 0, 3, 0, 1, 0, 0, 8, 0],\n# [9, 0, 0, 8, 6, 3, 0, 0, 5],\n# [0, 5, 0, 0, 9, 0, 6, 0, 0],\n# [1, 3, 0, 0, 0, 0, 2, 5, 0],\n# [0, 0, 0, 0, 0, 0, 0, 7, 4],\n# [0, 0, 5, 2, 0, 6, 3, 0, 0]]\n\n\ndef insert_grid():\n grid = []\n while True:\n row = list(input(\"Insert Row: \"))\n ints = []\n\n for n in row:\n ints.append(int(n))\n grid.append(ints)\n\n if len(grid) == 9:\n break\n print(\"Row \" + str(len(grid)) + ' completed')\n return grid\n\n\ndef put(matrix):\n\n counter = []\n str_final = list(np.array(matrix).astype(str).flatten())\n\n for number in str_final:\n pg.press(number)\n pg.hotkey('right')\n\n counter.append(number)\n if len(counter) % 9 == 0:\n pg.hotkey('down')\n\n # go left\n for i in range(9):\n pg.hotkey('left')\n\n\ndef board_print(board):\n \"\"\"\n Prints 9x9 numpy array input board in an easier to read format.\n \"\"\"\n\n board = np.array(board)\n\n # Some basic checks\n assert board.shape == (9, 9)\n assert type(board) == np.ndarray\n\n # Convert array elements to strings\n board_str = board.astype(str)\n\n # Our row separator\n row_sep = '-' * 25\n\n # Loop through 9 rows\n for i in range(9):\n\n # At each multiple of 3, print row separator\n if i % 3 == 0:\n print(row_sep)\n\n # Get row data\n row = board_str[i]\n\n # Format row of data with pipe separators at each end, and between each sub grid\n print('| ' + ' '.join(row[0:3]) + ' | ' + ' '.join(row[3:6]) + ' | ' + ' '.join(row[6:]) + ' |')\n\n # Print final row separator at bottom after loops finish\n print(row_sep)\n\n\ndef is_valid_move(grid, row, col, number):\n # is there something in the same block, row, or col\n\n # check for row\n for column in range(9):\n if grid[row][column] == number:\n return False\n\n # check for column\n for x in range(9):\n if grid[x][col] == number:\n return False\n\n # check for block\n corner_row = row - row % 3\n corner_col = col - col % 3\n for x in range(3):\n for y in range(3):\n if grid[corner_row + x][corner_col + y] == number:\n return False\n\n return True\n\n\ndef solve(grid, row, col):\n\n if row == 8 and col == 9:\n return True\n\n if col == 9:\n row += 1\n col = 0\n\n if grid[row][col] > 0:\n return solve(grid, row, col + 1)\n\n for num in range(1, 10):\n\n if is_valid_move(grid, row, col, num):\n\n grid[row][col] = num\n\n if solve(grid, row, col + 1):\n return True\n\n grid[row][col] = 0\n\n return False\n\n\ngrid = insert_grid()\ntime.sleep(2)\n\nif solve(grid, 0, 0):\n put(grid)\n print(\"This is the final solution:\\n\\n\\n\")\n board_print(grid)\n\nelse:\n print(\"there is no possible solution\")\n","repo_name":"eladyesh/Sudoku","sub_path":"sudoku_pytogui.py","file_name":"sudoku_pytogui.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13589082272","text":"from const import *\nfrom torchvision.utils import save_image\nimport torch\nimport matplotlib.pyplot as plt\n\n\ndef traverse_latent_space(vae, origin_frame, final_frame, total_ite):\n \" Linear latent space interpolation between 2 frames \"\n\n with torch.no_grad():\n origin_frame = origin_frame.view(-1, 3, WIDTH, HEIGHT)\n final_frame = final_frame.view(-1, 3, WIDTH, HEIGHT) \n res = final_frame\n origin_z = vae(origin_frame, encode=True)\n final_z = vae(final_frame, encode=True)\n number_frames = 50\n\n for i in range(0, number_frames):\n i /= number_frames\n translat_img = (i * origin_z) + (1 - i) * final_z\n res = torch.cat((res, vae.decode(translat_img)))\n \n res = torch.cat((res, origin_frame))\n save_image(res, 'results/vae/sample_traverse_{}.png'.format(total_ite))\n\n \ndef create_img_recons(vae, original_frames, version):\n \"\"\" Save the image and its reconstruction \"\"\"\n\n with torch.no_grad():\n final_sample, _, _ = vae(original_frames)\n save_image(torch.cat((original_frames, final_sample)),\n 'results/vae/sample_{}.png'.format(version))\n\n\ndef sample(seq, pi, mu, sigma):\n \"\"\" Sample a latent vector given pi, mu and sigma \"\"\"\n\n sampled = torch.sum(pi * torch.normal(mu, sigma), dim=2)\n return sampled.view(seq, LATENT_VEC)\n\n\ndef sample_long_term(vae, lstm, frames, version, total_ite):\n \"\"\" Given a frame, tries to predict the next 60 encoded vectors \"\"\"\n\n lstm.hidden = lstm.init_hidden(1)\n\n ## Add first 4 frames, then their reconstruction\n frames_z = vae(frames.view(-1, 3, WIDTH, HEIGHT), encode=True)[0:4]\n result = torch.cat((frames[0:4], vae.decode(frames_z)\\\n .view(-1, 3, WIDTH, HEIGHT)))\n z = frames_z[0].view(1, LATENT_VEC)\n with torch.no_grad():\n for i in range(1, 60):\n new_state = torch.cat((z, torch.full((1, 1), 1, device=DEVICE) / ACTION_SPACE_DISCRETE), dim=1)\n pi, sigma, mu = lstm(new_state.view(1, 1, LATENT_VEC + 1))\n z = sample(1, pi, mu, sigma)\n result = torch.cat((result, vae.decode(z).view(-1, 3, WIDTH, HEIGHT)))\n save_image(result, \"results/lstm/test-{}-{}.png\".format(version, total_ite))\n","repo_name":"dylandjian/retro-contest-sonic","sub_path":"lib/visu.py","file_name":"visu.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"52"} +{"seq_id":"36708139323","text":"def solution1(n):\n answer = sum([int(x) for x in str(n)] )\n return answer\n\ndef solution2(n):\n answer = 0\n x = 1\n while(x <= n):\n if(x % 2 ==0):\n answer += x\n x += 1\n return answer","repo_name":"skyjoozero/rp_project","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4919314489","text":"######################################################\r\n# CREATE BY Thiraphong Thiangphadung # \r\n# เลขประจำตัว 593684 แผนก หทปอ-ห. ฝ่าย อปอ. # \r\n# lesson6 Cotours #\r\n######################################################\r\nimport cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nimg = cv2.imread('3.png')\r\nimg1 = img.copy()\r\nimg2 = img.copy()\r\nimg3 = img.copy()\r\n\r\nimgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\nret, thresh = cv2.threshold(imgray,127,255,0)\r\n\r\ncontours, hierachy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\n\r\ncnt = contours[0]\r\n\r\n\r\nepsilon1 = 0.01*cv2.arcLength(cnt, True)\r\nepsilon2 = 0.1*cv2.arcLength(cnt, True)\r\nepsilon3 = 0.001*cv2.arcLength(cnt, True)\r\n\r\napprox1 = cv2.approxPolyDP(cnt, epsilon1, True)\r\napprox2 = cv2.approxPolyDP(cnt, epsilon2, True)\r\napprox3 = cv2.approxPolyDP(cnt, epsilon3, True)\r\n\r\ncv2.drawContours(img, [cnt],0,(0,255,0),3) \r\ncv2.drawContours(img1, [approx1], 0,(0,255,0), 3) # line\r\ncv2.drawContours(img2, [approx2], 0,(0,255,0), 3) # line\r\ncv2.drawContours(img3, approx3, -1, (0, 255, 0), 5) # points\r\n\r\ntitles = ['Original', '1%', '10%','points']\r\nimages = [img, img1, img2, img3]\r\n\r\nfor i in range(4):\r\n plt.subplot(1,4,i+1), plt.title(titles[i]), plt.imshow(images[i])\r\n plt.xticks([]), plt.yticks([])\r\n\r\nplt.show()","repo_name":"thiraphong101/lesson-CV2-2-","sub_path":"06_Contours in OpenCV/06_Contour Approximation.py","file_name":"06_Contour Approximation.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74716810085","text":"# -*- coding: utf-8 -*-\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\n'''father class'''\n\n\nclass Father(object):\n \"\"\"orm表父类,可以写固定字段等 被models.py里类继承\"\"\"\n pass\n\n\nclass DbSqlalchemy(object):\n __engine = None\n __session = None\n\n def __init__(self, **kwargs):\n prefix = kwargs['PREFIX']\n db_name = kwargs['DB_NAME']\n debug = kwargs['DEBUG']\n sqlalchemy = kwargs[prefix+'SQLALCHEMY']\n user = kwargs[prefix+'USER']\n pwd = kwargs[prefix+'PWD']\n server = kwargs[prefix+'SERVER']\n port = str(kwargs[prefix+'PORT'])\n\n uri = sqlalchemy + '://' + user + ':' + pwd + '@' + server + ':' + port + '/' + db_name + '?charset=utf8'\n self.__engine = create_engine(uri, pool_recycle=7200, echo=debug) # pool_recycle避免超时,2小时连一次\n self.__session = scoped_session(sessionmaker(autocommit=True, bind=self.__engine))\n\n @property\n def engine(self):\n return self.__engine\n\n @property\n def session(self):\n return self.__session","repo_name":"dingdan539/healer","sub_path":"src/common/db/father.py","file_name":"father.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11315085393","text":"import numpy\nfrom pyremap import LatLonGridDescriptor, Remapper\n\nfrom mpas_analysis.shared.constants import constants\n\ninputFileName = '/media/xylar/extra_data/analysis/output/GMPAS-QU240/' \\\n 'remap_obs/clim/obs/mld_1.0x1.0degree.nc'\n\nobsDescriptor = LatLonGridDescriptor.read(fileName=inputFileName,\n latVarName='lat',\n lonVarName='lon')\n\ncomparisonLatRes = 4.\ncomparisonLonRes = 4.\n\nnLat = int((constants.latmax - constants.latmin) / comparisonLatRes) + 1\nnLon = int((constants.lonmax - constants.lonmin) / comparisonLonRes) + 1\nlat = numpy.linspace(constants.latmin, constants.latmax, nLat)\nlon = numpy.linspace(constants.lonmin, constants.lonmax, nLon)\n\ncomparisonDescriptor = LatLonGridDescriptor.create(lat, lon, units='degrees')\n\nremapper = Remapper(obsDescriptor, comparisonDescriptor,\n mappingFileName='map.nc')\n\nremapper.build_mapping_file()\n\nremapper.remap_file(inputFileName, 'mld_4.0x4.0degree.nc',\n ['mld', 'month', 'year'],\n renormalize=0.05)\n","repo_name":"MPAS-Dev/MPAS-Analysis","sub_path":"mpas_analysis/test/test_remap_obs_clim_subtask/remap_mld_obs.py","file_name":"remap_mld_obs.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"52"} +{"seq_id":"37730821009","text":"import os\nimport sys\nimport wget\n\nfrom pytube import YouTube, exceptions, Playlist\nfrom tqdm import tqdm\n\nresolutions = [\"144p\", \"240p\", \"360p\", \"480p\", \"720p\", \"1080p\", \"1440p\", \"2160p\", \"3840p\"]\n\ndef setup_ffmpeg():\n if not os.path.isfile(\"../ffmpeg\") or not os.path.isfile(\"../ffmpeg.exe\"):\n\n if os.path.isfile(\"../ffmpeg.exe\"):\n print(\"ffmpeg.exe found\")\n\n elif os.path.isfile(\"../ffmpeg\"):\n print(\"ffmpeg found\")\n\n print(f\"Downloading ffmpeg...\")\n\n if sys.platform == \"linux\":\n wget.download(\"https://drive.google.com/uc?export=download&id=1TjnA9oISF58DWWZ0zss22uJuQYi3ltLU\", out=\"../ffmpeg\")\n\n elif sys.platform == \"win\":\n wget.download(\"https://drive.google.com/uc?export=download&id=1hls6bh_TFux8Agk5y9VkaEJ3LlXcNTIq\", out=\"../ffmpeg.exe\")\n\ndef create_config_file():\n with open(\"config.ini\", \"w\") as config:\n config.close()\n\n\ndef setup_config_file(force=False):\n data = \"\"\"\n[VidFetch]\noutput_path = ./\ndefault_quality = highest\ndefault_codec = aac\ndefault_mode = music\n\n\n\n\"\"\"\n\n if not os.path.isfile(\"../config.ini\") or force:\n create_config_file()\n\n with open(\"config.ini\", \"w\") as config:\n config.write(data)\n\n\nclass TqdmToLogger(tqdm):\n def __init__(self, *args, **kwargs):\n super(TqdmToLogger, self).__init__(*args, **kwargs)\n\n def print_bar(self, bytes_remaining, total_size):\n self.total = total_size\n self.n = total_size - bytes_remaining\n self.last_print_n = self.n\n self.refresh()\n\n\ndef strip_title(title):\n disallowed_characters = [\"/\", \"\\\\\", \":\", \"*\", \"?\", \"\\\"\", \"<\", \">\", \"|\", \"'\", '\"', \"[\", \"]\"]\n for disallowed_character in disallowed_characters:\n title = title.replace(disallowed_character, \"\")\n\n return title\n\n\ndef custom_progress_bar(stream, chunk, bytes_remaining):\n # If the progress bar doesn't exist, initialize it\n if not hasattr(custom_progress_bar, \"_bar\"):\n total_size = stream.filesize\n custom_progress_bar._bar = TqdmToLogger(\n total=total_size, unit='B', unit_scale=True, unit_divisor=1024, desc=stream.title\n )\n # Update the progress bar\n custom_progress_bar._bar.print_bar(bytes_remaining, stream.filesize)\n # Close the progress bar when download is finished\n if bytes_remaining == 0:\n custom_progress_bar._bar.close()\n del custom_progress_bar._bar\n\n\ndef get_available_resolutions(y):\n streams = y.streams.order_by(\"resolution\")\n available_resolutions = []\n for resolution in resolutions:\n for stream in streams:\n if stream.resolution == resolution:\n if not stream.resolution in available_resolutions:\n available_resolutions.append(stream.resolution)\n\n return available_resolutions\n\n\ndef check_url(url):\n try:\n return YouTube(url)\n\n except exceptions.RegexMatchError:\n print(f\"Invalid URL! : {url}\")\n\n\ndef check_playlist(url):\n try:\n return Playlist(url)\n\n except exceptions.RegexMatchError:\n print(f\"Invalid URL! : {url}\")\n\n\ndef get_highest_resolution(y):\n resolutions = y.streams.order_by(\"resolution\")\n return resolutions[-1].itag\n","repo_name":"EchterAlsFake/VidFetch","sub_path":"shared_functions/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2915380251","text":"# Program to draw a triangle when the user clicks where they would like the three verticies to be. and provides the area and length\n# Author: Chris Williams\n\nfrom graphics import *\nfrom math import *\n\ndef main():\n win = GraphWin(\"Draw a triangle\", 600, 600)\n win.setCoords(-300, -300, 300, 300)\n\n msg = Text(Point(0, -240),\"Click where you would like the verticies of the triangle to be.\")\n msg.draw(win)\n\n point1 = win.getMouse()\n x1 = point1.getX()\n y1 = point1.getY()\n \n point2 = win.getMouse()\n x2 = point2.getX()\n y2 = point2.getY()\n\n point3 = win.getMouse()\n x3 = point3.getX()\n y3 = point3.getY()\n \n triangle = Polygon(Point(x1, y1), Point(x2, y2), Point(x3, y3))\n triangle.draw(win)\n\n win.getMouse()\nmain()\n","repo_name":"chrisleewilliams/github-upload","sub_path":"Exercises/Chapter4/exercise10.py","file_name":"exercise10.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31179990440","text":"import os\n\n\nimport cupy as cp\nimport dask\nimport dask.array as da\nimport numpy as np\nimport zarr\nfrom cucim.skimage import restoration as restoration_gpu\nfrom skimage import restoration\n\n\"\"\"\n100 micron MRI data (downsampled to 200 micron for this demo)\n\nData download link:\nhttps://openneuro.org/datasets/ds002179/versions/1.1.0\n\nNIFTI-1 format volumes were read in using nibabel and converted to a Zarr array.\n\nReferences\n----------\n...[1] Edlow, B.L. et. al. 7 Tesla MRI of the ex vivo human brain at 100 micron\n resolution. Sci Data 6, 244 (2019).\n https://doi.org/10.1038/s41597-019-0254-8\n\"\"\"\n\ndata_dir = '/home/lee8rx/zarr_temp/'\nzarr_fname = os.path.join(data_dir, \"raw_demo_200um.zarr\")\n\ndata = da.from_zarr(zarr_fname)\n\n# print shape and chunk properties\nprint(f\"data.shape = {data.shape}\")\nprint(f\"data.chunksize = {data.chunksize}\")\nprint(f\"data.numblocks = {data.numblocks}\")\n\nuse_gpu = True\n\n# define a function to denoise a single block on the GPU using cuCIM\ndef denoise_gpu(x, weight=0.008, eps=2e-4, n_iter_max=50):\n\n x = cp.asarray(x, dtype=np.float32)\n x = x.mean(0)\n\n y = restoration_gpu.denoise_tv_chambolle(\n x,\n weight=weight,\n eps=eps,\n n_iter_max=n_iter_max,\n )\n\n return cp.asnumpy(y)\n\n\n# define a function to denoise a single block on the CPU using scikit-image\ndef denoise_cpu(x, weight=0.008, eps=2e-4, n_iter_max=50):\n\n x = x.astype(np.float32, copy=False).mean(0)\n\n return restoration.denoise_tv_chambolle(\n x,\n weight=weight,\n eps=eps,\n n_iter_max=n_iter_max,\n )\n\ndenoise_func = denoise_gpu if use_gpu else denoise_cpu\nscheduler = 'threads'\n# scheduler = 'single-threaded' # use single-threaded to minimize memory use\n\n# apply denoise_gpu over all blocks of the input\ndenoised = da.map_overlap(\n denoise_func,\n data,\n depth=(0, 1, 1, 1), # bug fixed in: https://github.com/dask/dask/pull/7894\n boundary='reflect',\n drop_axis=(0,),\n trim=True,\n dtype=np.float32,\n)\n\n# write the result of the computation to a new Zarr array\nout_file = '/home/lee8rx/zarr_temp/denoised.zarr'\nwith dask.config.set(scheduler=scheduler):\n denoised.to_zarr(out_file, overwrite=True, compute=True)\n\n# denoised = da.from_zarr(out_file)\n","repo_name":"grlee77/cucim-scipy2021-demos","sub_path":"mri_200um_zarr.py","file_name":"mri_200um_zarr.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34681705918","text":"import wndMgr\nimport ui\nimport ime\nimport localeInfo\nimport net\nclass PickMoneyDialog(ui.ScriptWindow):\n\tdef __init__(self):\n\t\tui.ScriptWindow.__init__(self)\n\n\t\tself.unitValue = 1\n\t\tself.maxValue = 0\n\t\tself.eventAccept = 0\n\n\tdef __del__(self):\n\t\tui.ScriptWindow.__del__(self)\n\n\tdef LoadDialog(self):\n\t\ttry:\n\t\t\tpyScrLoader = ui.PythonScriptLoader()\n\t\t\tpyScrLoader.LoadScriptFile(self, \"UIScript/PickMoneyDialog.py\")\n\t\texcept:\n\t\t\timport exception\n\t\t\texception.Abort(\"MoneyDialog.LoadDialog.LoadScript\")\n\n\t\ttry:\n\t\t\tself.board = self.GetChild(\"board\")\n\t\t\tself.maxValueTextLine = self.GetChild(\"max_value\")\n\t\t\tself.pickValueEditLine = self.GetChild(\"money_value\")\n\t\t\tself.acceptButton = self.GetChild(\"accept_button\")\n\t\t\tself.cancelButton = self.GetChild(\"cancel_button\")\n\t\texcept:\n\t\t\timport exception\n\t\t\texception.Abort(\"MoneyDialog.LoadDialog.BindObject\")\n\n\t\tself.pickValueEditLine.SetReturnEvent(ui.__mem_func__(self.OnAccept))\n\t\tself.pickValueEditLine.SetEscapeEvent(ui.__mem_func__(self.Close))\n\t\tself.acceptButton.SetEvent(ui.__mem_func__(self.OnAccept))\n\t\tself.cancelButton.SetEvent(ui.__mem_func__(self.Close))\n\t\tself.board.SetCloseEvent(ui.__mem_func__(self.Close))\n\n\tdef Destroy(self):\n\t\tself.ClearDictionary()\n\t\tself.eventAccept = 0\n\t\tself.maxValue = 0\n\t\tself.pickValueEditLine = 0\n\t\tself.acceptButton = 0\n\t\tself.cancelButton = 0\n\t\tself.board = None\n\n\tdef SetTitleName(self, text):\n\t\tself.board.SetTitleName(text)\n\n\tdef SetAcceptEvent(self, event):\n\t\tself.eventAccept = event\n\n\tdef SetMax(self, max):\n\t\tself.pickValueEditLine.SetMax(max)\n\n\tdef Open(self, maxValue, unitValue=1):\n\n\t\tif localeInfo.IsYMIR() or localeInfo.IsCHEONMA() or localeInfo.IsHONGKONG():\n\t\t\tunitValue = \"\"\n\n\t\twidth = self.GetWidth()\n\t\t(mouseX, mouseY) = wndMgr.GetMousePosition()\n\n\t\tif mouseX + width/2 > wndMgr.GetScreenWidth():\n\t\t\txPos = wndMgr.GetScreenWidth() - width\n\t\telif mouseX - width/2 < 0:\n\t\t\txPos = 0\n\t\telse:\n\t\t\txPos = mouseX - width/2\n\n\t\tself.SetPosition(xPos, mouseY - self.GetHeight() - 20)\n\n\t\tif localeInfo.IsARABIC():\n\t\t\tself.maxValueTextLine.SetText(\"/\" + str(maxValue))\n\t\telse:\n\t\t\tself.maxValueTextLine.SetText(\" / \" + str(maxValue))\n\n\t\tself.pickValueEditLine.SetText(str(unitValue))\n\t\tself.pickValueEditLine.SetFocus()\n\n\t\time.SetCursorPosition(1)\n\n\t\tself.unitValue = unitValue\n\t\tself.maxValue = maxValue\n\t\tself.Show()\n\t\tself.SetTop()\n\n\tdef Close(self):\n\t\tself.pickValueEditLine.KillFocus()\n\t\tself.Hide()\n\n\tdef OnAccept(self):\n\n\t\ttext = self.pickValueEditLine.GetText()\n\n\t\tif len(text) > 0 and text.isdigit():\n\n\t\t\tmoney = int(text)\n\t\t\tmoney = min(money, self.maxValue)\n\n\t\t\tif money > 0:\n\t\t\t\tif self.eventAccept:\n\t\t\t\t\tself.eventAccept(money)\n\n\t\tself.Close()\n\nclass NewPickMoneyDialog(ui.ScriptWindow):\n\tdef __init__(self):\n\t\tui.ScriptWindow.__init__(self)\n\t\tself.eventAccept = 0\n\t\tself.type = 0\n\n\tdef __del__(self):\n\t\tui.ScriptWindow.__del__(self)\n\n\tdef LoadDialog(self, type):\n\t\ttry:\n\t\t\tpyScrLoader = ui.PythonScriptLoader()\n\t\t\tpyScrLoader.LoadScriptFile(self, \"UIScript/newPickMoneyDialog\" + str(type) + \".py\")\n\t\t\t# pyScrLoader.LoadScriptFile(self, \"PickMoneyDialog.py\")\n\t\texcept:\n\t\t\timport exception\n\t\t\texception.Abort(\"MoneyDialog.LoadDialog.LoadScript\")\n\n\t\ttry:\n\t\t\tself.board = self.GetChild(\"board\")\n\t\t\tself.pickValueEditLine = self.GetChild(\"money_value\")\n\t\t\tself.pickValueWonEditLine = self.GetChild(\"won_value\")\n\t\t\tself.acceptButton = self.GetChild(\"accept_button\")\n\t\t\tself.cancelButton = self.GetChild(\"cancel_button\")\n\t\texcept:\n\t\t\timport exception\n\t\t\texception.Abort(\"MoneyDialog.LoadDialog.BindObject\")\n\n\t\tself.type = type\n\t\tself.pickValueWonEditLine.SetReturnEvent(ui.__mem_func__(self.OnAccept))\n\t\tself.pickValueWonEditLine.SetEscapeEvent(ui.__mem_func__(self.Close))\n\t\t# self.pickValueEditLine.OnIMEUpdate = ui.__mem_func__(self.RefreshMoney)\n\t\tself.acceptButton.SetEvent(ui.__mem_func__(self.OnAccept))\n\t\tself.cancelButton.SetEvent(ui.__mem_func__(self.Close))\n\t\tself.board.SetCloseEvent(ui.__mem_func__(self.Close))\n\n\tdef Destroy(self):\n\t\tself.ClearDictionary()\n\t\tself.eventAccept = 0\n\t\tself.pickValueWonEditLine = 0\n\t\tself.acceptButton = 0\n\t\tself.cancelButton = 0\n\t\tself.board = None\n\n\tdef Open(self):\n\n\t\twidth = self.GetWidth()\n\t\t(mouseX, mouseY) = wndMgr.GetMousePosition()\n\n\t\tif mouseX + width/2 > wndMgr.GetScreenWidth():\n\t\t\txPos = wndMgr.GetScreenWidth() - width\n\t\telif mouseX - width/2 < 0:\n\t\t\txPos = 0\n\t\telse:\n\t\t\txPos = mouseX - width/2\n\n\t\tself.SetPosition(xPos, mouseY - self.GetHeight() - 20)\n\n\t\tif self.type == 1:\n\t\t\tself.pickValueWonEditLine.SetText(1000000)\n\t\telse:\n\t\t\tself.pickValueWonEditLine.SetText(1)\n\t\tself.pickValueWonEditLine.SetFocus()\n\n\t\time.SetCursorPosition(2)\n\n\t\tself.Show()\n\t\tself.SetTop()\n\n\tdef Close(self):\n\t\tself.pickValueWonEditLine.KillFocus()\n\t\tself.Hide()\n\n\tdef RefreshMoney(self):\n\t\tif self.type == 1:\n\t\t\tself.pickValueEditLine.SetText(localeInfo.NumberToMoneyString(int(self.pickValueWonEditLine.GetText())*1000000))\n\t\telse:\n\t\t\tself.pickValueEditLine.SetText(localeInfo.NumberToWonString(int(self.pickValueWonEditLine.GetText())/1000000))\n\n\tdef OnUpdate(self):\n\t\tself.RefreshMoney()\n\t\t\n\tdef OnAccept(self):\n\t\tif (self.type == 1):\n\t\t\tnet.SendChatPacket(\"/yangtowon \" + str(self.pickValueWonEditLine.GetText()))\n\t\telse:\n\t\t\tnet.SendChatPacket(\"/wontoyang \" + str(self.pickValueEditLine.GetText()))\n\t\tself.Close()\n","repo_name":"Sophie-Williams/SrcClient","sub_path":"root/uipickmoney.py","file_name":"uipickmoney.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4038283002","text":"import os\nimport csv\nimport statistics\n\n# Specify the file to read from\ncsvpath = os.path.join(\"Resources\", \"budget_data.csv\")\nprint (csvpath)\n\n# Initialise the following to 0 to calculate \nmonthcount = 0 # of months\ntotal = 0 # Total profit/loss\n\n# Initialise list to store changes in profit/loss every month\nchanges = []\n\nmonths = []\n\n#Open the CSV\nwith open(csvpath, encoding='utf') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n # Read the header row first (skip this step if there is now header)\n csv_header = next(csvreader)\n\n for row in csvreader:\n monthcount = monthcount + 1 # Count # of rows\n rowamount = int(row[1]) # Covert profit/loss amputnt to int and store in rowamount\n total = total + rowamount # Add profit/loss for each row \n # Calculate change from 2nd month only\n if monthcount > 1: \n change = rowamount - prevamount\n changes.append(change)\n months.append(row[0]) # Store months against the changes\n prevamount = rowamount # Store the current month amount for calculating the change for next month \n \naverage = round( statistics.mean(changes),2) # Find the average change\n\n# Fnd the minimum and maximum changes and the corresponding months\nmaxchange = max(changes)\nmaxchangemonth = months[changes.index(maxchange)]\nminchange = min(changes)\nminchangemonth = months[changes.index(minchange)]\n\n\n# Create the result\noutput = (\"Financial Analysis\\n----------------------------\\nTotal Months: \"\n+str(monthcount) +\"\\nTotal: $\" + str(total) + \"\\nAverage Changes: $\"+str(average) +\n\"\\nGreatest Increase in Profits: \"+ maxchangemonth +\" ($\" + str(maxchange)+\")\\n\" +\n\"Greatest Decrease in Profits: \" + minchangemonth +\" ($\" + str(minchange)+\")\")\n\n# Print the result\n\nprint (output)\n\n # Specify the file to write to\noutput_path = os.path.join(\"analysis\", \"financial_analysis.txt\")\n\n# Open the file using \"write\" mode.\nwith open(output_path, 'w') as file:\n\n # Write the results to the txt file\n file.write(output)\n \n","repo_name":"pankajsethi1/python-challenge","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11152717165","text":"from road_vehicle import Tanker, ElectricRoadVehicle\n\nconsist = Tanker(id='oylbarral_tanker',\n base_numeric_id=320,\n name='Oylbarral',\n tram_type='ELRL',\n vehicle_life=40,\n intro_date=1945)\n\nconsist.add_unit(type=ElectricRoadVehicle,\n capacity=0,\n vehicle_length=4,\n effects=['EFFECT_SPRITE_ELECTRIC, 0, 0, 10'],\n always_use_same_spriterow=True)\n\nconsist.add_unit(capacity=36,\n vehicle_length=6,\n repeat=2)\n","repo_name":"andythenorth/road-hog","sub_path":"src/vehicles/oylbarral_tanker.py","file_name":"oylbarral_tanker.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"40152423389","text":"import os\nimport logging\nfrom pydub import AudioSegment\nimport speech_recognition as sr\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\n\ndef transcribe(audiofile, language='en-US'):\n f = \"\"\n logger.info(\"Grab the %s\", audiofile)\n logger.info(\"Grab the %s\", type(audiofile))\n if audiofile.endswith('.ogg'):\n f = audiofile.replace('.ogg', '.wav')\n convert = AudioSegment.from_file(audiofile)\n convert.export(f, format='wav')\n elif audiofile.endswith('.mp3'):\n f = audiofile.replace('.mp3', '.wav')\n convert = AudioSegment.from_file(audiofile)\n convert.export(f, format='wav')\n else:\n logger.info(\"File %s not supported.\", audiofile)\n\n logger.info(\"Transcribing %s\", f)\n\n recognizer = sr.Recognizer()\n audio_file = sr.AudioFile(f)\n with audio_file as source:\n data = recognizer.record(source)\n\n text = recognizer.recognize_google(data, language=language)\n\n logger.info(\"Transcription: %s\", text)\n\n os.remove(\"/tmp/\"+audiofile)\n os.remove(\"/tmp/\"+f)\n\n return text\n","repo_name":"karvanpy/audiotranscribe_web","sub_path":"Transcribe.py","file_name":"Transcribe.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23226365127","text":"# -*- coding: utf-8 -*-\nfrom datetime import date\nfrom operator import itemgetter\n\nfrom django.contrib.auth.models import AbstractUser\nfrom django.contrib.postgres import fields as pg_fields\nfrom django.db import models\nfrom django.urls import reverse\n\nfrom training.core.models import Resource, TrainingUnit\nfrom training.organizations.models import Organization\n\n\nclass UserEmployeeType(models.Model):\n # Constants\n # -------------------------------------------------------\n class Type:\n TEACHER = \"teacher\"\n ADMINISTRATIVE = \"administrative\"\n\n ALL = [TEACHER, ADMINISTRATIVE]\n\n CHOICES = (\n (TEACHER, \"Docente\"),\n (ADMINISTRATIVE, \"Administrativo\"),\n )\n\n # Fields\n # -------------------------------------------------------\n name = models.CharField(\"Nombre\", max_length=150)\n type = models.CharField(\"Tipo\", max_length=30, choices=Type.CHOICES)\n\n # Meta\n # -------------------------------------------------------\n class Meta:\n db_table = 'employee_type'\n verbose_name = 'Tipo de Empleado'\n verbose_name_plural = 'Tipos de Empleados'\n\n # Magic methods\n # -------------------------------------------------------\n def __str__(self):\n return f'{self.name} ({self.get_type_display()})'\n\n\nclass User(AbstractUser):\n # Constants\n # -------------------------------------------------------\n class Gender:\n MALE = 'male'\n FEMALE = 'female'\n OTHER = 'other'\n\n ALL = [MALE, FEMALE, OTHER]\n\n CHOICES = (\n (MALE, 'Masculino'),\n (FEMALE, 'Femenino'),\n (OTHER, 'Otro')\n )\n\n class Role:\n STUDENT = \"student\"\n TEACHER = \"teacher\"\n ORGANIZATIONAL = \"organizational\"\n ADMIN = \"admin\"\n SUPERUSER = \"superuser\"\n\n ALL = [STUDENT, TEACHER, ORGANIZATIONAL, ADMIN, SUPERUSER]\n\n CHOICES = (\n (STUDENT, \"Estudiante\"),\n (TEACHER, 'Facilitador'),\n (ORGANIZATIONAL, 'Usuario organizacional'),\n (ADMIN, 'Administrador'),\n (SUPERUSER, \"Super usuario\")\n )\n\n class ExtraDataKeys:\n CURRENT_POSITION = \"current_position\"\n\n class CurrentPosition:\n NAME = \"name\"\n START_DATE = \"start_date\"\n\n # Fields\n # -------------------------------------------------------\n first_name = models.CharField('Nombres', max_length=150)\n last_name = models.CharField('Apellidos', max_length=150)\n full_name = models.CharField('Nombre completo', max_length=300, null=True)\n avatar = models.ForeignKey(\n 'core.Resource',\n on_delete=models.CASCADE,\n verbose_name='Avatar',\n limit_choices_to={\"type\": Resource.Type.AVATAR},\n null=True,\n blank=True\n )\n residence_place = models.ForeignKey(\n \"core.Area\",\n on_delete=models.CASCADE,\n related_name=\"area_user\",\n verbose_name=\"Lugar de residencia\",\n null=True,\n blank=True\n )\n email = models.EmailField('Correo electrónico', blank=True)\n alternative_email = models.EmailField('Correo electrónico alternativo', null=True, blank=True)\n phone_number = models.CharField('Número de teléfono', max_length=15, null=True, blank=True)\n alternative_phone_number = models.CharField('Número de teléfono alternativo', max_length=15, null=True, blank=True)\n gender = models.CharField('Género', choices=Gender.CHOICES, max_length=10)\n birth_day = models.DateField('Fecha de nacimiento', null=True, blank=True)\n\n employee_type = models.ForeignKey(\n UserEmployeeType, on_delete=models.CASCADE, verbose_name=\"Tipo de Empleado\", null=True, blank=True\n )\n\n is_student = models.BooleanField('Es estudiante?', default=False)\n is_teacher = models.BooleanField('Es facilitador?', default=False)\n is_organizational = models.BooleanField('Es usuario organizacional?', default=False)\n is_admin = models.BooleanField('Es administrador?', default=False)\n\n \"\"\"\n Examples:\n extra_data = {\n 'current_position': {\n 'name': 'Secretario',\n 'start_date': '2018-01-01'\n }\n }\n \"\"\"\n extra_data = pg_fields.JSONField('Datos extra', default=dict, blank=True)\n\n # Meta\n # -------------------------------------------------------\n class Meta:\n verbose_name = 'Usuario'\n verbose_name_plural = 'Usuarios'\n\n # Magic methods\n # -------------------------------------------------------\n def __str__(self):\n return self.full_name\n\n # Properties\n # -------------------------------------------------------\n @property\n def age(self):\n if self.birth_day:\n today = date.today()\n born = self.birth_day\n age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))\n return age\n else:\n return 0\n\n @property\n def age_str(self):\n if self.birth_day:\n today = date.today()\n age = today.year - self.birth_day.year - (\n (today.month, today.day) < (self.birth_day.month, self.birth_day.day))\n return \"{} años\".format(age, )\n else:\n return \" -- \"\n\n @property\n def roles(self):\n role_map = dict(self.Role.CHOICES)\n\n return [{\n \"type\": role,\n \"type_label\": role_map.get(role, \"unknown\")\n } for role in self.Role.ALL if getattr(self, f\"is_{role}\", False)]\n\n @property\n def current_position(self):\n return self.extra_data.get(self.ExtraDataKeys.CURRENT_POSITION, {})\n\n @property\n def current_position_name(self):\n return self.current_position.get(self.ExtraDataKeys.CurrentPosition.NAME, \"\")\n\n @property\n def current_position_start_date(self):\n return self.current_position.get(self.ExtraDataKeys.CurrentPosition.START_DATE, \"\")\n\n @property\n def phone_numbers(self):\n return [\n self.phone_number, self.alternative_phone_number\n ] if self.alternative_phone_number else [\n self.phone_number\n ]\n\n @property\n def emails(self):\n return [self.email, self.alternative_email] if self.alternative_email else [self.email]\n\n # Methods\n # -------------------------------------------------------\n def save(self, *args, **kwargs):\n full_name = f\"{self.first_name} {self.last_name}\"\n self.full_name = ' '.join(full_name.split())\n\n return super().save(*args, **kwargs)\n\n def get_achievements_record(self):\n \"\"\"\n Retorna un listado compuesto por las representaciones de los logros académicos del usuario incluyendo tanto\n grados académicos como capacitaciones externas e internas.\n \"\"\"\n academic_degrees = [degree.to_representation() for degree in UserAcademicDegree.objects.filter(user=self)]\n external_trainings = [training.to_representation() for training in\n UserExternalTraining.objects.filter(user=self)]\n trainings = []\n for enrollment in self.user_enrollment.filter(status='approved'):\n trainings.append({\n 'name': enrollment.group.training_unit.name,\n 'type_label': enrollment.group.training_unit.get_type_display(),\n 'tags': enrollment.group.training_unit.tags.all().values_list('display_name'),\n 'finished_at': enrollment.group.classes_ends_at.date(),\n 'location': enrollment.group.group_classroom.all().values_list('space__organization__name')[0][0],\n 'uuid': enrollment.uuid\n })\n\n records = academic_degrees + external_trainings + trainings\n records = sorted(records, key=itemgetter('finished_at'), reverse=True)\n\n return records\n\n def get_historic_enroll(self):\n \"\"\"\n Retorna un listado de capacitaciones actuales e históricas no aprobadas\n \"\"\"\n trainings = []\n for enrollment in self.user_enrollment.exclude(status='approved'):\n trainings.append({\n 'name': enrollment.group.training_unit.name,\n 'description': enrollment.group.training_unit.description,\n 'type_label': enrollment.group.training_unit.get_type_display(),\n 'modality_label': enrollment.group.get_modality_display(),\n 'teacher': enrollment.group.teacher.full_name,\n 'tags': enrollment.group.training_unit.tags.all().values_list('display_name'),\n 'started_at': enrollment.group.classes_starts_at.date(),\n 'status_label': enrollment.get_status_display(),\n 'duration': enrollment.group.training_unit.duration\n })\n return trainings\n\n def get_absolute_url(self):\n return reverse(\"users:detail\", kwargs={\"username\": self.username})\n\n def to_representation(self):\n return dict(\n id=self.id,\n username=self.username,\n full_name=self.full_name,\n first_name=self.first_name,\n last_name=self.last_name,\n age=self.age,\n email=self.email,\n phone_number=self.phone_number,\n gender=self.gender,\n gender_label=self.get_gender_display(),\n roles=self.roles\n )\n\n\nclass StudentProfile(models.Model):\n # Fields\n # -------------------------------------------------------\n student = models.OneToOneField(\n User, on_delete=models.CASCADE, verbose_name='Estudiante', limit_choices_to={'is_student': True}\n )\n\n # Meta\n # -------------------------------------------------------\n class Meta:\n db_table = 'student_profile'\n verbose_name = 'Perfil de estudiante'\n verbose_name_plural = 'Perfiles de estudiantes'\n\n # Magic methods\n # -------------------------------------------------------\n def __str__(self):\n return self.student.full_name\n\n\nclass UserAcademicDegree(models.Model):\n # Constants\n # -------------------------------------------------------\n class Type:\n PRIMARY_EDUCATION = \"primary_education\"\n SECONDARY_EDUCATION = \"secondary_education\"\n UNDERGRADUATE = \"undergraduate\"\n POSTGRADUATE = \"postgraduate\"\n DOCTORATE = \"doctorate\"\n\n ALL = [PRIMARY_EDUCATION, SECONDARY_EDUCATION, UNDERGRADUATE, POSTGRADUATE, DOCTORATE]\n\n CHOICES = (\n (PRIMARY_EDUCATION, \"Educación básica\"),\n (SECONDARY_EDUCATION, \"Educación media\"),\n (UNDERGRADUATE, \"Pregrado\"),\n (POSTGRADUATE, \"Postgrado\"),\n (DOCTORATE, \"Doctorado\"),\n )\n\n # Fields\n # -------------------------------------------------------\n user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=\"Usuario\")\n type = models.CharField(\"Grado\", max_length=30, choices=Type.CHOICES)\n achieved_title = models.CharField(\"Título obtenido\", max_length=300)\n study_center = models.CharField(\"Centro de estudios\", max_length=300)\n started_at = models.DateField(\"Fecha de inicio\")\n finished_at = models.DateField(\"Fecha de finalización\")\n\n # Meta\n # -------------------------------------------------------\n class Meta:\n db_table = 'user_academic_degree'\n verbose_name = 'Grado académico'\n verbose_name_plural = 'Grados académicos'\n\n # Magic methods\n # -------------------------------------------------------\n def __str__(self):\n return f\"{self.user.full_name} - {self.achieved_title}\"\n\n # Methods\n # -------------------------------------------------------\n def to_representation(self):\n return dict(\n id=self.id,\n user=self.user.id,\n type=self.type,\n type_label=self.get_type_display(),\n achieved_title=self.achieved_title,\n study_center=self.study_center,\n started_at=self.started_at,\n finished_at=self.finished_at\n )\n\n\nclass UserExternalTraining(models.Model):\n # Constants\n # -------------------------------------------------------\n class Type:\n TRAINING = \"training\"\n DIPLOMAT = \"diplomat\"\n COURSE = \"course\"\n WORKSHOP = \"workshop\"\n SEMINAR = \"seminar\"\n MODULE = \"module\"\n\n ALL = [TRAINING, DIPLOMAT, COURSE, WORKSHOP, SEMINAR, MODULE]\n\n CHOICES = (\n (TRAINING, \"Capacitación\"),\n (DIPLOMAT, \"Diplomado\"),\n (COURSE, \"Curso\"),\n (WORKSHOP, \"Taller\"),\n (SEMINAR, \"Seminario\"),\n (MODULE, \"Módulo\")\n )\n\n class Modality:\n FACE_TO_FACE = 'face_to_face'\n VIRTUAL = 'virtual'\n COMBINED = 'combined'\n\n CHOICES = (\n (FACE_TO_FACE, 'Presencial'),\n (VIRTUAL, 'Virtual'),\n (COMBINED, 'Presencial/Virtual')\n )\n\n # Fields\n # -------------------------------------------------------\n user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=\"Usuario\")\n type = models.CharField(\"Tipo\", max_length=30, choices=Type.CHOICES)\n name = models.CharField(\"Nombre\", max_length=150)\n description = models.CharField(\"Descripción\", max_length=300)\n location = models.CharField(\"Lugar\", max_length=300)\n started_at = models.DateField(\"Fecha de inicio\")\n finished_at = models.DateField(\"Fecha de finalización\")\n duration = models.SmallIntegerField('Duración', help_text='Duración de la capacitación en horas')\n modality = models.CharField('Modalidad', max_length=20, choices=Modality.CHOICES)\n tags = models.ManyToManyField(\"core.Tag\", verbose_name=\"Temas\", help_text='Área de conocimiento')\n\n # Meta\n # -------------------------------------------------------\n class Meta:\n db_table = 'user_external_trainings'\n verbose_name = 'Capacitación Externa'\n verbose_name_plural = 'Capacitaciones Externas'\n\n # Magic methods\n # -------------------------------------------------------\n def __str__(self):\n return self.name\n\n # Methods\n # -------------------------------------------------------\n def to_representation(self):\n return dict(\n id=self.id,\n user=self.user.id,\n type=self.type,\n type_label=self.get_type_display(),\n name=self.name,\n description=self.description,\n location=self.location,\n started_at=self.started_at,\n finished_at=self.finished_at,\n modality=self.get_modality_display(),\n duration=self.duration,\n tags=self.tags.all().values_list('display_name')\n )\n\n\nclass TeacherProfile(models.Model):\n # Fields\n # -------------------------------------------------------\n teacher = models.OneToOneField(\n User, on_delete=models.CASCADE, verbose_name='Facilitador', limit_choices_to={'is_teacher': True}\n )\n\n # Meta\n # -------------------------------------------------------\n class Meta:\n db_table = 'teacher_profile'\n verbose_name = 'Perfil de facilitador'\n verbose_name_plural = 'Perfiles de facilitadores'\n\n # Magic methods\n # -------------------------------------------------------\n def __str__(self):\n return self.teacher.full_name\n\n\nclass OrganizationalProfile(models.Model):\n # Fields\n # -------------------------------------------------------\n user = models.OneToOneField(\n User, on_delete=models.CASCADE, verbose_name='Usuario', limit_choices_to={'is_organizational': True}\n )\n organization = models.ForeignKey(Organization, on_delete=models.CASCADE, verbose_name='Organización')\n\n # position = models.CharField('Puesto', max_length=100)\n\n # Meta\n # -------------------------------------------------------\n class Meta:\n db_table = 'organizational_profile'\n verbose_name = 'Perfil de usuario organizacional'\n verbose_name_plural = 'Perfiles de usuarios organizacionales'\n\n # Magic methods\n # -------------------------------------------------------\n def __str__(self):\n return self.user.full_name\n","repo_name":"hmachuca22/agglad","sub_path":"training/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13806415532","text":"\"\"\"judge all tests\"\"\"\nimport argparse\nfrom concurrent.futures import ProcessPoolExecutor\nimport json\nimport multiprocessing\nimport os\nimport sys\nimport time\nfrom . import common\n\n\ndef print_results(results, expect_verdict=None, show_details=False):\n \"\"\"print results\"\"\"\n res = all([x['success'] for x in results])\n if expect_verdict:\n res &= any([x['verdict'] == expect_verdict for x in results])\n\n if show_details:\n time = [x['run_result'].get('time', 0.0) / 1000 for x in results]\n verdict = [x['verdict'] for x in results]\n score = [\n x.get('score') or (1.0 if x['verdict'] == 'AC' else 0.0)\n for x in results\n ]\n\n if res:\n print('\\033[32m' + 'PASS' + '\\033[0m')\n else:\n print('\\033[31m' + 'FAIL' + '\\033[0m')\n\n if show_details:\n print(' results: ', verdict)\n print(' time: ', time)\n if 'PC' in verdict:\n print(' score: ', score)\n print(' score_min: ', min(score))\n\n if res:\n return True\n\n for result in results:\n # not expect_verdict == validator\n if (not expect_verdict and\n not result['success']) or (expect_verdict and\n result['verdict'] != expect_verdict):\n print(json.dumps(\n result,\n indent=2,\n ensure_ascii=False,\n sort_keys=True,\n ))\n return False\n\n\ndef init_args():\n \"\"\"init_args\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--workers',\n default=8,\n type=int,\n help='number of parallel workers for running submissions')\n parser.add_argument(\n '--probs',\n nargs='*',\n default=[],\n help='Problems wanted to be validated, leave it blank to run all.')\n parser.add_argument(\n '--ignore-probs',\n nargs='*',\n default=[],\n help='Problems wanted to be ignored, leave it blank to run all.')\n parser.add_argument(\n '--writers',\n nargs='*',\n default=[],\n help='Judge only some writers code, leave it blank to run all.')\n parser.add_argument('--ignore-solutions',\n action='store_true',\n help='Ignore all solutions.')\n parser.add_argument('--ignore-validators',\n action='store_true',\n help='Ignore all validators.')\n parser.add_argument(\n '--sleep',\n action='store_true',\n help=\n 'Sleep after compile finish (resolve permission issue for samba mount)')\n return parser.parse_args()\n\n\ndef compile_all(args, problems):\n \"\"\"compile_all\"\"\"\n exes = []\n for prob in problems:\n prob_id = prob.prob_id\n if args.probs and prob_id not in args.probs:\n continue\n if args.ignore_probs and prob_id in args.ignore_probs:\n continue\n\n exes.append(prob.checker)\n for exe in prob.validators:\n exes.append(exe)\n for exe in prob.solutions:\n exes.append(exe)\n\n print('Pre compiling...: ', end='', flush=True)\n\n with ProcessPoolExecutor(max_workers=32) as pool:\n m = multiprocessing.Manager()\n lock = m.Lock()\n results = list(\n pool.map(common.Compiler.parallel_compile, exes, [lock] * len(exes)))\n for i in range(0, len(exes)):\n common.Compiler.update_result(exes[i], results[i])\n print('DONE\\n')\n if args.sleep:\n time.sleep(1)\n\n\ndef main():\n \"\"\"main\"\"\"\n args = init_args()\n problems = common.get_probs()\n result = True\n\n # pre compile\n compile_all(args, problems)\n\n with ProcessPoolExecutor(max_workers=args.workers) as pool:\n m = multiprocessing.Manager()\n lock = m.Lock()\n\n for prob in problems:\n prob_id = prob.prob_id\n # ignore problem\n if args.probs and prob_id not in args.probs:\n continue\n if args.ignore_probs and prob_id in args.ignore_probs:\n continue\n\n for testcase in prob.tests:\n print('Problem %s Testcase %s:' % (prob_id, testcase))\n\n if not args.ignore_validators:\n print(' validator:')\n for v in prob.validators:\n if args.writers and v.writer not in args.writers:\n continue\n if v.testcase == 'all' or v.testcase == testcase:\n fn = os.path.relpath(v.filename,\n os.path.join(os.getcwd(), 'validator'))\n _n = len(prob.tests[testcase])\n results = list(\n pool.map(common.run_validator, [v] * _n,\n prob.tests[testcase]))\n print(' %s: ' % fn, end='')\n result &= print_results(results)\n\n if not args.ignore_solutions:\n print(' solution:')\n for s in prob.solutions:\n if args.writers and s.writer not in args.writers:\n continue\n if s.testcase == 'all' or s.testcase == testcase:\n fn = os.path.relpath(s.filename,\n os.path.join(os.getcwd(), 'solution'))\n _n = len(prob.tests[testcase])\n results = list(\n pool.map(common.run_solution, [s] * _n, prob.tests[testcase],\n [prob] * _n, [lock] * _n))\n print(' %s: ' % fn, end='')\n result &= print_results(results, s.expect, show_details=True)\n print('')\n\n # clean\n for prob in problems:\n common.remove_exes(prob)\n\n return result\n\n\nif __name__ == '__main__':\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', buffering=1)\n success = main()\n if success:\n print('All tests passed')\n sys.exit(0)\n else:\n print('Test failed')\n sys.exit(1)\n","repo_name":"twpca/toi-primary-2022","sub_path":"scripts/judge.py","file_name":"judge.py","file_ext":"py","file_size_in_byte":5552,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"2685409457","text":"import sys\n\n\ndef count_safezone(map):\n result = 0\n for i in map:\n result += i.count(0)\n return result\n\n\ndef viruszone_init(map, seeds):\n global N\n global M\n for i in range(N):\n for j in range(M):\n if map[i][j] == 2:\n map[i][j] = 0\n for seed in seeds:\n map[seed[0]][seed[1]] = 2\n\n \ndef search_seed(map):\n result = []\n for i in range(len(map)):\n for j in range(len(map[i])):\n if map[i][j] == 2:\n result.append((i, j))\n return result\n\n\ndef search_safezone_coordinates(map):\n result = []\n for i in range(len(map)):\n for j in range(len(map[i])):\n if map[i][j] == 0:\n result.append((i, j))\n return result\n\n\ndef dfs(map):\n N, M = len(map), len(map[0])\n dx, dy = [0, 0, 1, -1], [1, -1, 0, 0]\n queue = search_seed(map)\n while queue:\n current = queue.pop()\n for i in range(4):\n next = (current[0] + dy[i], current[1] + dx[i])\n if 0 <= next[0] < N and 0 <= next[1] < M:\n if map[next[0]][next[1]] == 0:\n map[next[0]][next[1]] = 2\n queue.append((next[0], next[1]))\n return count_safezone(map)\n\n\nif __name__ == \"__main__\":\n N, M = map(int, sys.stdin.readline().split())\n lab_map = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]\n allsafezone = search_safezone_coordinates(lab_map)\n fisrt_seed = search_seed(lab_map)\n\n ans = 0\n i, j, k = 0, 1, 2\n tmp = []\n flag = True\n while flag:\n walls = [allsafezone[i], allsafezone[j], allsafezone[k]]\n for wall in walls: # 벽 3개 생성\n lab_map[wall[0]][wall[1]] = 1\n\n ans = max(ans, dfs(lab_map))\n viruszone_init(lab_map, fisrt_seed)\n\n for wall in walls: # 벽 3개 제거\n lab_map[wall[0]][wall[1]] = 0\n\n k += 1\n if k == len(allsafezone):\n j += 1\n k = j + 1\n if j == len(allsafezone) - 1:\n i += 1\n j = i + 1\n k = j + 1\n if i == len(allsafezone) - 2:\n flag = False\n \n print(ans)\n","repo_name":"SeongJun-Ham/PS","sub_path":"divertissement/14502_G4.py","file_name":"14502_G4.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29206956135","text":"import torch\nimport torch.nn as nn\nfrom tqdm import tqdm\n# from tqdm.notebook import tqdm\n\n\ndef validate(model: torch.nn.Module,\n device: str,\n val_loader: torch.utils.data.DataLoader,\n criterion_classification: nn.Module,\n criterion_regression: nn.Module,\n bins_midpoints: torch.Tensor,\n epoch: int) -> tuple:\n \"\"\"Validate the model for one epoch\n\n Args:\n model (Model): The model to validate\n device (string): The device to use (cpu or cuda)\n val_loader (Dataloader): The validation data loader\n criterion_classification (Loss): The classification loss to use\n criterion_regression (Loss): The regression loss to use\n bins_midpoints (ndarray): The midpoints of the bins used to discretize\n the traversal costs\n epoch (int): The current epoch\n \n Returns:\n double, double, double: The validation loss, the validation accuracy\n and the validation regression loss\n \"\"\"\n # Initialize the validation loss and accuracy\n val_loss = 0.\n val_correct = 0\n val_regression_loss = 0.\n \n # Configure the model for testing\n # (turn off dropout layers, batchnorm layers, etc)\n model.eval()\n \n # Add a progress bar\n val_loader_pbar = tqdm(val_loader, unit=\"batch\")\n \n # Turn off gradients computation (the backward computational graph is\n # built during the forward pass and weights are updated during the backward\n # pass, here we avoid building the graph)\n with torch.no_grad():\n \n # Loop over the validation batches\n for images,\\\n traversal_costs,\\\n traversability_labels,\\\n linear_velocities in val_loader_pbar:\n\n # Print the epoch and validation mode\n val_loader_pbar.set_description(f\"Epoch {epoch} [val]\")\n\n # Move images and traversal scores to GPU (if available)\n images = images.to(device)\n traversal_costs = traversal_costs.to(device)\n traversability_labels = traversability_labels.to(device)\n linear_velocities = linear_velocities.type(torch.float32).to(device)\n \n # Add a dimension to the linear velocities tensor\n linear_velocities.unsqueeze_(1)\n \n # Perform forward pass (only, no backpropagation)\n predicted_traversability_labels = model(images, linear_velocities)\n # predicted_traversal_scores = nn.Softmax(dim=1)(model(images))\n\n # Compute loss\n loss = criterion_classification(predicted_traversability_labels,\n traversability_labels)\n\n # Print the batch loss next to the progress bar\n val_loader_pbar.set_postfix(batch_loss=loss.item())\n\n # Accumulate batch loss to average over the epoch\n val_loss += loss.item()\n \n # Get the number of correct predictions\n val_correct += torch.sum(\n torch.argmax(predicted_traversability_labels, dim=1) == traversability_labels\n ).item()\n \n # Compute the expected traversal cost over the bins\n expected_traversal_costs = torch.matmul(\n nn.Softmax(dim=1)(predicted_traversability_labels),\n bins_midpoints)\n\n # Compute and accumulate the batch loss\n val_regression_loss += criterion_regression(\n expected_traversal_costs[:, 0],\n traversal_costs).item()\n \n # Compute the losses and accuracies\n val_loss /= len(val_loader)\n val_accuracy = 100*val_correct/len(val_loader.dataset)\n val_regression_loss /= len(val_loader)\n \n return val_loss, val_accuracy, val_regression_loss\n","repo_name":"TomRavaud/Internship-U2IS","sub_path":"src/models_development/multimodal_velocity/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39588852254","text":"from sys import stdout,stdin\r\nfrom collections import Counter\r\nimport math\r\ndef nCr(n,r):\r\n f=math.factorial\r\n if(n<2):\r\n pass\r\n else:\r\n return(f(n)//f(r)//f(n-r))\r\n \r\nt=int(stdin.readline())\r\nwhile(t>0):\r\n t=t-1\r\n n=int(stdin.readline())\r\n l=[int(x) for x in stdin.readline().split()]\r\n q=int(stdin.readline())\r\n while(q>0):\r\n q=q-1\r\n a,b=map(int,input().split())\r\n p=l[a-1:b]\r\n l2=list(set(p))\r\n c=Counter(p)\r\n s=0\r\n for i in range(0,len(c)):\r\n n=int(c[l2[i]])\r\n # print(n)\r\n if(len(p)==1):\r\n s=1\r\n if(n==1 and len(p)!=1):\r\n s=s\r\n if(n!=1):\r\n s=s+nCr(n,2)\r\n print(s%998244353)\r\n \r\n \r\n","repo_name":"Manthanc007/APS-2o2o","sub_path":"msdwin2.py","file_name":"msdwin2.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72298469924","text":"from cx_Freeze import setup, Executable\n\n# ADD FILES\nfiles = ['icon.ico','pydracula/themes/']\n\n# TARGET\ntarget = Executable(\n script=\"run.py\",\n icon=\"icon.ico\"\n)\n\noptions = {\n \"build_exe\": {\n \"excludes\": [\n \"tkinter\",\n \"PyQt5\",\n \"PyQt6\",\n ],\n \"zip_include_packages\": [\"PySide6\"],\n 'include_files' : files\n },\n}\n\n# SETUP CX FREEZE\nsetup(\n name = \"PyDracula\",\n version = \"1.0\",\n description = \"Modern GUI for Python applications\",\n author = \"Wanderson M. Pimenta\",\n options = options,\n executables = [target] \n)","repo_name":"lgili/pydracula-pyside6-template","sub_path":"_packaging/build_linux.py","file_name":"build_linux.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"25190194158","text":"from rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .serializers import ImageSerializer\nimport cv2\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom django.shortcuts import render\n\n\n@api_view(['GET', 'POST'])\ndef detect_colors(request, num_colors=10):\n if request.method == 'POST':\n serializer = ImageSerializer(data=request.data)\n if serializer.is_valid():\n image_file = serializer.validated_data['image']\n image = cv2.imdecode(np.frombuffer(image_file.read(), np.uint8), cv2.IMREAD_COLOR)\n image, pixels = preprocess_image(image)\n colors = quantize_colors(pixels, num_colors)\n color_names = ['URO', 'BIL', 'KET', 'BLD', 'PRO', 'NIT', 'LEU', 'GLU', 'SG', 'PH']\n color_values = get_color_values(colors)\n response = {name: list(value) for name, value in zip(color_names, color_values)}\n return Response(response)\n else:\n return Response(serializer.errors, status=400)\n else:\n return render(request, 'upload_image.html')\ndef preprocess_image(image):\n # Convert the image from BGR to RGB\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n # Reshape the image to a 2D array of pixels\n pixels = image.reshape(-1, 3)\n # Convert the pixels to float type\n pixels = pixels.astype(float)\n # Normalize the pixel values\n pixels /= 255.0\n return image, pixels\n\ndef quantize_colors(pixels, num_colors):\n # Apply K-means clustering to identify the dominant colors\n kmeans = KMeans(n_clusters=num_colors)\n kmeans.fit(pixels)\n # Get the RGB values of the cluster centers\n colors = kmeans.cluster_centers_\n # Scale the RGB values back to the range of 0-255\n colors *= 255.0\n colors = colors.round().astype(int)\n return colors\n\ndef get_color_values(colors):\n # Convert the colors to a list of tuples\n color_values = colors.tolist()\n # Convert the color values to integers\n color_values = [[int(value) for value in color] for color in color_values]\n return color_values\n\n\n\n","repo_name":"vamsi3856/color-detection.github.io","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"2475266572","text":"#!/usr/bin/env python3\n\nimport copy\nfrom decimal import DecimalTuple\nfrom genericpath import exists\nimport itertools\nimport sys\nimport os\nimport subprocess\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.linear_model import RidgeClassifier\n\nfrom sklearn.tree import DecisionTreeClassifier\n\nimport fastinference.Loader\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.metrics import accuracy_score\n\nimport tempfile\nimport numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom scipy.io.arff import loadarff\nimport urllib.request\n\nfrom fastinference.models.Ensemble import Ensemble\n\ndef download(url, filename, tmpdir = None):\n \"\"\"Download the file under the given url and store it in the given tmpdir udner the given filename. If tmpdir is None, then `tempfile.gettmpdir()` will be used which is most likely /tmp on Linux systems.\n\n Args:\n url (str): The URL to the file which should be downloaded.\n filename (str): The name under which the downlaoded while should be stored.\n tmpdir (Str, optional): The directory in which the file should be stored. Defaults to None.\n\n Returns:\n str: Returns the full path under which the file is stored. \n \"\"\"\n if tmpdir is None:\n tmpdir = os.path.join(tempfile.gettempdir(), \"data\")\n\n os.makedirs(tmpdir, exist_ok=True)\n\n if not os.path.exists(os.path.join(tmpdir,filename)):\n print(\"{} not found. Downloading.\".format(os.path.join(tmpdir,filename)))\n urllib.request.urlretrieve(url, os.path.join(tmpdir,filename))\n return os.path.join(tmpdir,filename)\n\ndef read_arff(path, class_name):\n \"\"\"Loads the ARFF file under the given path and transforms it into a pandas dataframe. Each column which does not match class_name is copied into the pandas frame without changes. The column with the name `class_name` is renamed to `label` in the DataFrame. The behaviour of this method is undefined if the ARFF file already contains a `label` column and `class_name != 'label'`. \n\n Args:\n path (str): The path to the ARFF file.\n class_name (str): The label column in the ARFF file\n\n Returns:\n pandas.DataFrame : A pandas dataframe containing the data from the ARFF file and an additional `label` column.\n \"\"\"\n data, meta = loadarff(path)\n Xdict = {}\n for cname, ctype in zip(meta.names(), meta.types()):\n # Get the label attribute for the specific dataset:\n # eeg: eyeDetection\n # elec: class\n # nomao: Class\n # polish-bankruptcy: class\n if cname == class_name:\n #if cname in [\"eyeDetection\", \"class\", \"Class\"]:\n enc = LabelEncoder()\n Xdict[\"label\"] = enc.fit_transform(data[cname])\n else:\n Xdict[cname] = data[cname]\n return pd.DataFrame(Xdict)\n\ndef get_dataset(dataset, tmpdir = None, split = 0.3):\n \"\"\"Returns XTrain, YTrain, XTest, YTest of the given dataset by name. If the dataset does not exist it will be automatically downloaded.\n\n Args:\n dataset (str): The name of the dataset to be returned (and downloaded if required.). Currently supports {magic, mnist, fashion, eeg}\n tmpdir (str, optional): The temporary folder to which the dataset is downloaded if it does not exist. If None then uses tempfile.gettempdir() to query for an appropriate temp folder. Defaults to None.\n split (float, optional): The applied train/test split. If the data-set comes with a pre-defined split (e.g. mnist) this value is ignored. Defaults to 0.3\n\n Raises:\n ValueError: Raises a ValueError if an unsupported dataset is passed as an argument\n\n Returns:\n XTrain, YTrain, XTest, YTest (2d np.array, np.array, 2d np.array, np.array): Returns the (N, d) train/test data and the (N, ) train/test labels where N is the number of data points and d is the number of features. \n \"\"\"\n\n if dataset == \"magic\":\n magic_path = download(\"http://archive.ics.uci.edu/ml/machine-learning-databases/magic/magic04.data\", \"magic.csv\", tmpdir)\n df = pd.read_csv(magic_path)\n X = df.values[:,:-1].astype(np.float64)\n Y = df.values[:,-1]\n Y = np.array([0 if y == 'g' else 1 for y in Y])\n XTrain, XTest, YTrain, YTest = train_test_split(X, Y, test_size=split, random_state=42)\n elif dataset == \"fashion\" or dataset == \"mnist\":\n def load_mnist(path, kind='train'):\n # Taken from https://github.com/zalandoresearch/fashion-mnist/blob/master/utils/mnist_reader.py\n import os\n import gzip\n import numpy as np\n\n \"\"\"Load MNIST data from `path`\"\"\"\n labels_path = os.path.join(path,'%s-labels-idx1-ubyte.gz'% kind)\n images_path = os.path.join(path,'%s-images-idx3-ubyte.gz'% kind)\n\n with gzip.open(labels_path, 'rb') as lbpath:\n labels = np.frombuffer(lbpath.read(), dtype=np.uint8,offset=8)\n\n with gzip.open(images_path, 'rb') as imgpath:\n images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels), 784)\n\n return images, labels\n\n if dataset == \"fashion\":\n if tmpdir is None:\n out_path = os.path.join(tempfile.gettempdir(), \"data\", \"fashion\")\n else:\n out_path = os.path.join(tmpdir, \"data\", \"fashion\")\n\n train_path = download(\"http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz\", \"train-images-idx3-ubyte.gz\", out_path)\n train_path = download(\"http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz\", \"train-labels-idx1-ubyte.gz\", out_path)\n test_path = download(\"http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz\", \"t10k-images-idx3-ubyte.gz\", out_path)\n test_path = download(\"http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz\", \"t10k-labels-idx1-ubyte.gz\", out_path)\n else:\n if tmpdir is None:\n out_path = os.path.join(tempfile.gettempdir(), \"data\", \"mnist\")\n else:\n out_path = os.path.join(tmpdir, \"data\", \"mnist\")\n\n train_path = download(\"http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz\", \"train-images-idx3-ubyte.gz\", out_path)\n train_path = download(\"http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz\", \"train-labels-idx1-ubyte.gz\", out_path)\n test_path = download(\"http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\", \"t10k-images-idx3-ubyte.gz\", out_path)\n test_path = download(\"http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\", \"t10k-labels-idx1-ubyte.gz\", out_path)\n\n XTrain, YTrain = load_mnist(out_path, kind='train')\n XTest, YTest = load_mnist(out_path, kind='t10k')\n elif dataset == \"eeg\":\n eeg_path = download(\"https://archive.ics.uci.edu/ml/machine-learning-databases/00264/EEG%20Eye%20State.arff\", \"eeg.arff\", tmpdir)\n \n df = read_arff(eeg_path, \"eyeDetection\")\n df = pd.get_dummies(df)\n df.dropna(axis=1, inplace=True)\n Y = df[\"label\"].values.astype(np.int32)\n df = df.drop(\"label\", axis=1)\n\n X = df.values.astype(np.float64)\n XTrain, XTest, YTrain, YTest = train_test_split(X, Y, test_size=split, random_state=42)\n else:\n raise ValueError(\"Unsupported dataset provided to get_dataset in test_utils.py: {}. Currently supported are {mnist, fashion eeg, magic}\".format(dataset))\n # return None, None\n\n return XTrain, YTrain, XTest, YTest\n\ndef make_hash(o):\n \"\"\"Generates a positive hash from the given object. Does also work for tuples / dicts and lists\n\n Args:\n o (The object to be hashed): A positive hash value\n \"\"\"\n def freeze(o):\n # if isinstance(o, tuple):\n # return frozenset( freeze(oi) for oi in o)\n\n if isinstance(o,dict):\n return frozenset({ k:freeze(v) for k,v in o.items()}.items())\n elif isinstance(o,(list,tuple,set)):\n return tuple([freeze(v) for v in o])\n else: \n return hash(str(o)) \n # return o\n \n return str(hash(freeze(o)) + sys.maxsize + 1) \n\ndef cfg_to_str(d):\n \"\"\"A simple helper functions that formats a dictionary or lists of dictionaries into readable string by removing large numpy arrays from them. \n\n Args:\n d (dict or list of dict): The dictionary or list of dictionaries to be converted into a string\n\n Returns:\n str: The string\n \"\"\"\n _d = copy.deepcopy(d)\n\n if isinstance(_d, list):\n return str([cfg_to_str(di) for di in _d])\n else:\n for k in list(_d.keys()):\n v = _d[k]\n if isinstance(v, np.ndarray) and (len(v.shape) > 2 or len(v) > 5):\n del _d[k]\n #_d[k] = \"np.array\"\n return str(_d)\n\ndef prepare_onnxmodel(onnx_path, out_path, name, benchmark_file, implementation_type, implementation_args = {}, base_optimizer = [], base_optimizer_args = [], ensemble_optimizer = [], ensemble_optimizer_args = []):\n # print(\"Loading testing data\")\n # df = pd.read_csv(benchmark_file)\n # y_test = df[\"label\"].to_numpy()\n # x_test = df.drop(columns=[\"label\"]).to_numpy()\n # print(\"\")\n # accuracy = accuracy_score(y_test, model.predict(x_test))*100.0\n\n fi_model = fastinference.Loader.NeuralNet(onnx_path)\n\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n\n print(\"Exporting {} with {} to {}\".format(\n {\"implementation_type\":implementation_type, **implementation_args},{n:a for n, a in zip(base_optimizer, base_optimizer_args)}, name,out_path)\n )\n if len(base_optimizer) > 0 and base_optimizer[0] is not None:\n fi_model.optimize(base_optimizer, base_optimizer_args)\n fi_model.implement(out_path, \"model\", \"cpp.{}\".format(implementation_type), **implementation_args)\n\n prepare_and_compile = \"\"\"\n cp ./main.cpp {outpath} && \n cp {test_file} {outpath}/ && \n cp ./CMakeLists.txt {outpath}\n \"\"\".replace(\"{outpath}\", out_path).replace(\"{test_file}\", benchmark_file)\n \n subprocess.call(prepare_and_compile, shell=True)\n\ndef run_experiment(out_path, name, feature_type, label_type, benchmark_file, n_repeat = 5):\n \"\"\"Compiles and executes the cpp code in the given filename using the supplied benchmark file.\n\n Note 1: This code requires cmake for the compilation.\n Note 2: This call will likely only work on Linux / MAC as it utilizes cp to move some files around\n\n TODO: Make it platform independent. \n\n Args:\n out_path (str): Folder in which all the cpp files are located.\n name (str): The name of the function that should be tested. In most cases this is the model name\n benchmark_file (str): A *.csv file that contains the test data\n n_repeat (int, optional): The number of repetitions the experiment is repeated to get a more accurate estimation of the latency. Defaults to 5.\n\n Returns:\n dict: A dictionary that contains the output of the binary. It has the following fields: \"accuracy\", \"diff accuracy\", \"latency [ms]\", \"size [Bytes]\"\n \"\"\" \n \n prepare_and_compile = \"\"\"\n cd {outpath} &&\n cmake . -DMODELNAME={name} -DLABEL_TYPE={label_type} -DFEATURE_TYPE={feature_type} &&\n make\"\"\".replace(\"{outpath}\", out_path).replace(\"{name}\", name).replace(\"{feature_type}\", feature_type).replace(\"{label_type}\", label_type).replace(\"{test_file}\", benchmark_file)\n \n print(\"Calling {}\".format(prepare_and_compile))\n subprocess.call(prepare_and_compile, shell=True)\n\n print(\"Running {} {} {}\".format(os.path.join(out_path, \"testCode\"), benchmark_file, str(n_repeat)))\n output = subprocess.check_output([\n os.path.join(out_path, \"testCode\"),\n benchmark_file,\n str(n_repeat)\n ]).decode(sys.stdout.encoding).strip()\n \n accuracy = output.split(\"\\n\")[-1].split(\",\")[0]\n diff = output.split(\"\\n\")[-1].split(\",\")[2]\n latency = output.split(\"\\n\")[-1].split(\",\")[3]\n \n return {\n \"accuracy\": accuracy,\n \"diff accuracy\": diff,\n \"latency [ms]\": latency,\n \"size [Bytes]\": os.path.getsize(os.path.join(out_path, \"testCode\"))\n }\n\ndef prepare_fastinference(model_path, out_path, implementation_type, implementation_args = {}, base_optimizer = [], base_optimizer_args = [], ensemble_optimizer = [], ensemble_optimizer_args = []):\n \"\"\"Prepares all files for the given model and optimizations / implementations for the cpp backend.\n\n Note: This call will likely only work on Linux / MAC as it utilizes cp to move some files around\n\n TODO: Make it platform independent. \n\n Args:\n model_path ([type]): The model to be generated\n out_path ([type]): The path in which all cpp files should be stored\n implementation_type (str): The cpp implementation. \n implementation_args (dict, optional): A dictionaries of additional parameters used during implementation. Defaults to {}.\n base_optimizer (list of string, optional): A list of optimizations that are applied before implementing the model. Defaults to [].\n base_optimizer_args (list of dict, optional): A list of parameters for each optimizer. Defaults to [].\n ensemble_optimizer (list of string, optional): A list of optimizations that are applied to the ensemble. Defaults to [].\n ensemble_optimizer_args (list of dict, optional): A list of parameters for each ensemble optimizer. Defaults to [].\n \"\"\" \n fi_model = fastinference.Loader.model_from_file(model_path)\n\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n\n if isinstance(fi_model, (Ensemble)):\n print(\"Exporting {} using {}:{} with {}:{} and {}:{} to {}\".format(\n fi_model.name, implementation_type, cfg_to_str(implementation_args), ensemble_optimizer, cfg_to_str(ensemble_optimizer_args), base_optimizer, cfg_to_str(base_optimizer_args), out_path\n ))\n if len(ensemble_optimizer) > 0 and ensemble_optimizer[0] is not None:\n fi_model.optimize(ensemble_optimizer, ensemble_optimizer_args, base_optimizer, base_optimizer_args)\n fi_model.implement(out_path, \"model\", \"cpp\", \"cpp.{}\".format(implementation_type), **implementation_args)\n else:\n print(\"Exporting {} using {}:{} with {}:{} to {}\".format(\n fi_model.name, implementation_type, cfg_to_str(implementation_args), base_optimizer, cfg_to_str(base_optimizer_args), out_path\n ))\n if len(base_optimizer) > 0 and base_optimizer[0] is not None:\n fi_model.optimize(base_optimizer, base_optimizer_args)\n fi_model.implement(out_path, \"model\", \"cpp.{}\".format(implementation_type), **implementation_args)\n \n prepare_and_compile = \"\"\"\n cp ./main.cpp {outpath} && \n cp ./CMakeLists.txt {outpath}\n \"\"\".replace(\"{outpath}\", out_path).replace(\"{name}\", fi_model.name).replace(\"{feature_type}\", \"double\")\n \n print(\"Calling {}\".format(prepare_and_compile))\n subprocess.call(prepare_and_compile, shell=True)\n\ndef test_implementations(model, dataset, split, implementations, base_optimizers = [([None], [{}])], ensemble_optimizers = [([None], [{}])], out_path = \".\", model_name=\"Model\", n_repeat=5):\n print(\"Loading {}\".format(dataset))\n XTrain, YTrain, XTest, YTest = get_dataset(dataset,out_path,split)\n\n print(\"Fitting model\")\n model.fit(XTrain, YTrain)\n\n print(\"Storing model\")\n acc = accuracy_score(model.predict(XTest), YTest)*100.0\n if isinstance(model, (DecisionTreeClassifier, RidgeClassifier, QuadraticDiscriminantAnalysis, RandomForestClassifier)):\n fimodel = fastinference.Loader.model_from_sklearn(model, name = model_name, accuracy = acc)\n path_to_model = fastinference.Loader.model_to_json(fimodel, os.path.join(out_path), file_name=model_name)\n print(\"SK ACC:\", acc)\n print(\"MY ACC:\", accuracy_score(fimodel.predict(XTest), YTest)*100.0)\n else:\n path_to_model = model.store(out_path, acc, model_name)\n \n print(\"Storing test data\")\n dfTest = pd.concat([pd.DataFrame(XTest, columns=[\"f{}\".format(i) for i in range(len(XTrain[0]))]), pd.DataFrame(YTest,columns=[\"label\"])], axis=1)\n path_to_testfile = os.path.join(out_path, \"testing.csv\")\n dfTest.to_csv(path_to_testfile, header=True, index=False)\n performance = []\n print(implementations)\n print(base_optimizers)\n print(ensemble_optimizers)\n for impl, bopt, eopt in itertools.product(implementations, base_optimizers, ensemble_optimizers):\n impl_path = os.path.join(out_path, model_name + \"_\" + make_hash(impl) + \"_\" + make_hash(bopt) + \"_\" + make_hash(eopt))\n\n prepare_fastinference(path_to_model, impl_path, implementation_type = impl[0], implementation_args = impl[1], base_optimizer = bopt[0], base_optimizer_args = bopt[1], ensemble_optimizer = eopt[0], ensemble_optimizer_args = eopt[1])\n\n feature_type = impl[1].get(\"feature_type\", \"double\")\n label_type = impl[1].get(\"label_type\", \"double\")\n\n performance.append(\n {\n \"impl\":impl[0],\n #\"implt_args\":cfg_to_str(impl[1]),\n \"base_opt\":bopt[0],\n #\"base_opt_args\":cfg_to_str(bopt[1]),\n \"opt\":eopt[0],\n #\"opt_args\":cfg_to_str(eopt[1]),\n **run_experiment(impl_path, model_name, feature_type, label_type, path_to_testfile, n_repeat)\n }\n )\n\n if len(bopt[0]) == 1 and bopt[0][0] is None and len(eopt[0]) == 1 and eopt[0][0] is None and abs(float(performance[-1][\"diff accuracy\"])) > 1e-5:\n print(\"FAILED: Diff accuracy did not match in un-optimized implementation. Difference is {}\".format(performance[-1][\"diff accuracy\"]))\n sys.exit(1)\n \n return performance","repo_name":"sbuschjaeger/fastinference","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":18091,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"} +{"seq_id":"8174572438","text":"import logging\n\n_logger = logging.getLogger(__name__)\n\n\ndef check_header( a_jwt , a_headers):\n w_token = get_token_from_header(a_headers)\n if w_token is None:\n return False\n return a_jwt.verify(w_token)\n\n\ndef get_token_decoded(a_jwt, a_headers):\n w_token = get_token_from_header(a_headers)\n if w_token is None:\n return False\n return a_jwt.get_token_decoded(w_token)\n\ndef get_token_from_header(a_headers):\n if \"authorization\" in a_headers:\n w_authorization = a_headers[\"authorization\"]\n if w_authorization is not None and \"Bearer\" in w_authorization:\n w_token = w_authorization[len(\"Bearer \"):]\n return w_token\n else:\n return None\n elif \"Cookie\" in a_headers:\n w_cookies = a_headers[\"Cookie\"]\n w_token = \"\"\n if \";\" in w_cookies:\n w_arr = w_cookies.split(\";\")\n for w_cookie in w_arr:\n if \"_ycappuccino\" in w_cookie:\n w_token = w_cookie.split(\"=\")[1]\n else:\n w_token = w_cookies.split(\"=\")[1]\n _logger.info(\"token {}\".format(w_token))\n return w_token\n","repo_name":"pisua/ycappuccino-core","sub_path":"endpoints/bundles/utils_header.py","file_name":"utils_header.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"17817046904","text":"# -*- coding: utf-8 -*-\nimport os\nimport torch\nfrom pathlib import Path\nfrom utils.splitter import splitter\nfrom mmaction.apis import init_recognizer, inference_recognizer\n\ndef action_recognition(video_path, sav_dir, config_file, checkpoint_file, device, topk, split=False, segment_sec=None, fourcc=None):\n \n \"\"\"\n 1. video_path: str, action_recognition 돌릴 영상 주소 e.g) '/home/Cook_Video_Analysis/Dataset/meat.mp4'\n 2. sav_dir: str, 구간 분할한 영상 저장할 경로 e.g) '/home/Cook_Video_Analysis/Dataset/segment/'\n 3. config_file: str, action_recognition config(module) e.g) 'configs/recognition/tsn/tsn_r50_video_inference_1x1x3_100e_kinetics400_rgb.py'\n 4. checkpoints_file: str, weight check point 주소 e.g) 'checkpoints/tsn_r50_1x1x3_100e_kinetics400_rgb_20200614-e508be42.pth'\n 5. device: str, 사용할 device e.g) 'cuda:0' or 'cpu'\n 6. topk: int, 몇 개의 빈도수 상위 태그를 뽑을 것인지 e.g) 3\n 7. split: bool, default=False, 영상 분할을 할 것인지, False시 통 영상 채로 분석 결과 도출 e.g) False\n 8. segment_sec: int, default=None, 몇 초씩 구간 분할을 할 것인지 e.g) 10\n 9. fourcc: str, default=None, four character code : 코덱, 압축 방식, 색상, 픽셀 포맷 등을 정의하는 정수 값 e.g) 'mp4v'\n \"\"\"\n \n # sort segment in ascending order\n video_name = Path(video_path).stem\n \n # assign the desired device.\n device = torch.device(device)\n \n # build the model from a config file and a checkpoint file\n model = init_recognizer(config_file, checkpoint_file, device=device)\n \n # label open\n labels = open('tools/data/kinetics/label_map_k400.txt').readlines()\n labels = [x.strip() for x in labels]\n \n # split video into segments, and output\n if split:\n splitter(video_path, segment_sec, sav_dir, fourcc)\n\n seg_list = os.listdir(f'{sav_dir}{video_name}/')\n seg_sort = sorted(seg_list, key = lambda x: int(Path(x).stem[len(video_name)+1:]))\n \n results_dict = {}\n\n # action recognition execute with seg videoes\n for name in seg_sort:\n video = f'{sav_dir}{video_name}/{name}'\n results = inference_recognizer(model, video)\n\n # results\n results = [(labels[k[0]], k[1]) for k in results]\n results_dict[name] = results\n \n # analysis result by value count\n results_count = {}\n\n for key in results_dict.keys():\n\n for label, score in results_dict[key]:\n\n if label in results_count:\n results_count[label] += score\n else:\n results_count[label] = score\n \n # topk label tag list\n topk_tags = [label[0] for label in sorted(results_count.items(), key = lambda x: -x[1])[:topk]]\n \n else: # not split video output\n results = inference_recognizer(model, video=video_path)\n topk_tags = [labels[k[0]] for k in results[:topk]]\n \n return topk_tags\n","repo_name":"jaechanjo/Cook-Video_Analysis","sub_path":"action_recognition.py","file_name":"action_recognition.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23987312324","text":"import re\nfrom datetime import datetime, timedelta\n\nfile_name = input(\"Percorso (completo) del log .ubx (e.g. C:/../../../file.ubx): \")\nacq_date = datetime.strptime(input(\"Data dell'acquisizione (gg/mm/aaaa): \"), \"%d/%m/%Y\")\n\nfile_path = file_name[:-4]\n\nnmea_regex = re.compile(rb'\\$GN[A-Z]{3}.*?\\r\\n')\n\nwith open(file_name, 'rb') as file:\n binary_data = file.read()\n\n# crea i due file in cui salvare tempi e stringhe NMEA\nnmea_file = open(file_path + \"_NMEA.txt\", \"w\")\nnmea_times_file = open(file_path + \"_NMEA_times.txt\", \"w\")\n\nnmea_strings = nmea_regex.findall(binary_data)\nnmea_strings = [nmea.decode('utf-8') for nmea in nmea_strings]\n\nfor s in nmea_strings:\n # Estrae il timestamp dalla stringa NMEA\n timestamp = s.split(',')[1]\n # Converte il timestamp in un oggetto datetime e aggiunge 2 ore\n nmea_datetime = datetime.strptime(timestamp, \"%H%M%S.%f\").replace(year=acq_date.year, month=acq_date.month, day=acq_date.day)\n nmea_datetime = nmea_datetime + timedelta(hours=2)\n # Formatta il datetime nel formato desiderato\n formatted_datetime = nmea_datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n # scrivo nei files\n nmea_times_file.write(formatted_datetime + \"\\t\" + timestamp + \"\\n\")\n nmea_file.write(s[:-1])\n\nnmea_file.close()\nnmea_times_file.close()\n\nprint(\"Estrazione stringhe NMEA completata con successo. Controllare i risultati nella directory del file .ubx.\")","repo_name":"lucapada/GPSDataLoggerParser","sub_path":"extractNMEA.py","file_name":"extractNMEA.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6116168298","text":"from time import sleep\nfrom datetime import datetime\nimport serial\nimport config\n\n# setup\nser = serial.Serial(config.dev, 115200)\nser.timeout = 2\n\nprint(\"----- Start -----\")\nser.write(str.encode(\"SKJOIN \" + config.ipv6 + \"\\r\\n\"))\n\nwhile True:\n read = ser.readline().decode()\n if (read != \"\"):\n print(datetime.now(), end=\": \")\n print(read, end=\"\")\n sleep(1)\n","repo_name":"doariva/wisun","sub_path":"loopGet.py","file_name":"loopGet.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39390914066","text":"# # # Distribution Statement A. Approved for public release. Distribution unlimited.\n# # #\n# # # Author:\n# # # Naval Research Laboratory, Marine Meteorology Division\n# # #\n# # # This program is free software: you can redistribute it and/or modify it under\n# # # the terms of the NRLMMD License included with this program. This program is\n# # # distributed WITHOUT ANY WARRANTY; without even the implied warranty of\n# # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the included license\n# # # for more details. If you did not receive the license, for more information see:\n# # # https://github.com/U-S-NRL-Marine-Meteorology-Division/\n\n\"\"\"Standard geoips filename production.\"\"\"\n\n# Python Standard Libraries\nimport logging\n\nfrom os.path import join as pathjoin\n\nfrom geoips.filenames.base_paths import PATHS as gpaths\n\nLOG = logging.getLogger(__name__)\n\ninterface = \"filename_formatters\"\nfamily = \"standard\"\nname = \"geoips_fname\"\n\n\ndef call(\n area_def,\n xarray_obj,\n product_name,\n coverage=None,\n output_type=\"png\",\n output_type_dir=None,\n product_dir=None,\n product_subdir=None,\n source_dir=None,\n basedir=gpaths[\"ANNOTATED_IMAGERY_PATH\"],\n):\n \"\"\"Create GeoIPS standard filenames, sector-based subdirs.\n\n This uses the sector specification (continent, country, area, subarea,\n state, city), product name, source name, and platform name\n to generate a full unique path, as well as additional attributes to\n create a fully unique file name.\n \"\"\"\n # from geoips.xarray_utils.time import get_min_from_xarray_time\n # start_dt = get_min_from_xarray_time(xarray_obj, 'time')\n start_dt = xarray_obj.start_datetime\n\n resolution = max(area_def.pixel_size_x, area_def.pixel_size_y) / 1000.0\n\n kwargs = {}\n sector_info = (\n area_def.sector_info\n if \"region\" not in area_def.sector_info.keys()\n else area_def.sector_info[\"region\"]\n )\n if \"continent\" in sector_info:\n kwargs[\"continent\"] = sector_info[\"continent\"]\n if \"country\" in sector_info:\n kwargs[\"country\"] = sector_info[\"country\"]\n if \"area\" in sector_info:\n kwargs[\"area\"] = sector_info[\"area\"]\n if \"subarea\" in sector_info:\n kwargs[\"subarea\"] = sector_info[\"subarea\"]\n if \"state\" in sector_info:\n kwargs[\"state\"] = sector_info[\"state\"]\n if \"city\" in sector_info:\n kwargs[\"city\"] = sector_info[\"city\"]\n\n extra = \"{0:0.1f}\".format(resolution).replace(\".\", \"p\")\n web_fname = assemble_geoips_fname(\n basedir=basedir,\n product_name=product_name,\n source_name=xarray_obj.source_name,\n platform_name=xarray_obj.platform_name,\n sector_name=area_def.area_id,\n coverage=coverage,\n resolution=resolution,\n product_datetime=start_dt,\n output_type=output_type,\n data_provider=xarray_obj.data_provider,\n extra=extra,\n product_dir=product_dir,\n source_dir=source_dir,\n **kwargs,\n )\n return web_fname\n\n\ndef assemble_geoips_fname(\n basedir,\n product_name,\n source_name,\n platform_name,\n sector_name,\n coverage,\n resolution,\n product_datetime,\n output_type=\"png\",\n data_provider=None,\n extra=None,\n product_dir=None,\n source_dir=None,\n continent=None,\n country=None,\n area=None,\n subarea=None,\n state=None,\n city=None,\n):\n \"\"\"Produce full output product path from product / sensor specifications.\n\n standard web paths are of the format:\n /--/--/\n /``\n standard filenames are of the format:\n .....\n ...\n\n Parameters\n ----------\n basedir : str\n Full path to base directory of final product.\n product_name : str\n Name of product\n source_name : str\n Name of data source (sensor)\n platform_name : str\n Name of platform (satellite)\n coverage : float\n Image coverage, float between 0.0 and 100.0\n resolution : float\n Image resolution, float greater than 0.0\n product_datetime : datetime.datetime\n Datetime object - start time of data used to generate product.\n\n Other Parameters\n ----------------\n output_type : str, optional\n file extension type, default is png\n data_provider : str, optional\n String to include in filename \"data_provider\" field\n extra : str, optional\n String to include in filename \"extra\" field, default is None\n If None, use fillval of 'x'\n continent : str, optional\n String to include in filename \"continent\" field, default is None\n If None, use fillval of 'x'\n country : str, optional\n String to include in filename \"country\" field, default is None\n If None, use fillval of 'x'\n area : str, optional\n String to include in filename \"area\" field, default is None\n If None, use fillval of 'x'\n subarea : str, optional\n String to include in filename \"subarea\" field, default is None\n If None, use fillval of 'x'\n state : str, optional\n String to include in filename \"state\" field, default is None\n If None, use fillval of 'x'\n city : str, optional\n String to include in filename \"city\" field, default is None\n If None, use fillval of 'x'\n \"\"\"\n fillval = \"x\"\n if continent is None:\n continent = fillval\n if country is None:\n country = fillval\n if area is None:\n area = fillval\n if subarea is None:\n subarea = fillval\n if state is None:\n state = fillval\n if city is None:\n city = fillval\n if data_provider is None:\n data_provider = fillval\n if extra is None:\n extra = fillval\n if product_dir is None:\n product_dir = product_name\n if source_dir is None:\n source_dir = source_name\n LOG.info(basedir)\n path = pathjoin(\n basedir,\n \"{0}-{1}-{2}\".format(continent, country, area),\n \"{0}-{1}-{2}\".format(subarea, state, city),\n product_dir,\n source_dir,\n )\n # source_dir,\n # '{0:0.1f}'.format(resolution).replace('.', 'p'))\n # fname = '...\n # ..\n # ...'\n fname = \".\".join(\n [\n product_datetime.strftime(\"%Y%m%d\"),\n product_datetime.strftime(\"%H%M%S\"),\n platform_name,\n source_name,\n product_name,\n sector_name,\n \"{0:0.2f}\".format(coverage).replace(\".\", \"p\"),\n data_provider,\n str(extra),\n ]\n )\n fname = \"{0}.{1}\".format(fname, output_type)\n return pathjoin(path, fname)\n\n\ndef geoips_fname_remove_duplicates(fname, mins_to_remove=10, remove_files=False):\n \"\"\"remove_duplicates function currently not defined.\n\n If defined, this function will identify duplicate files, and remove\n appropriately. It should identify duplicates specifically based\n on the format/location of the geoips_fname formatted files.\n\n Currently returns empty lists. When defined, will return a list of\n deleted files and a list of saved files.\n \"\"\"\n LOG.info(\"MUST ADD LOGIC TO REMOVE STANDARD GEOIPS FILENAME DUPLICATES\")\n return [], []\n","repo_name":"NRLMMD-GEOIPS/geoips","sub_path":"geoips/plugins/modules/filename_formatters/geoips_fname.py","file_name":"geoips_fname.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"43391484762","text":"#更改button文字內容\nfrom tkinter import *\nfrom PIL import Image, ImageTk\nroot= Tk()\nroot.title('Class7')\nroot.geometry('200x200')\n\n#方1\n# counter=0\n# def clicked():\n# global counter\n# counter +=1\n# mybutton['text']='click'+str(counter)\n\n# mybutton=Button(root,text='Click', command=clicked)\n# mybutton.pack()\n#方法2\n# mystringvar=StringVar()\n# mystringvar.set('Click')\n\n# counter=0\n# def clicked():\n# global counter\n# counter += 1\n# mystringvar.set('click'+str(counter))\n\n# mybutton=Button(root, textvariable=mystringvar, command=clicked)\n# mybutton.pack()\n\n\n#way1\n# mybutton=Button(root,text='Hello World')\n# mybutton.pack()\n# Label(root, text=mybutton['text']).pack()\n\n#way2\n# mystringvar=StringVar()\n# mystringvar.set('Hello World')\n# mybutton=Button(root, textvariable=mystringvar)\n# mybutton.pack()\n# Label(root,text=mystringvar.get()).pack()\n\n#開啟圖片\n# img=Image.open('/Users/scofield/Documents/Python_2022Autumn/class8/corgi1.jpg')\n#更改圖片大小\n# resized_image=img.resize((100,100))\n#轉換為TK圖片物件\n# tk_img=ImageTk.PhotoImage(resized_image)\n\n#在lable中放入圖片\n# label=Label(root, image=tk_img)\n# label.pack()\n# mybutton=Button(root, image=tk_img)\n# mybutton.pack()\n#已入tkinter 的 messagebox\nfrom tkinter import messagebox\n#出現message test的普通訊息匡\n# messagebox.showinfo('showinfo', 'message test')\n\n#出現message test的普通訊息匡\n# messagebox.askquestion('askquestion', 'is it sunday')\n\n# def popup():\n# # result=messagebox.askyesno('askyesno', 'Do you want to contine?')\n# result=messagebox.askquestion('askyesno', 'Do you want to contine?')\n# print(result)\n# popupbutton=Button(root,text='Click to pop Up!', command=popup)\n# popupbutton.pack()\n# #放no.1單選按鈕\n# radiobtn1=Radiobutton(root, text='Black')\n# radiobtn1.pack()\n# #放no.2單選按鈕\n# radiobtn2=Radiobutton(root, text='Red')\n# radiobtn2.pack()\n#宣告文字變數\nval=StringVar()\n宣告文字變數\nradiobtn1=Radiobutton(root, text='Black',variable=val,value='Black')\nradiobtn1.pack()\nradiobtn1.select()\nradiobtn2=Radiobutton(root, text='Red',variable=val,value='Red')\nradiobtn2.pack()\n\n\n\nroot.mainloop()","repo_name":"scofield0605/Python_2022Autumn","sub_path":"class8/20221127.py","file_name":"20221127.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73439415206","text":"from scrapy.item import Field\nfrom scrapy.item import Item\nfrom scrapy.spiders import Spider\nfrom scrapy.selector import Selector\nfrom scrapy.loader.processors import MapCompose\nfrom scrapy.loader import ItemLoader\n#from bs4 import BeautifulSoup\nfrom scrapy.crawler import CrawlerProcess\n\n# xpath nombres_productos = $x('//*[@id=\"grid\"]/div[2]/div/div//a/span/@data-original-title').map(x=>x.value)\n# xpath precios = $x('//div/div[@class=\"span2 product-item-mosaic\"]/div[@class=\"cash-price\"]/text()').map(x=>x.wholeText)\n# xpath stock = $x('//*[@id=\"grid\"]/div[2]/div/div/div[6]/text()').map(x=>x.wholeText)\n# xpath next_page = $x('//div[@class=\"pagination\"]/ul/li/a[@class=\"next\"]/@href').map(x=>x.value)\n# xpath link = $x('//div[@class=\"span2 product-item-mosaic\"]/div[@class=\"image\"]/a/@href').map(x=>x.value)\n\ncustom_settings = {\n 'FEED_URI': 'spfinal.json',\n 'CURRENT_REQUESTS': 24,\n 'MEMUSAGE_LIMIT_MB': 2048,\n 'FEED_FORMAT': 'json',\n 'MEMUSAGE_NOTIFY_MAIL': ['cgutierrez.infor@gmail.com'],\n 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/74.0.3729.169 Safari/537.36',\n 'FEED_EXPORT_ENCODING': 'utf-8'\n }\n \nclass videoSpider(Spider):\n name = 'spdigital'\n start_urls = [\n 'https://www.spdigital.cl/categories/view/379/page:1'\n ]\n\n def parse_nextpages(self, response, **kwargs):\n if kwargs:\n nombre_sp = kwargs['nombre_sp']\n precios_sp = kwargs['precios_sp']\n stock_sp = kwargs['stock_sp']\n links_sp = kwargs['links_sp']\n\n nombre_sp.extend(response.xpath('//*[@id=\"grid\"]/div[2]/div/div//a/span/@data-original-title').getall())\n precios_sp.extend(response.xpath('//div/div[@class=\"span2 product-item-mosaic\"]/div[@class=\"cash-price\"]/text()').getall())\n stock_sp.extend(response.xpath('//*[@id=\"grid\"]/div[2]/div/div/div[6]/text()').getall())\n links_sp.extend(response.xpath('//div[@class=\"span2 product-item-mosaic\"]/div[@class=\"image\"]/a/@href').getall())\n\n next_page_button_link = response.xpath('//div[@class=\"pagination\"]/ul/li/a[@class=\"next\"]/@href').get()\n if next_page_button_link:\n yield response.follow(next_page_button_link, callback=self.parse_nextpages, cb_kwargs={'nombre_sp': nombre_sp, 'precios_sp': precios_sp, 'stock_sp': stock_sp, 'links_sp': links_sp})\n else:\n yield{\n 'nombre_sp': nombre_sp,\n 'precios_sp': precios_sp,\n 'stock_sp' : stock_sp,\n 'links_sp' : links_sp\n }\n\n def parse(self, response):\n\n nombre_sp = response.xpath('//*[@id=\"grid\"]/div[2]/div/div//a/span/@data-original-title').getall()\n precios_sp = response.xpath('//div/div[@class=\"span2 product-item-mosaic\"]/div[@class=\"cash-price\"]/text()').getall()\n stock_sp = response.xpath('//*[@id=\"grid\"]/div[2]/div/div/div[6]/text()').getall()\n links_sp = response.xpath('//div[@class=\"span2 product-item-mosaic\"]/div[@class=\"image\"]/a/@href').getall()\n\n\n\n next_page_button_link = response.xpath('//div[@class=\"pagination\"]/ul/li/a[@class=\"next\"]/@href').get()\n if next_page_button_link:\n yield response.follow(next_page_button_link, callback=self.parse_nextpages, cb_kwargs={'nombre_sp': nombre_sp, 'precios_sp': precios_sp, 'stock_sp': stock_sp, 'links_sp': links_sp})\n\n\nprocess = CrawlerProcess({\n \"FEEDS\": {\"/home/ubuntu/gitprojects/webscraper_chile_video_cards/video_cards/video_cards/resultados/sp_pre.json\": {\"format\": \"json\", \"overwrite\": True}},\n 'ROBOTSTXT_OBEY':'False',\n 'USER_AGENT': 'Mozilla/5.0',\n\n\n\n #'AUTOTHROTTLE_ENABLED':'True',\n #'AUTOTHROTTLE_START_DELAY': '1'\n })\n\n #guardado de archivos\n \n\nprocess.crawl(videoSpider)\nprocess.start()","repo_name":"cristian-data-science/webscraper_chile_video_cards","sub_path":"video_cards/video_cards/spiders/older_version/autospdigital.py","file_name":"autospdigital.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70015355686","text":"\"\"\" main entry point for collatz encryption \"\"\"\nimport argparse\nimport time\nimport bytes_int\nimport bytes_file\nimport collatz\n\n\ndef init_parser():\n \"\"\" initializes parser \"\"\"\n parser_result = argparse.ArgumentParser(\n prog=\"collatz_encrypt.py\",\n description=\"Encryption using the collatz conjecture\"\n )\n\n parser_result.add_argument('--key', dest='key', action='store')\n\n parser_result.add_argument(\n 'mode', choices=['encrypt', 'decrypt', 'encode', 'decode'])\n parser_result.add_argument('source_file', type=argparse.FileType('rb'))\n parser_result.add_argument('dest_file', type=argparse.FileType('wb'))\n\n return parser_result\n\n\ndef get_args(parser_result):\n \"\"\" gets arguments passed to program \"\"\"\n args_result = vars(parser_result.parse_args())\n\n return args_result\n\n\nif __name__ == \"__main__\":\n\n parser = init_parser()\n args = get_args(parser)\n\n start = time.process_time_ns()\n\n with args['source_file'] as source_file, args['dest_file'] as dest_file:\n IS_VERBOSE = True\n mode = args['mode']\n\n print('[Info] Starting to ' + mode + ' ' + source_file.name + '...')\n\n source_file = args['source_file']\n dest_file = args['dest_file']\n\n if mode == \"encode\":\n FILE_RESULT = bytes_file.read_file(\n source_file, collatz.encode, is_verbose=IS_VERBOSE)\n bytes_file.write_file(dest_file, FILE_RESULT,\n is_verbose=IS_VERBOSE)\n\n elif mode == \"decode\":\n FILE_RESULT = bytes_file.read_file(\n source_file, collatz.decode, is_verbose=IS_VERBOSE)\n bytes_file.write_file(dest_file, FILE_RESULT,\n is_verbose=IS_VERBOSE)\n\n elif mode == \"encrypt\":\n if not args['key']:\n print(\"Error: Missing key. Please use --key to specify a key.\")\n exit()\n key = bytes_int.to_int(bytearray(args['key'], 'utf-8'))\n FILE_RESULT = bytes_file.read_file(source_file,\n collatz.encrypt(\n key, is_verbose=IS_VERBOSE),\n is_verbose=IS_VERBOSE)\n bytes_file.write_file(dest_file, FILE_RESULT,\n is_verbose=IS_VERBOSE)\n\n elif mode == \"decrypt\":\n if not args['key']:\n print(\"Error: Missing key. Please use --key to specify a key.\")\n exit()\n key = bytes_int.to_int(bytearray(args['key'], 'utf-8'))\n FILE_RESULT = bytes_file.read_file(\n source_file, is_verbose=IS_VERBOSE)\n bytes_file.write_file(dest_file, FILE_RESULT,\n encoder=collatz.decrypt(\n key, is_verbose=IS_VERBOSE),\n is_verbose=IS_VERBOSE)\n\n source_file.close()\n dest_file.close()\n\n print(\"Completed in \", (time.process_time_ns() - start) / 1e6, \" ms\")\n","repo_name":"gliu20/collatz-encoder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30833096020","text":"import aiohttp\nimport asyncio\nimport time\n\nfrom multiprocessing import Process\nfrom aiohttp import ServerDisconnectedError, ClientResponseError, ClientConnectorError\nfrom DB.DBClient import *\nfrom Util.error import ResourceDepletionError\nfrom ProxyGetter.getFreeProxy import *\nfrom Config.ConfigGetter import config\n\nclass ValidityTester(object):\n\n test_api = config.get_test_api\n\n def __init__(self):\n # 代理list\n self._raw_proxies = None\n # 可用代理list\n self._usable_proxies = []\n self._conn = DBClient()\n\n def set_raw_proxies(self, proxies):\n \"\"\"\n 设置代表list\n :param proxies:\n :return:\n \"\"\"\n self._raw_proxies = proxies\n\n async def test_single_proxy(self, proxy):\n \"\"\"\n 异步检测单个代理,若有效,放入_usable_proxies\n :param proxy:\n :return:\n \"\"\"\n try:\n async with aiohttp.ClientSession() as session:\n try:\n if isinstance(proxy, bytes):\n # 对取出的代理进行转码\n proxy = proxy.decode('utf-8')\n\n # 拼接代理地址\n real_proxy = 'http://' + proxy\n print(u'测试ip: ', proxy)\n async with session.get(config.get_test_api, proxy=real_proxy,\n timeout=config.get_proxy_timeout) as response:\n if response.status == 200:\n # 测试通过,入库\n self._conn.put(proxy)\n print(u'有效IP: ', proxy)\n except (ProcessLookupError, TimeoutError, ValueError) as e:\n print(u'无效IP:', proxy)\n print(str(e))\n except (ServerDisconnectedError, ClientResponseError, ClientConnectorError) as e:\n print(str(e))\n\n def test(self):\n \"\"\"\n aio 测试所有代理\n :return:\n \"\"\"\n print(u'ValidityTester is working...')\n try:\n loop = asyncio.get_event_loop()\n tasks = [self.test_single_proxy(proxy) for proxy in self._raw_proxies]\n loop.run_until_complete(asyncio.wait(tasks))\n except ValueError as e:\n print(u'Async Error')\n print(str(e))\n\n\nclass PoolAdder(object):\n \"\"\"\n 添加代理到代理池\n \"\"\"\n\n def __init__(self, threshould):\n self._threshold = threshould\n self._conn = DBClient()\n self._tester = ValidityTester()\n self._crawler = GetFreeProxy()\n\n def is_over_threshold(self):\n \"\"\"\n 判断当前代理个数是否达到上限\n :return:\n \"\"\"\n if self._conn.queue_len >= self._threshold:\n return True\n else:\n return False\n\n def add_to_queue(self):\n print(u'PoolAdder is working...')\n proxy_count = 0\n\n while not self.is_over_threshold():\n # 取出属性列表中的所有方法\n for callback_label in range(self._crawler.__CrawlFuncCount__):\n callback = self._crawler.__CrawlFunc__[callback_label]\n raw_proxies = self._crawler.get_raw_proxies(callback)\n # 测试爬虫代理\n self._tester.set_raw_proxies(raw_proxies)\n self._tester.test()\n proxy_count += len(raw_proxies)\n if self.is_over_threshold():\n print('IP数量达到上限')\n break\n if proxy_count == 0:\n raise ResourceDepletionError\n\n\nclass Schedule(object):\n\n @staticmethod\n def valid_proxy(cycle=config.get_valid_check_cycle):\n \"\"\"\n 取出库中一半代理进行验证\n :param cycle:\n :return:\n \"\"\"\n conn = DBClient()\n tester = ValidityTester()\n\n with True:\n print(u'Refreshing ip')\n count = int(0.5 * conn.queue_len)\n\n while count == 0:\n print('代理池无IP')\n time.sleep(cycle)\n continue\n\n raw_proxies = conn.get(count)\n tester.set_raw_proxies(raw_proxies)\n tester.test()\n time.sleep(cycle)\n\n @staticmethod\n def check_pool(lower_threshold=config.get_pool_lower_threshold,\n upper_threshold=config.get_pool_upper_threshold,\n cycle=config.get_valid_check_cycle):\n \"\"\"\n 如果IP数量小于下限数量,则添加代理\n :param lower_threshold:\n :param upper_threshold:\n :param cycle:\n :return:\n \"\"\"\n\n conn = DBClient()\n adder = PoolAdder(upper_threshold)\n\n while True:\n if conn.queue_len < lower_threshold:\n adder.add_to_queue()\n time.sleep(cycle)\n\n def run(self):\n print(u'Ip processing running...')\n # 开启从数据库拿IP进行检查的线程\n valid_process = Process(target=Schedule.valid_proxy)\n # 开启抓取IP并存储的线程\n check_process = Process(target=Schedule.check_pool)\n\n # 启动进程\n valid_process.start()\n check_process.start()\n","repo_name":"skyz319/simpleness_proxy_pool","sub_path":"Schedule/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12821622666","text":"from lesson_15.mosut_sorin.hw_lesson15_mosut_sorin_base_file import Triangle, Square\nimport unittest\n\n\nclass TestPolygins(unittest.TestCase):\n\n def test_triangle_class_has_proper_atributes(self):\n # arange\n l_1, l_2, l_3 = 2, 3, 4\n # act\n test_triangle = Triangle(l_1, l_2, l_3)\n s1, s2, s3 = test_triangle.sides\n # assert\n assert s1 == l_1 and s2 == l_2 and s3 == l_3, 'incorect Triangle object atributes'\n\n # def test_triangle_class_imposible_triangle_values(self):\n # # arange\n # l_1, l_2, l_3 = 1, 3, 4\n # # act\n # test_triangle = Triangle(l_1, l_2, l_3)\n # s1, s2 ,s3 = test_triangle.sides\n # # assert\n # assert s1 == l_1 and s2 == l_2 and s3 == l_3, 'incorect Triangle object atributes'\n\n def test_triangle_object_area(self):\n # arange\n l_1, l_2, l_3 = 2, 3, 4\n # act\n test_triangle = Triangle(l_1, l_2, l_3)\n test_triangle_area = test_triangle.area()\n semi_per = (l_1 + l_2 + l_3) / 2\n refrence_area = (semi_per * (semi_per - l_1) * (semi_per - l_2) * (semi_per - l_3)) ** 0.5\n # assert\n assert test_triangle_area == refrence_area, 'incorect Triangle area result'\n\n def test_triangle_object_perimeter(self):\n # arange\n l_1, l_2, l_3 = 2, 3, 4\n # act\n test_triangle = Triangle(l_1, l_2, l_3)\n test_triangle_perimeter = test_triangle.perimeter()\n refrence_perimeter = l_1 + l_2 + l_3\n # assert\n assert test_triangle_perimeter == refrence_perimeter, 'incorect Triangle perimeter result'\n\n def test_square_class_has_proper_atributes(self):\n # arange\n l_1 = l_2 = l_3 = l_4 = 4\n # act\n test_square = Square(l_1, l_2, l_3, l_4)\n s1, s2, s3, s4 = test_square.sides\n # assert\n assert s1 == l_1 and s2 == l_2 and s3 == l_3 and s4 == l_4, 'incorect Square objects atributes'\n\n def test_square_object_area(self):\n # arange\n l_1 = l_2 = l_3 = l_4 = 4\n # act\n test_square = Square(l_1, l_2, l_3, l_4)\n test_square_area = test_square.area()\n refrence_area = l_1 ** 2\n # assert\n assert test_square_area == refrence_area, 'incorect Square area result'\n\n def test_square_object_from_area(self):\n # arange\n l_1 = l_2 = l_3 = l_4 = 5\n area = l_1 ** 2\n\n # act\n test_square_from_area = Square.from_area(area)\n test_square = Square(l_1, l_2, l_3, l_4)\n # assert\n assert test_square_from_area == test_square, 'incorect from_area result'\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"mariuspodean/CJ-PYTHON-01","sub_path":"lesson_15/mosut_sorin/hw_lesson15_mosut_sorin_test_file.py","file_name":"hw_lesson15_mosut_sorin_test_file.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"17345869024","text":"from picamera import PiCamera\nfrom time import sleep\n\ncamera = PiCamera()\n\ndef takePicture(i, x):\n\tfilename = str(x) + '/image' + str(i) + '.jpg'\n\tcamera.capture(filename)\n\tprint(\"Image Saved to \", filename) \n\ncamera.start_preview(alpha=200)\nsleep(2)\n\nfor i in range (10):\n\ttakePicture(i, \"/home/pi/Projects/Python/NanoNets/FireDetection/FireImages\")\n\tsleep(1)\n\ncamera.stop_preview()\n","repo_name":"fncr/Raspi-Fire-Detection","sub_path":"usecamera.py","file_name":"usecamera.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38830807738","text":"import argparse\nfrom os import path\n\n\ndef get_arguments():\n # create parser\n parser = argparse.ArgumentParser()\n\n # misc\n parser.add_argument('--it',\n type=int,\n default=0,\n help='iteration number (log files and figures')\n parser.add_argument('--seed', type=int, default=0, help='random seed')\n parser.add_argument(\n '--device',\n type=str,\n default='auto',\n help='device(s) (e.g., \"cpu\", \"cuda:0\", \"cuda:0,cuda:1\")')\n parser.add_argument('--log',\n type=str,\n default='INFO',\n help='logging level (DEBUG, INFO, WARNING, '\n 'ERROR, CRITICAL)')\n\n # data\n parser.add_argument('--data',\n type=str,\n default='data/requests',\n help='path of the trace folder')\n parser.add_argument('--save_corpus',\n action='store_true',\n help='save the corpus in the data folder')\n parser.add_argument('--load_corpus',\n action='store_true',\n help='load the corpus from the data folder')\n parser.add_argument('--requests',\n action='store_true',\n help='consider individual requests')\n parser.add_argument('--limit',\n type=int,\n default=None,\n help='maximum number of sequence to load')\n parser.add_argument('--max_length',\n type=int,\n default=None,\n help='maximum sequence lengths')\n parser.add_argument('--plot_hist',\n action='store_true',\n help='Plot the system calls and processes histograms')\n\n # model\n parser.add_argument('--load_model',\n type=int,\n default=None,\n help='model number to load')\n parser.add_argument('--model',\n type=str,\n default='transformer',\n choices=['ngram', 'lstm', 'transformer'],\n help='model to use')\n parser.add_argument('--order',\n type=int,\n default=2,\n help='N-gram order (value of N)')\n\n # model hyperparameters\n parser.add_argument('--emb_sys',\n type=int,\n default=32,\n help='embedding dimension of system '\n 'call names and entry/exit')\n parser.add_argument('--emb_proc',\n type=int,\n default=16,\n help='embedding dimension of process names')\n parser.add_argument('--emb_pid',\n type=int,\n default=4,\n help='embedding dimension of the process if')\n parser.add_argument('--emb_tid',\n type=int,\n default=4,\n help='embedding dimension of the thread id')\n parser.add_argument('--emb_time',\n type=int,\n default=8,\n help='embedding dimension of the timestamp')\n parser.add_argument('--emb_order',\n type=int,\n default=8,\n help='embedding dimension of the ordering')\n parser.add_argument('--heads',\n type=int,\n default=8,\n help='number of attention heads')\n parser.add_argument('--hiddens',\n type=int,\n default=128,\n help='number of hidden units of each encoder MLP')\n parser.add_argument('--layers',\n type=int,\n default=2,\n help='number of layers')\n parser.add_argument('--dropout',\n type=float,\n default=0.5,\n help='model dropout rate (embedding & encoder)')\n # training\n parser.add_argument('--batch', type=int, default=64, help='batch size')\n parser.add_argument('--valid',\n type=float,\n default=0.25,\n help='percentage of the test set used for valdiation')\n parser.add_argument('--p_mask',\n type=float,\n default=0.25,\n help='percentage of the input masked')\n parser.add_argument('--mlm_epochs',\n type=int,\n default=0,\n help='number of epochs using MLM (pre-training)')\n parser.add_argument('--lm_epochs',\n type=int,\n default=0,\n help='number of epochs using LM (fine-tuning)')\n parser.add_argument('--eval',\n type=int,\n default=1000,\n help='number of update before evaluating the model '\n '(impact early stopping)')\n parser.add_argument('--lr', type=float, default=1e-3, help='learning rate')\n parser.add_argument('--early_stopping',\n type=int,\n default=5,\n help='number of iteration before early stopping')\n parser.add_argument('--checkpoint',\n action='store_true',\n help='trade computation for memory')\n\n # ablation study\n parser.add_argument('--disable_entry',\n action='store_true',\n help='Do not use entry/exit for the embedding')\n parser.add_argument('--disable_ret',\n action='store_true',\n help='Do not use the return value for the embedding')\n parser.add_argument('--disable_time',\n action='store_true',\n help='Do not use the timestamp')\n parser.add_argument('--disable_proc',\n action='store_true',\n help='Do not use the process name for the embedding')\n parser.add_argument('--disable_pid',\n action='store_true',\n help='Do not use the process id for the embedding')\n parser.add_argument('--disable_tid',\n action='store_true',\n help='Do not use the thread id for the embedding')\n parser.add_argument('--disable_order',\n action='store_true',\n help='Do not use the event order')\n\n args = parser.parse_args()\n\n # check arguments\n assert path.exists(args.data), 'data folder not found'\n assert path.exists('{}/train'.format(\n args.data)), 'train data folder not found'\n assert path.exists('{}/test'.format(\n args.data)), 'test data folder not found'\n assert not (args.save_corpus\n and args.load_corpus), 'cannot save and load the Corpus'\n assert args.max_length is None or args.max_length > 0, \\\n 'max_length must be greater than 0'\n assert args.load_model is None or path.exists('models/{}'.format(\n args.load_model)), 'model not found'\n assert args.order > 1, 'order must be greater than 1'\n assert args.batch > 0, 'batch must be greater than 0'\n assert args.p_mask > 0, 'p_mask must be greater than 0'\n assert args.emb_sys > 0, 'emb_sys must be greater than 0'\n assert args.disable_time or args.emb_time > 0, \\\n 'emb_time must be greater than 0'\n assert args.disable_proc or args.emb_proc > 0, \\\n 'emb_sys must be greater than 0'\n assert args.disable_pid or args.emb_pid > 0, \\\n 'emb_pid must be greater than 0'\n assert args.disable_tid or args.emb_tid > 0, \\\n 'emb_tid must be greater than 0'\n assert args.heads > 0, 'heads must be greater than 0'\n assert args.hiddens > 0, \\\n 'hiddens must be greater than 0'\n assert args.layers > 0, 'layers must be greater than 0'\n assert args.dropout >= 0 and args.dropout < 1, \\\n 'dropout must be between in [0, 1)'\n if args.model.lower() == 'lstm':\n assert args.mlm_epochs == 0, 'MLM not compatible with LSTM'\n assert args.early_stopping > 0, 'early_stopping must be greater than 0'\n\n return args\n","repo_name":"qfournier/syscall_args","sub_path":"source/arguments.py","file_name":"arguments.py","file_ext":"py","file_size_in_byte":8584,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"23037268978","text":"from airflow.models import DAG\nfrom datetime import datetime\nfrom airflow.operators.python import PythonOperator\n# from function.connection import m6\n# from function.m6_hashing import m6_hashing\nfrom function.connection import m6\nfrom function.m6_hashing import m6_hashing\nimport pandas as pd\n\n\n\n# no_need = ['service_apply_settings', 'custom_delegations', 'flat_packages','customer_trackings', 'locations', 'box_sizes',\n# 'bag_templates', 'agency_configs', 'shipping_domestic_address', 'service_mappings', 'agency_settings', 'partner_settings',\n# 'shipping_fee_details', 'property_mappings', 'shipping_domestic_partners', 'partner_shipping_domestic_carriers',\n# 'global_settings', 'shipping_domestic_locations', 'delivery_note_returns', 'warehouse_shipping_partners', 'package_process_shipping_fees',\n# 'jobs', 'failed_jobs', 'product_groups', 'bag_template_agencies', 'settings', 'storage_fees',\n# 'inventory_tracking_bills', 'user_identity', 'notice_stage_services', 'bag_areas', 'feature_apply_settings', 'last_mile_orders',\n# 'process_shipping_fees', 'notice_stages', 'bag_wildcard_locations', 'migrations', 'shipping_domestic_carriers', 'fake_name_customers',\n# 'shipping_return_partners', 'notice_stage_properties','lockings']\nneed = ['bags']\nsql = \"\"\"select table_schema, table_name from information_schema.tables \nwhere table_schema = 'm6' and table_type = 'base table';\"\"\"\nm6_db = pd.read_sql(sql, con=m6())\nm6_db = m6_db[m6_db.table_name.isin(need)]\n \n\ndefault_args = {\n 'start_date': datetime(2022,4,1)\n}\n\n\nwith DAG('elt_m6', schedule_interval = '0 0 * * 1-6', default_args = default_args, catchup=False) as dag:\n\n elt_m6 = PythonOperator(\n task_id = 'elt_m6',\n python_callable = m6_hashing,\n op_kwargs = {'m6_db':m6_db}\n )","repo_name":"GobizBi/test_airflow","sub_path":"dags/etl_dags/elt_m6.py","file_name":"elt_m6.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39000834482","text":"import glob\nimport argparse\nimport cv2\nimport os\nfrom shutil import copyfile\n\nparser = argparse.ArgumentParser(description='Convert Yolo relative to Abs cordinates')\nparser.add_argument('-i', '--test_dir_path', type=str, required= True, help='Path for test images')\nparser.add_argument('-o', '--res_dir_path', type=str, help='Path for result dir')\nparser.add_argument('-d', '--draw', action='store_true', help= \"Use this bool flag if you want to draw on the boxes pn the image\")\n\nargs = parser.parse_args()\n\nres_dir = args.res_dir_path\nif not os.path.exists(res_dir):\n os.mkdir(res_dir)\n\nfor img_path in glob.glob(args.test_dir_path + \"/**/*.jpg\", recursive = True):\n print()\n print()\n\n img = cv2.imread(img_path)\n h, w, c = img.shape\n print(\"img res: \", (h,w,c))\n\n label_path = img_path.replace(\".jpg\", \".txt\")\n print(\"Working on: \", label_path)\n\n res = res_dir + \"/\" + label_path.split(\"/\")[-1]\n abs_label_file = open(res, \"a+\")\n\n draw_img_name = img_path.split(\"/\")[-1]\n copyfile(img_path, res_dir + \"/\" + draw_img_name)\n\n with open(label_path, 'r') as label_file:\n for line in label_file.readlines():\n rel_cords = line.split(\" \")\n print(\"Rel cords: \", rel_cords)\n\n # convert the rel_cords to abs cords\n cen_x = float(rel_cords[1]) * float(w)\n cen_y = float(rel_cords[2]) * float(h)\n\n w_abs = float(rel_cords[3]) * float(w)\n h_abs = float(rel_cords[4]) * float(h)\n\n x_abs = int(cen_x) - int(w_abs/2)\n y_abs = int(cen_y) - int(h_abs/2)\n\n abs_cords = \"human\" +\" \" + str(x_abs) + \" \" + str(y_abs) + \" \" + str(int(w_abs)) + \" \" + str(int(h_abs)) + \"\\n\"\n print(\"Abs cords: \",abs_cords)\n\n abs_label_file.write(abs_cords)\n\n if args.draw:\n cv2.rectangle(img, (x_abs, y_abs), (x_abs + int(w_abs), y_abs + int(h_abs)), (0, 255, 0), 3)\n draw_img_name = img_path.split(\"/\")[-1]\n print(\"drawing on: \", res_dir + \"/\" + draw_img_name)\n cv2.imwrite(res_dir + \"/\" + draw_img_name, img)\n\n\nprint(\"Completed all files\")\n\n\n\n\n\n","repo_name":"jyadavso/Object-Detection-Metrics-withPRC","sub_path":"convert_to_abs.py","file_name":"convert_to_abs.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12818612647","text":"import sys\nimport queue\nimport requests\n\ndef getMovieTitles(substr):\n # 기본 url 설정\n base_url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title='\n base_url += substr + '&page='\n\n # 응답 받고 json으로 만들기\n response = requests.get(base_url+str(1))\n page_json = response.json()\n page_num = page_json['total_pages']\n\n # result\n result = []\n\n for i in range(1, page_num + 1):\n response = requests.get(base_url + str(i))\n response_json = response.json()\n for j in range(0, len(response_json['data'])):\n result.append(response_json['data'][j]['Title'])\n\n result.sort()\n return result\n\nprint(getMovieTitles('spiderman'))\n\n\n\n\n\n","repo_name":"galid1/Algorithm","sub_path":"python/exams/19.04.08/exam4.py","file_name":"exam4.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"17896124662","text":"\nimport csv\nfrom operator import itemgetter\n\nINDUSTRIES = ['Agriculture', 'Business services', 'Construction', 'Leisure/hospitality', 'Manufacturing']\n\ndef read_file(fp):\n reader = csv.reader(fp)\n next(reader, None)\n next(reader, None)\n next(reader, None)\n next(reader, None)\n li_of_state_data = []\n for line in reader:\n if line[0] != '':\n li_of_state_data.append(line)\n return li_of_state_data\n\ndef get_totals(L):\n US_total = 0\n states_total = 0\n for index, line in enumerate(L):\n index_one = \"\"\n if index != 0:\n index_one = line[1]\n if \"<\" in index_one:\n index_one = index_one[1:]\n states_total += int(\"\".join(index_one.split(\",\")))\n else:\n US_total = int(\"\".join(line[1].split(\",\")))\n return US_total, states_total\n\ndef get_industry_counts(L):\n \"\"\"Docstring\"\"\"\n arg, bus, con, lh, man = 0, 0, 0, 0, 0\n for i in L[1:]:\n if i[9] not in INDUSTRIES:\n continue\n else:\n if i[9] == 'Agriculture':\n arg += 1\n elif i[9] == 'Business services':\n bus += 1\n elif i[9] == 'Construction':\n con += 1\n elif i[9] == 'Leisure/hospitality':\n lh += 1\n else:\n man += 1\n lst = [['Agriculture', arg], ['Business services', bus], ['Construction',\n con],\n ['Leisure/hospitality', lh], ['Manufacturing', man]]\n return sorted(lst, key=itemgetter(1), reverse=True)\n\ndef get_largest_states (L):\n li_of_largest_states = []\n US_percent = float(L[0][2][:3])\n for line in L:\n if float(line [2][:3]) > US_percent:\n li_of_largest_states.append(line[0])\n return li_of_largest_states\n\ndef main(): \n fp = open(\"immigration.csv\")\n L = read_file(fp)\n \n us_pop,total_pop = get_totals(L)\n if us_pop and total_pop: # if their values are not None\n print(\"\\nData on Illegal Immigration\\n\")\n print(\"Summative:\", us_pop)\n print(\"Total :\", total_pop)\n \n states = get_largest_states(L)\n if states: # if their value is not None\n print(\"\\nStates with large immigrant populations\")\n for state in states:\n state = state.replace('\\n',' ')\n print(state) \n \n counters = get_industry_counts(L)\n if counters: # if their value is not None\n print(\"\\nIndustries with largest immigrant populations by state\")\n print(\"{:24s} {:10s}\".format(\"industry\",\"count\"))\n for tup in counters:\n print(\"{:24s} {:2d}\".format(tup[0],tup[1]))\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"ShahViraj11/CSE-231-Projects","sub_path":"Labs/Lab 07/lab07.py","file_name":"lab07.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35354090244","text":"print(\"hello\")\n\nl = len([1, 2, 3])\n\nprint(l)\n\n# for loop - braces are not needed\nfor i in range(5):\n x = i * 10\n print(x)\n\n# never mix tab and spaces\n\nprint(\"1\")\n\nimport math\n\nprint(math.sin(0)) # we can use dot ...\n\nn = 5\nk = 3\nresult = math.factorial(n) / (math.factorial(k))\n\nprint(\"result:\" + str(result)) # str - to string\n\nprint(0x10) # to hex\n\nprint(float(1)) # 1.0\n\n# None, True, False\nbool(0) # False\nbool(42) # True\nbool(0.2) # True\nbool([]) # False\nbool([1, 2, 3]) # True\nbool(\"\") # False\nbool(\"False\") # True\n\n# flow\n\nif 1 < 2:\n print(\"it is indeed\")\n\nif False:\n print(\"never\")\nelse: # elif\n print(\"Always\")\n\ntimes = 0\nwhile times < 3:\n times += 1\n print(times)\n\ncount = 0\nwhile True:\n count += 1\n if count == 3:\n break\n\nprint(\"count:\" + str(count))\n\n\n\n\n","repo_name":"Sergey80/python-samples","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27136616290","text":"#!/usr/bin/env python3\n\nimport glob\n\n\"\"\"Recursively executes an action expanding using a glob.\"\"\"\n\ndef main():\n for filename in glob.glob(\"*/*/*.EDT\"):\n print(\"Executing a script or command with file %s\" % filename)\n\nif __name__ == '__main__':\n main()\n","repo_name":"kinow/python-sandbox","sub_path":"folders/recursive_files_ant_pattern.py","file_name":"recursive_files_ant_pattern.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12258070275","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys # sys нужен для передачи argv в QApplication\nimport openpyxl\nimport datetime\nimport img\nimport os\n\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\n\nimport doorclass #doorclass\nimport door2 # desinger\nimport scene#this is scene\n\nupGlass = doorclass.UpGlass('upGlass')\nrightGlass = doorclass.UpGlass('upGlass')\nleftGlass = doorclass.UpGlass('upGlass')\nnewDoor = doorclass.Door('New Door') #my door 1\nnewDoor.pushbase = 'DoorHandle'\n#door places\nbotfitting = doorclass.BottomFitting('None')\nbotfitting2 = doorclass.BottomFitting('None')\ndoorglass = doorclass.Glass('None')\ntopfitting = doorclass.TopFitting('None')\ntopfitting2 = doorclass.TopFitting('None')\nsupportbf = doorclass.SupportBF('None')\nsupportbf2 = doorclass.SupportBF('None')\nsupporttf = doorclass.SupportTopFitting('None')\nsupporttf2 = doorclass.SupportTopFitting('None')\nhinge = doorclass.Hinge('None'); hinge2 = doorclass.Hinge('None')\nDoorHandle = doorclass.DoorHandle('None')\nDoorHandle2 = doorclass.DoorHandle('None')\nPushHandle = doorclass.PushHandle('None')\nPushHandle2 = doorclass.PushHandle('None')\nknob = doorclass.knob('None')\nknob2 = doorclass.knob('None')\nDoorLock = doorclass.DoorLock('None')\nDoorLock2 = doorclass.DoorLock('None')\nMateDoorLock = doorclass.MateDoorLock('None')\nMateDoorLock2 = doorclass.MateDoorLock('None')\nCompactor_down = doorclass.Compactor('None')\nCompactor_down2 = doorclass.Compactor('None')\nCompactor_side = doorclass.Compactor('None')\nCompactor_side2 = doorclass.Compactor('None')\nCompactor_up = doorclass.Compactor('None')\nCompactor_up2 = doorclass.Compactor('None')\nCompactor_hinge = doorclass.Compactor('None')\nCompactor_hinge2 = doorclass.Compactor('None')\nupProfile = doorclass.GlazingProfile('none')\nleftProfile = doorclass.GlazingProfile('none')\nrightProfile = doorclass.GlazingProfile('none')\ndownProfile = doorclass.GlazingProfile('none')\nupCap = doorclass.GlazingCap('none')\nleftCap = doorclass.GlazingCap('none')\nrightCap = doorclass.GlazingCap('none')\ndownCap = doorclass.GlazingCap('none')\n\n\ndiscount = 1.5\ndoor_installation_price=0\ninst_door_closer = 0\n\n\n\ndef connectbs(basename):#database for listwiew\n import sqlite3\n conn = sqlite3.connect(\"mydatabase.db\")\n c = conn.cursor()\n c.execute('select * from %s order by code' %(basename))\n codelist = [x[0] for x in c]\n c.close()\n return codelist\n\n\ndef connectbs2(text, basename, xxx):#database for listwiew doorhandle\n import sqlite3\n conn = sqlite3.connect(\"mydatabase.db\")\n c = conn.cursor()\n\n g = (text,); c.execute('select * from %s where code=?'%(basename), g)\n z2 = [x1 for x1 in c.fetchone()]\n if len(z2) == 5:\n xcx = xxx(z2[0],z2[1],z2[2],z2[3],z2[4])#xxx это сам класс\n else:\n xcx = xxx(z2[0],z2[1],z2[2],float(z2[3]))\n c.close()\n return xcx\n\n\n\nclass ExampleApp(QMainWindow, door2.Ui_GlassCalc, scene.myyScene):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.pushButton.clicked.connect(self.upt)\n self.pushButton_2.clicked.connect(self.screenshot)\n#chekbox\n self.checkBox.stateChanged.connect(self.state_changed)\n self.checkBox_2.stateChanged.connect(self.state_changed_2)\n self.checkBox_3.stateChanged.connect(self.state_changed_3)#upGlass\n self.checkBox_4.stateChanged.connect(self.state_changed_4)#rightGlass\n self.checkBox_5.stateChanged.connect(self.state_changed_5)#leftGlass\n#отключение глухих полей\n self.label_39.hide()\n self.label_36.hide()\n self.lineEdit_5.hide()\n self.lineEdit_6.hide()\n self.label_40.hide()\n self.label_37.hide()\n self.lineEdit_7.hide()\n self.lineEdit_8.hide()\n self.label_38.hide()\n self.label_41.hide()\n self.lineEdit_9.hide()\n self.lineEdit_10.hide()\n#radiobuttn\n self.button_group_2 = QButtonGroup()\n self.button_group_2.addButton(self.radioButton_3)\n self.button_group_2.addButton(self.radioButton_4)\n self.button_group_2.buttonClicked.connect(self.on_radio)\n self.button_group = QButtonGroup()\n self.button_group.addButton(self.radioButton)\n self.button_group.addButton(self.radioButton_2)\n self.button_group.buttonClicked.connect(self.on_radio2)\n self.button_group_3 = QButtonGroup()\n self.button_group_3.addButton(self.radioButton_5)\n self.button_group_3.addButton(self.radioButton_6)\n self.button_group_3.addButton(self.radioButton_12)\n self.button_group_3.buttonClicked.connect(self.on_radio3)\n self.button_group_4 = QButtonGroup()\n self.button_group_4.addButton(self.radioButton_7)\n self.button_group_4.addButton(self.radioButton_8)\n self.button_group_4.buttonClicked.connect(self.on_radio4)\n self.button_group_5 = QButtonGroup()\n self.button_group_5.addButton(self.radioButton_9)\n self.button_group_5.addButton(self.radioButton_10)\n self.button_group_5.addButton(self.radioButton_11)\n self.button_group_5.buttonClicked.connect(self.on_radio5)\n#comboBox\n self.comboBox_4.addItems(['без']+connectbs('glass'))\n self.comboBox_4.activated[str].connect(self.onActivated)\n self.comboBox_6.addItems(['без']+connectbs('BottomFitting'))\n self.comboBox_6.activated[str].connect(self.onActivated6)\n self.comboBox_7.addItems(['без']+connectbs('supportbf'))\n self.comboBox_7.activated[str].connect(self.onActivated7)\n self.comboBox_8.addItems(['без']+connectbs('TopFitting'))\n self.comboBox_8.activated[str].connect(self.onActivated8)\n self.comboBox_9.addItems(['без']+connectbs('supporttf'))\n self.comboBox_9.activated[str].connect(self.onActivated9)\n self.comboBox_10.addItems(['без']+connectbs('Hinge'))\n self.comboBox_10.activated[str].connect(self.onActivated10)\n self.comboBox_13.addItems(['без']+connectbs('BottomFitting'))\n self.comboBox_13.activated[str].connect(self.onActivated6_2)\n self.comboBox_14.addItems(['без']+connectbs('DoorLock'))\n self.comboBox_14.activated[str].connect(self.onActivated14)\n self.comboBox_15.addItems(['без']+connectbs('MateDoorLock'))\n self.comboBox_15.activated[str].connect(self.onActivated15)\n self.comboBox_16.addItems(['без']+connectbs('Compactor'))\n self.comboBox_16.activated[str].connect(self.onActivated16)\n self.comboBox_17.addItems(['без']+connectbs('Compactor'))\n self.comboBox_17.activated[str].connect(self.onActivated17)\n self.comboBox_18.addItems(['без']+connectbs('Compactor'))\n self.comboBox_18.activated[str].connect(self.onActivated18)\n self.comboBox_19.addItems(['без']+connectbs('supportbf'))\n self.comboBox_19.activated[str].connect(self.onActivated7_2)\n self.comboBox_20.addItems(['без']+connectbs('TopFitting'))\n self.comboBox_20.activated[str].connect(self.onActivated8_2)\n self.comboBox_21.addItems(['без']+connectbs('supporttf'))\n self.comboBox_21.activated[str].connect(self.onActivated9_2)\n self.comboBox_22.addItems(['без']+connectbs('Hinge'))\n self.comboBox_22.activated[str].connect(self.onActivated10_2)\n self.comboBox_25.addItems(['без']+connectbs('DoorLock'))\n self.comboBox_25.activated[str].connect(self.onActivated14_2)\n self.comboBox_26.addItems(['без']+connectbs('MateDoorLock'))\n self.comboBox_26.activated[str].connect(self.onActivated15_2)\n self.comboBox_27.addItems(['без']+connectbs('Compactor'))\n self.comboBox_27.activated[str].connect(self.onActivated27)\n self.comboBox_28.addItems(['без']+connectbs('Compactor'))\n self.comboBox_28.activated[str].connect(self.onActivated28)\n self.comboBox_29.addItems(['без']+connectbs('Compactor'))\n self.comboBox_29.activated[str].connect(self.onActivated29)\n self.comboBox_30.addItems(['без']+connectbs('Compactor'))\n self.comboBox_30.activated[str].connect(self.onActivated30)\n self.comboBox_31.addItems(['без']+connectbs('Compactor'))\n self.comboBox_31.activated[str].connect(self.onActivated31)\n self.comboBox_32.addItems(['Клиент', 'Дилер', '0%'])\n self.comboBox_32.activated[str].connect(self.onActivated32)\n self.comboBox_33.addItems(['верх без']+connectbs('profile40'))\n self.comboBox_33.activated[str].connect(self.onActivated33)\n self.comboBox_34.addItems(['лев без']+connectbs('profile40'))\n self.comboBox_34.activated[str].connect(self.onActivated34)\n self.comboBox_35.addItems(['прав. без']+connectbs('profile40'))\n self.comboBox_35.activated[str].connect(self.onActivated35)\n self.comboBox_36.addItems(['низ без']+connectbs('profile40'))\n self.comboBox_36.activated[str].connect(self.onActivated36)\n self.comboBox_37.addItems(['верх без']+connectbs('cap40'))\n self.comboBox_37.activated[str].connect(self.onActivated37)\n self.comboBox_38.addItems(['лев без']+connectbs('cap40'))\n self.comboBox_38.activated[str].connect(self.onActivated38)\n self.comboBox_39.addItems(['прав. без']+connectbs('cap40'))\n self.comboBox_39.activated[str].connect(self.onActivated39)\n self.comboBox_40.addItems(['низ без']+connectbs('cap40'))\n self.comboBox_40.activated[str].connect(self.onActivated40)\n#scene\n self.der(*newDoor.for_scene(), *upGlass.for_scene(),\n *rightGlass.for_scene(), *leftGlass.for_scene(),\n *newDoor.for_scene2())\n self.lineEdit.setText('1000')\n self.lineEdit_2.setText('2000')\n self.lineEdit_3.setText('1000')\n self.lineEdit_4.setText('2000')\n self.update()\n\n#radioButton\n def on_radio(self, button):#кол-во створок\n newDoor.quantitydoor = int(button.text())\n if newDoor.quantitydoor == 2:\n self.radioButton.hide()\n self.radioButton_2.hide()\n self.comboBox_13.show()\n self.comboBox_19.show()\n self.comboBox_20.show()\n self.comboBox_21.show()\n self.comboBox_22.show()\n self.comboBox_23.show()\n self.comboBox_25.show()\n self.comboBox_26.show()\n self.comboBox_27.show()\n self.comboBox_28.show()\n self.comboBox_29.show()\n self.comboBox_31.show()\n else:\n self.comboBox_13.hide()\n self.comboBox_19.hide()\n self.comboBox_20.hide()\n self.comboBox_21.hide()\n self.comboBox_22.hide()\n self.comboBox_23.hide()\n self.comboBox_25.hide()\n self.comboBox_26.hide()\n self.comboBox_27.hide()\n self.comboBox_28.hide()\n self.comboBox_29.hide()\n self.comboBox_31.hide()\n self.radioButton.show()\n self.radioButton_2.show()\n#radioButton connect\n def on_radio2(self, button):#сторона открывания\n newDoor.sidedoor = button.text()\n\n def on_radio3(self, button):\n if button.text() == 'Офисная':\n self.comboBox_11.clear()\n self.comboBox_23.clear()\n self.label_11.setText('Офисная')\n newDoor.pushbase = 'PushHandle'\n elif button.text() == 'кноб':\n self.comboBox_11.clear()\n self.comboBox_23.clear()\n self.label_11.setText('кноб')\n newDoor.pushbase = 'knob'\n else:\n self.comboBox_11.clear()\n self.comboBox_23.clear()\n self.label_11.setText('нажимной гарнитур')\n newDoor.pushbase = 'DoorHandle'\n #self.comboBox_12.hide()\n #self.comboBox_11.show()\n #self.comboBox_24.hide()\n if button.text() != 'Офисная' and newDoor.quantitydoor==2:\n self.comboBox_23.clear()\n self.comboBox_23.show()\n if button.text() == 'Офисная' and newDoor.quantitydoor==2:\n self.comboBox_23.clear()\n self.comboBox_11.addItems(['без']+connectbs(newDoor.pushbase))\n self.comboBox_11.activated[str].connect(self.onActivated11)\n self.comboBox_23.addItems(['без']+connectbs(newDoor.pushbase))\n self.comboBox_23.activated[str].connect(self.onActivated11_2)\n\n def on_radio4(self, button):\n newDoor.hinge_quantity=int(button.text())\n\n def on_radio5(self, button):\n newDoor.doorlock_y2 = button.text()\n newDoor.doorlock_y2_2 = button.text()\n\n#активаторы выпадающего списка\n def onActivated(self, text):#for glass\n global doorglass#denote the global variable\n xxx = doorclass.Glass#write to class variable for later transfer\n if text == 'без':\n doorglass = doorclass.Glass('None')\n else:\n basename = 'glass'\n doorglass = connectbs2(text, basename, xxx)#create an instance\n def onActivated6(self, text):#активация нижниго фитинга\n global botfitting\n xxx = doorclass.BottomFitting\n if text == 'без':\n botfitting = doorclass.BottomFitting('None')\n else:\n basename = 'BottomFitting'\n botfitting = connectbs2(text, basename, xxx)\n def onActivated6_2(self, text):#активация нижниго фитинга\n global botfitting2\n xxx = doorclass.BottomFitting\n if text == 'без':\n botfitting2 = doorclass.BottomFitting('None')\n else:\n basename = 'BottomFitting'\n botfitting2 = connectbs2(text, basename, xxx)\n def onActivated7(self, text):#activate support bf\n global supportbf\n xxx = doorclass.SupportBF\n if text == 'без':\n supportbf = doorclass.SupportBF('None')\n else:\n basename = 'supportbf'\n supportbf = connectbs2(text, basename, xxx)\n def onActivated7_2(self, text):#activate support bf\n global supportbf2\n xxx = doorclass.SupportBF\n if text == 'без':\n supportbf2 = doorclass.SupportBF('None')\n else:\n basename = 'supportbf'\n supportbf2 = connectbs2(text, basename, xxx)\n def onActivated8(self, text):#activate topfitting\n global topfitting\n xxx = doorclass.TopFitting\n if text == 'без':\n topfitting = doorclass.TopFitting('None')\n else:\n basename = 'TopFitting'\n topfitting = connectbs2(text, basename, xxx)\n def onActivated8_2(self, text):#activate topfitting\n global topfitting2\n xxx = doorclass.TopFitting\n if text == 'без':\n topfitting2 = doorclass.TopFitting('None')\n else:\n basename = 'TopFitting'\n topfitting2 = connectbs2(text, basename, xxx)\n def onActivated9(self, text):#активация нижниго фитинга\n global supporttf\n xxx = doorclass.SupportTopFitting\n if text == 'без':\n supporttf = doorclass.SupportTopFitting('None')\n else:\n basename = 'supporttf'\n supporttf = connectbs2(text, basename, xxx)\n def onActivated9_2(self, text):#активация нижниго фитинга\n global supporttf2\n xxx = doorclass.SupportTopFitting\n if text == 'без':\n supporttf2 = doorclass.SupportTopFitting('None')\n else:\n basename = 'supporttf'\n supporttf2 = connectbs2(text, basename, xxx)\n def onActivated10(self, text):#активация нижниго фитинга\n global hinge\n xxx = doorclass.Hinge\n if text == 'без':\n hinge = doorclass.Hinge('None')\n else:\n basename = 'Hinge'\n hinge = connectbs2(text, basename, xxx)\n def onActivated10_2(self, text):#активация нижниго фитинга\n global hinge2\n xxx = doorclass.Hinge\n if text == 'без':\n hinge2 = doorclass.Hinge('None')\n else:\n basename = 'Hinge'\n hinge2 = connectbs2(text, basename, xxx)\n def onActivated11(self, text):#активация нижниго фитинга\n global DoorHandle\n global PushHandle\n global knob\n if newDoor.pushbase == 'DoorHandle':\n PushHandle = doorclass.PushHandle('None')\n knob = doorclass.knob('none')\n xxx = doorclass.DoorHandle\n if text == 'без':\n DoorHandle = doorclass.DoorHandle('None')\n else:\n basename = 'DoorHandle'\n DoorHandle = connectbs2(text, basename, xxx)\n elif newDoor.pushbase == 'PushHandle':\n DoorHandle = doorclass.DoorHandle('None')\n knob = doorclass.knob('none')\n xxx = doorclass.PushHandle\n if text == 'без':\n PushHandle = doorclass.PushHandle('None')\n else:\n basename = 'PushHandle'\n PushHandle = connectbs2(text, basename, xxx)\n else:\n DoorHandle = doorclass.DoorHandle('None')\n PushHandle = doorclass.PushHandle('None')\n xxx = doorclass.knob\n if text == 'без':\n knob = doorclass.knob('None')\n else:\n basename = 'knob'\n knob = connectbs2(text, basename, xxx)\n def onActivated11_2(self, text):#активация нижниго фитинга\n global DoorHandle2\n global PushHandle2\n global knob2\n if newDoor.pushbase == 'DoorHandle':\n PushHandle2 = doorclass.PushHandle('None')\n knob2 = doorclass.knob('none')\n xxx = doorclass.DoorHandle\n if text == 'без':\n DoorHandle2 = doorclass.DoorHandle('None')\n else:\n basename = 'DoorHandle'\n DoorHandle2 = connectbs2(text, basename, xxx)\n elif newDoor.pushbase == 'PushHandle':\n knob2 = doorclass.knob('none')\n DoorHandle2 = doorclass.DoorHandle('None')\n xxx = doorclass.PushHandle\n if text == 'без':\n PushHandle2 = doorclass.PushHandle('None')\n else:\n basename = 'PushHandle'\n PushHandle2 = connectbs2(text, basename, xxx)\n else:\n DoorHandle2 = doorclass.DoorHandle('None')\n PushHandle2 = doorclass.PushHandle('None')\n xxx = doorclass.knob\n if text == 'без':\n knob2 = doorclass.knob('None')\n else:\n basename = 'knob'\n knob2 = connectbs2(text, basename, xxx)\n def onActivated14(self, text):#активация нижниго фитинга\n global DoorLock\n xxx = doorclass.DoorLock\n if text == 'без':\n DoorLock = doorclass.DoorLock('None')\n else:\n basename = 'DoorLock'\n DoorLock = connectbs2(text, basename, xxx)\n def onActivated14_2(self, text):#активация нижниго фитинга\n global DoorLock2\n xxx = doorclass.DoorLock\n if text == 'без':\n DoorLock2 = doorclass.DoorLock('None')\n else:\n basename = 'DoorLock'\n DoorLock2 = connectbs2(text, basename, xxx)\n def onActivated15(self, text):#активация нижниго фитинга\n global MateDoorLock\n xxx = doorclass.MateDoorLock\n if text == 'без':\n MateDoorLock=doorclass.MateDoorLock('None')\n else:\n basename = 'MateDoorLock'\n MateDoorLock = connectbs2(text, basename, xxx)\n def onActivated15_2(self, text):#активация нижниго фитинга\n global MateDoorLock2\n xxx = doorclass.MateDoorLock\n if text == 'без':\n MateDoorLock2=doorclass.MateDoorLock('None')\n else:\n basename = 'MateDoorLock'\n MateDoorLock2 = connectbs2(text, basename, xxx)\n def onActivated16(self, text):\n global Compactor_down\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_down=doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_down = connectbs2(text, basename, xxx)\n def onActivated17(self, text):\n global Compactor_side\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_side=doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_side = connectbs2(text, basename, xxx)\n def onActivated28(self, text):\n global Compactor_side2\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_side2=doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_side2 = connectbs2(text, basename, xxx)\n def onActivated18(self, text):\n global Compactor_up\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_up=doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_up = connectbs2(text, basename, xxx)\n def onActivated29(self, text):\n global Compactor_up2\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_up2=doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_up2 = connectbs2(text, basename, xxx)\n def onActivated30(self, text):\n global Compactor_hinge\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_hinge=doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_hinge = connectbs2(text, basename, xxx)\n def onActivated31(self, text):\n global Compactor_hinge2\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_hinge2 = doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_hinge2 = connectbs2(text, basename, xxx)\n def onActivated27(self, text):#активация нижниго фитинга\n global Compactor_down2\n xxx = doorclass.Compactor\n if text == 'без':\n Compactor_down2=doorclass.Compactor('None')\n else:\n basename = 'Compactor'\n Compactor_down2 = connectbs2(text, basename, xxx)\n def onActivated32(self, text):#активация дисконтной группы\n global discount\n xxx = doorclass.MateDoorLock\n if text == 'Клиент':\n discount = 1.5#наценка 50%\n elif text == 'Дилер':\n discount = 1.3#наценка 30%\n else:\n discount = 1#без наценки\n def onActivated33(self, text):#активация дисконтной группы\n global upProfile\n xxx = doorclass.GlazingProfile\n if text == 'верх без':\n upProfile = doorclass.GlazingProfile('none')\n else:\n basename = 'profile40'\n upProfile = connectbs2(text, basename, xxx)\n def onActivated34(self, text):#активация дисконтной группы\n global leftProfile\n xxx = doorclass.GlazingProfile\n if text == 'лев без':\n leftProfile = doorclass.GlazingProfile('none')\n else:\n basename = 'profile40'\n leftProfile = connectbs2(text, basename, xxx)\n def onActivated35(self, text):#активация дисконтной группы\n global rightProfile\n xxx = doorclass.GlazingProfile\n if text == 'прав. без':\n rightProfile = doorclass.GlazingProfile('none')\n else:\n basename = 'profile40'\n rightProfile = connectbs2(text, basename, xxx)\n def onActivated36(self, text):#активация дисконтной группы\n global downProfile\n xxx = doorclass.GlazingProfile\n if text == 'низ без':\n downProfile = doorclass.GlazingProfile('none')\n else:\n basename = 'profile40'\n downProfile = connectbs2(text, basename, xxx)\n def onActivated37(self, text):#активация дисконтной группы\n global upCap\n xxx = doorclass.GlazingProfile\n if text == 'верх без':\n upCap = doorclass.GlazingCap('none')\n else:\n basename = 'cap40'\n upCap = connectbs2(text, basename, xxx)\n def onActivated38(self, text):#активация дисконтной группы\n global leftCap\n xxx = doorclass.GlazingProfile\n if text == 'лев без':\n leftCap = doorclass.GlazingCap('none')\n else:\n basename = 'cap40'\n leftCap = connectbs2(text, basename, xxx)\n def onActivated39(self, text):#активация дисконтной группы\n global rightCap\n xxx = doorclass.GlazingProfile\n if text == 'прав. без':\n rightCap = doorclass.GlazingCap('none')\n else:\n basename = 'cap40'\n rightCap = connectbs2(text, basename, xxx)\n def onActivated40(self, text):#активация дисконтной группы\n global downCap\n xxx = doorclass.GlazingProfile\n if text == 'низ без':\n downCap = doorclass.GlazingCap('none')\n else:\n basename = 'cap40'\n downCap = connectbs2(text, basename, xxx)\n#checkBox checkBox checkBox checkBox checkBox checkBox checkBox checkBox\n def state_changed(self, int):\n global door_installation_price\n if self.checkBox.isChecked():\n door_installation_price=1300\n else:\n door_installation_price=0\n\n def state_changed_2(self, int):\n global inst_door_closer\n if self.checkBox_2.isChecked():\n if newDoor.supportbf_name[2] == '8' or newDoor.supportbf_name[2] == '7':\n inst_door_closer =+ 1500\n if newDoor.supportbf_name2[2] == '8' or newDoor.supportbf_name[2] == '7':\n inst_door_closer =+ 1500\n else:\n inst_door_closer = 0\n def state_changed_3(self, int):\n if self.checkBox_3.isChecked():\n self.label_39.show()\n self.label_36.show()\n self.lineEdit_5.show()\n self.lineEdit_6.show()\n upGlass.name = doorglass.name\n upGlass.colour = doorglass.colour\n else:\n upGlass.name = 'none'\n upGlass.colour = 'none'\n upGlass.price = 0\n upGlass.width = 0\n upGlass.height = 0\n self.label_39.hide()\n self.label_36.hide()\n self.lineEdit_5.hide()\n self.lineEdit_6.hide()\n self.lineEdit_5.clear()\n self.lineEdit_6.clear()\n\n def state_changed_4(self, int):\n if self.checkBox_4.isChecked():\n self.label_40.show()\n self.label_37.show()\n self.lineEdit_7.show()\n self.lineEdit_8.show()\n rightGlass.name = doorglass.name\n rightGlass.colour = doorglass.colour\n else:\n rightGlass.name = 'none'\n rightGlass.colour = 'none'\n rightGlass.price = 0\n rightGlass.width = 0\n rightGlass.height = 0\n self.label_40.hide()\n self.label_37.hide()\n self.lineEdit_7.hide()\n self.lineEdit_8.hide()\n self.lineEdit_7.clear()\n self.lineEdit_8.clear()\n def state_changed_5(self, int):\n if self.checkBox_5.isChecked():\n self.label_41.show()\n self.label_38.show()\n self.lineEdit_9.show()\n self.lineEdit_10.show()\n leftGlass.name = doorglass.name\n leftGlass.colour = doorglass.colour\n else:\n leftGlass.name = 'none'\n leftGlass.colour = 'none'\n leftGlass.price = 0\n leftGlass.width = 0\n leftGlass.height = 0\n self.label_41.hide()\n self.label_38.hide()\n self.lineEdit_9.hide()\n self.lineEdit_10.hide()\n #self.lineEdit_9.clear()\n #self.lineEdit_10.clear()\n\n\n#Вывод на печать\n def upt(self):\n self.update()\n\n#filling class newDoor\n if len(self.lineEdit.text()) > 1:\n newDoor.doorx = float(self.lineEdit.text())\n newDoor.doory = float(self.lineEdit_2.text())\n else:\n pass\n if newDoor.quantitydoor == 2:\n newDoor.sidedoor = 'лев+прав'\n if len(self.lineEdit_3.text()) > 1:\n newDoor.doorx2 = float(self.lineEdit_3.text())\n newDoor.doory2 = float(self.lineEdit_4.text())\n else:\n pass\n else:\n newDoor.doorx2 = 0\n newDoor.doory2 = 0\n newDoor.glassname = doorglass.name\n if newDoor.quantitydoor == 1:\n newDoor.area = (newDoor.doory*newDoor.doorx/1000000)\n\n else:\n newDoor.area = (newDoor.doory*\n newDoor.doorx/1000000)+(newDoor.doory2*\n newDoor.doorx2/1000000)\n#up Glass\n try:\n upGlass.width = float(self.lineEdit_5.text())\n upGlass.height = float(self.lineEdit_6.text())\n except:\n upGlass.width = 0\n upGlass.height = 0\n\n try:\n rightGlass.width = float(self.lineEdit_7.text())\n rightGlass.height = float(self.lineEdit_8.text())\n except:\n rightGlass.width = 0\n rightGlass.height = 0\n try:\n leftGlass.width = float(self.lineEdit_9.text())\n leftGlass.height = float(self.lineEdit_10.text())\n except:\n leftGlass.width = 0\n leftGlass.height = 0\n\n newDoor.doorglassprice = float(doorglass.price)*newDoor.area\n upGlass.price = doorglass.price\n rightGlass.price = doorglass.price\n leftGlass.price = doorglass.price\n newDoor.glass_colour = doorglass.colour\n newDoor.botfit_name = botfitting.name\n newDoor.botfit_name2 = botfitting2.name\n newDoor.botfit_colour = botfitting.colour\n newDoor.botfit_colour2 = botfitting2.colour\n newDoor.botfitprice = float(botfitting.price)\n newDoor.botfitprice2 = float(botfitting2.price)\n newDoor.supportbf_name = supportbf.name\n newDoor.supportbf_name2 = supportbf2.name\n newDoor.supportbf_colour = supportbf.colour\n newDoor.supportbf_colour2 = supportbf2.colour\n newDoor.supportbf_price = float(supportbf.price)\n newDoor.supportbf_price2 = float(supportbf2.price)\n newDoor.topfit_name = topfitting.name\n newDoor.topfit_colour = topfitting.colour\n newDoor.topfitprice = float(topfitting.price)\n newDoor.topfit_name2 = topfitting2.name\n newDoor.topfit_colour2 = topfitting2.colour\n newDoor.topfitprice2 = float(topfitting2.price)\n newDoor.supporttf_name = supporttf.name\n newDoor.supporttf_colour = supporttf.colour\n newDoor.supporttf_colour2 = supporttf2.colour\n newDoor.supporttf_price = float(supporttf.price)\n newDoor.supporttf_name2 = supporttf2.name\n newDoor.supporttf_price2 = float(supporttf2.price)\n newDoor.hinge_code = hinge.code\n newDoor.hinge_code2 = hinge2.code\n newDoor.hinge_name = hinge.name\n newDoor.hinge_price = float(hinge.price)\n newDoor.hinge_name2 = hinge2.name\n newDoor.hinge_price2 = float(hinge2.price)\n newDoor.doorhandle_code = DoorHandle.code\n newDoor.doorhandle_code2 = DoorHandle2.code\n newDoor.doorhandle_name = DoorHandle.name\n newDoor.doorhandle_price = float(DoorHandle.price)\n newDoor.doorhandle_name2 = DoorHandle2.name\n newDoor.doorhandle_price2 = float(DoorHandle2.price)\n newDoor.pushhandle_code = PushHandle.code\n newDoor.pushhandle_code2 = PushHandle2.code\n newDoor.pushhandle_name = PushHandle.name\n newDoor.pushhandle_l = int(PushHandle.length)\n newDoor.pushhandle_price = float(PushHandle.price)\n newDoor.pushhandle_name2 = PushHandle2.name\n newDoor.pushhandle_l2 = int(PushHandle2.length)\n newDoor.pushhandle_price2 = float(PushHandle2.price)\n newDoor.doorlock_code = DoorLock.code\n newDoor.doorlock_code2 = DoorLock2.code\n newDoor.doorlock_name = DoorLock.name\n newDoor.doorlock_price = float(DoorLock.price)\n newDoor.doorlock_name2 = DoorLock2.name\n newDoor.doorlock_price2 = float(DoorLock2.price)\n newDoor.matedoorlock_name = MateDoorLock.name\n newDoor.matedoorlock_price = float(MateDoorLock.price)\n newDoor.matedoorlock_name2 = MateDoorLock2.name\n newDoor.matedoorlock_price2 = float(MateDoorLock2.price)\n newDoor.compactor_down_name = Compactor_down.name\n newDoor.compactor_down_price = float(Compactor_down.price)\n newDoor.compactor_down_name2 = Compactor_down2.name\n newDoor.compactor_down_price2 = Compactor_down2.price\n newDoor.compactor_side_name = Compactor_side.name\n newDoor.compactor_side_price = Compactor_side.price\n newDoor.compactor_side_name2 = Compactor_side2.name\n newDoor.compactor_side_price2 = Compactor_side2.price\n newDoor.compactor_up_name = Compactor_up.name\n newDoor.compactor_up_price = Compactor_up.price\n newDoor.compactor_up_name2 = Compactor_up2.name\n newDoor.compactor_up_price2 = Compactor_up2.price\n newDoor.compactor_hinge_name = Compactor_hinge.name\n newDoor.compactor_hinge_price = Compactor_hinge.price\n newDoor.compactor_hinge_name2 = Compactor_hinge2.name\n newDoor.compactor_hinge_price2 = Compactor_hinge2.price\n newDoor.knob_code = knob.code\n newDoor.knob_code2 = knob2.code\n newDoor.knob_name = knob.name\n newDoor.knob_name2 = knob2.name\n newDoor.knob_price = float(knob.price)\n newDoor.knob_price2 = float(knob2.price)\n newDoor.left_profile_name = leftProfile.name\n newDoor.right_profile_name = rightProfile.name\n newDoor.leftCap_name = leftCap.name\n newDoor.rightCap_name = rightCap.name\n\n newDoor.upProfile_name = upProfile.name\n newDoor.upCap_name = upCap.name\n newDoor.downProfile_name = downProfile.name\n newDoor.downCap_name = downCap.name\n\n#для верхнего профиля\n if (upGlass.width == 0 and rightGlass.width == 0 and leftGlass.width ==0):\n #upProfile = doorclass.GlazingProfile('none')\n\n self.comboBox_33.setCurrentIndex(0)\n self.comboBox_33.activated[str].connect(self.onActivated33)\n self.comboBox_34.setCurrentIndex(0)\n self.comboBox_35.setCurrentIndex(0)\n self.comboBox_36.setCurrentIndex(0)\n self.comboBox_37.setCurrentIndex(0)\n self.comboBox_38.setCurrentIndex(0)\n self.comboBox_39.setCurrentIndex(0)\n self.comboBox_40.setCurrentIndex(0)\n\n leftProfile.price = 0\n newDoor.left_profile_name = 'none'\n rightProfile.price = 0\n newDoor.right_profile_name = 'none'\n upProfile.price = 0\n newDoor.upProfile_name = 'none'\n upCap.price = 0\n newDoor.upCap_name = 'none'\n downProfile.price = 0\n newDoor.downProfile_name ='none'\n downCap.price = 0\n newDoor.downCap_name = 'none'\n\n leftCap.price = 0\n newDoor.leftCap_name = 'none'\n rightCap.price = 0\n newDoor.rightCap_name = 'none'\n\n elif (upGlass.width == 0 and rightGlass.width == 0):\n self.comboBox_35.setCurrentIndex(0)\n rightProfile.price = 0# = doorclass.GlazingProfile('none')\n newDoor.right_profile_name = 'none'\n rightCap.price = 0\n newDoor.rightCap_name = 'none'\n self.comboBox_39.setCurrentIndex(0)\n\n elif (upGlass.width == 0 and leftGlass.width ==0):\n self.comboBox_34.setCurrentIndex(0)\n leftProfile.price = 0#doorclass.GlazingProfile('none')\n newDoor.left_profile_name = 'none'\n leftCap.price = 0\n newDoor.leftCap_name = 'none'\n self.comboBox_38.setCurrentIndex(0)\n leftCap.price = 0#doorclass.GlazingCap('none')\n elif (leftGlass.width == 0 and leftGlass.width ==0):\n self.comboBox_36.setCurrentIndex(0)\n self.comboBox_40.setCurrentIndex(0)\n\n#downProfile\n try:\n newDoor.downProfile_length = (rightGlass.width + leftGlass.width)\n newDoor.downCap_length = (rightGlass.width + leftGlass.width)\n except:\n newDoor.downProfile_length = 0\n newDoor.downCap_length = 0\n#upProfile\n try:\n newDoor.upProfile_length = (rightGlass.width + leftGlass.width +\n upGlass.width)\n newDoor.upCap_length = (rightGlass.width + leftGlass.width +\n upGlass.width)\n\n except:\n newDoor.upProfile_lengh = 0\n newDoor.upCap_length = 0\n#left profile start\n\n if (leftGlass.height == 0 and upGlass.height != 0):\n try:\n newDoor.left_profile_length = upGlass.height\n newDoor.leftCap_length = upGlass.height\n except:\n newDoor.left_profile_length = 0\n newDoor.leftCap_length = 0\n else:\n newDoor.left_profile_length = leftGlass.height\n newDoor.leftCap_length = leftGlass.height\n\n if (rightGlass.height == 0 and upGlass.height != 0):\n try:\n newDoor.right_profile_length = upGlass.height\n newDoor.rightCap_length = upGlass.height\n except:\n newDoor.right_profile_length = 0\n newDoor.rightCap_length = 0\n else:\n newDoor.right_profile_length = rightGlass.height\n newDoor.rightCap_length = rightGlass.height\n\n newDoor.left_profile_price = (float(leftProfile.price)*\n newDoor.left_profile_length/1000)\n newDoor.right_profile_price = (float(rightProfile.price)*\n newDoor.right_profile_length/1000)\n newDoor.leftCap_price = (float(leftCap.price)*\n newDoor.leftCap_length/1000*2)\n newDoor.rightCap_price = (float(rightCap.price)*\n newDoor.rightCap_length/1000*2)\n newDoor.upProfile_price = (float(upProfile.price)*\n newDoor.upProfile_length/1000)\n newDoor.upCap_price = (float(upCap.price)*\n newDoor.upCap_length/1000*2)\n newDoor.downCap_price = (float(downCap.price)*\n newDoor.downCap_length/1000*2)\n newDoor.downProfile_price = (float(downProfile.price)*\n newDoor.downProfile_length/1000*2)\n\n if newDoor.left_profile_price == 0:\n newDoor.left_profile_length = 0\n if newDoor.right_profile_price == 0:\n newDoor.right_profile_length = 0\n if newDoor.leftCap_price == 0:\n newDoor.leftCap_length = 0\n if newDoor.rightCap_price == 0:\n newDoor.rightCap_length = 0\n upProfile.length_real = (upGlass.width + rightGlass.width +leftGlass.width)\n#left profile end\n self.newScene()#call scene\n self.textBrowser.setText('готово')\n\n self.label_23.setText(str((newDoor.doorPrice() +\n upGlass.priceup() + rightGlass.priceup() +\n leftGlass.priceup())*\n discount +\n (door_installation_price*\n (newDoor.area + upGlass.area() +\n rightGlass.area() + leftGlass.area()) +\n inst_door_closer*newDoor.quantitydoor)))#цена двери на скидку + установка на площадь + уст. даводчиков на двери\n#save image and exel file\n def screenshot(self):\n \"\"\"\n save image in file and kp\n \"\"\"\n date_kp = str(datetime.datetime.now()) #date our kp\n number_kp = date_kp[11:13]+date_kp[14:16]+date_kp[17:19] #number of kp\n image = QImage((newDoor.doorx + newDoor.doorx2 + leftGlass.width + rightGlass.width)/10, (upGlass.height+newDoor.doory)/10 + 10, QImage.Format_ARGB32_Premultiplied)\n painter = QPainter(image)\n # Render the region of interest to the QImage.\n self.scene.render(painter)\n painter.end()\n # Save the image to a file.\n if sys.platform == \"linux\" or sys.platform == \"linux2\":\n image.save(\"img/drw\" + number_kp + \".png\")\n else:\n image.save(\"img\\\\drw\" + number_kp + \".png\")\n\n wb = openpyxl.load_workbook(filename = 'kp3.xlsx')\n ws = wb.active\n if sys.platform == \"linux\" or sys.platform == \"linux2\":\n img = openpyxl.drawing.image.Image(\"img/drw\" + number_kp + \".png\")\n else:\n img = openpyxl.drawing.image.Image(\"img\\\\drw\" + number_kp + \".png\")\n ws.add_image(img, 'B11')\n rows=11\n\n ws['H9'] = number_kp\n ws['I10'] = date_kp[8:10] + '.' + date_kp[5:7] + '.' + date_kp[0:4]\n ws['F11'] = newDoor.accessories()\n\n if newDoor.quantitydoor == 2:\n ws['B36'] = 'Дверь цельно стеклянная двустворчатая'\n else:\n ws['B36'] = 'Дверь цельно стеклянная одностворчатая'\n ws['F36'] = '1'\n ws['H36'] = (newDoor.doorPrice() +\n upGlass.priceup() + rightGlass.priceup() +\n leftGlass.priceup())* discount\n ws['I36'] = (newDoor.doorPrice() +\n upGlass.priceup() + rightGlass.priceup() +\n leftGlass.priceup())* discount\n ws['F37'] = newDoor.area\n if door_installation_price != 0:\n ws['B37'] = 'монтаж'\n ws['H37'] = door_installation_price\n ws['I37'] = door_installation_price*(newDoor.area + upGlass.area() + rightGlass.area() + leftGlass.area())\n if inst_door_closer != 0:\n ws['B38'] = 'установка доводчика'\n ws['F38'] = newDoor.quantitydoor\n ws['G38'] = 'шт.'\n ws['H38'] = inst_door_closer\n ws['I38'] = inst_door_closer*newDoor.quantitydoor\n ws['I39'] = ((newDoor.doorPrice() +\n upGlass.priceup() + rightGlass.priceup() +\n leftGlass.priceup())*\n discount +\n (door_installation_price*\n (newDoor.area + upGlass.area() +\n rightGlass.area() + leftGlass.area()) +\n inst_door_closer*newDoor.quantitydoor))\n date_kp2 = date_kp[8:10] + '-' + date_kp[5:7] + '-' + date_kp[0:4]+'-' + number_kp\n\n if sys.platform == \"linux\" or sys.platform == \"linux2\":\n wb.save('newkp/kp'+date_kp2+'.xlsx')\n os.startfile(r'\"newkp/kp'+date_kp2+'.xlsx\"')\n else:\n wb.save('newkp\\\\kp'+date_kp2+'.xlsx')\n os.startfile(r'\"newkp\\\\kp'+date_kp2+'.xlsx\"')\n self.textBrowser.setText('Номер коммерческого ' + number_kp)\n#my scene\n def newScene(self):\n #botFitting\n\n if botfitting.price != 0:\n if newDoor.sidedoor == 'правая':\n newDoor.botfitx = newDoor.doorx-161\n else:\n newDoor.botfitx = 0.01\n else:\n newDoor.botfitx = 0\n if botfitting2.price != 0 :\n newDoor.botfitx2 = newDoor.doorx+newDoor.doorx2+5-161\n else:\n newDoor.botfitx2 = 0\n #supportbf\n if supportbf.price != 0:\n if newDoor.supportbf_name[2] == '8' or newDoor.supportbf_name[2] == '7':\n newDoor.supportbf_w = 306\n newDoor.supportbf_l = 40\n else:\n newDoor.supportbf_w = 101\n newDoor.supportbf_l = 20\n if newDoor.sidedoor == 'правая':\n newDoor.supportbf_x = newDoor.doorx-newDoor.supportbf_w\n else:\n newDoor.supportbf_x = 0.01\n else:\n newDoor.supportbf_x = 0\n if supportbf2.price != 0:\n if newDoor.supportbf_name2[2] == '8' or newDoor.supportbf_name2[2] == '7':\n newDoor.supportbf_w2 = 306\n newDoor.supportbf_l2 = 40\n else:\n newDoor.supportbf_w2 = 101\n newDoor.supportbf_l2 = 20\n newDoor.supportbf_x2 = (newDoor.doorx + 5 + newDoor.doorx2 -\n newDoor.supportbf_w2)\n else:\n newDoor.supportbf_x2 = 0\n #topfitting\n if topfitting.price != 0:\n if newDoor.sidedoor == 'правая':\n newDoor.topfitx = newDoor.doorx - 161\n else:\n newDoor.topfitx = 0.01\n else:\n newDoor.topfitx = 0\n if topfitting2.price != 0:\n newDoor.topfitx2 = newDoor.doorx+newDoor.doorx2 + 5 - 161\n else:\n newDoor.topfitx2 = 0\n #supporttf\n if supporttf.price != 0:\n if newDoor.supporttf_name[2] == '8':\n newDoor.supporttf_w = 161\n newDoor.supporttf_l = 51\n else:\n newDoor.supporttf_w = 101\n newDoor.supporttf_l = 20\n if newDoor.sidedoor == 'правая':\n newDoor.supporttf_x = newDoor.doorx - newDoor.supporttf_w\n else:\n newDoor.supporttf_x = 0.01\n else:\n newDoor.supporttf_x = 0\n\n if supporttf2.price != 0:\n if newDoor.supporttf_name2[2] == '8':\n newDoor.supporttf_w2 = 161\n newDoor.supporttf_l2 = 51\n else:\n newDoor.supporttf_w2 = 101\n newDoor.supporttf_l2 = 20\n\n newDoor.supporttf_x2 = (newDoor.doorx+newDoor.doorx2 -\n newDoor.supporttf_w2)\n else:\n newDoor.supporttf_x2 = 0\n\n #hinge\n if hinge.price != 0:\n if newDoor.sidedoor == 'правая':\n newDoor.hinge_x = newDoor.doorx - 62 + 15\n else:\n newDoor.hinge_x = -15\n else:\n newDoor.hinge_x = 0\n if hinge2.price != 0:\n newDoor.hinge_x2 = newDoor.doorx+newDoor.doorx2 - 62 + 15\n else:\n newDoor.hinge_x2 = 0\n #doorhandle\n if DoorHandle.price != 0:\n if newDoor.sidedoor == 'левая' or newDoor.quantitydoor == 2:\n newDoor.doorhandle_x = newDoor.doorx - 120\n newDoor.doorhandle_x2 = newDoor.doorx - 170\n else:\n newDoor.doorhandle_x = 0.01\n newDoor.doorhandle_x2 = 0.01\n else:\n newDoor.doorhandle_x = 0\n\n if DoorHandle2.price != 0:\n newDoor.doorhandle_x_2 = newDoor.doorx + 5\n newDoor.doorhandle_x2_2 = newDoor.doorx + 5\n else:\n newDoor.doorhandle_x_2 = 0\n#PushHandle\n if newDoor.pushhandle_price != 0:\n\n if newDoor.sidedoor == 'правая':\n newDoor.pushhandle_x = 68\n else:\n\n newDoor.pushhandle_x = newDoor.doorx - 132\n else:\n newDoor.pushhandle_x = 0\n\n if newDoor.pushhandle_price2 != 0:\n newDoor.pushhandle_x2 = newDoor.doorx + 68\n else:\n newDoor.pushhandle_x2 = 0\n#DoorLock\n if DoorLock.price != 0:\n if newDoor.doorlock_y2 == 'с':\n newDoor.doorlock_w = 77\n newDoor.doorlock_l = 110\n newDoor.doorlock_y = newDoor.doory/2 - newDoor.doorlock_l/2\n elif newDoor.doorlock_y2 == 'в':\n newDoor.doorlock_w = 161\n newDoor.doorlock_l = 51\n newDoor.doorlock_y = 0\n else:\n newDoor.doorlock_w = 161\n newDoor.doorlock_l = 51\n newDoor.doorlock_y = newDoor.doory - newDoor.doorlock_l\n if newDoor.sidedoor == 'левая' or newDoor.quantitydoor == 2:\n newDoor.doorlock_x = newDoor.doorx - newDoor.doorlock_w\n else:\n newDoor.doorlock_x = 0.01\n else:\n newDoor.doorlock_x = 0\n\n if DoorLock2.price != 0:\n if newDoor.doorlock_y2_2 == 'с':\n newDoor.doorlock_w2 = 77\n newDoor.doorlock_l2 = 110\n newDoor.doorlock_y_2 = newDoor.doory2/2 - newDoor.doorlock_l2/2\n elif newDoor.doorlock_y2_2 == 'в':\n newDoor.doorlock_w2 = 161\n newDoor.doorlock_l2 = 51\n newDoor.doorlock_y_2 = 0\n else:\n newDoor.doorlock_w2 = 161\n newDoor.doorlock_l2 = 51\n newDoor.doorlock_y_2 = newDoor.doory2 - newDoor.doorlock_l2\n newDoor.doorlock_x2 = newDoor.doorx + 5\n else:\n newDoor.doorlock_x2 = 0\n\n self.der(*newDoor.for_scene(), *upGlass.for_scene(),\n *rightGlass.for_scene(), *leftGlass.for_scene(),\n *newDoor.for_scene2())\n#scene screenshot\n\ndef main():\n app = QApplication(sys.argv)\n window = ExampleApp()\n window.show()\n app.exec_()\n\nif __name__ == '__main__':\n main()\n","repo_name":"mitinva1/glasscalc","sub_path":"сlassicdoor.py","file_name":"сlassicdoor.py","file_ext":"py","file_size_in_byte":50360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"205412381","text":"import sys, gzip, re\nfrom Bio import SeqIO\n\nfa_file = gzip.open(sys.argv[1], 'rb')\ncdna = SeqIO.to_dict(SeqIO.parse(fa_file, 'fasta'))\n\nout_file = open(sys.argv[3], 'w')\n\nwith open(sys.argv[2]) as file:\n\tfor line in file:\n\t\tlst = line.strip().split('\\t')\n\t\tgene_id = lst[0]\n\t\ttrans_id = lst[1]\n\t\tlst[4] = lst[4].replace('NA,', '')\n\t\tlst[4] = lst[4].replace(',NA', '')\n\t\tlst[5] = lst[5].replace('NA,', '')\n\t\tlst[5] = lst[5].replace(',NA', '')\n\t\tcds_start = [int(i) for i in lst[4].replace('NA,', '').split(',')][0] - 1\n\t\tcds_end = [int(i) for i in lst[5].replace('NA,', '').split(',')][-1]\n\t\tseq = cdna[trans_id].seq\n\t\tstart_codon = seq[cds_start:(cds_start+3)]\n\t\tstop_codon = seq[(cds_end-3):cds_end]\n\t\tif start_codon == 'ATG' and (stop_codon == 'TAA' or stop_codon == 'TAG' or stop_codon == 'TGA'):\n\t\t\tseq_ext = 'N'*400 + seq + 'N'*400\n\t\t\tcds_start += 400\n\t\t\tcds_end += 400\n\t\t\tstart_region = seq_ext[cds_start - 399 : cds_start + 400]\n\t\t\tstop_region = seq_ext[cds_end - 400 : cds_end + 399]\n\t\t\tout_file.write('%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' % (gene_id, trans_id, start_codon, stop_codon, start_region, stop_region))\n\nout_file.close()","repo_name":"bioxfu/m6A","sub_path":"script/extract_start_stop_coden_region.py","file_name":"extract_start_stop_coden_region.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27402861911","text":"import os\nimport threading\n\nfrom datetime import timedelta \nfrom flask import Flask, render_template, flash, url_for, redirect, request, session\nfrom werkzeug.utils import secure_filename\nfrom flask_socketio import SocketIO, emit # pip install Flask-SocketIO==5.3.5\n\nimport mcqGptAppGlobal as gv\nimport mcqGptAppDataMgr as dataManager\n\nasync_mode = None\n\n#-----------------------------------------------------------------------------\n# Init the flask web app program.\ndef createApp():\n \"\"\" Create the flask App.\"\"\"\n app = Flask(__name__)\n app.config['SECRET_KEY'] = gv.APP_SEC_KEY\n app.config['REMEMBER_COOKIE_DURATION'] = timedelta(seconds=gv.COOKIE_TIME)\n app.config['UPLOAD_FOLDER'] = gv.UPLOAD_FOLDER\n # init the data manager\n gv.iDataMgr = dataManager.DataManager(app)\n if not gv.iDataMgr: exit()\n gv.iDataMgr.start()\n return app\n\ndef checkFile(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in gv.ALLOWED_EXTENSIONS\n\ndef initGlobal():\n gv.gSrceName = None\n gv.gSrcPath = None\n gv.gSrcType = None\n gv.gRstPath = None\n\n#-----------------------------------------------------------------------------\n#-----------------------------------------------------------------------------\napp = createApp()\nsocketio = SocketIO(app, async_mode=async_mode)\ngv.iSocketIO = socketio\nthread = None\nthreadLock = threading.Lock()\n\n#-----------------------------------------------------------------------------\n# web request handling functions. \n\n@app.route('/')\ndef index():\n posts = {'mode': gv.gParserMode}\n return render_template('index.html', \n async_mode=socketio.async_mode, \n posts=posts)\n\n@app.route('/mdselect', methods = ['POST', 'GET']) \ndef mdselect():\n posts = None\n if request.method == 'POST':\n option = request.form['options']\n if gv.iDataMgr:\n gv.gParserMode = 1 if option =='mode1'else 2\n gv.iDataMgr.reInitQuestionParser(mode=gv.gParserMode)\n posts = {'mode': gv.gParserMode}\n return render_template('index.html', posts=posts)\n \n@app.route('/fileupload', methods = ['POST', 'GET']) \ndef fileupload():\n posts = None\n if request.method == 'POST':\n file = request.files['file']\n print(file.filename)\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n elif file and checkFile(file.filename):\n filename = secure_filename(file.filename)\n gv.gSrceName = filename\n gv.gSrcPath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n gv.gSrcType = filename.rsplit('.', 1)[1].lower()\n gv.gRstPath = None\n file.save(gv.gSrcPath)\n posts = {'filename': gv.gSrceName}\n return render_template('index.html', posts=posts)\n\n@app.route('/urlupload', methods=['POST', 'GET'])\ndef urlupload():\n posts = None\n if request.method == 'POST':\n urlStr = request.form['mcqurl']\n gv.gSrceName = 'mcq_from_url'\n gv.gSrcPath = urlStr\n gv.gSrcType = 'url'\n gv.gRstPath = None\n posts = {'filename': gv.gSrceName}\n return render_template('index.html', posts=posts)\n\n@app.route('/introduction')\ndef introduction():\n return render_template('introduction.html', posts=None)\n\n#-----------------------------------------------------------------------------\n# socketIO communication handling functions. \n@socketio.event\ndef connect():\n gv.gWeblogCount = 0\n emit('serv_response', {'data': 'MCQ-Solver Ready', 'count': gv.gWeblogCount})\n\n@socketio.event\ndef cli_request(message):\n session['receive_count'] = session.get('receive_count', 0) + 1\n if message['data'] == 'download' and gv.gRstPath:\n if os.path.exists(gv.gRstPath):\n gv.gDebugPrint(\"Download the file.\")\n with open(gv.gRstPath) as fh:\n socketio.emit('file_ready', {'filename': gv.gSrceName, 'content': fh.read()})\n else:\n emit('serv_response',\n {'data': message['data'], 'count': session['receive_count']})\n \n@socketio.on('startprocess')\ndef startProcess(data):\n print('received message: ' + str(data))\n gv.iDataMgr.startProcess()\n emit('startprocess', {'data': 'Starting to process MCQ-source: %s' %str(gv.gSrceName)})\n\n#-----------------------------------------------------------------------------\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5000, debug=False, threaded=True)\n","repo_name":"LiuYuancheng/MCQ-GPT-Bot","sub_path":"src/mcqGptApp.py","file_name":"mcqGptApp.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"18870929640","text":"import keys\nimport tweepy as t\nimport json\n\nauth = t.OAuthHandler(keys.api_key, keys.api_secret)\n\nauth.set_access_token(keys.access_token, keys.secret_token)\n\napi = t.API(auth, wait_on_rate_limit = True, wait_on_rate_limit_notify = True)\n\n\ntweets = api.search(q = 'vote', count = 3)\n#print(tweets)\n''''\n#print user and text of tweet\nfor tweet in tweets:\n print(tweet.user.screen_name,':',tweet.text)\n\n\ntweets = api.search(q = '#collegefootball', count = 3)\n\nfor tweet in tweets:\n print(tweet.user.screen_name,':',tweet.text)\n'''\n#places with trending topics\n\ntrends_available = api.trends_available() #a list of dictionaries\n\n#print(len(trends_available))\n#print(trends_available[:3])\n\nworld_trends = api.trends_place(id = 1)\n#print(world_trends)\n\noutfile = open('world_trends.json', 'w')\njson.dump(world_trends, outfile, indent = 5)\n\ntrends_list = world_trends[0]['trends']\n#print(trends_list)\n\ntrends_list = [x for x in world_trends[0]['trends'] if x[\"tweet_volume\"]] #if x[tweetvol] defaults to true aka is not null\n#print(trends_list)\n\nfrom operator import itemgetter #allows us to use another key to specify sorting\n\ntrends_list.sort(key = itemgetter('tweet_volume'), reverse = True)\n\n#print(trends_list[:5])\n\n#for t in trends_list:\n #print(t['name'])\n\n#create worldcloud of trending topics in NYC\n\nfrom wordcloud import WordCloud\n\nnyc_trends = api.trends_place(id = 2459115)\n\nnyc_trends_list = [t for t in nyc_trends[0]['trends']]\n\nnyc_trends_list.sort(key = itemgetter('tweet_volume'), reverse = True)\n\ntopics = {}\nfor t in nyc_trends_list:\n topics[t['name']] = t['tweet_volume']\n\nwordcloud = WordCloud(\n width = 1600,\n height = 900,\n prefer_horizontal = 0.5,\n min_font_size = 10,\n colormap = 'prism',\n background_color = 'white'\n)\n\nwc = wordcloud.fit_words(topics)\nwc = wordcloud.to_file('TrendingTwitter_fall2020.png')","repo_name":"lukewheless/Data_Mining","sub_path":"dm_2LW.py","file_name":"dm_2LW.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27143344161","text":"from prep_test_data import *\nfrom pathlib import Path\nimport json\nimport torch\nimport sys\nfrom torchray.attribution.common import Probe, get_module\nfrom torchray.attribution.grad_cam import gradient_to_grad_cam_saliency\nfrom torchray.attribution.guided_backprop import GuidedBackpropReLU\nimport shutil\nimport numpy as np\nimport cv2\n\ndef create_maps_folders(main_folder, beat, labels, delete_prior):\n if delete_prior and Path(main_folder).exists():\n shutil.rmtree(main_folder)\n for label in labels:\n folder = Path(main_folder) / f\"label_{beat}_beat/\"\n Path(folder / label).mkdir(parents=True, exist_ok=True)\n return folder\n\ndef deprocess(image):\n transform = transforms.Compose([\n transforms.Normalize(mean=[0, 0, 0], std=[4.3668, 4.4643, 4.4444]),\n transforms.Normalize(mean=[-0.485, -0.456, -0.406], std=[1, 1, 1]),\n transforms.ToPILImage(),\n ])\n return transform(image)\n\ndef deprocess_image_gb(img):\n \"\"\" see https://github.com/jacobgil/keras-grad-cam/blob/master/grad-cam.py#L65 \"\"\"\n img = img - np.mean(img)\n img = img / (np.std(img) + 1e-5)\n img = img * 0.1\n img = img + 0.5\n img = np.clip(img, 0, 1)\n return np.uint8(img*255)\nclass GuidedBackpropReLUModel:\n def __init__(self, model):\n self.model = model.cpu()\n# self.model.eval()\n\n def recursive_relu_apply(module_top):\n for idx, module in module_top._modules.items():\n recursive_relu_apply(module)\n if module.__class__.__name__ == 'ReLU':\n module_top._modules[idx] = GuidedBackpropReLU.apply\n\n # replace ReLU with GuidedBackpropReLU\n recursive_relu_apply(self.model)\n\n def forward(self, input_img):\n return self.model(input_img)\n\n def __call__(self, input_img, target_category=None):\n\n input_img = input_img.requires_grad_(True)\n\n output = self.forward(input_img)\n\n if target_category == None:\n target_category = np.argmax(output.cpu().data.numpy())\n\n one_hot = np.zeros((1, output.size()[-1]), dtype=np.float32)\n one_hot[0][target_category] = 1\n one_hot = torch.from_numpy(one_hot).requires_grad_(True)\n\n one_hot = torch.sum(one_hot * output)\n one_hot.backward(retain_graph=True)\n output = input_img.grad.cpu().data.numpy()\n output = output[0, :, :, :]\n\n return output\n\ndef guided_backprop_grad_cam(model, data, main_folder, n_batches=None):\n gb_model = GuidedBackpropReLUModel(model=model)\n classes = data[\"test\"].dataset.classes\n i = 0\n for inputs, labels in data['test']:\n # print(f\"{i}/{int(len(data['test'].dataset.samples)/16)}\", end=\"\\r\")\n sys.stdout.write('\\r' + f\"batch nr: {i + 1}\")\n inputs = inputs#.to('cuda:0')\n labels = labels\n x = inputs\n # break\n x.requires_grad_();\n saliency_layer = get_module(model, model.layer4)\n probe = Probe(saliency_layer, target='output')\n y = model(x)\n score_max_index = y.argmax(dim=1)\n z = y[:, score_max_index]\n z.backward(torch.ones_like(z))\n saliency = gradient_to_grad_cam_saliency(probe.data[0])\n\n for index in range(len(saliency)):\n heatmap = np.float32(saliency[index, 0].cpu().detach())\n img = np.array(deprocess(x[index].cpu().detach()))\n\n heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))\n heatmap = np.uint8(255 * heatmap)\n cam_mask = cv2.merge([heatmap, heatmap, heatmap])\n\n gb = gb_model(x[index].unsqueeze(0).detach().cpu(), target_category=labels[index].cpu())\n gb = gb.transpose((1, 2, 0))\n cam_gb = deprocess_image_gb(cam_mask*gb)\n\n label = classes[labels[index]]\n true = labels[index]\n pred = score_max_index[index]\n pred_res = \"OK\"\n if pred != true:\n pred_res = \"wrong\"\n\n input_filename = Path(data['test'].dataset.samples[i * len(saliency) + index][0]).stem\n cv2.imwrite(str(main_folder / f\"{label}/{input_filename}_{pred_res}.png\"), cam_gb)\n\n# if n_batches:\n# if i + 1 == n_batches:\n# break\n i += 1\n\ndef create_gb_grad_cam_maps_one_heartbeat(data_path, models_main_path, model_name, beat, saliency_maps_path, nr_egs=None):\n data_prep = DataPreparation(str(data_path))\n data, size = data_prep.create_dataloaders(16, False, 4)\n model_path = models_main_path / f\"label_{beat}/{model_name}.pth\"\n model = torch.load(model_path, map_location=torch.device(0))\n model.eval();\n guided_backprop_grad_cam(model, data, saliency_maps_path, nr_egs)\n\n\ndef get_model_name(beat):\n d = {\n \"final\": \"resnet50_d_22_t_12_17\",\n \"initial\": \"resnet50_d_22_t_19_13\",\n \"mid\": \"resnet50_d_22_t_13_24\"\n }\n return d[beat]\n\nwith open(\"./config.json\") as f:\n config_data = json.load(f)\n f.close()\n\nif __name__ == '__main__':\n MODELS_PATH = Path(f\"./models/\")\n MAP_DIR = \"./attribution_maps/gb_grad_cam\"\n DELETE_PRIOR_DIR = False\n # TEST_DATA_PATH = Path(f'./data/figures_final/test')\n TEST_DATA_PATH = Path(f'/mnt/Media/bernardo/DSL_test_data')\n NR_BATCHES = 2\n\n for HEARTBEAT in [\"initial\", \"final\", \"mid\"]:\n print(f\"BEAT:{HEARTBEAT}\")\n MODEL_NAME = get_model_name(HEARTBEAT)\n saliency_folder = create_maps_folders(MAP_DIR, HEARTBEAT, config_data['labels_bin'], DELETE_PRIOR_DIR)\n create_gb_grad_cam_maps_one_heartbeat(TEST_DATA_PATH, MODELS_PATH, MODEL_NAME, HEARTBEAT, saliency_folder)","repo_name":"ruivarandas/DSLproject","sub_path":"guided_back_prop.py","file_name":"guided_back_prop.py","file_ext":"py","file_size_in_byte":5616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27612415422","text":"# https://open.kattis.com/problems/alphabet\n# Time: 2022-09-18 22:17:30\n# title: Alphabet\n# language: Python 3\n\n\ndef lis(arr):\n n = len(arr)\n lis = [1]*n\n \n for i in range (1, n):\n for j in range(0, i):\n if arr[i] > arr[j] and lis[i]< lis[j] + 1 :\n lis[i] = lis[j]+1\n maximum = 0\n for i in range(n):\n maximum = max(maximum, lis[i])\n \n return maximum\ns=input()\narr = []\nfor i in s:\n arr.append(ord(i)-97)\nm= lis(arr)\nprint(26-m)","repo_name":"mukerem/competitive-programming","sub_path":"kattis/alphabet.py","file_name":"alphabet.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"9412701251","text":"import pytest\nimport numpy as np\nimport pandas as pd\n\nfrom dragon_fruit.calculation_functions.CalculateFeatures import calculate_time_between_orders\n\nmock_orders_data = {'customer_id':\n {0: 'a',\n 1: 'a',\n 2: 'a',\n 3: 'a',\n 4: 'a',\n 5: 'a'},\n 'order_date': \n {0: '2016-09-01',\n 1: '2016-09-02',\n 2: '2016-09-04',\n 3: '2016-09-05',\n 4: '2016-09-14',\n 5: '2016-10-31'},\n 'order_hour':\n {0: 14, 1: 20, 2: 14, 3: 11, 4: 15, 5: 19},\n 'customer_order_rank':\n {0: np.nan, 1: 1.0, 2: 2.0, 3: np.nan, 4: 3.0, 5: 4.0},\n 'is_failed':\n {0: 1, 1: 0, 2: 0, 3: 1, 4: 0, 5: 0}\n }\ndef is_matching(List1: np.array, List2: np.array):\n if len(List1) != len(List2):\n return False\n return ((List1 == List2) | (np.isnan(List1) & np.isnan(List2))).all()\n\n\ndef test_calculate_is_returning_customer_counting_failed():\n result_df = calculate_time_between_orders(Data= pd.DataFrame(mock_orders_data), COUNT_FAILED_ORDERS= True)\n\n assert (is_matching(result_df.customer_order_rank.to_numpy(),[1, 2, 3, 4, 5, 6])), \"Some values in the calculated order rank were incorrect\"\n assert (is_matching(result_df.time_to_next_order.to_numpy(),[30.0, 42.0, 21.0, 220.0, 1132.0, np.nan])), \"Some values in the day_diff were incorrect\"\n #assert (is_matching(result_df.is_returning_customer.to_numpy(),[1, 1, 1, 1, 1, 0])), \"Some values in the is_returning_customer were incorrect\"\n\ndef test_calculate_is_returning_customer_not_counting_failed():\n result_df = calculate_time_between_orders(Data= pd.DataFrame(mock_orders_data), COUNT_FAILED_ORDERS= False)\n\n assert (is_matching(result_df.time_to_next_order.to_numpy(),[np.nan, 42.0, 241.0, np.nan, 1132.0, np.nan])), \"Some values in the day_diff were incorrect\"\n #assert (is_matching(result_df.is_returning_customer.to_numpy(),[0, 1, 1, 0, 1, 0])), \"Some values in the is_returning_customer were incorrect\"\n\n\n","repo_name":"amr-jawwad/dragon-fruit","sub_path":"tests/test_CalculateTimeToNextOrder.py","file_name":"test_CalculateTimeToNextOrder.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36698259131","text":"puzzle_input = open('aoc2020_6_input.txt').read().strip()\n\ntest_input = '''abc\n\na\nb\nc\n\nab\nac\n\na\na\na\na\n\nb'''\n\ndef first(text):\n groups = text.split('\\n\\n')\n all_answers = 0\n for group in groups:\n group = ''.join(group.split())\n answers = []\n for answer in group:\n if answer not in answers:\n answers.append(answer)\n all_answers += len(answers)\n print(all_answers)\n\ndef second(text):\n groups = text.split('\\n\\n')\n all_answers = 0\n for group in groups:\n people = len(group.split('\\n'))\n group = ''.join(group.split())\n answers = {}\n for answer in group:\n if answer not in answers:\n answers[answer] = 1\n else:\n answers[answer] += 1\n for key in answers:\n if answers[key] == people:\n all_answers += 1\n print(all_answers)\n\nfirst(test_input)\nfirst(puzzle_input)\nsecond(test_input)\nsecond(puzzle_input)","repo_name":"ladymarengo/advent-of-code","sub_path":"2020/aoc2020_6.py","file_name":"aoc2020_6.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"43728783862","text":"from point import Point\nfrom path_interface import PathInterface\n\n\"\"\"\nExtensible image processing and Etch-a-sketch drawing program\nCopyright (C) 2014 Oliver Hickman\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see .\n\"\"\"\n\nclass EdgeDetectDONTUSE(PathInterface):\n \"\"\" As of 2014-01-05 this path generator doesn't do anything. Sorry.\"\"\"\n # from scipy import ndimage\n # import numpy as np\n def __init__(self, image):\n # self._source = source \n # img = plt.imread(self._source)\n # image = np.flipud(image)\n self.image = image\n self.height = len(iamge[1])\n self.width = len(image)\n self.path = []\n # what did I put in Megan's text? Grab that stuff!\n # now do all that fancy edge detection stuff here.\n\n image = image[...,2] # Grab only one chanel?\n image = ndimage.gaussian_filter(image, sigma=10) #sigma fn of img size\n image = (image > image.mean()).astype(np.float) # threshold mask at\n image = ndimage.sobel(image, axis=0, mode='constant') # edge-detection\n\n\nclass NullPath(PathInterface):\n def __init__(self, image):\n self.width = \"0\"\n self.height = \"0\"\n self.path = []\n\n\nclass TinyTestPath(PathInterface):\n \"\"\" Tiny path handy for doctest examples.\n [(0, 0), (12, 18), (24, 9), (0, 0)]\n \"\"\"\n def __init__(self, image):\n self.width = 24\n self.height = 18\n self.path = [Point(0,0),\n Point(12, 18),\n Point(24, 9),\n Point(0,0)]\n\n\nclass ShortTestPath(PathInterface):\n \"\"\" Short path handy for testing code. Includes Points initialized\n with negative values, non-ints, vertical lines, horizontal lines, lines\n with zero length, etc.\n \"\"\"\n def __init__(self, image):\n self.width = 100\n self.height = 100\n self.path = [Point(0,0),\n Point(20,20),\n Point(20,100), # Vertical line up\n Point(100,100), # Horizontal line right\n Point(120,120), # Point outside height, width\n Point(100,100),\n Point(20,100), # Horizontal line left\n Point(20,20), # Vertical line down\n Point(60,60), # Positive slope up\n Point(100,20), # Negative slope down\n Point(100,20), # Line of zero length\n Point(60,60), # Negative slope up\n Point(20,20), # Positive slope down\n Point(80,20),\n Point(50,-30), # Point with negative element\n Point(20,20.1234), # Point with non int num\n Point(\"cow\", 20), # Point with invalid value\n Point(0,20),\n Point(0,0)]\n\nclass HelloWorld( PathInterface ):\n \"\"\" This path is quick and dirty - I wrote it quickly so that I'd have a \n path to play with, don't judge.\"\"\"\n def __init__(self, image):\n # for this path image is not used.\n self.width = 980\n self.height = 230\n self.path = [Point(0,0), #H\n Point(0,220),\n Point(0,110),\n Point(90,110),\n Point(90,220),\n Point(90,0),\n Point(215,0), #e\n Point(215,30),\n Point(180,0),\n Point(145,25),\n Point(130,90),\n Point(145,145),\n Point(180,170),\n Point(210,145),\n Point(215,90),\n Point(130,90),\n Point(145,25),\n Point(180,0),\n Point(250,0), #l\n Point(250,230),\n Point(250,0),\n Point(300,0), #l\n Point(300,230),\n Point(300,0),\n Point(380,0), #o\n Point(350,25),\n Point(340,90),\n Point(350,145),\n Point(380,170),\n Point(410,145),\n Point(420,90),\n Point(410,25),\n Point(380,0),\n Point(545,0), #W\n Point(510,220),\n Point(545,0),\n Point(580,220),\n Point(620,0),\n Point(655,220),\n Point(620,0),\n Point(715,0), #o\n Point(685,25),\n Point(675,90),\n Point(685,145),\n Point(715,170),\n Point(745,145),\n Point(755,90),\n Point(745,25),\n Point(715,0),\n Point(790,0), #r\n Point(790,170),\n Point(790,140),\n Point(820,155),\n Point(820,160),\n Point(820,155),\n Point(790,140),\n Point(790,0),\n Point(870,0), #l\n Point(870,230),\n Point(870,0),\n Point(980,0), #d\n Point(980,230),\n Point(980,130),\n Point(970,145),\n Point(940,170),\n Point(910,145),\n Point(900,90),\n Point(910,25),\n Point(940,0),\n Point(970,25),\n Point(980,40),\n Point(980,0),\n Point(0,0)]\n\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"ohickman/etch-a-sketch","sub_path":"render_strategy.py","file_name":"render_strategy.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10560013324","text":"from math import isclose\nimport pandas as pd\nfrom ..finance.mtgprice import mtgprice\nfrom ..finance.mtgyield import mtgyield\nfrom ..use import use\nfrom .._quietly import quietly\nfrom .._dataset import current\nfrom ..drop import drop\n\nloan_df = {\n \"beyield\": {0: 6, 1: 7},\n \"coupon\": {0: 5, 1: 5},\n \"cpr\": {0: 15, 1: 15},\n \"age\": {0: 0, 1: 0},\n \"origfixedterm\": {0: 360, 1: 360},\n \"origterm\": {0: 360, 1: 360},\n \"servicing_fee\": {0: 0, 1: 0},\n}\n\n\ndef test_mtg_price_yield():\n with quietly():\n use(pd.DataFrame(loan_df))\n yield_series = current.df.beyield.copy()\n mtgprice()\n drop(\"beyield\")\n assert \"beyield\" not in current.df.columns\n mtgyield()\n yield_series2 = current.df.beyield.copy()\n assert isclose(yield_series[0], yield_series2[0], abs_tol=0.000001)\n assert isclose(yield_series[1], yield_series2[1], abs_tol=0.000001)\n","repo_name":"pandichef/pdexplorer","sub_path":"pdexplorer/tests/test_mtg_price_yield.py","file_name":"test_mtg_price_yield.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"27290495137","text":"'''\nhttps://www.reddit.com/r/dailyprogrammer/comments/4n6hc2/20160608_challenge_270_intermediate_generating/\n'''\n\nimport sys, collections, random\nfrom pprint import pprint\nprint(\"Starting...\")\n\n# prefix length\nn = 2\n\nuserInput = \"\".join(sys.stdin.readlines()).strip().replace('\\n', '')\nwords = userInput.split(' ')\nlast_word = len(words) - 1\n\nfreqTable = collections.defaultdict(list)\nfreqTable[(\"\", \"\")].append((words[0], 1))\nfreqTable[(\"\", words[0])].append((words[1], 1))\nfreqTable[(words[-2], words[-1])].append((\"\", 1))\n\nfor i in range(len(words) - 1):\n\tif i + 1 == last_word:\n\t\tbreak\n\telse:\n\t\ttmp_list = freqTable[(words[i], words[i+1])]\n\t\tfor index, elem in enumerate(tmp_list):\n\t\t\tif words[i+2] == elem[0]:\n\t\t\t\ttmp_list.append((words[i+2], elem[1] + 1))\n\t\t\t\tdel tmp_list[index]\n\t\t\t\tbreak\n\t\telse:\n\t\t\tfreqTable[(words[i], words[i+1])].append((words[i+2], 1))\n\t\npprint(freqTable)\nprint()\n\nprefix = (\"\", \"\")\nsuffix = freqTable[prefix][0]\nwhile suffix[0] != \"\":\n\tprint(suffix[0], \"\", end='')\n\tprefix = (prefix[1], suffix[0])\n\tsuffix = random.choice(freqTable[prefix])\nprint()\n","repo_name":"christarazi/dailyprogrammer","sub_path":"270Intermediate/270_inter.py","file_name":"270_inter.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26626027477","text":"import csv\nimport sys\nimport traceback\nimport logging\nimport json\nimport os\nfrom typing import Optional, Set, Union\nfrom pathlib import Path\nfrom fnmatch import fnmatch\n\nfrom ..database import PickledDataBase, DataBase\nfrom .. import ostools\nfrom ..vunit_cli import VUnitCLI\nfrom ..sim_if.factory import SIMULATOR_FACTORY\nfrom ..sim_if import SimulatorInterface\nfrom ..color_printer import COLOR_PRINTER, NO_COLOR_PRINTER\n\nfrom ..project import Project\nfrom ..exceptions import CompileError\nfrom ..location_preprocessor import LocationPreprocessor\nfrom ..check_preprocessor import CheckPreprocessor\nfrom ..parsing.encodings import HDL_FILE_ENCODING\nfrom ..builtins import Builtins\nfrom ..vhdl_standard import VHDL, VHDLStandard\nfrom ..test.bench_list import TestBenchList\nfrom ..test.report import TestReport\nfrom ..test.runner import TestRunner\n\nfrom .common import LOGGER, TEST_OUTPUT_PATH, select_vhdl_standard, check_not_empty\nfrom .source import SourceFile, SourceFileList\nfrom .library import Library, LibraryList\nfrom .results import Results\n\n\nclass VUnit(object): # pylint: disable=too-many-instance-attributes, too-many-public-methods\n \"\"\"\n The public interface of VUnit\n\n :example:\n\n .. code-block:: python\n\n from vunit import VUnit\n \"\"\"\n\n @classmethod\n def from_argv(\n cls,\n argv=None,\n vhdl_standard: Optional[str] = None,\n ):\n \"\"\"\n Create VUnit instance from command line arguments.\n\n :param argv: Use explicit argv instead of actual command line argument\n :param vhdl_standard: The VHDL standard used to compile files,\n if None the VUNIT_VHDL_STANDARD environment variable is used\n :returns: A :class:`.VUnit` object instance\n\n :example:\n\n .. code-block:: python\n\n from vunit import VUnit\n prj = VUnit.from_argv()\n prj.add_vhdl_builtins()\n\n .. IMPORTANT::\n As of VUnit v5, option ``compile_builtins`` is removed.\n VHDL users need to call method :meth:`add_vhdl_builtins` explicitly in order to preserve the\n functionality.\n See :vunit_issue:`777`.\n \"\"\"\n args = VUnitCLI().parse_args(argv=argv)\n return cls.from_args(args, vhdl_standard=vhdl_standard)\n\n @classmethod\n def from_args(\n cls,\n args,\n vhdl_standard: Optional[str] = None,\n ):\n \"\"\"\n Create VUnit instance from args namespace.\n Intended for users who adds custom command line options.\n See :class:`vunit.vunit_cli.VUnitCLI` class to learn about\n adding custom command line options.\n\n :param args: The parsed argument namespace object\n :param vhdl_standard: The VHDL standard used to compile files,\n if None the VUNIT_VHDL_STANDARD environment variable is used\n :returns: A :class:`.VUnit` object instance\n\n .. IMPORTANT::\n As of VUnit v5, option ``compile_builtins`` is removed.\n VHDL users need to call method :meth:`add_vhdl_builtins` explicitly in order to preserve the\n functionality.\n See :vunit_issue:`777`.\n \"\"\"\n return cls(args, vhdl_standard=vhdl_standard)\n\n def __init__(\n self,\n args,\n vhdl_standard: Optional[str] = None,\n ):\n self._args = args\n self._configure_logging(args.log_level)\n self._output_path = str(Path(args.output_path).resolve())\n\n if args.no_color:\n self._printer = NO_COLOR_PRINTER\n else:\n self._printer = COLOR_PRINTER\n\n def test_filter(name, attribute_names):\n keep = any(fnmatch(name, pattern) for pattern in args.test_patterns)\n\n if args.with_attributes is not None:\n keep = keep and set(args.with_attributes).issubset(attribute_names)\n\n if args.without_attributes is not None:\n keep = keep and set(args.without_attributes).isdisjoint(attribute_names)\n return keep\n\n self._test_filter = test_filter\n self._vhdl_standard: VHDLStandard = select_vhdl_standard(vhdl_standard)\n\n self._preprocessors = [] # type: ignore\n\n self._simulator_class = SIMULATOR_FACTORY.select_simulator()\n\n # Use default simulator options if no simulator was present\n if self._simulator_class is None:\n simulator_class = SimulatorInterface\n self._simulator_output_path = str(Path(self._output_path) / \"none\")\n else:\n simulator_class = self._simulator_class\n self._simulator_output_path = str(Path(self._output_path) / simulator_class.name)\n\n self._create_output_path(args.clean)\n\n database = self._create_database()\n self._project = Project(\n database=database,\n depend_on_package_body=simulator_class.package_users_depend_on_bodies,\n )\n\n self._test_bench_list = TestBenchList(database=database)\n\n self._builtins = Builtins(self, self._vhdl_standard, simulator_class)\n\n def _create_database(self):\n \"\"\"\n Create a persistent database to store expensive parse results\n\n Check for Python version used to create the database is the\n same as the running python instance or re-create\n \"\"\"\n project_database_file_name = str(Path(self._output_path) / \"project_database\")\n create_new = False\n key = b\"version\"\n version = str((9, sys.version)).encode()\n database = None\n try:\n database = DataBase(project_database_file_name)\n create_new = (key not in database) or (database[key] != version)\n except KeyboardInterrupt as exk:\n raise KeyboardInterrupt from exk\n except: # pylint: disable=bare-except\n traceback.print_exc()\n create_new = True\n\n if create_new:\n database = DataBase(project_database_file_name, new=True)\n database[key] = version\n\n return PickledDataBase(database)\n\n @staticmethod\n def _configure_logging(log_level):\n \"\"\"\n Configure logging based on log_level string\n \"\"\"\n level = getattr(logging, log_level.upper())\n logging.basicConfig(filename=None, format=\"%(levelname)7s - %(message)s\", level=level)\n\n def _which_vhdl_standard(self, vhdl_standard: Optional[str]) -> VHDLStandard:\n \"\"\"\n Return default vhdl_standard if the argument is None\n The argument is a string from the user\n \"\"\"\n if vhdl_standard is None:\n return self._vhdl_standard\n\n return VHDL.standard(vhdl_standard)\n\n def add_external_library(self, library_name, path: Union[str, Path], vhdl_standard: Optional[str] = None):\n \"\"\"\n Add an externally compiled library as a black-box\n\n :param library_name: The name of the external library\n :param path: The path to the external library directory\n :param vhdl_standard: The VHDL standard used to compile files,\n if None the VUNIT_VHDL_STANDARD environment variable is used\n :returns: The created :class:`.Library` object\n\n :example:\n\n .. code-block:: python\n\n prj.add_external_library(\"unisim\", \"path/to/unisim/\")\n\n \"\"\"\n\n self._project.add_library(\n library_name,\n Path(path).resolve(),\n self._which_vhdl_standard(vhdl_standard),\n is_external=True,\n )\n return self.library(library_name)\n\n def add_source_files_from_csv(self, project_csv_path: Union[str, Path], vhdl_standard: Optional[str] = None):\n \"\"\"\n Add a project configuration, mapping all the libraries and files\n\n :param project_csv_path: path to csv project specification, each line contains the name\n of the library and the path to one file 'lib_name,filename'\n note that all filenames are relative to the parent folder of the\n csv file\n :param vhdl_standard: The VHDL standard used to compile files,\n if None, the VUNIT_VHDL_STANDARD environment variable is used\n :returns: A list of files (:class:`.SourceFileList`) that were added\n\n \"\"\"\n libs: Set[str] = set()\n files = SourceFileList([])\n\n ppath = Path(project_csv_path)\n\n with ppath.open(\"r\", encoding=\"utf-8\") as csv_path_file:\n for row in csv.reader(csv_path_file):\n if len(row) == 2:\n lib_name = row[0].strip()\n no_normalized_file = row[1].strip()\n file_name_ = str((ppath.parent / no_normalized_file).resolve())\n lib = self.library(lib_name) if lib_name in libs else self.add_library(lib_name)\n libs.add(lib_name)\n file_ = lib.add_source_file(file_name_, vhdl_standard=vhdl_standard)\n files.append(file_)\n elif len(row) > 2:\n LOGGER.error(\"More than one library and one file in csv description\")\n return files\n\n def add_library(\n self,\n library_name: str,\n vhdl_standard: Optional[str] = None,\n allow_duplicate: Optional[bool] = False,\n ):\n \"\"\"\n Add a library managed by VUnit.\n\n :param library_name: The name of the library\n :param vhdl_standard: The VHDL standard used to compile files,\n if None the VUNIT_VHDL_STANDARD environment variable is used\n :param allow_duplicate: Set to True to allow the same library\n to be added multiple times. Subsequent additions will just\n return the previously created library.\n :returns: The created :class:`.Library` object\n\n :example:\n\n .. code-block:: python\n\n library = prj.add_library(\"lib\")\n\n \"\"\"\n standard = self._which_vhdl_standard(vhdl_standard)\n path = Path(self._simulator_output_path) / \"libraries\" / library_name\n if not self._project.has_library(library_name):\n self._project.add_library(library_name, str(path.resolve()), standard)\n elif not allow_duplicate:\n raise ValueError(f\"Library {library_name!s} already added. Use allow_duplicate to ignore this error.\")\n return self.library(library_name)\n\n def library(self, library_name: str):\n \"\"\"\n Get a library\n\n :param library_name: The name of the library\n :returns: A :class:`.Library` object\n \"\"\"\n if not self._project.has_library(library_name):\n raise KeyError(library_name)\n return Library(library_name, self, self._project, self._test_bench_list)\n\n def get_libraries(\n self,\n pattern=\"*\",\n allow_empty: Optional[bool] = False,\n ):\n \"\"\"\n Get a list of libraries\n\n :param pattern: A wildcard pattern matching the library name\n :param allow_empty: To disable an error if no labraries matched the pattern\n :returns: A :class:`.LibraryList` object\n \"\"\"\n results = []\n\n for library in self._project.get_libraries():\n if not fnmatch(library.name, pattern):\n continue\n\n results.append(self.library(library.name))\n\n check_not_empty(results, allow_empty, f\"Pattern {pattern} did not match any library\")\n\n return LibraryList(results)\n\n def set_attribute(self, name: str, value: str, allow_empty: Optional[bool] = False):\n \"\"\"\n Set a value of attribute in all |configurations|\n\n :param name: The name of the attribute\n :param value: The value of the attribute\n :param allow_empty: To disable an error when no test benches were found\n\n :example:\n\n .. code-block:: python\n\n prj.set_attribute(\".foo\", \"bar\")\n\n .. note::\n Only affects test benches added *before* the attribute is set.\n \"\"\"\n test_benches = self._test_bench_list.get_test_benches()\n for test_bench in check_not_empty(test_benches, allow_empty, \"No test benches found\"):\n test_bench.set_attribute(name, value)\n\n def set_generic(self, name: str, value: str, allow_empty: Optional[bool] = False):\n \"\"\"\n Set a value of generic in all |configurations|\n\n :param name: The name of the generic\n :param value: The value of the generic\n :param allow_empty: To disable an error when no test benches were found\n\n :example:\n\n .. code-block:: python\n\n prj.set_generic(\"data_width\", 16)\n\n .. note::\n Only affects test benches added *before* the generic is set.\n \"\"\"\n test_benches = self._test_bench_list.get_test_benches()\n for test_bench in check_not_empty(test_benches, allow_empty, \"No test benches found\"):\n test_bench.set_generic(name.lower(), value)\n\n def set_parameter(self, name: str, value: str, allow_empty: Optional[bool] = False):\n \"\"\"\n Set value of parameter in all |configurations|\n\n :param name: The name of the parameter\n :param value: The value of the parameter\n :param allow_empty: To disable an error when no test benches were found\n\n :example:\n\n .. code-block:: python\n\n prj.set_parameter(\"data_width\", 16)\n\n .. note::\n Only affects test benches added *before* the parameter is set.\n \"\"\"\n test_benches = self._test_bench_list.get_test_benches()\n for test_bench in check_not_empty(test_benches, allow_empty, \"No test benches found\"):\n test_bench.set_generic(name, value)\n\n def set_sim_option(\n self,\n name: str,\n value: str,\n allow_empty: Optional[bool] = False,\n overwrite: Optional[bool] = True,\n ):\n \"\"\"\n Set simulation option in all |configurations|\n\n :param name: |simulation_options|\n :param value: The value of the simulation option\n :param allow_empty: To disable an error when no test benches were found\n :param overwrite: To overwrite the option or append to the existing value\n\n :example:\n\n .. code-block:: python\n\n prj.set_sim_option(\"ghdl.a_flags\", [\"--no-vital-checks\"])\n\n .. note::\n Only affects test benches added *before* the option is set.\n \"\"\"\n test_benches = self._test_bench_list.get_test_benches()\n for test_bench in check_not_empty(test_benches, allow_empty, \"No test benches found\"):\n test_bench.set_sim_option(name, value, overwrite)\n\n def set_compile_option(self, name: str, value: str, allow_empty: Optional[bool] = False):\n \"\"\"\n Set compile option of all files\n\n :param name: |compile_option|\n :param value: The value of the compile option\n :param allow_empty: To disable an error when no source files were found\n\n :example:\n\n .. code-block:: python\n\n prj.set_compile_option(\"ghdl.a_flags\", [\"--no-vital-checks\"])\n\n\n .. note::\n Only affects files added *before* the option is set.\n \"\"\"\n source_files = self._project.get_source_files_in_order()\n for source_file in check_not_empty(source_files, allow_empty, \"No source files found\"):\n source_file.set_compile_option(name, value)\n\n def add_compile_option(self, name: str, value: str, allow_empty: Optional[bool] = False):\n \"\"\"\n Add compile option to all files\n\n :param name: |compile_option|\n :param value: The value of the compile option\n :param allow_empty: To disable an error when no source files were found\n\n .. note::\n Only affects files added *before* the option is set.\n \"\"\"\n source_files = self._project.get_source_files_in_order()\n for source_file in check_not_empty(source_files, allow_empty, \"No source files found\"):\n source_file.add_compile_option(name, value)\n\n def get_source_file(self, file_name: Union[str, Path], library_name: Optional[str] = None):\n \"\"\"\n Get a source file\n\n :param file_name: The name of the file as a relative or absolute path\n :param library_name: The name of a specific library to search if not all libraries\n :returns: A :class:`.SourceFile` object\n \"\"\"\n\n fstr = str(file_name)\n\n files = self.get_source_files(fstr, library_name, allow_empty=True)\n if len(files) > 1:\n raise ValueError(f\"Found file named '{fstr!s}' in multiple-libraries, \" \"add explicit library_name.\")\n if not files:\n if library_name is None:\n raise ValueError(f\"Found no file named '{fstr!s}'\")\n\n raise ValueError(f\"Found no file named '{fstr!s}' in library '{library_name!s}'\")\n return files[0]\n\n def get_source_files(\n self,\n pattern=\"*\",\n library_name: Optional[str] = None,\n allow_empty: Optional[bool] = False,\n ):\n \"\"\"\n Get a list of source files\n\n :param pattern: A wildcard pattern matching either an absolute or relative path\n :param library_name: The name of a specific library to search if not all libraries\n :param allow_empty: To disable an error if no files matched the pattern\n :returns: A :class:`.SourceFileList` object\n \"\"\"\n results = []\n for source_file in self._project.get_source_files_in_order():\n if library_name is not None:\n if source_file.library.name != library_name:\n continue\n\n if not (\n fnmatch(str(Path(source_file.name).resolve()), pattern)\n or fnmatch(ostools.simplify_path(source_file.name), pattern)\n ):\n continue\n\n results.append(SourceFile(source_file, self._project, self))\n\n check_not_empty(\n results,\n allow_empty,\n f\"Pattern {pattern!r} did not match any file\"\n + (f\"within library {library_name!s}\" if library_name is not None else \"\"),\n )\n\n return SourceFileList(results)\n\n def add_source_files( # pylint: disable=too-many-arguments\n self,\n pattern,\n library_name: str,\n preprocessors=None,\n include_dirs=None,\n defines=None,\n allow_empty: Optional[bool] = False,\n vhdl_standard: Optional[str] = None,\n no_parse: Optional[bool] = False,\n file_type=None,\n ):\n \"\"\"\n Add source files matching wildcard pattern to library\n\n :param pattern: A wildcard pattern matching the files to add or a list of files\n :param library_name: The name of the library to add files into\n :param include_dirs: A list of include directories\n :param defines: A dictionary containing Verilog defines to be set\n :param allow_empty: To disable an error if no files matched the pattern\n :param vhdl_standard: The VHDL standard used to compile files,\n if None VUNIT_VHDL_STANDARD environment variable is used\n :param no_parse: Do not parse file(s) for dependency or test scanning purposes\n :param file_type: The type of the file; ``\"vhdl\"``, ``\"verilog\"`` or ``\"systemverilog\"``.\n Auto-detected by default when set to ``None``.\n :returns: A list of files (:class:`.SourceFileList`) which were added\n\n :example:\n\n .. code-block:: python\n\n prj.add_source_files(\"*.vhd\", \"lib\")\n\n \"\"\"\n return self.library(library_name).add_source_files(\n pattern=pattern,\n preprocessors=preprocessors,\n include_dirs=include_dirs,\n defines=defines,\n allow_empty=allow_empty,\n vhdl_standard=vhdl_standard,\n no_parse=no_parse,\n file_type=file_type,\n )\n\n def add_source_file( # pylint: disable=too-many-arguments\n self,\n file_name: Union[str, Path],\n library_name: str,\n preprocessors=None,\n include_dirs=None,\n defines=None,\n vhdl_standard: Optional[str] = None,\n no_parse: Optional[bool] = False,\n file_type=None,\n ):\n \"\"\"\n Add source file to library\n\n :param file_name: The name of the file\n :param library_name: The name of the library to add the file into\n :param include_dirs: A list of include directories\n :param defines: A dictionary containing Verilog defines to be set\n :param vhdl_standard: The VHDL standard used to compile this file,\n if None VUNIT_VHDL_STANDARD environment variable is used\n :param no_parse: Do not parse file for dependency or test scanning purposes\n :param file_type: The type of the file; ``\"vhdl\"``, ``\"verilog\"`` or ``\"systemverilog\"``.\n Auto-detected by default when set to ``None``.\n :returns: The :class:`.SourceFile` which was added\n\n :example:\n\n .. code-block:: python\n\n prj.add_source_file(\"file.vhd\", \"lib\")\n\n \"\"\"\n return self.library(library_name).add_source_file(\n file_name=str(file_name),\n preprocessors=preprocessors,\n include_dirs=include_dirs,\n defines=defines,\n vhdl_standard=vhdl_standard,\n no_parse=no_parse,\n file_type=file_type,\n )\n\n def _preprocess(self, library_name: str, file_name: Union[str, Path], preprocessors):\n \"\"\"\n Preprocess file_name within library_name using explicit preprocessors\n if preprocessors is None then use implicit globally defined preprocessors.\n \"\"\"\n # @TODO dependency checking etc...\n\n if preprocessors is None:\n preprocessors = self._preprocessors\n\n fstr = str(file_name)\n\n if not preprocessors:\n return fstr\n\n preprocessors.sort(key=lambda x: 0 if not hasattr(x, \"order\") else x.order)\n\n fname = str(Path(file_name).name)\n\n try:\n code = ostools.read_file(file_name, encoding=HDL_FILE_ENCODING)\n for preprocessor in preprocessors:\n code = preprocessor.run(code, fname)\n except KeyboardInterrupt as exk:\n raise KeyboardInterrupt from exk\n except: # pylint: disable=bare-except\n traceback.print_exc()\n LOGGER.error(\"Failed to preprocess %s\", fstr)\n return fstr\n else:\n pp_file_name = str(Path(self._preprocessed_path) / library_name / fname)\n\n idx = 1\n while ostools.file_exists(pp_file_name):\n LOGGER.debug(\"Preprocessed file exists '%s', adding prefix\", pp_file_name)\n pp_file_name = str(\n Path(self._preprocessed_path) / library_name / f\"{idx}_{fname!s}\",\n )\n idx += 1\n\n ostools.write_file(pp_file_name, code, encoding=HDL_FILE_ENCODING)\n return pp_file_name\n\n def add_preprocessor(self, preprocessor):\n \"\"\"\n Adds a custom preprocessor to be used on all files. Must be called before adding any files.\n\n :param preprocessor: Instance of of :class:`.Preprocessor`\n \"\"\"\n self._preprocessors.append((preprocessor))\n\n def enable_location_preprocessing(self, additional_subprograms=None, exclude_subprograms=None, order=100):\n \"\"\"\n Inserts file name and line number information into VUnit check and log subprograms calls. Custom\n subprograms can also be added. Must be called before adding any files.\n\n :param additional_subprograms: List of custom subprograms to add the line_num and file_name parameters to.\n :param exclude_subprograms: List of VUnit subprograms to exclude from location preprocessing. Used to \\\navoid location preprocessing of other functions sharing name with a VUnit log or check subprogram.\n :param order: Integer controlling in which order the location preprocessor is applied in relation to \\\nother preprocessors. Lowest value first. The order between preprocessors with the same value is undefined.\n\n :example:\n\n .. code-block:: python\n\n prj.enable_location_preprocessing(additional_subprograms=['my_check'],\n exclude_subprograms=['log'])\n\n \"\"\"\n preprocessor = LocationPreprocessor(order)\n if additional_subprograms is not None:\n for subprogram in additional_subprograms:\n preprocessor.add_subprogram(subprogram)\n\n if exclude_subprograms is not None:\n for subprogram in exclude_subprograms:\n preprocessor.remove_subprogram(subprogram)\n\n self.add_preprocessor(preprocessor)\n\n def enable_check_preprocessing(self, order=200):\n \"\"\"\n Inserts error context information into VUnit check_relation calls.\n\n :param order: Integer controlling in which order the check preprocessor is applied in relation to \\\nother preprocessors. Lowest value first. The order between preprocessors with the same value is undefined.\n\n \"\"\"\n self.add_preprocessor(CheckPreprocessor(order))\n\n def main(self, post_run=None):\n \"\"\"\n Run vunit main function and exit\n\n :param post_run: A callback function which is called after\n running tests. The function must accept a single `results`\n argument which is an instance of :class:`.Results`\n \"\"\"\n try:\n all_ok = self._main(post_run)\n except KeyboardInterrupt:\n sys.exit(1)\n except CompileError:\n sys.exit(1)\n except SystemExit:\n sys.exit(1)\n except: # pylint: disable=bare-except\n if self._args.dont_catch_exceptions:\n raise\n traceback.print_exc()\n sys.exit(1)\n\n if (not all_ok) and (not self._args.exit_0):\n sys.exit(1)\n\n sys.exit(0)\n\n def _create_tests(self, simulator_if: Union[None, SimulatorInterface]):\n \"\"\"\n Create the test cases\n \"\"\"\n self._test_bench_list.warn_when_empty()\n test_list = self._test_bench_list.create_tests(simulator_if, self._args.elaborate)\n test_list.keep_matches(self._test_filter)\n return test_list\n\n def _main(self, post_run):\n \"\"\"\n Base vunit main function without performing exit\n \"\"\"\n\n if self._args.export_json is not None:\n return self._main_export_json(self._args.export_json)\n\n if self._args.list:\n return self._main_list_only()\n\n if self._args.files:\n return self._main_list_files_only()\n\n if self._args.compile:\n return self._main_compile_only()\n\n all_ok = self._main_run(post_run)\n return all_ok\n\n def _create_simulator_if(self):\n \"\"\"\n Create new simulator instance\n \"\"\"\n\n if self._simulator_class is None:\n LOGGER.error(\n \"No available simulator detected.\\n\"\n \"Simulator binary folder must be available in PATH environment variable.\\n\"\n \"Simulator binary folder can also be set the in VUNIT__PATH environment variable.\\n\"\n )\n sys.exit(1)\n\n if not Path(self._simulator_output_path).exists():\n os.makedirs(self._simulator_output_path)\n\n return self._simulator_class.from_args(args=self._args, output_path=self._simulator_output_path)\n\n def _main_run(self, post_run):\n \"\"\"\n Main with running tests\n \"\"\"\n simulator_if = self._create_simulator_if()\n test_list = self._create_tests(simulator_if)\n self._compile(simulator_if)\n print()\n\n start_time = ostools.get_time()\n report = TestReport(printer=self._printer)\n\n try:\n self._run_test(test_list, report)\n except KeyboardInterrupt:\n print()\n LOGGER.debug(\"_main: Caught Ctrl-C shutting down\")\n finally:\n del test_list\n\n report.set_real_total_time(ostools.get_time() - start_time)\n report.print_str()\n\n if post_run is not None:\n post_run(results=Results(self._output_path, simulator_if, report))\n\n del simulator_if\n\n if self._args.xunit_xml is not None:\n xml = report.to_junit_xml_str(self._args.xunit_xml_format)\n ostools.write_file(self._args.xunit_xml, xml)\n\n return report.all_ok()\n\n def _main_list_only(self):\n \"\"\"\n Main function when only listing test cases\n \"\"\"\n test_list = self._create_tests(simulator_if=None)\n for test_name in test_list.test_names:\n print(test_name)\n print(f\"Listed {test_list.num_tests} tests\")\n return True\n\n def _main_export_json(self, json_file_name: Union[str, Path]): # pylint: disable=too-many-locals\n \"\"\"\n Main function when exporting to JSON\n \"\"\"\n\n file_objects = self.get_compile_order()\n files = []\n for source_file in file_objects:\n files.append(\n {\n \"file_name\": str(Path(source_file.name).resolve()),\n \"library_name\": source_file.library.name,\n }\n )\n\n tests = []\n for test_suite in self._create_tests(simulator_if=None):\n test_information = test_suite.test_information\n test_configuration = test_suite.test_configuration\n for name in test_suite.test_names:\n info = test_information[name]\n config = test_configuration[name]\n\n attributes = {}\n for attr in info.attributes:\n attributes[attr.name] = attr.value\n\n attributes.update(config.attributes)\n\n tests.append(\n {\n \"name\": name,\n \"location\": {\n \"file_name\": str(info.location.file_name),\n \"offset\": info.location.offset,\n \"length\": info.location.length,\n },\n \"attributes\": attributes,\n }\n )\n\n json_data = {\n # The semantic version (https://semver.org/) of the JSON export data format\n \"export_format_version\": {\"major\": 1, \"minor\": 0, \"patch\": 0},\n # The set of files added to the project\n \"files\": files,\n # The list of all tests\n \"tests\": tests,\n }\n\n with Path(json_file_name).open(\"w\", encoding=\"utf-8\") as fptr:\n json.dump(json_data, fptr, sort_keys=True, indent=4, separators=(\",\", \": \"))\n\n return True\n\n def _main_list_files_only(self):\n \"\"\"\n Main function when only listing files\n \"\"\"\n files = self.get_compile_order()\n for source_file in files:\n print(f\"{source_file.library.name!s}, {source_file.name!s}\")\n print(f\"Listed {len(files)} files\")\n return True\n\n def _main_compile_only(self):\n \"\"\"\n Main function when only compiling\n \"\"\"\n simulator_if = self._create_simulator_if()\n self._compile(simulator_if)\n return True\n\n def _create_output_path(self, clean: bool):\n \"\"\"\n Create or re-create the output path if necessary\n \"\"\"\n if clean:\n ostools.renew_path(self._output_path)\n elif not Path(self._output_path).exists():\n os.makedirs(self._output_path)\n\n ostools.renew_path(self._preprocessed_path)\n\n @property\n def vhdl_standard(self) -> str:\n return str(self._vhdl_standard)\n\n @property\n def _preprocessed_path(self):\n return str(Path(self._output_path) / \"preprocessed\")\n\n @property\n def codecs_path(self):\n return str(Path(self._output_path) / \"codecs\")\n\n def _compile(self, simulator_if: SimulatorInterface):\n \"\"\"\n Compile entire project\n \"\"\"\n # get test benches\n if self._args.minimal:\n target_files = self._get_testbench_files(simulator_if)\n else:\n target_files = None\n\n simulator_if.compile_project(\n self._project,\n continue_on_error=self._args.keep_compiling,\n printer=self._printer,\n target_files=target_files,\n )\n\n def _get_testbench_files(self, simulator_if: Union[None, SimulatorInterface]):\n \"\"\"\n Return the list of all test bench files for the currently selected tests to run\n \"\"\"\n test_list = self._create_tests(simulator_if)\n tb_file_names = {test_suite.file_name for test_suite in test_list}\n return [\n self.get_source_file(file_name)._source_file # pylint: disable=protected-access\n for file_name in tb_file_names\n ]\n\n def _run_test(self, test_cases, report):\n \"\"\"\n Run the test suites and return the report\n \"\"\"\n\n if self._args.verbose:\n verbosity = TestRunner.VERBOSITY_VERBOSE\n elif self._args.quiet:\n verbosity = TestRunner.VERBOSITY_QUIET\n else:\n verbosity = TestRunner.VERBOSITY_NORMAL\n\n runner = TestRunner(\n report,\n str(Path(self._output_path) / TEST_OUTPUT_PATH),\n verbosity=verbosity,\n num_threads=self._args.num_threads,\n fail_fast=self._args.fail_fast,\n dont_catch_exceptions=self._args.dont_catch_exceptions,\n no_color=self._args.no_color,\n )\n runner.run(test_cases)\n\n def add_verilog_builtins(self):\n \"\"\"\n Add VUnit Verilog builtin libraries.\n\n .. IMPORTANT::\n As of VUnit v5, class ``vunit.verilog`` is removed.\n Verilog users need to call this method explicitly in order to preserve the functionality.\n See :vunit_issue:`777`.\n \"\"\"\n self._builtins.add_verilog_builtins()\n\n def add_vhdl_builtins(self, external=None, use_external_log=None):\n \"\"\"\n Add VUnit VHDL builtin libraries.\n\n :param external: struct to provide bridges for the external VHDL API.\n :param use_external_log: path to external implementation of common_log_pkg-body to allow\n VUnit log messages to be redirected to another logging framework.\n\n :example:\n\n .. code-block:: python\n\n VU.add_vhdl_builtins(external={\n 'string': ['path/to/custom/file'],\n 'integer': ['path/to/custom/file']}\n )\n\n .. IMPORTANT::\n As of VUnit v5, option ``compile_builtins`` of methods :meth:`from_argv` and :meth:`from_args` is removed.\n VHDL users need to call this method explicitly in order to preserve the functionality.\n See :vunit_issue:`777`.\n \"\"\"\n self._builtins.add_vhdl_builtins(external=external, use_external_log=use_external_log)\n\n def add_com(self):\n \"\"\"\n Add communication package\n \"\"\"\n self._builtins.add(\"com\")\n\n def add_array_util(self):\n \"\"\"\n Add array util\n \"\"\"\n self._builtins.add(\"array_util\")\n\n def add_random(self):\n \"\"\"\n Add random\n \"\"\"\n self._builtins.add(\"random\")\n\n def add_verification_components(self):\n \"\"\"\n Add verification component library\n \"\"\"\n self._builtins.add(\"verification_components\")\n\n def add_osvvm(self):\n \"\"\"\n Add osvvm library\n \"\"\"\n self._builtins.add(\"osvvm\")\n\n def add_json4vhdl(self):\n \"\"\"\n Add JSON-for-VHDL library\n \"\"\"\n self._builtins.add(\"json4vhdl\")\n\n def get_compile_order(self, source_files=None):\n \"\"\"\n Get the compile order of all or specific source files and\n their dependencies.\n\n A dependency of file **A** in terms of compile order is any\n file **B** which **must** be successfully compiled before **A**\n can be successfully compiled.\n\n This is **not** the same as all files required to successfully elaborate **A**.\n For example using component instantiation in VHDL there is no\n compile order dependency but the component instance will not\n elaborate if there is no binding component.\n\n :param source_files: A list of :class:`.SourceFile` objects or `None` meaning all\n :returns: A list of :class:`.SourceFile` objects in compile order.\n \"\"\"\n if source_files is None:\n source_files = self.get_source_files(allow_empty=True)\n\n target_files = [source_file._source_file for source_file in source_files] # pylint: disable=protected-access\n source_files = self._project.get_dependencies_in_compile_order(target_files)\n return SourceFileList([SourceFile(source_file, self._project, self) for source_file in source_files])\n\n def get_implementation_subset(self, source_files):\n \"\"\"\n Get the subset of files which are required to successfully\n elaborate the list of input files without any missing\n dependencies.\n\n :param source_files: A list of :class:`.SourceFile` objects\n :returns: A list of :class:`.SourceFile` objects which is the implementation subset.\n \"\"\"\n target_files = [source_file._source_file for source_file in source_files] # pylint: disable=protected-access\n source_files = self._project.get_dependencies_in_compile_order(target_files, implementation_dependencies=True)\n return SourceFileList([SourceFile(source_file, self._project, self) for source_file in source_files])\n\n def get_simulator_name(self):\n \"\"\"\n Get the name of the simulator used.\n\n Will return None if no simulator was found.\n \"\"\"\n if self._simulator_class is None:\n return None\n return self._simulator_class.name\n\n def simulator_supports_coverage(self):\n \"\"\"\n Returns True when the simulator supports coverage\n\n Will return None if no simulator was found.\n \"\"\"\n if self._simulator_class is None:\n return None\n return self._simulator_class.supports_coverage()\n","repo_name":"VUnit/vunit","sub_path":"vunit/ui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":38555,"program_lang":"python","lang":"en","doc_type":"code","stars":651,"dataset":"github-code","pt":"52"} +{"seq_id":"35893238793","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pymongo\nimport re\n\nclass diseaseSpider3:\n\n def __init__(self):\n self.conn = pymongo.MongoClient('Localhost',27017)\n self.db = self.conn['medical']\n self.col = self.db['data6']\n\n\n def get_html(self,url):\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}\n html = requests.get(url,headers = headers)\n return html\n\n\n def get_allurl(self):\n print('begin url')\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}\n pages = []\n count = 0\n names = []\n for index in range(1, 217):\n all_url = 'https://www.wiki8.com/search?q=%E8%80%81%E5%B9%B4%E7%97%85&Page=' + str(index)\n html = requests.get(all_url, headers=headers)\n Soup = BeautifulSoup(html.text, 'lxml')\n for nums in range(1, 31):\n for disease in Soup.select('#content > ul.sResult > li:nth-child('+str(nums)+' )> a'):\n pages.append(disease['href'])\n names.append(disease.get_text())\n count+=1\n print(pages)\n print(names)\n print(count)\n return pages\n #\n # def getPageUrl(self,url):\n # html = self.get_html(url)\n # headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}\n # html = requests.get('https://www.wiki8.com/laoniandaixiexingjianzhongdu_161885/',headers = headers)\n # Soup = BeautifulSoup(html.text,'lxml')\n # ul = Soup.find('div',\"TableOfContents\").find('ul').findAll('a')\n # names = []\n # hrefs = []\n # for u in ul:\n # print(u)\n # names.append(u.get_text())\n # hrefs.append(u['href'])\n # urls = {}\n # for i in range(0,names.__len__()):\n # urls[names[i]] = hrefs[i]\n # # return urls\n # print(urls)\n\n def spider_main(self):\n print('begin')\n all_url = self.get_allurl()\n for u in all_url:\n try:\n data = self.data_spider(u)\n self.col.insert(data)\n except Exception as e:\n print(e, u)\n return\n\n\n def data_spider(self,url):\n # headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}\n # html = requests.get('https://www.wiki8.com/laoniandaixiexingjianzhongdu_161885/',headers = headers)\n html = self.get_html(url)\n soup = BeautifulSoup(html.text,'lxml')\n names = []\n for n in soup.find('div',id=\"content\").findAll('h2'):\n names.append(n.get_text())\n names.remove('目录')\n print(names)\n\n data = {}\n i=1\n content = soup.find('div',id=\"content\").get_text().split('目录')[1]\n content1 = content.split(str(names[0]))[2].replace('\\n','')\n data[names[0]] = content1.split(str(names[1]))[0]\n newcontent = str(names[0]).join(content1.split(str(names[1]))[1:])\n while i<(names.__len__()-1):\n\n if(names[i] == '21 相关药品'):\n infobox = []\n infobox = newcontent.split(str(names[i + 1]))[0].replace(' ', '').split('、')\n data[names[i]] = infobox\n\n elif (names[i] == '22 相关检查'):\n infobox = []\n infobox = newcontent.split(str(names[i + 1]))[0].replace(' ', '').split('、')\n data[names[i]] = infobox\n\n else:\n data[names[i]] = newcontent.split(str(names[i + 1]))[0].replace(' ', '')\n newcontent = str(names[i]).join(newcontent.split(str(names[i + 1]))[1:])\n i += 1\n\n # data.pop('相关文献')\n # data.pop('1 拼音')\n # data.pop('ICD号')\n print(data)\n print(names)\n print(newcontent)\n return data\n\na = diseaseSpider3()\na.spider_main()\n\n","repo_name":"358263986/baojianQA","sub_path":"spider/spider3.py","file_name":"spider3.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29248180389","text":"import torch\nimport math\nimport numpy as np\nfrom torch import tensor,where,zeros,mul,permute\nfrom torch.fft import fft2,fftshift,ifft2,ifftshift\nfrom math import *\nfrom utils import rizer_filters\nimport cv2\nimport operator\nfrom functools import reduce\ndef idx_num(x,y,size):\n result = x + size[0]*(y-1)\n return result\ndef find(arr):\n #寻找满足数组中等于数组最小元素值的第一个元素\n proc = np.where(arr == min(arr))\n result = proc[0][0]\n return result+1\ndef get_num(slice_idx,paths,i):\n #返回的结果当前离散线中每个点距所有离散线中哪条线最近\n result =[]\n arr = paths[0,i]\n arr = arr.astype(int)\n for i in range(0,len(arr)):\n result.append(slice_idx[arr[i]-1])\n result = np.array(result)\n return result\ndef atan2_array(arr1,arr2):\n arr_len = len(arr1)\n arr =[]\n for i in range(0,arr_len):\n result = atan2(arr1[i],arr2[i])\n arr.append(result)\n arr = np.array(arr)\n return arr\ndef atan2D_array(arr1,arr2):\n H,W = arr1.shape\n arr = np.zeros((H,W))\n for i in range(0,H):\n for j in range(0,W):\n result = atan2(arr1[i,j],arr2[i,j])\n arr[i,j] = result\n return arr\ndef dim1to2(num,H,W):\n #将一维数组按列排列转换为二维数组\n col = (num-1) / H\n row = (num-1) % H\n col = col.astype(int)\n row = row.astype(int)\n col = col.tolist()\n row = row.tolist()\n return row,col\ndef Fourier_slice(size,line_type):\n #ft_dims, ang, sub_path_idx, paths = Fourier_slice(size,line_type)\n #size:[H,W,C]\n H = size[0]\n W = size[1]\n\n Ho = 2 * math.floor(H / 2) + 1\n Wo = 2 * math.floor(W / 2) + 1\n\n Hc = math.ceil(Ho / 2)\n Wc = math.ceil(Wo / 2)\n\n #y1\n half1_y = np.arange(1,Wc+1)\n half1_y = half1_y[::-1]\n half2_y = np.arange(Wc+1,W+1)\n half2_y = half2_y[::-1]\n y1 = np.concatenate((half1_y, half2_y), axis=0)\n\n #x1\n x1 = Hc*(np.ones((1,len(y1))))\n\n #x2\n proc1_x2 = np.arange(Hc, H+1)\n proc2_x2 = np.arange(1, Hc)\n x2 = np.concatenate((proc1_x2, proc2_x2), axis=0)\n\n #y2\n y2 = Wc * (np.ones((1, len(x2))))\n\n #paths\n paths = np.empty((1,Ho+Wo-1),dtype=object)\n paths[0, 1] = idx_num(x1[0, :], y1, [H, W])\n paths[0,Hc+Wc-1] = idx_num(x2,y2[0,:],[H,W])\n\n #x0\n proc1_x0 = np.arange(Hc + 1, Ho+1)\n proc2_x0 = Ho*np.ones((1,Wc-2))\n x0 = np.concatenate((proc1_x0, proc2_x0[0, :]), axis=0)\n\n #y0\n proc1_y0 = np.ones((1,Ho-Hc))\n proc2_y0 = np.arange(2, Wc)\n y0 = np.concatenate((proc1_y0[0, :], proc2_y0), axis=0)\n\n for i in range(1, Hc + Wc - 2):\n X = []\n Y = []\n x = x0[i - 1]\n y = y0[i - 1]\n\n a = x - Hc\n b = y - Wc\n if line_type == 0:\n d = max(abs(a), abs(b)) / 2\n if line_type == 1:\n d = sqrt(a ** 2 + b ** 2) / 2\n if line_type == 2:\n d = (1 + abs(a) + abs(b)) / 2\n\n while x != Hc or y != Wc:\n X.append(x)\n Y.append(y)\n temp_ab = a * (y - Wc) - b * (x - Hc)\n if abs(temp_ab + b) <= d:\n x = x - 1\n elif abs(temp_ab + a) <= d:\n y = y + 1\n else:\n x = x - 1\n y = y + 1\n X = np.array(X)\n Y = np.array(Y)\n\n X1_len = len(X)\n X1 = np.insert(X[::-1], [X1_len], -X + Ho + 1, axis=0)\n X1 = np.insert(X1, [0], Hc, axis=0)\n\n Y1_len = len(Y)\n Y1 = np.insert(Y[::-1], [Y1_len], -Y + Wo + 1, axis=0)\n Y1 = np.insert(Y1, [0], Wc, axis=0)\n\n X2 = X1\n Y2 = Wo - Y1 + 1\n #f\n idx1 = (X1 <= H) & (Y1 <= W)\n idx2 = (X2 <= H) & (Y2 <= W)\n #\n paths[0, i + 1] = idx_num(X1[idx1], Y1[idx1], [H, W]);\n paths[0, Ho + Wo - i - 1] = idx_num(X2[idx2], Y2[idx2], [H, W])\n # ang\n proc1_ang1 = np.arange(0, Hc - 1)\n proc2_ang1 = (Hc - 1) * np.ones((1, Wo))\n\n proc3_ang1 = np.arange(1, Hc - 1)\n proc3_ang1 = proc3_ang1[::-1]\n ang1 = np.concatenate((proc1_ang1, proc2_ang1[0, :], proc3_ang1), axis=0)\n\n proc1_ang2 = (1 - Wc) * np.ones((1, Hc - 1))\n proc2_ang2 = np.arange(1 - Wc, Wc)\n proc3_ang2 = (Wc - 1) * np.ones((1, Hc - 2))\n ang2 = np.concatenate((proc1_ang2[0, :], proc2_ang2, proc3_ang2[0, :]), axis=0)\n ang = atan2_array(ang2, ang1)\n\n # ang2D\n oneH = np.arange(-math.floor(H / 2), math.ceil(H / 2))\n oneW = np.arange(-math.floor(W / 2), math.ceil(W / 2))\n oneH = np.array([oneH])\n H1 = oneH.T * np.ones((1, W))\n H2 = oneW * np.ones((H, 1))\n ang2D = atan2D_array(H2, H1)\n\n idx = (ang2D >= pi / 2)\n ang2D[idx] = ang2D[idx] - pi\n idx = (ang2D < -pi / 2)\n ang2D[idx] = ang2D[idx] + pi\n\n slice_idx = np.zeros((H, W))\n for i in range(0, H):\n for j in range(0, W):\n ang_dif = abs(ang - ang2D[i, j])\n slice_idx[i, j] = find(ang_dif)\n\n slice_idx = slice_idx.flatten(order=\"F\")\n sub_path_idx = np.empty((1, Ho + Wo - 2), dtype=object)\n ft_dims = np.zeros((1, Ho + Wo - 2))\n sub_dims = np.zeros((1, Ho + Wo - 2))\n for i in range(1, Ho + Wo - 1):\n num = get_num(slice_idx, paths, i)\n sub = np.where(i == num)\n sub_path_idx[0, i - 1] = sub[0] + 1\n ft_dims[0, i - 1] = len(paths[0, i])\n sub_dims[0, i - 1] = len(sub_path_idx[0, i - 1])\n ft_dims = ft_dims[0,:].astype(int)\n sub_dims = sub_dims[0, :].astype(int)\n paths1 = np.zeros((len(ft_dims), np.max(ft_dims)))\n sub_path_idx1 = np.zeros((len(sub_dims), np.max(sub_dims)), dtype=int)\n row = []\n col = []\n row_sub = []\n col_sub = []\n cos_ang = np.zeros((len(ft_dims),1),dtype=np.float32)\n sin_ang = np.zeros((len(ft_dims),1),dtype=np.float32)\n for i in range(len(ft_dims)):\n paths1[i,0:ft_dims[i]]=paths[0,i+1].astype(int)\n sub_path_idx1[i,:sub_dims[i]]=sub_path_idx[0,i].astype(int)\n sign3 = paths[0, i + 1]\n sign4 = sub_path_idx1[i, :sub_dims[i]]\n row1, col1 = dim1to2(sign3[sign4 - 1], H, W)\n row.append(row1)\n col.append(col1)\n save_path = (sign4-1).copy()\n save_path = save_path.tolist()\n for j in range(len(sign4)):\n row_sub.append(i)\n col_sub.append(save_path)\n cos_ang[i,0] = cos(ang[i])\n sin_ang[i,0] = sin(ang[i])\n row = np.asarray(reduce(operator.add, row))\n col = np.asarray(reduce(operator.add, col))\n row_sub = np.asarray(row_sub)\n col_sub = np.asarray(reduce(operator.add, col_sub))\n cos_ang = torch.from_numpy(cos_ang)\n cos_ang = cos_ang.type(torch.float32).cuda()\n cos_ang.requires_grad = False\n sin_ang = torch.from_numpy(sin_ang)\n sin_ang = sin_ang.type(torch.float32).cuda()\n sin_ang.requires_grad = False\n return ft_dims,cos_ang,sin_ang,paths1,row_sub,col_sub,row,col\ndef get_filters(ft_dims,scal,factor,batch_size,cos_ang,sin_ang):\n f_filters = zeros((batch_size,3,len(ft_dims),max(ft_dims)),dtype=torch.float32)\n g_filters = zeros((batch_size,3,len(ft_dims),max(ft_dims)),dtype=torch.float32)\n gh_filters = zeros((batch_size,3,len(ft_dims),max(ft_dims)),dtype=torch.complex64)\n for i in range(batch_size):\n for j in range(3):\n for k in range(len(ft_dims)):\n f,g,gh = rizer_filters(ft_dims[k],scal,factor)\n f_filters[i,j,k,0:ft_dims[k]]=f\n g_filters[i,j,k,0:ft_dims[k]]=g\n gh_filters[i,j,k,0:ft_dims[k]]=gh\n f_filters=f_filters.cuda()\n g_filters=g_filters.cuda()\n gh_filters=gh_filters.cuda()\n cos_gh = mul(cos_ang,gh_filters)\n sin_gh = mul(sin_ang,gh_filters)\n filters = torch.cat((f_filters,g_filters,cos_gh,sin_gh),1)\n filters = filters.cuda()\n filters.requires_grad=False\n return filters\n#hilbert =(a+bi)(c+dj)=ac+bci+adj-bdk\ndef get_original(input,ft_dims,paths):\n B,C,H,W = input.shape\n #传入的input的shape为 [B,C,H,W]\n ft_img = fftshift(fft2(input)).permute(0, 1, 3, 2).flatten(start_dim=2, end_dim=3)\n original = zeros((B, C, len(ft_dims), max(ft_dims)), dtype=torch.complex64).cuda()\n original[:, :, :, :] = ft_img[:, :, paths[:, :] - 1]\n return original\ndef MWT_ana(img, ft_dims, paths,row_sub,col_sub,row,col, filters):\n B,C,H,W=img.shape\n original = get_original(img,ft_dims,paths)\n original = torch.cat((original,original,original,original),1)\n out = zeros((B, C*4, H, W), dtype=torch.complex64).cuda()\n rizer_mwt = mul(filters,original)\n out[:,:,row,col]=rizer_mwt[:,:,row_sub,col_sub]\n out1 = ifft2(ifftshift(out)).real\n return out1\ndef MWT_sys(img, ft_dims, paths,row_sub,col_sub,row,col, filters):\n B, C, H, W = img.shape\n out = zeros((B, 3, H, W), dtype=torch.complex64).cuda()\n rizer_sys = get_original(img,ft_dims,paths)\n back_mwt = mul(rizer_sys[:, 0:3, :, :], filters[:,0:3,:,:]) + (mul(rizer_sys[:, 3:6, :, :], filters[:, 3:6, :, :])\n - (mul(rizer_sys[:, 6:9, :, :], filters[:, 6:9, :, :]) + mul(rizer_sys[:, 9:12, :, :], filters[:, 9:12, :, :]))) / 2\n out[:, :, row, col] = back_mwt[:, :, row_sub, col_sub]\n out1 = ifft2(ifftshift(out)).real\n return out1\nimport time\nimport os\nif __name__=='__main__':\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n img1 = cv2.imread('./data/real/GT_rain_acc22.jpg')\n # img2 = cv2.imread('./data/rain100H/norain/norain-003.png')\n img1 = img1[0:301, 0:301, :]\n # img2 = img2[0:101, 0:101, :]\n img1 = torch.tensor(img1).cuda()\n # img2 = torch.tensor(img2)\n img = torch.zeros((2, 301, 301, 3))\n for i in range(2):\n img[i, :, :, :] = img1\n img = img.permute(0, 3, 1, 2).cuda()\n ft_dims,cos_ang,sin_ang, paths,row_sub,col_sub,row,col = Fourier_slice([301, 301], 0)\n filters = get_filters(ft_dims, 1, 0.5,2,cos_ang,sin_ang)\n start = time.time()\n r = MWT_ana(img, ft_dims, paths,row_sub,col_sub,row,col,filters)\n back = MWT_sys(r, ft_dims, paths,row_sub,col_sub,row,col,filters)\n save_out = back.data.cpu().numpy().squeeze() # back to cpu\n\n print(time.time()-start)\n print(torch.max(back-img))\n print(torch.min(back-img))\n\n\n\n","repo_name":"smart-hzw/MDARNet","sub_path":"MWT_complex.py","file_name":"MWT_complex.py","file_ext":"py","file_size_in_byte":10144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1649651767","text":"import sys\r\nimport ibmiotf.application\r\nimport ibmiotf.device\r\nimport random\r\n#Provide your IBM Watson Device Credentials\r\norganization = \"rgjd96\"\r\ndeviceType = \"raspberrypi\"\r\ndeviceId = \"654321\"\r\nauthMethod = \"token\"\r\nauthToken = \"17481a04m7\"\r\n\r\n\r\ndef myCommandCallback(cmd):\r\n print(\"Command received: %s\" % cmd.data)#Commands\r\n \r\n\r\ntry:\r\n\tdeviceOptions = {\"org\": organization, \"type\": deviceType, \"id\": deviceId, \"auth-method\": authMethod, \"auth-token\": authToken}\r\n\tdeviceCli = ibmiotf.device.Client(deviceOptions)\r\n\t#..............................................\r\n\t\r\nexcept Exception as e:\r\n\tprint(\"Caught exception connecting device: %s\" % str(e))\r\n\tsys.exit()\r\n\r\n# Connect and send a datapoint \"hello\" with value \"world\" into the cloud as an event of type \"greeting\" 10 times\r\ndeviceCli.connect()\r\n\r\nwhile True:\r\n \r\n temp=random.randint(20, 90)\r\n #print(temp)\r\n hum =random.randint(30, 85)\r\n #print(hum)\r\n vib =random.randint (20, 50)\r\n #Send Temperature, Humidity, &Vibration to IBM Watson\r\n data = { 'Temprature' : temp, 'Humidity' : hum, 'Vibration': vib }\r\n #print (data)\r\n def myOnPublishCallback():\r\n print (\"Published Temperature = %s C\" % temp, \"Humidity = %s %%\" % hum, \"Vibration = %s m/s2\" % vib, \"to IBM Watson\")\r\n \r\n\r\n success = deviceCli.publishEvent(\"Wheater\", \"json\", data, qos=0, on_publish=myOnPublishCallback)\r\n if not success:\r\n print(\"Not connected to IoTF\")\r\n time.sleep(2)\r\n \r\n deviceCli.commandCallback = myCommandCallback\r\n\r\n# Disconnect the device and application from the cloud\r\ndeviceCli.disconnect()\r\n\r\n","repo_name":"jenifa-pixel/Internship-project-industrial-motor","sub_path":"industrial motor.py","file_name":"industrial motor.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9557138110","text":"import time\nimport ctypes\nimport win32api\nimport win32con\nfrom argsolver import args\nkeycooldown = 0.001+args.keydelay\nLEFT = 37\nUP = 38\nRIGHT = 39\nDOWN = 40\nENTER = 13\n\nLEFT = 65\nDOWN = 83\nUP = 87\nRIGHT = 68\nkeybind = {\n \"up\": UP,\n \"left\": LEFT,\n \"down\": DOWN,\n \"right\": RIGHT,\n 'enter': ENTER,\n \"esc\": 27,\n 'tab':9\n}\n\n\ndef press(key, cooldown=keycooldown):\n MapKey = ctypes.windll.user32.MapVirtualKeyA\n win32api.keybd_event(key, MapKey(key, 0), 0, 0)\n time.sleep(cooldown)\n win32api.keybd_event(key, MapKey(key, 0), win32con.KEYEVENTF_KEYUP, 0)\n time.sleep(cooldown)\n\n\ndef press_str(keystr,**kwargs):\n press(keybind[keystr],**kwargs)\n\n\nif __name__ == \"__main__\":\n pass\n # time.sleep(1)\n # press(72)\n # import pyautogui\n #\n # pyautogui.moveTo(x=100, y=100, duration=2, tween=pyautogui.linear)\n # pyautogui.press('esc')\n","repo_name":"Yuandiaodiaodiao/gta-helper","sub_path":"perico/keyboardsim.py","file_name":"keyboardsim.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"52"} +{"seq_id":"5307271846","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport random\r\nfrom collections import deque\r\nimport os\r\ntf.compat.v1.disable_eager_execution()\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\n\r\ndef flat(state):\r\n state = np.concatenate(state, axis=0)\r\n state = np.concatenate(state, axis=0)\r\n return state\r\n\r\n\r\nclass BuildModel:\r\n def __init__(self, numStateSpace, numActionSpace, gamma, tau, seed=1):\r\n self.numStateSpace = numStateSpace\r\n self.numActionSpace = numActionSpace\r\n self.gamma = gamma\r\n self.seed = seed\r\n self.tau = tau\r\n\r\n def __call__(self, layersWidths, summaryPath=\"./tbdata\"):\r\n print(\"Generating DQN Model with layers: {}\".format(layersWidths))\r\n graph = tf.Graph()\r\n with graph.as_default():\r\n if self.seed is not None:\r\n tf.set_random_seed(self.seed)\r\n\r\n with tf.name_scope('inputs'):\r\n states_ = tf.placeholder(tf.float32, [None, self.numStateSpace], name=\"states\")\r\n nextStates_ = tf.placeholder(tf.float32, [None, self.numStateSpace], name=\"nextStates\")\r\n act_ = tf.placeholder(tf.float32, [None, self.numActionSpace], name=\"act\")\r\n reward_ = tf.placeholder(tf.float32, [None, 1], name=\"reward\")\r\n # done_ = tf.placeholder(tf.float32, [None, 1], name=\"done\")\r\n tf.add_to_collection(\"states\", states_)\r\n tf.add_to_collection(\"nextStates\", nextStates_)\r\n tf.add_to_collection(\"act\", act_)\r\n tf.add_to_collection(\"reward\", reward_)\r\n # tf.add_to_collection(\"done\", done_)\r\n\r\n initWeight = tf.random_uniform_initializer(-0.03, 0.03)\r\n initBias = tf.constant_initializer(0.01)\r\n\r\n with tf.variable_scope(\"evalNet\"):\r\n with tf.variable_scope(\"trainEvalHiddenLayers\"):\r\n activation_ = states_\r\n for i in range(len(layersWidths)):\r\n fcLayer = tf.layers.Dense(units=layersWidths[i], activation=None,\r\n kernel_initializer=initWeight,\r\n bias_initializer=initBias, name=\"fcEvalHidden{}\".format(i + 1),\r\n trainable=True)\r\n activation_ = fcLayer(activation_)\r\n\r\n tf.add_to_collections([\"weights\", f\"weight/{fcLayer.kernel.name}\"], fcLayer.kernel)\r\n tf.add_to_collections([\"biases\", f\"bias/{fcLayer.bias.name}\"], fcLayer.bias)\r\n tf.add_to_collections([\"activations\", f\"activation/{activation_.name}\"], activation_)\r\n evalHiddenOutput_ = tf.identity(activation_, name=\"outputHiddenEval\")\r\n outputEvalFCLayer = tf.layers.Dense(units=self.numActionSpace, activation=None,\r\n kernel_initializer=initWeight,\r\n bias_initializer=initBias,\r\n name=\"fcEvalOut{}\".format(len(layersWidths) + 1),\r\n trainable=True)\r\n evalNetOutput_ = outputEvalFCLayer(evalHiddenOutput_)\r\n tf.add_to_collections([\"weights\", f\"weight/{outputEvalFCLayer.kernel.name}\"], outputEvalFCLayer.kernel)\r\n tf.add_to_collections([\"biases\", f\"bias/{outputEvalFCLayer.bias.name}\"], outputEvalFCLayer.bias)\r\n tf.add_to_collections(\"evalNetOutput\", evalNetOutput_)\r\n\r\n with tf.variable_scope(\"targetNet\"):\r\n with tf.variable_scope(\"trainTargetHiddenLayers\"):\r\n activation_ = nextStates_\r\n for i in range(len(layersWidths)):\r\n fcLayerTarget = tf.layers.Dense(units=layersWidths[i], activation=None,\r\n kernel_initializer=initWeight,\r\n bias_initializer=initBias, name=\"fcTargetHidden{}\".format(i + 1),\r\n trainable=True)\r\n activation_ = fcLayerTarget(activation_)\r\n\r\n tf.add_to_collections([\"weights\", f\"weight/{fcLayerTarget.kernel.name}\"], fcLayerTarget.kernel)\r\n tf.add_to_collections([\"biases\", f\"bias/{fcLayerTarget.bias.name}\"], fcLayerTarget.bias)\r\n tf.add_to_collections([\"activations\", f\"activation/{activation_.name}\"], activation_)\r\n targetHiddenOutput_ = tf.identity(activation_, name=\"outputHiddenTarget\")\r\n outputTargetFCLayer = tf.layers.Dense(units=self.numActionSpace, activation=None,\r\n kernel_initializer=initWeight,\r\n bias_initializer=initBias,\r\n name=\"fcTargetOut{}\".format(len(layersWidths) + 1),\r\n trainable=True)\r\n targetNetOutput_ = outputTargetFCLayer(targetHiddenOutput_)\r\n tf.add_to_collections([\"weights\", f\"weight/{outputTargetFCLayer.kernel.name}\"], outputTargetFCLayer.kernel)\r\n tf.add_to_collections([\"biases\", f\"bias/{outputTargetFCLayer.bias.name}\"], outputTargetFCLayer.bias)\r\n tf.add_to_collections(\"TargetNetOutput\", targetNetOutput_)\r\n\r\n with tf.variable_scope(\"trainingParams\"):\r\n learningRate_ = tf.constant(0.001, dtype=tf.float32)\r\n tf.add_to_collection(\"learningRate\", learningRate_)\r\n\r\n with tf.variable_scope(\"QTable\"):\r\n QEval_ = tf.reduce_sum(tf.multiply(evalNetOutput_, act_), reduction_indices=1)\r\n tf.add_to_collections(\"QEval\", QEval_)\r\n QEval_ = tf.reshape(QEval_, [-1, 1])\r\n Qtarget_ = tf.reduce_max(targetNetOutput_)\r\n Qtarget_ = tf.reshape(Qtarget_, [-1, 1])\r\n yi_ = reward_ + self.gamma*Qtarget_\r\n # yi_ = reward_ + self.gamma * Qtarget_ * (1 - done_)\r\n yi_ = tf.reshape(yi_, [-1, 1])\r\n loss_ = tf.reduce_mean(tf.square(yi_ - QEval_))\r\n # loss_ = tf.losses.mean_squared_error(labels=yi_, predictions=QEval_)\r\n tf.add_to_collection(\"loss\", loss_)\r\n\r\n evalParams = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='evalNet')\r\n targetParams = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='targetNet')\r\n softReplace_ = [tf.assign(t, (1 - self.tau) * t + self.tau * e) for t, e in zip(targetParams, evalParams)]\r\n tf.add_to_collection(\"softReplace\", softReplace_)\r\n\r\n with tf.variable_scope(\"train\"):\r\n trainOpt_ = tf.train.AdamOptimizer(learningRate_, name='adamOptimizer').minimize(loss_, var_list=evalParams)\r\n tf.add_to_collection(\"trainOp\", trainOpt_)\r\n\r\n saver = tf.train.Saver(max_to_keep=None)\r\n tf.add_to_collection(\"saver\", saver)\r\n\r\n fullSummary = tf.summary.merge_all()\r\n tf.add_to_collection(\"summaryOps\", fullSummary)\r\n if summaryPath is not None:\r\n trainWriter = tf.summary.FileWriter(summaryPath + \"/train\", graph=tf.get_default_graph())\r\n testWriter = tf.summary.FileWriter(summaryPath + \"/test\", graph=tf.get_default_graph())\r\n tf.add_to_collection(\"writers\", trainWriter)\r\n tf.add_to_collection(\"writers\", testWriter)\r\n saver = tf.train.Saver(max_to_keep=None)\r\n tf.add_to_collection(\"saver\", saver)\r\n\r\n model = tf.Session(graph=graph)\r\n model.run(tf.global_variables_initializer())\r\n\r\n return model\r\n\r\n\r\nclass TrainOneStep:\r\n\r\n def __init__(self, batchSize, tau, learningRate, gamma):\r\n self.batchSize = batchSize\r\n self.tau = tau\r\n self.learningRate = learningRate\r\n self.gamma = gamma\r\n self.step = 0\r\n # self.softReplace = softReplace\r\n\r\n def __call__(self, model, miniBatch, batchSize):\r\n\r\n # print(\"ENTER TRAIN\")\r\n graph = model.graph\r\n states_ = graph.get_collection_ref(\"states\")[0]\r\n nextStates_ = graph.get_collection_ref(\"nextStates\")[0]\r\n reward_ = graph.get_collection_ref(\"reward\")[0]\r\n act_ = graph.get_collection_ref(\"act\")[0]\r\n learningRate_ = graph.get_collection_ref(\"learningRate\")[0]\r\n loss_ = graph.get_collection_ref(\"loss\")[0]\r\n # done_ = graph.get_collection_ref(\"done\")[0]\r\n trainOp_ = graph.get_collection_ref(\"trainOp\")[0]\r\n softReplace_ = graph.get_collection_ref(\"softReplace\")\r\n fetches = [loss_, trainOp_]\r\n\r\n # config = tf.compat.v1.ConfigProto(allow_soft_placement=True)\r\n # sess = tf.Session(graph=graph)\r\n evalParams = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='evalNet')\r\n targetParams = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='targetNet')\r\n softReplace_ = [tf.assign(t, (1 - self.tau) * t + self.tau * e) for t, e in zip(targetParams, evalParams)]\r\n model.run(softReplace_)\r\n\r\n states, actions, nextStates, rewards, done = miniBatch\r\n statesBatch = np.asarray(states).reshape(batchSize, -1)\r\n actBatch = np.asarray(actions).reshape(batchSize, -1)\r\n # print(\"actBatch:{}\".format(actBatch))\r\n nextStatesBatch = np.asarray(nextStates).reshape(batchSize, -1)\r\n rewardBatch = np.asarray(rewards).reshape(batchSize, -1)\r\n doneBatch = np.asarray(done).reshape(batchSize, -1)\r\n feedDict = {states_: statesBatch, nextStates_: nextStatesBatch, act_: actBatch, learningRate_: self.learningRate, reward_: rewardBatch}\r\n # feedDict = {states_: statesBatch, nextStates_: nextStatesBatch, act_: actBatch,\r\n # learningRate_: self.learningRate, reward_: rewardBatch, done_: doneBatch}\r\n lossDict, trainOp = model.run(fetches, feed_dict=feedDict)\r\n\r\n return model, lossDict\r\n\r\n\r\nclass SampleAction:\r\n\r\n def __init__(self, actionDim):\r\n self.actionDim = actionDim\r\n\r\n def __call__(self, model, states, epsilon):\r\n if random.random() < epsilon:\r\n graph = model.graph\r\n evalNetOutput_ = graph.get_collection_ref('evalNetOutput')[0]\r\n states_ = graph.get_collection_ref(\"states\")[0]\r\n states = flat(states)\r\n evalNetOutput = model.run(evalNetOutput_, feed_dict={states_: [states]})\r\n # print(\"evalNetOutput:{}\".format(evalNetOutput))\r\n # print(np.argmax(QEval[0]))\r\n # print(evalNetOutput)\r\n return np.argmax(evalNetOutput)\r\n else:\r\n return np.random.randint(0, self.actionDim)\r\n\r\n\r\ndef memorize(replayBuffer, states, act, nextStates, reward, done, actionDim):\r\n onehotAction = np.zeros(actionDim)\r\n onehotAction[act] = 1\r\n replayBuffer.append((states, onehotAction, nextStates, reward, done))\r\n return replayBuffer\r\n\r\n\r\nclass InitializeReplayBuffer:\r\n\r\n def __init__(self, reset, forwardOneStep, isTerminal, actionDim):\r\n self.reset = reset\r\n self.isTerminal = isTerminal\r\n self.forwardOneStep = forwardOneStep\r\n self.actionDim = actionDim\r\n\r\n def __call__(self, replayBuffer, maxReplaySize):\r\n for i in range(maxReplaySize):\r\n states = self.reset()\r\n action = np.random.randint(0, self.actionDim)\r\n nextStates, reward = self.forwardOneStep(states, action)\r\n done = self.isTerminal(nextStates)\r\n replayBuffer = memorize(replayBuffer, states, action, nextStates, reward, done, self.actionDim)\r\n return replayBuffer\r\n\r\n\r\ndef sampleData(data, batchSize):\r\n batch = [list(varBatch) for varBatch in zip(*random.sample(data, batchSize))]\r\n return batch\r\n\r\ndef upgradeEpsilon(epsilon):\r\n epsilon = epsilon + 0.0001*(1-0.5)\r\n return epsilon\r\n\r\n\r\nclass RunTimeStep:\r\n\r\n def __init__(self, forwardOneStep, isTerminal, sampleAction, trainOneStep, batchSize, epsilon, actionDelay, actionDim):\r\n self.forwardOneStep = forwardOneStep\r\n self.sampleAction = sampleAction\r\n self.trainOneStep = trainOneStep\r\n self.batchSize = batchSize\r\n self.actionDelay = actionDelay\r\n self.epsilon = epsilon\r\n self.actionDim = actionDim\r\n self.isTerminal = isTerminal\r\n\r\n def __call__(self, states, trajectory, model, replayBuffer, score):\r\n action = self.sampleAction(model, states, self.epsilon)\r\n # print(action)\r\n for i in range(self.actionDelay):\r\n self.epsilon = upgradeEpsilon(self.epsilon)\r\n nextStates, reward = self.forwardOneStep(states, action)\r\n done = self.isTerminal(nextStates)\r\n replayBuffer = memorize(replayBuffer, states, action, nextStates, reward, done, self.actionDim)\r\n miniBatch = sampleData(replayBuffer, self.batchSize)\r\n model, loss = self.trainOneStep(model, miniBatch, self.batchSize)\r\n # print(\"loss:{}\".format(loss))\r\n score += reward\r\n trajectory.append(states)\r\n states = nextStates\r\n return states, done, trajectory, score, replayBuffer, model\r\n\r\n\r\nclass RunEpisode:\r\n\r\n def __init__(self, reset, runTimeStep):\r\n self.runTimeStep = runTimeStep\r\n self.reset = reset\r\n\r\n def __call__(self, model, scoreList, replayBuffer, episode):\r\n states = self.reset()\r\n score = 0\r\n trajectory = []\r\n while True:\r\n states, done, trajectory, score, replayBuffer, model = self.runTimeStep(states, trajectory, model, replayBuffer, score)\r\n if done or score < -800:\r\n scoreList.append(score)\r\n print('episode:', episode, 'score:', score, 'max:', max(scoreList))\r\n break\r\n return model, scoreList, trajectory, replayBuffer\r\n\r\n\r\nclass RunAlgorithm:\r\n\r\n def __init__(self, episodeRange, runEpisode):\r\n self.episodeRange = episodeRange\r\n self.runEpisode = runEpisode\r\n\r\n def __call__(self, model, replayBuffer):\r\n scoreList = []\r\n for i in range(self.episodeRange):\r\n model, scoreList, trajectory, replayBuffer = self.runEpisode(model, scoreList, replayBuffer, i)\r\n return model, scoreList, trajectory\r\n","repo_name":"peanutwall/dqn","sub_path":"src/buildModelSoft.py","file_name":"buildModelSoft.py","file_ext":"py","file_size_in_byte":14658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73805042404","text":"def wordBreak(s, wordDict):\n def dfs(s, wordDict, memo):\n if s in memo:\n return memo[s]\n\n result = []\n if len(s) == 0:\n return result\n\n for word in wordDict:\n if not s.startswith(word):\n continue\n\n if len(s) == len(word):\n result.append(word)\n else:\n sub_list = dfs(s[len(word):], wordDict, memo)\n for item in sub_list:\n item = word + \" \" + item\n result.append(item)\n memo[s] = result\n return result\n\n memo = {}\n res = dfs(s, wordDict, memo)\n return res\n\ns = \"pineapplepenapple\"\nwordDict = [\"apple\", \"pen\", \"applepen\", \"pine\", \"pineapple\"]\nprint(wordBreak(s, wordDict))\n","repo_name":"tanjingjing123/LeetcodeAlgorithms","sub_path":"wordBreakII.py","file_name":"wordBreakII.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27387964507","text":"import pandas as pd\nimport numpy as np\nimport random\nfrom sqlalchemy import create_engine\nimport itertools\n\n\"\"\"\nFormat: \n\nuser_id : 5\nitem_id : 10\nrates: {key: rating} + average_rating[item]\nyear: year - 1900\ntype: 4\nground truth: 3\n\n==>\n\n# User: 5000, # Movie: 41785\n3 5:1 10+1000:1 key+2000:rating 3000+type: 1 3028+usr following id\n\n\"\"\"\n\nFILENAME1 = \"/home/shran/Others/Douban/Features/douban-plus.adjlist\"\nFILENAME2 = \"/home/shran/Others/Douban/Features/douban-plus.edgelist\"\n\n\ndef connectSql():\n engine = create_engine('mysql://root:qwert12345@localhost:3306/rcmd', convert_unicode=True, encoding='utf-8',\n connect_args={\"charset\": \"utf8\"})\n df_movie = pd.read_sql('movie', engine, index_col='number')\n df_user = pd.read_sql('user', engine, index_col='user_id')\n df_movie.index = range(0, len(df_movie))\n df_user.index = range(0, len(df_user))\n return df_movie, df_user\n\ndf_movie, df_user = connectSql()\n\n# movie index\nmovie2index = np.array(range(len(df_movie)))\nmovies = np.array(range(len(df_movie)))\n\n# director index\noffset = len(df_movie)\ndirectors = list(df_movie[\"directors\"].values)\ndirectors = [d.strip().split(\"/\") for d in directors]\n\ndirect_set = set([])\nfor i in directors:\n for d in i:\n direct_set.add(d)\ndirector2index = {}\nfor i, d in enumerate(direct_set):\n director2index[d] = i + offset\n\n# actor index\noffset = len(df_movie) + len(direct_set)\nactors = list(df_movie[\"actors\"].values)\nactors = [a.strip().split(\"/\") for a in actors]\n\nactor_set = set([])\nfor i in actors:\n for a in i:\n actor_set.add(a)\n\nactor2index = {}\nfor i, a in enumerate(actor_set):\n actor2index[a] = i + offset\n\nwith open(FILENAME1, \"w\") as f:\n # 电影邻接矩阵:\n for movieId, directorIds, actorIds in zip(movies, directors, actors):\n d_idx = \" \".join([str(director2index[i]) for i in directorIds])\n a_idx = \" \".join([str(actor2index[i]) for i in actorIds])\n print(str(movieId) + \" \" + d_idx + \" \" + a_idx, file=f)\n # 导演邻接矩阵\n for directorIds, actorIds in zip(directors, actors):\n d_idx = [director2index[i] for i in directorIds]\n a_idx = \" \".join([str(actor2index[i]) for i in actorIds])\n for d in d_idx:\n print(str(d) + \" \" + a_idx, file=f)\nprint(len(direct_set))\nprint(len(actor_set))\n\nprint(\"Done!\")\n\nwith open(FILENAME2, \"w\") as f:\n for movieId, directorIds, actorIds in zip(movies, directors, actors):\n m_idx = [str(movieId)]\n d_idx = [str(director2index[i]) for i in directorIds]\n a_idx = [str(actor2index[i]) for i in actorIds]\n for a, b in itertools.product(m_idx, d_idx):\n print(\"%s %s\" % (a,b), file=f)\n # print(\"%s %s\" % (a,b))\n\n for a, b in itertools.product(m_idx, a_idx):\n print(\"%s %s\" % (a,b), file=f)\n # print(\"%s %s\" % (a,b))\n\n for a, b in itertools.product(a_idx, d_idx):\n print(\"%s %s\" % (a,b), file=f)\n # print(\"%s %s\" % (a,b))\n\nprint(\"Done!\")\n","repo_name":"AaronHeee/FDU-Recommender-Systems-for-Douban-Movie","sub_path":"features/GraphDeepWalk.py","file_name":"GraphDeepWalk.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"11776008995","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom keras import datasets, layers, models, losses\nfrom keras import backend as K\n\nimport os\nimport sys\n\nCLASSES_MODULE_PATH = \"../../../\"\nWEIGHT_FILE_PATH = \"../\"\nMODELS_PATH = CLASSES_MODULE_PATH + \"models\"\n\n# appending a path\nsys.path.append(CLASSES_MODULE_PATH) # CHANGE THIS LINE\n\nfrom src.injection_sites_generator import *\n\n\n### PERFORMING INJECTIONS ON A LINEAR MODEL\n#\n# To correctly perform injections on a linear model we first have to select the layer we want to inject.\n# We can iterate through model.layers to find the corresponding index and store it (line 109)\n# Then we define the number of tests that we want to perform (line 107)\n# and execute the function inject_layer each time (lines 115 - 116)\n# We need to pass the following parameters\n# \t\t1. model: the model we are targeting\n#\t\t2. img: an image on which we will perform inference\n#\t\t3. selected layer index: the index referring to the layer we selected for the injection\n#\t\t4. operator type: a value from the OperatorType enum that defines the type of the layer we are injecting\n#\t\t5. shape: the output shape of the layer as a string in the following format: (None, channels, widht, height)\n# 6. models_path: the folder in src/ where we placed the error models, it can be specified if the user does not\n# want to use the defaults one.\n#\n# The function will return the corrupted output of the model\n\ndef generate_injection_sites(sites_count, layer_type, layer_name, size, models_path, models_mode=''):\n injection_site = InjectableSite(layer_type, layer_name, size)\n\n try:\n injection_sites, cardinality, pattern = InjectionSitesGenerator([injection_site], models_mode, models_path) \\\n .generate_random_injection_sites(sites_count)\n except:\n return []\n\n return injection_sites, cardinality, pattern\n\n\ndef build_model(input_shape, saved_weights=None):\n \"\"\"\n Saved weights should be the path to a h5 file if you have already trained the model\n \"\"\"\n if saved_weights is not None:\n model = keras.models.load_model(saved_weights)\n return model\n inputs = keras.Input(shape=input_shape, name='input')\n conv1 = layers.Conv2D(filters=6, kernel_size=(5, 5), activation='relu', name='conv1')(inputs)\n pool1 = layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), name='maxpool1')(conv1)\n conv2 = layers.Conv2D(filters=16, kernel_size=(5, 5), strides=(1, 1), activation='relu', padding=\"same\",\n name='conv2')(pool1)\n pool2 = layers.MaxPool2D(pool_size=(2, 2), strides=(1, 1), name='maxpool2')(conv2)\n conv3 = layers.Conv2D(filters=120, kernel_size=(5, 5), strides=(1, 1), activation='relu', padding=\"same\",\n name='conv3')(pool2)\n flatten = layers.Flatten(name='flatten')(conv3)\n dense1 = layers.Dense(84, activation='relu', name='dense1')(flatten)\n outputs = layers.Dense(10, activation='softmax', name='dense3')(dense1)\n\n return keras.Model(inputs=(inputs,), outputs=outputs)\n\n\ndef load_data():\n (x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()\n x_train = tf.pad(x_train, [[0, 0], [2, 2], [2, 2]]) / 255\n x_test = tf.pad(x_test, [[0, 0], [2, 2], [2, 2]]) / 255\n x_train = tf.expand_dims(x_train, axis=3, name=None)\n x_test = tf.expand_dims(x_test, axis=3, name=None)\n\n x_val = x_train[-2000:, :, :, :]\n y_val = y_train[-2000:]\n x_train = x_train[:-2000, :, :, :]\n y_train = y_train[:-2000]\n\n return x_train, y_train, x_val, y_val\n\n\ndef inject_layer(model, img, selected_layer_idx, layer_type, layer_output_shape_cf, models_path='models'):\n get_selected_layer_output = K.function([model.layers[0].input], [model.layers[selected_layer_idx].output])\n get_model_output = K.function([model.layers[selected_layer_idx + 1].input], [model.layers[-1].output])\n\n output_selected_layer = get_selected_layer_output([np.expand_dims(img, 0)])[0]\n\n injection_site, cardinality, pattern = generate_injection_sites(1, layer_type, '',\n layer_output_shape_cf, models_path)\n\n if len(injection_site) > 0:\n for idx, value in injection_site[0].get_indexes_values():\n channel_last_idx = (idx[0], idx[2], idx[3], idx[1])\n if value.value_type == '[-1,1]':\n output_selected_layer[channel_last_idx] += value.raw_value\n else:\n output_selected_layer[channel_last_idx] = value.raw_value\n\n model_output = get_model_output(output_selected_layer)\n\n return model_output\n\n\nNUM_INJECTIONS = 100\nNUM = 42\nSELECTED_LAYER_IDX = 3\n\nx_train, y_train, x_val, y_val = load_data()\npath_weights = os.path.join(WEIGHT_FILE_PATH, 'weights.h5')\nprint(f\"Load weights from => {path_weights}\")\nmodel = build_model(x_train[0].shape, saved_weights=path_weights)\nerrors = 0\n\n\nfor _ in range(NUM_INJECTIONS):\n res = inject_layer(model, x_val[NUM], SELECTED_LAYER_IDX, OperatorType['Conv2D'], '(None, 16, 27, 27)',\n models_path=MODELS_PATH)\n if np.argmax(res) != y_val[NUM]:\n errors += 1\n\nprint(f'Number of misclassification over {NUM_INJECTIONS} injections: {errors}')\n","repo_name":"D4De/classes","sub_path":"examples/tensorflow2/as_a_function/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":5224,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"42002532844","text":"import requests\n\nresponse = requests.get(\"https://playground.learnqa.ru/api/long_redirect\", allow_redirects=True)\n\nnumber_of_responses = len(response.history)\n\nprint(f\"Total number of redirects: {number_of_responses}\")\nprint(f\"Resulting URL: {response.url}\")\n\n\n","repo_name":"khizha/LearnQA_PythonAPI","sub_path":"long_redirect.py","file_name":"long_redirect.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41170854876","text":"import math\nimport argparse\nimport sys\n\n\nclass CreditCalculator:\n\n overpayment = 0\n\n def __init__(self, pay, prd, prn, inst):\n self.payment = pay\n self.periods = prd\n self.principal = prn\n self.interest = inst\n\n def cal_differentiate_payment(self):\n interest_rate = self.interest / (12 * 100)\n for m in range(1, self.periods + 1):\n differentiate_payment = (self.principal / self.periods) + interest_rate * (\n self.principal - (self.principal * (m - 1)) / self.periods)\n differentiate_payment = math.ceil(differentiate_payment)\n self.overpayment = self.overpayment + differentiate_payment\n print(f\"Month {m}: paid out {differentiate_payment}\")\n print()\n self.overpayment = self.overpayment - self.principal\n return self.overpayment\n\n def cal_annuity_payment(self):\n if self.principal != 0 and self.periods != 0:\n interest_rate = self.interest / (12 * 100)\n annuity_payment = self.principal * (\n interest_rate * (1 + interest_rate) ** self.periods) / (\n (1 + interest_rate) ** self.periods - 1)\n annuity_payment = math.ceil(annuity_payment)\n print(f\"Your annuity payment = {annuity_payment}!\")\n\n self.overpayment = (annuity_payment * self.periods) - self.principal\n return self.overpayment\n\n elif self.interest != 0 and self.periods != 0:\n interest_rate = self.interest / (12 * 100)\n credit_principal = self.payment * (\n (1 + interest_rate) ** self.periods - 1) / (\n interest_rate * (1 + interest_rate) ** self.periods)\n credit_principal = math.floor(credit_principal)\n print(f\"Your credit principal = {credit_principal}!\")\n\n self.overpayment = (self.payment * self.periods) - credit_principal\n return self.overpayment\n\n else:\n interest_rate = self.interest / (12 * 100)\n periods = math.log((self.payment / (self.payment - (interest_rate * self.principal))),\n (1 + interest_rate))\n periods = math.ceil(periods)\n year = periods // 12\n month = periods % 12\n if month > 1 and year > 1:\n print(f\"You need {year} years and {month} months to repay this credit!\")\n elif year > 1 and month == 0:\n print(f\"You need {year} year to repay this credit!\")\n else:\n print(f\"You need {month} months to repay this credit!\")\n\n self.overpayment = (self.payment * periods) - self.principal\n return self.overpayment\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--type\", help=\"to get type of calculation\")\n parser.add_argument(\"--payment\", help=\"to get monthly_payment\", type=int, default=0)\n parser.add_argument(\"--periods\", help=\"to get count of months\", type=int, default=0)\n parser.add_argument(\"--principal\", help=\"to get credit_principal\", type=int, default=0)\n parser.add_argument(\"--interest\", help=\"to get credit_interest\", type=float, default=0.0)\n args = parser.parse_args()\n\n option = args.type\n payment = args.payment\n months = args.periods\n principal = args.principal\n interest = args.interest\n\n overpayment = 0\n\n if len(sys.argv) < 5 or interest < 0 or principal < 0 or months < 0 or payment < 0 or \\\n option != \"annuity\" and option != \"diff\":\n print(\"Incorrect parameters\")\n\n else:\n credit_cal = CreditCalculator(payment, months, principal, interest)\n if option == \"diff\":\n overpayment = credit_cal.cal_differentiate_payment()\n else:\n overpayment = credit_cal.cal_annuity_payment()\n print(f\"Overpayment = {overpayment}\")\n\n# credit_principal = 'Credit principal: 1000'\n# final_output = 'The credit has been repaid!'\n# first_month = 'Month 1: paid out 250'\n# second_month = 'Month 2: paid out 250'\n# third_month = 'Month 3: paid out 500'\n\n# write your code here\n# print(credit_principal)\n# print(first_month)\n# print(second_month)\n# print(third_month)\n# print(final_output)\n\n# credit_principal = int(input(\"Enter the credit principal: \").strip())\n# option = input(\"\"\"What do you want to calculate?\n# type \"m\" - for count of months,\n# type \"p\" - for monthly payment:\n# \"\"\").strip()\n# if option == \"m\":\n# monthly_payment = int(input(\"Enter monthly payment: \").strip())\n# months = round(credit_principal / monthly_payment)\n# if months > 1:\n# print(f\"It takes {months} months to repay the credit\")\n# else:\n# print(f\"It takes {months} month to repay the credit\")\n# else:\n# periods = int(input(\"Enter count of months: \").strip())\n# payment = math.ceil(credit_principal / periods)\n# last_payment = credit_principal - (periods - 1) * payment\n# if payment == last_payment:\n# print(f\"Your monthly payment = {payment}\")\n# else:\n# print(f\"Your monthly payment = {payment} with last month payment = {last_payment}.\")\n\n# option = input(\"\"\"What do you want to calculate?\n# type \"n\" - for count of months,\n# type \"a\" - for annuity monthly payment,\n# type \"p\" - for credit principal:\n# \"\"\").strip()\n# if option == \"n\":\n# credit_principal = float(input(\"Enter the credit principal: \").strip())\n# monthly_payment = float(input(\"Enter monthly payment: \").strip())\n# credit_interest = float(input(\"Enter credit interest: \").strip())\n#\n# interest_rate = credit_interest / (12 * 100)\n# months = math.log((monthly_payment / (monthly_payment - (interest_rate * credit_principal))), (1 + interest_rate))\n# months = math.ceil(months)\n# year = months // 12\n# month = months % 12\n# if month > 1 and year > 1:\n# print(f\"You need {year} years and {month} months to repay this credit!\")\n# elif year > 1 and month == 0:\n# print(f\"You need {year} year to repay this credit!\")\n# else:\n# print(f\"You need {month} months to repay this credit!\")\n#\n# elif option == \"a\":\n# credit_principal = float(input(\"Enter the credit principal: \").strip())\n# periods = int(input(\"Enter count of periods: \").strip())\n# credit_interest = float(input(\"Enter credit interest: \").strip())\n#\n# interest_rate = credit_interest / (12 * 100)\n# annuity_payment = credit_principal * \\\n# (interest_rate * (1 + interest_rate) ** periods) / ((1 + interest_rate) ** periods - 1)\n# annuity_payment = math.ceil(annuity_payment)\n# print(f\"Your annuity payment = {annuity_payment}!\")\n#\n# else:\n# monthly_payment = float(input(\"Enter monthly payment: \").strip())\n# periods = int(input(\"Enter count of periods: \").strip())\n# credit_interest = float(input(\"Enter credit interest: \").strip())\n#\n# interest_rate = credit_interest / (12 * 100)\n# credit_principal = monthly_payment * \\\n# ((1 + interest_rate) ** periods - 1) / (interest_rate * (1 + interest_rate) ** periods)\n# credit_principal = math.floor(credit_principal)\n# print(f\"Your credit principal = {credit_principal}!\")\n","repo_name":"dineshgumray/Credit_Calculator","sub_path":"Credit Calculator/task/creditcalc/creditcalc.py","file_name":"creditcalc.py","file_ext":"py","file_size_in_byte":7257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21186828650","text":"import argparse\n\nimport cv2\nimport numpy as np\n\nfrom onnxruntime.quantization import quantize_static, CalibrationDataReader, QuantType\nfrom onnxruntime.quantization.calibrate import CalibrationMethod\nfrom onnxruntime.quantization.quant_utils import QuantFormat\n\nfrom dataset import pre_process_vgg\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"ONNXRuntime quantization tool\")\n parser.add_argument(\"--input\", \"-i\", type=str)\n parser.add_argument(\"--output\", \"-o\", type=str)\n parser.add_argument(\"--dataset\", \"-d\", type=str)\n parser.add_argument(\"--entropy-calibration\", default=False, action=\"store_true\")\n return parser.parse_args()\n\n\n# https://github.com/microsoft/onnxruntime/blob/master/onnxruntime/python/tools/quantization/notebooks/imagenet_v2/mobilenet.ipynb\ndef preprocess_image(image_path, height, width, channels=3):\n image = cv2.imread(image_path)\n image_data = pre_process_vgg(image, dims=[height, width, channels], need_transpose=True)\n image_data = np.expand_dims(image_data, axis=0)\n return image_data\n\n\ndef preprocess_func(images_folder, height, width, size_limit=0):\n unconcatenated_batch_data = []\n import pathlib\n\n image_filepathes = [str(path) for path in pathlib.Path(images_folder).glob(\"*.JPEG\")]\n for image_filepath in image_filepathes:\n # image_filepath = images_folder + '/' + image_name\n image_data = preprocess_image(image_filepath, height, width)\n unconcatenated_batch_data.append(image_data)\n batch_data = np.concatenate(np.expand_dims(unconcatenated_batch_data, axis=0), axis=0)\n return batch_data\n\n\nimage_height = 224\nimage_width = 224\n\n\nclass ResNetDataReader(CalibrationDataReader):\n def __init__(self, calibration_image_folder):\n self.image_folder = calibration_image_folder\n self.preprocess_flag = True\n self.enum_data_dicts = []\n self.datasize = 0\n\n def get_next(self):\n if self.preprocess_flag:\n self.preprocess_flag = False\n nhwc_data_list = preprocess_func(\n self.image_folder, image_height, image_width, size_limit=0\n )\n self.datasize = len(nhwc_data_list)\n self.enum_data_dicts = iter(\n [{\"input_tensor:0\": nhwc_data} for nhwc_data in nhwc_data_list]\n )\n return next(self.enum_data_dicts, None)\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n dr = ResNetDataReader(args.dataset)\n\n if args.entropy_calibration:\n method = CalibrationMethod.Entropy\n else:\n method = CalibrationMethod.MinMax\n\n quantize_static(\n args.input,\n args.output,\n dr,\n quant_format=QuantFormat.QDQ,\n per_channel=True,\n calibrate_method=method,\n )\n","repo_name":"mlcommons/inference_results_v2.0","sub_path":"closed/FuriosaAI/code/quantization/mlperf_evaluation/python/ort_quantization.py","file_name":"ort_quantization.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"42014142799","text":"# SevenSegment.py\n# Produces a visual representation of a seven-segment display which the user\n# can control.\n\n# Import Tkinter to do the graphics and the time package for the demo mode.\ntry:\n import Tkinter\nexcept:\n import tkinter as Tkinter\nimport time\n\n\n# Display - a seven-segment display\nclass Display(Tkinter.Tk):\n\n # Set up some colours to use for background, segment outlines and\n # segment colours when they're on and off.\n bgcolor = '#111111'\n linecolor = '#222222'\n oncolor = '#00FF00'\n offcolor = '#111111'\n\n # Set up size of each cell and the border around them (pixels).\n cell_width = 100\n cell_height = 150\n border = 5\n max_cells = 10\n\n # Class representing a single cell in a 7-segment display.\n class Cell():\n\n class Segment():\n\n ON = 1\n OFF = 0\n\n # Constructor.\n # Parms:\n # flag_value - the bit(s) that this segment responds to.\n # x_pos - the x-position of the top-left corner of the\n # space where this segment exists on a canvas.\n # y_pos - the y-position of the top-left corner of the\n # space where this segment exists on a canvas.\n # width - the width of the canvas where this segment can\n # be drawn.\n # height - the height of the canvas where this segment can\n # be drawn.\n # coordinates - a list of (x,y) tuples giving coordinates of a\n # polygon (expressed as % of width and height)\n # where the segment is drawn.\n # line_color - the line colour to use when drawing.\n # on_colour - the colour to use when the segment is active.\n # off_colour - the colour to use when the segment in inactive.\n def __init__(self, flag_value, x_pos, y_pos, width, height,\n coordinates, line_color, on_color, off_color):\n\n # Save off the colours to use.\n self.line_color = line_color\n self.on_color = on_color\n self.off_color = off_color\n\n # Save the value this segment is responsive to.\n self.flag_value = flag_value\n\n # Convert raw coordinate tuples to a list of absolute\n # coordinates.\n self.coords = []\n for coord in coordinates:\n (x, y) = coord\n x = x_pos + ((width * x) / 100)\n y = y_pos + ((height * y) / 147)\n self.coords.append(x)\n self.coords.append(y)\n\n self.set_state(self.OFF)\n\n # Set the state of the segment and update the colour accordingly.\n def set_state(self, new_state):\n self.state = new_state\n if self.state == self.ON:\n self.color = self.on_color\n else:\n self.color = self.off_color\n\n # Draw the segment on a canvas.\n def draw(self, canvas):\n canvas.create_polygon(self.coords,\n outline=self.line_color,\n fill=self.color)\n\n # END class Segment\n\n def __init__(self, x_pos, y_pos, width, height,\n line_color, on_color, off_color):\n self.bitflags = 0\n\n # Create the cell's segments, giving them each coordinates for\n # their polygons as a list of x,y pairs where the coordinate assume\n # a cell 100 pixels wide and 150 high. The segments will scale\n # appropriately based on the actual width and height.\n seg_coords = [\n [(17, 0), (65, 0), (73, 8), (65, 16), (17, 16), (9, 8)],\n [(74, 9), (82, 17), (82, 65), (74, 73), (66, 65), (66, 17)],\n [(74, 74), (82, 82), (82, 130), (74, 138), (66, 130),\n (66, 82)],\n [(17, 131), (65, 131), (73, 139), (65, 147), (17, 147),\n (9, 139)],\n [(8, 74), (16, 82), (16, 130), (8, 138), (0, 130), (0, 82)],\n [(8, 9), (16, 17), (16, 65), (8, 73), (0, 65), (0, 17)],\n [(17, 66), (65, 66), (73, 74), (65, 82), (17, 82), (9, 74)],\n [(83, 139), (91, 131), (99, 139), (91, 147)]]\n self.segments = []\n for ii in range(len(seg_coords)):\n self.segments.append(self.Segment(2**ii,\n x_pos,\n y_pos,\n width,\n height,\n seg_coords[ii],\n line_color,\n on_color,\n off_color))\n\n def set(self, bitflags=0):\n self.bitflags = bitflags\n\n # Loop through the cell's segments, setting them on or off based\n # on the bitflags.\n for segment in self.segments:\n if bitflags & segment.flag_value:\n segment.set_state(segment.ON)\n else:\n segment.set_state(segment.OFF)\n\n def draw(self, canvas):\n # Loop through the segments, adding each one to the canvas.\n for segment in self.segments:\n segment.draw(canvas)\n\n # END class Cell\n\n def __init__(self, num_cells=1):\n # Initialization just creates a blank display.\n Tkinter.Tk.__init__(self)\n self.title(\"Seven Segment Display\")\n\n num_cells = min(num_cells, self.max_cells)\n num_cells = max(num_cells, 1)\n self.canvas = Tkinter.Canvas(self,\n width=(self.cell_width*num_cells +\n 2 * self.border),\n height=(self.cell_height +\n 2 * self.border),\n borderwidth=0,\n highlightthickness=0,\n background=self.bgcolor)\n\n # Create a line of cells with a border above and to the left.\n self.cells = []\n for ii in range(num_cells):\n new_cell = self.Cell(self.border + ii * self.cell_width,\n self.border,\n self.cell_width,\n self.cell_height,\n self.linecolor,\n self.oncolor,\n self.offcolor)\n self.cells.append(new_cell)\n\n self.redraw()\n\n def redraw(self):\n # Clear the canvas and redraw each cell.\n self.canvas.delete(\"all\")\n for cell in self.cells:\n cell.draw(self.canvas)\n self.canvas.pack()\n self.update()\n\n # set()\n # Sets which segments of the display are lit.\n # Params: Variable number of integers indicating what each cell should\n # display.\n # Examples: set(0)\n # set(0b00000110, 0b01011011)\n def set(self, *args):\n arglist = list(args)\n\n # Before setting new values, clear the existing values for each\n # cell.\n for cell in self.cells:\n cell.set(0)\n\n # Make sure we set the right-most cells in the display.\n num_cells_to_set = min(len(self.cells), len(arglist))\n cells_to_set = self.cells[num_cells_to_set * -1:]\n\n # Now set the cells according to the passed in arguments\n for cell, value in zip(cells_to_set, arglist):\n cell.set(value)\n self.redraw()\n\n # scroll()\n # Scroll a sequence across the display from right to left.\n # Params: sequence - List of integers which make up the \"message\" to scroll\n # across the display.\n # delay - The delay, in seconds, between movements.\n def scroll(self, sequence, delay=0.5):\n # Put a load of 'blank' entries at either end of the passed in\n # sequence so that we get something like this.\n #\n # | | | | | |s|e|q|u|e|n|c|e| | | | | |\n #\n # We can then display a chunk of that at a time to make the\n # \"sequence\" bit appear to scroll.\n # The number of blanks we need at either end needs to match the\n # size of the display so that scrolling starts and finishes with a\n # blank display.\n blanks = []\n for ii in range(len(self.cells)):\n blanks.append(0)\n sequence.extend(blanks)\n sequence[:0] = blanks\n\n # Now display the message one chunk at a time.\n for ii in range(1 + len(sequence) - len(self.cells)):\n self.set(*sequence[ii:ii+len(self.cells)])\n time.sleep(delay)\n\n # A cheater's way to make a display show a number. If the display isn't\n # big enough then it will only show the lowest-order digits.\n def show_number(self, number):\n # Have a helper array of the bit-patterns for each digit.\n numbers = [0b00111111, # 0\n 0b00000110, # 1\n 0b01011011, # 2\n 0b01001111, # 3\n 0b01100110, # 4\n 0b01101101, # 5\n 0b01111101, # 6\n 0b00000111, # 7\n 0b01111111, # 8\n 0b01101111] # 9\n\n # Start by blanking all cells except the last, which is a zero.\n for ii in range(len(self.cells)):\n self.cells[ii].set(0)\n self.cells[len(self.cells)-1].set(numbers[0])\n\n number = int(number)\n dig_pos = len(self.cells)\n values_to_set = []\n while number > 0 and dig_pos > 0:\n dig_pos = dig_pos - 1\n self.cells[dig_pos].set(numbers[number % 10])\n number = number / 10\n self.redraw()\n\n # demo()\n # Do a demo of the display, Showing the word \"HELLO\" scrolling on and off\n # Params: none.\n def demo(self):\n self.scroll(sequence=[0b01110110, 0b01111001, 0b00111000,\n 0b00111000, 0b00111111], delay=0.2)\n\n\ndef main():\n disp = Display(8)\n disp.demo()\n\nif __name__ == '__main__':\n main()\n","repo_name":"sedm0973/codeclub","sub_path":"SevenSegment/SevenSegment.py","file_name":"SevenSegment.py","file_ext":"py","file_size_in_byte":10627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14931335866","text":"# -*- coding: utf-8 -*-\nimport string\n\n\nclass CustomFormatter(string.Formatter):\n\n def __init__(self):\n super(CustomFormatter, self).__init__()\n\n def convert_field(self, value, conversion):\n # do any conversion on the resulting object\n if conversion is None:\n return value\n elif conversion == 's':\n return str(value)\n elif conversion == 'r':\n return repr(value)\n elif conversion == 'u':\n return value.upper()\n elif conversion == 'l':\n return value.lower()\n raise ValueError(\n \"Unknown conversion specifier {0!s}\".format(conversion))\n","repo_name":"dgb-sistemas/biblat_process","sub_path":"biblat_process/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23913727286","text":"from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase, APIClient\nfrom api.models import Tree, Photo, Record\nfrom django.contrib.gis.geos import Point\n\nclass BaseViewTest(APITestCase):\n client = APIClient()\n\n @staticmethod\n def create_tree(point = None):\n if point:\n Tree.objects.create(location=point)\n\n def setUp(self):\n # add test data\n self.create_tree(Point(30.5, 31.7))\n self.create_tree(Point(30.4, 31.7))\n self.create_tree(Point(30.5, 31.1))\n\nclass TreeTests(APITestCase):\n def test_create_tree(self):\n \"\"\"\n Ensure we can create a new account object.\n \"\"\"\n url = reverse('tree')\n\n data = {'location':\n {\n 'type': 'Point',\n 'location': (38.4,44.45),\n }\n }\n tree = Point(30.5, 31.1)\n Tree.objects.create(location=tree)\n response = self.client.post(url, data, format='json')\n #self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Tree.objects.count(), 1)\n self.assertEqual(Tree.objects.get().location, tree)","repo_name":"MariToshik/everytree","sub_path":"Server/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6133026525","text":"import numpy as np\nimport torch\n\nfrom second.pytorch.train import example_convert_to_torch\n\ndef LC_PROCESS(prev_sensor_data, net, dataset, policy, sparsify_config):\n \"\"\"\n Processes prev_sensor_data and feeds it to the net, places light curtain using\n generated confidence scores, gets light curtain return, and adds it to a new\n sensor data.\n \n While processing the sensor_data, only the dataset._prep_main_func is used.\n No calls to _prep_data_aug and _prep_targets are made.\n\n sensor_data[\"lidar\"][\"points\"] will be considered the main input to the model.\n prev_sensor_data[\"lidar\"][\"points\"] will be used as the input cloud, and the output\n cloud will be saved into sensor_data[\"lidar\"][\"points\"].\n This only handles 4-dimensional points, of the form (x, y, z, intensity).\n\n Args:\n * prev_sensor_data: a dict containing the following items\n {\n \"lidar\": {\n \"type\": \"lidar\",\n \"points\": ...\n },\n \"calib\": {\n ...\n },\n \"depth\": {\n \"type\": \"depth_map\",\n \"image\": ...\n },\n \"init_lidar\": {\n \"num_beams\": ...,\n \"points\": ...\n }\n\n }\n sensor_data[\"lidar\"][\"points\"] constitutes the main input the network.\n It could be initialized by sensor_data[\"init_lidar\"] for example.\n \n * net: (VoxelNet)\n\n * dataset: (Dataset) dataset.\n\n * policy: (Policy) one of the light curtain policies in second.light_curtain.policy.\n\n * sparsify_config: (config) options that are used to subsample a point cloud return.\n \n Returns:\n * dictionary of all information generated during the LC process\n {\n \"prev_sensor_data\": previous sensor data,\n \"next_sensor_data\": the new sensor data dict,\n \"lc_image\": lc_image returned by pylc API,\n \"lc_cloud\": lc_image processed into a point cloud; this is the main return,\n \"net_pred\": pred of the network,\n \"net_preds_dict\": preds_dict of the network, \n \"confidence_map\": network predictions converted to a confidence_map\n }\n * sensor_data: the same sensor_data, but with sensor_data[\"lidar\"][\"points\"] replaced by\n the new cumulative point cloud.\n\n \"\"\"\n net_was_training = net.training\n net.eval()\n\n points = prev_sensor_data[\"lidar\"][\"points\"]\n calib = prev_sensor_data[\"calib\"]\n\n example = dataset._prep_func_main(points, calib)\n if \"image_idx\" in prev_sensor_data[\"metadata\"]:\n example[\"metadata\"] = prev_sensor_data[\"metadata\"]\n\n if \"anchors_mask\" in example:\n example[\"anchors_mask\"] = example[\"anchors_mask\"].astype(np.uint8)\n \n # don't forget to pad batch idx in coordinates\n example[\"coordinates\"] = np.pad(\n example[\"coordinates\"], ((0, 0), (1, 0)),\n mode='constant',\n constant_values=0)\n \n # don't forget to add newaxis for anchors\n example[\"anchors\"] = example[\"anchors\"][np.newaxis, ...]\n\n with torch.no_grad():\n example_torch = example_convert_to_torch(example)\n pred, preds_dict = net(example_torch, ret_preds_dict=True)\n\n # Creating confidence map.\n cls_preds = preds_dict['cls_preds'] # shape=(1, 2, 200, 176, 1)\n cls_preds = cls_preds[0, :, :, :, 0] # shape=(2, 200, 176)\n cls_preds = torch.sigmoid(cls_preds).detach().cpu().numpy() # shape=(2, 200, 176)\n \n anchors = example[\"anchors\"][0] # (2 * 200 * 176, 7)\n anchors_mask = example.get(\"anchors_mask\", None) # (200 * 176,) dtype=np.uint8\n confidence_map = _get_confidence_map(anchors, anchors_mask, cls_preds, dataset.lc_device.TRANSFORMS[\"wTc\"])\n\n # Light curtain point cloud.\n depth_image = prev_sensor_data[\"depth\"][\"image\"]\n # Design points should be in the camera frame.\n design_pts = policy.get_design_points(confidence_map)\n lc_image = dataset.lc_device.get_return(depth_image, design_pts)\n lc_cloud = lc_image.reshape(-1, 4) # (N, 4)\n # Remove points which are NaNs.\n non_nan_mask = np.all(np.isfinite(lc_cloud), axis=1)\n lc_cloud = lc_cloud[non_nan_mask] # (N, 4)\n # Convert lc_cloud to velo frame.\n lc_cloud_xyz1 = np.hstack((lc_cloud[:, :3], np.ones([len(lc_cloud), 1], dtype=np.float32)))\n lc_cloud_xyz1 = lc_cloud_xyz1 @ dataset.lc_device.TRANSFORMS[\"cTw\"].T\n lc_cloud[:, :3] = lc_cloud_xyz1[:, :3] # (N, 4)\n # Rescale LC return to [0, 1].\n lc_cloud[:, 3] /= 255.\n\n lc_pts_added = lc_cloud\n if sparsify_config is not None:\n lc_pts_added = sparsify_lc_return(lc_pts_added, sparsify_config)\n\n next_sensor_data = prev_sensor_data.copy()\n next_sensor_data[\"lidar\"] = prev_sensor_data[\"lidar\"].copy()\n next_sensor_data[\"lidar\"][\"points\"] = np.vstack((next_sensor_data[\"lidar\"][\"points\"],\n lc_pts_added))\n\n # Reset training state of network.\n net.train(net_was_training)\n\n return {\n \"prev_sensor_data\": prev_sensor_data,\n \"next_sensor_data\": next_sensor_data,\n \"lc_image\": lc_image,\n \"lc_cloud\": lc_cloud,\n \"net_pred\": pred,\n \"net_preds_dict\": preds_dict, \n \"confidence_map\": confidence_map\n }\n\n\ndef sparsify_lc_return(lc_cloud, sparsify_config):\n \"\"\"\n Args:\n lc_cloud: (np.ndarray, dtype=np.float32, shape=(N, 4)) lc cloud.\n Axis 2 corresponds to (x, y, z, i):\n - x : x in velo frame.\n - y : y in velo frame.\n - z : z in velo frame.\n - i : intensity of LC cloud, lying in [0, 1].\n sparsify_config: (config) options that are used to subsample a point cloud return.\n \n Returns:\n lc_cloud: (same as above) subsampled lc cloud.\n \"\"\"\n # STEP 1: Remove points with large height.\n z = lc_cloud[:, 2]\n keep = (z <= sparsify_config.max_height)\n lc_cloud = lc_cloud[keep]\n\n # STEP 2: Split points according to high and low intensities.\n i = lc_cloud[:, 3]\n lc_cloud_pos = lc_cloud[i >= sparsify_config.pos_intensity_thresh / 255.]\n\n # STEP 3: Subsample negative points.\n if sparsify_config.neg_subsampling_rate > 0.0:\n lc_cloud_neg = lc_cloud[i < sparsify_config.pos_intensity_thresh / 255.]\n num_neg_pts_old = len(lc_cloud_neg)\n num_neg_pts_new = int(sparsify_config.neg_subsampling_rate * num_neg_pts_old)\n keep_inds = np.random.choice(num_neg_pts_old, num_neg_pts_new, replace=False)\n lc_cloud_neg = lc_cloud_neg[keep_inds]\n else:\n lc_cloud_neg = np.zeros((0, 4), dtype=np.float32) # (0, 4)\n\n lc_cloud = np.vstack([lc_cloud_pos, lc_cloud_neg])\n return lc_cloud\n\n\ndef _get_confidence_map(anchors, anchors_mask, cls_preds, vel2cam):\n \"\"\"Creates confidence map (definition below)\n Note: input (x, y, z) are in velo frame, and input matrices are ordered according to\n increasing velo Y and increasing velo X.\n \n Args:\n anchors: (np.ndarray, dtype=np.float32, shape=(K * Y * X, 7)) anchor boxes.\n Axis 2 corresponds to (velo x, velo y, velo z, w, b, h, orientation)\n K is the number of anchor boxes per location. Y and X are the dimensions sizes along\n velo y and velo x.\n anchors_mask: (np.ndarray, dtype=np.uint8, shape=(K * Y * X)) anchor mask.\n The anchors which are masked out are ignored while computing the networks loss\n and their predicted bounding boxes if any are also ignored at test time.\n We will set the confidence to 0 for these anchors.\n - K is the number of anchor boxes per location.\n - Y and X are the dimensions sizes along velo y and velo x.\n cls_preds: (np.ndarray, dtype=np.float32, shape=(K, Y, X)) confidence scores.\n Returns:\n confidence_map: (np.ndarray, dtype=float32, shape=(X, Z, 2+K)) confidence map of detector.\n Axis 0 corresponds to increasing X (camera frame) / decreasing Y (velo frame).\n Axis 1 corresponds to increasing Z (camera frame) / increasing X (velo frame).\n Axis 2 corresponds to (x, z, c_1, ..., c_K):\n - x : x in camera frame.\n - z : z in camera frame.\n - c_k : kth confidence score lying in [0, 1]. \n \"\"\"\n K, Y, X = cls_preds.shape\n \n cls_preds = cls_preds.transpose(1, 2, 0) # (Y, X, K)\n \n anchors = anchors.reshape(K, Y, X, 7) # (K, Y, X, 7)\n \n if anchors_mask is not None:\n anchors_mask = anchors_mask.reshape(K, Y, X) # (K, Y, X)\n\n # We will mask out all those anchor locations where any of the anchors is not in the mask.\n anchors_mask = np.all(anchors_mask, axis=0) # (Y, X)\n\n # Set confidence for locations outside anchors_mask to 0.\n y_out_inds, x_out_inds = np.where(np.logical_not(anchors_mask))\n cls_preds[y_out_inds, x_out_inds] = 0\n\n # The assumption is that all anchors at a location have the same x, y, z.\n for k in range(1, K):\n assert np.all(anchors[0, :, :, :3] == anchors[k, :, :, :3])\n anchors = anchors[0, :, :, :3] # (Y, X, 3)\n\n # Convert x, y, z from velo frame to cam frame.\n anchor_ones = np.concatenate([\n anchors,\n np.ones([anchors.shape[0], anchors.shape[1], 1], dtype=np.float32)\n ], axis=2) # (Y, X, 4)\n anchors = (anchor_ones @ vel2cam.T)[:, :, [0, 2]] # (Y, X, 2 -> cam x, cam z)\n\n confidence_map = np.concatenate((anchors, cls_preds), axis=2) # (Y, X, 2+K)\n # Note: axis 0 and axis 1 correspond to increasing velo Y and increasing velo X.\n # But, for confidence map, we need decreasing velo Y (increasing cam X)\n # and increasing velo X (increasing cam Z).\n confidence_map = np.flip(confidence_map, axis=0)\n \n return confidence_map\n","repo_name":"CMU-Light-Curtains/ObjectDetection","sub_path":"second/light_curtain/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10154,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"3375437591","text":"from django.urls import path\n\nfrom .views import ClienteCreate, ClienteDelete, ClienteUpdate, ClienteListView\n\nurlpatterns = [\n\tpath('cliente/new/', ClienteCreate.as_view(), name='new_cliente'),\n\tpath('clientes/', ClienteListView.as_view(), name='list_cliente'),\n\tpath('clientes/edit/', ClienteUpdate.as_view(), name='update_cliente'),\n\tpath('clientes/delete/', ClienteDelete.as_view(), name='delete_cliente'),\n]","repo_name":"KevCode53/GuaterP_Git","sub_path":"guaterpura/cliente/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18002283001","text":"import unittest\nimport hashlib\nimport warnings\n\nimport apt_pkg\n\nimport testcommon\n\n\nclass TestHashes(testcommon.TestCase):\n \"\"\"Test apt_pkg.Hashes() and the various apt_pkg.*sum() functions.\"\"\"\n\n def setUp(self):\n \"\"\"Prepare the tests, create reference values...\"\"\"\n testcommon.TestCase.setUp(self)\n self.file = open(apt_pkg.__file__, \"rb\")\n self.value = self.file.read()\n self.hashes = apt_pkg.Hashes(self.value)\n self.file.seek(0)\n self.fhashes = apt_pkg.Hashes(self.file)\n # Reference values.\n self.md5 = hashlib.md5(self.value).hexdigest()\n self.sha1 = hashlib.sha1(self.value).hexdigest()\n self.sha256 = hashlib.sha256(self.value).hexdigest()\n self.file.seek(0)\n\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n def tearDown(self):\n \"\"\"Cleanup, Close the file object used for the tests.\"\"\"\n testcommon.TestCase.tearDown(self)\n warnings.resetwarnings()\n self.file.close()\n\n def test_md5sum(self):\n \"\"\"hashes: Test apt_pkg.md5sum()\"\"\"\n self.assertEqual(apt_pkg.md5sum(self.value), self.md5)\n self.assertEqual(apt_pkg.md5sum(self.file), self.md5)\n\n def test_sha1sum(self):\n \"\"\"hashes: Test apt_pkg.sha1sum()\"\"\"\n self.assertEqual(apt_pkg.sha1sum(self.value), self.sha1)\n self.assertEqual(apt_pkg.sha1sum(self.file), self.sha1)\n\n def test_sha256sum(self):\n \"\"\"hashes: Test apt_pkg.sha256sum()\"\"\"\n self.assertEqual(apt_pkg.sha256sum(self.value), self.sha256)\n self.assertEqual(apt_pkg.sha256sum(self.file), self.sha256)\n\n def test_bytes(self):\n \"\"\"hashes: Test apt_pkg.Hashes(bytes)\"\"\"\n self.assertEqual(self.hashes.hashes.find(\"md5sum\").hashvalue,\n self.md5)\n self.assertEqual(self.hashes.hashes.find(\"md5sum\"),\n apt_pkg.HashString(\"MD5Sum\", self.md5))\n self.assertEqual(self.hashes.hashes.find(\"sha1\"),\n apt_pkg.HashString(\"SHA1\", self.sha1))\n self.assertEqual(self.hashes.hashes.find(\"sha256\"),\n apt_pkg.HashString(\"SHA256\", self.sha256))\n self.assertRaises(KeyError, self.hashes.hashes.find, \"md5\")\n\n def test_file(self):\n \"\"\"hashes: Test apt_pkg.Hashes(file).\"\"\"\n self.assertEqual(self.fhashes.hashes.find(\"md5sum\").hashvalue,\n self.md5)\n self.assertEqual(self.fhashes.hashes.find(\"md5sum\"),\n apt_pkg.HashString(\"MD5Sum\", self.md5))\n self.assertEqual(self.fhashes.hashes.find(\"sha1\"),\n apt_pkg.HashString(\"SHA1\", self.sha1))\n self.assertEqual(self.fhashes.hashes.find(\"sha256\"),\n apt_pkg.HashString(\"SHA256\", self.sha256))\n\n def test_unicode(self):\n \"\"\"hashes: Test apt_pkg.Hashes(unicode).\"\"\"\n self.assertRaises(TypeError, apt_pkg.Hashes, \"D\")\n self.assertRaises(TypeError, apt_pkg.md5sum, \"D\")\n self.assertRaises(TypeError, apt_pkg.sha1sum, \"D\")\n self.assertRaises(TypeError, apt_pkg.sha256sum, \"D\")\n\n\nclass TestHashString(testcommon.TestCase):\n \"\"\"Test apt_pkg.HashString().\"\"\"\n\n def setUp(self):\n \"\"\"Prepare the test by reading the file.\"\"\"\n testcommon.TestCase.setUp(self)\n self.file = open(apt_pkg.__file__)\n self.hashes = apt_pkg.Hashes(self.file)\n\n self.md5 = self.hashes.hashes.find(\"md5sum\")\n self.sha1 = self.hashes.hashes.find(\"sha1\")\n self.sha256 = self.hashes.hashes.find(\"sha256\")\n\n def tearDown(self):\n \"\"\"Cleanup, Close the file object used for the tests.\"\"\"\n self.file.close()\n\n def test_md5(self):\n \"\"\"hashes: Test apt_pkg.HashString().md5\"\"\"\n self.assertIn(\"MD5Sum:\", str(self.md5))\n self.assertTrue(self.md5.verify_file(apt_pkg.__file__))\n\n def test_sha1(self):\n \"\"\"hashes: Test apt_pkg.HashString().sha1\"\"\"\n self.assertIn(\"SHA1:\", str(self.sha1))\n self.assertTrue(self.sha1.verify_file(apt_pkg.__file__))\n\n def test_sha256(self):\n \"\"\"hashes: Test apt_pkg.HashString().sha256\"\"\"\n self.assertIn(\"SHA256:\", str(self.sha256))\n self.assertTrue(self.sha256.verify_file(apt_pkg.__file__))\n\n def test_wrong(self):\n \"\"\"hashes: Test apt_pkg.HashString(wrong_type).\"\"\"\n self.assertRaises(TypeError, apt_pkg.HashString, 0)\n self.assertRaises(TypeError, apt_pkg.HashString, bytes())\n\n\nclass TestHashStringList(testcommon.TestCase):\n \"\"\"Test apt_pkg.HashStringList()\"\"\"\n\n def test_file_size(self):\n hsl = apt_pkg.HashStringList()\n self.assertEqual(hsl.file_size, 0)\n hsl.file_size = 42\n self.assertEqual(hsl.file_size, 42)\n self.assertEqual(len(hsl), 1)\n\n # Verify that I can re-assign value (this handles the long case on\n # Python 2).\n hsl.file_size = hsl.file_size\n\n with self.assertRaises(OverflowError):\n hsl.file_size = -1\n\n hsl.file_size = 0\n\n def test_append(self):\n \"\"\"Testing whether append works correctly.\"\"\"\n hs1 = apt_pkg.HashString(\"MD5Sum\",\n \"a60599e6200b60050d7a30721e3532ed\")\n hs2 = apt_pkg.HashString(\"SHA1\",\n \"ef113338e654b1ada807a939ad47b3a67633391b\")\n\n hsl = apt_pkg.HashStringList()\n hsl.append(hs1)\n hsl.append(hs2)\n self.assertEqual(len(hsl), 2)\n self.assertEqual(hsl[0].hashtype, \"MD5Sum\")\n self.assertEqual(hsl[1].hashtype, \"SHA1\")\n self.assertEqual(str(hsl[0]), str(hs1))\n self.assertEqual(str(hsl[1]), str(hs2))\n\n def test_find(self):\n \"\"\"Testing whether append works correctly.\"\"\"\n hs1 = apt_pkg.HashString(\"MD5Sum\",\n \"a60599e6200b60050d7a30721e3532ed\")\n hs2 = apt_pkg.HashString(\"SHA1\",\n \"ef113338e654b1ada807a939ad47b3a67633391b\")\n\n hsl = apt_pkg.HashStringList()\n hsl.append(hs1)\n hsl.append(hs2)\n\n self.assertEqual(hsl.find(\"MD5Sum\").hashtype, \"MD5Sum\")\n self.assertEqual(hsl.find(\"SHA1\").hashtype, \"SHA1\")\n self.assertEqual(hsl.find().hashtype, \"SHA1\")\n\n def test_verify_file(self):\n with open(apt_pkg.__file__) as fobj:\n hashes = apt_pkg.Hashes(fobj)\n with warnings.catch_warnings(record=True):\n warnings.simplefilter(\"always\")\n sha1 = hashes.hashes.find(\"sha1\")\n sha256 = hashes.hashes.find(\"sha256\")\n\n hsl = apt_pkg.HashStringList()\n hsl.append(sha1)\n hsl.append(sha256)\n\n self.assertTrue(hsl.verify_file(apt_pkg.__file__))\n\n md5sum = apt_pkg.HashString(\"MD5Sum\",\n \"a60599e6200b60050d7a30721e3532ed\")\n hsl.append(md5sum)\n\n self.assertFalse(hsl.verify_file(apt_pkg.__file__))\n\n hsl2 = hashes.hashes\n self.assertIsInstance(hsl2, apt_pkg.HashStringList)\n self.assertGreater(len(hsl2), 0)\n self.assertTrue(hsl2.verify_file(apt_pkg.__file__))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"PikaOS-Linux/pkgs-baseos","sub_path":"python-apt/python-apt/tests/test_hashes.py","file_name":"test_hashes.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"73397572646","text":"# Tools for reading in the various configuration files in the JEA\n\nimport csv\n\ndef do_csvRead(filename, delimiter=','):\n '''Read a CSV file and return the rows as a list'''\n rows = []\n with open(filename, newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=delimiter, quotechar='|')\n for row in spamreader:\n rows += [row]\n return rows\n\ndef parseJournalEntries2(links):\n '''Interpret each entry in the list of strings, links, as two side-by-side\n journal entries indicating that the doubly-entry accounting on the left\n flows over to the double-entry accounting on the right. Check to make sure\n each line balances out.'''\n entity1 = links[1][0]\n entity2 = links[1][3]\n s = []\n for link in links[2:]:\n (acct1, dr1, cr1, acct2, dr2, cr2) = tuple(link[:6])\n assert (len(dr1)==0) ^ (len(cr1)==0), \"One debit or credit per line, but not both\"\n assert (len(dr2)==0) ^ (len(cr2)==0), \"One debit or credit per line, but not both\"\n assert (len(dr1)==0) ^ (len(dr2)==0), \"Debit on one entity must go to credit on the other\"\n assert (len(cr1)==0) ^ (len(cr2)==0), \"Debit on one entity must go to credit on the other\"\n if len(cr1) > 0:\n fromPt = (entity1, acct1)\n toPt = (entity2, acct2)\n assert cr1 == dr2, \"Line not balanced\"\n amount = cr1\n elif len(cr2) > 0:\n fromPt = (entity2, acct2)\n toPt = (entity1, acct1)\n assert cr2==dr1, \"Line not balanced\"\n amount = cr2\n else:\n assert False, \"Could not determine from/to: %s\" % link\n s += [(fromPt, toPt, amount)]\n return s\n\ndef parseJournalEntries(links):\n '''Interpret each entry in the list of strings, links, as two side-by-side\n journal entries indicating that the doubly-entry accounting on the left\n flows over to the double-entry accounting on the right. Check to make sure\n each line balances out.'''\n entity1 = links[1][0]\n entity2 = links[1][3]\n s = []\n for link in links[2:]:\n (from_entity, from_acct, to_entity, to_acct, gp) = tuple(link[:5])\n# print('(from_entity, from_acct, to_entity, to_acct, gp)=',(from_entity, from_acct, to_entity, to_acct, gp))\n #assert (len(dr1)==0) ^ (len(cr1)==0), \"One debit or credit per line, but not both\"\n #assert (len(dr2)==0) ^ (len(cr2)==0), \"One debit or credit per line, but not both\"\n #assert (len(dr1)==0) ^ (len(dr2)==0), \"Debit on one entity must go to credit on the other\"\n #assert (len(cr1)==0) ^ (len(cr2)==0), \"Debit on one entity must go to credit on the other\"\n if len(gp) > 0:\n fromPt = (from_entity, from_acct)\n toPt = (to_entity, to_acct)\n #assert cr1 == dr2, \"Line not balanced\"\n amount = gp\n# elif len(cr2) > 0:\n# fromPt = (entity2, acct2)\n# toPt = (entity1, acct1)\n# assert cr2==dr1, \"Line not balanced\"\n# amount = cr2\n else:\n assert False, \"Could not determine graphPoint: %s\" % link\n s += [(fromPt, toPt, amount)]\n return s\n\ndef parseAccountMapping(lines):\n '''Interprest each entry as an account in the JEA\n with the following format:'''\n accounts = [line[0] for line in lines[1:]]\n assert len(accounts) == len(set(accounts)), \"Not all account names in account mapping are unique\"\n return accounts\n\n\nif __name__ == '__main__':\n import sys\n\n for filename in sys.argv[1:]:\n print('Filename=',filename)\n rows = do_csvRead(filename)\n print('\\trows=',rows)\n s = parseJournalEntries(rows)\n print('\\ts=',s)\n print()\n \n","repo_name":"bches/journalEconomicAssertions","sub_path":"src/tools/JEAfileIO.py","file_name":"JEAfileIO.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25770333094","text":"\nfrom prediction import increment_model\nfrom db_conexion import engine\nimport time\nimport pickle\nfrom db_conexion import logging\nimport sys\n\nlogging.info(\"[ML] Loading Models...\")\nht_regressor = pickle.load(open('models/ht_regressor12F74.p', 'rb'))\n\nlogging.info(\"[ML] Models Loaded...\")\n\ndef get_integrate():\n while True:\n try:\n cnt = engine.execute(\"SELECT count(client_id) \\\n FROM Consumption \\\n WHERE integrated = 0\").first()[0] \n return cnt\n except:\n logging.error(\"[ML] Error to read the database\")\n\n return \n# try:\nstart_time = time.time()\ncounter = 75\nwhile True:\n while get_integrate() == 0:\n logging.info(\"[ML] Waiting new data...\"+str(round(time.time() - start_time,2)))\n time.sleep(60)\n start_time = time.time()\n logging.info(\"[ML] \" + str(get_integrate())+\" data points to be integrated...\"+ str(round(time.time() - start_time,2)))\n\n ht_regressor,client_id_min,client_id_max = increment_model(ht_regressor)\n time.sleep(3)\n logging.info(\"[ML] Last Client integrated: \"+ client_id_max)\n logging.info(\"[ML] Saving model at 'models/ht_regressor12F'...\" + str(counter))\n pickle.dump(ht_regressor, open( \"models/ht_regressor12F\"+str(counter)+ \".p\", \"wb\" ) )\n logging.info(\"[ML] Updating from \" + client_id_min + \" to \" + client_id_max)\n engine.execute(\"UPDATE Consumption \\\n SET integrated = 1 \\\n WHERE client_id BETWEEN \" + client_id_min + \" and \" + client_id_max)\n logging.info(\"[ML] Integration successfull execution in %d--- seconds ---\" % round(time.time() - start_time,2))\n time.sleep(7)\n counter += 1\n\n# except:\n# logging.error(\"[ML] Exception...\")\n# sys.exit(1)\n\n\n \n \n\n","repo_name":"Goduu/noveltyDetection","sub_path":"ML_service.py","file_name":"ML_service.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13115252312","text":"from sys import stdin\nn = int(stdin.readline())\ngraph = []\nd = []\nfor _ in range(n):\n graph.append(list(map(int, stdin.readline().split())))\n d.append([0] * n)\nd[0][0] = 1\nfor i in range(n):\n for j in range(n):\n if i == n-1 and j == n-1:\n break\n ni = i + graph[i][j]\n nj = j + graph[i][j]\n if ni < n:\n d[ni][j] += d[i][j]\n if nj < n:\n d[i][nj] += d[i][j]\n\nprint(d[n-1][n-1])\n","repo_name":"olive-su/1day_1Algorithm","sub_path":"22.03_PS/0302_점프.py","file_name":"0302_점프.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39959722635","text":"def _send_to_server(myDict):\n '''REALLY bad socket client code, used as a wrapper to interface with a remote server'''\n # All functions that start with _ are ignored by the game server\n import socket, sys, pickle\n HOST, PORT = \"localhost\", 9001\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((HOST, PORT))\n sock.sendall(pickle.dumps(myDict))\n\n received = pickle.loads(sock.recv(1024))\n return received\n\n# kwargs is a catch all for future compatability, right now it only contains \"playerName\"\ndef net_test(data = None, answer = None, **kwargs):\n '''No business logic for this challenge is exposed to the user'''\n return _send_to_server({\"question\": \"net_test\", \"data\": data, \"answer\": answer, 'playerName': kwargs[\"playerName\"]})\n","repo_name":"Code-Hugger/LEAP","sub_path":"game/remote.py","file_name":"remote.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"44541362922","text":"\n\"\"\"BMI calculator\nBMI = (weight/(height**2))\nUnderweight = BMI < 18.5\nNormal = BMI >= 18.5 and < 25 \nOverweight = BMI >= 25 and <30\nObese = BMI >30\"\"\"\n\n#input raw data of height and weight\nweight = float(input(\"How much do you weight? (in whole pound)\"))\nounces = float(input(\"Any ounces to your weight?\"))\nheight = float(input(\"How Tall are you? (in whole feet): \"))\ninches = float(input(\"Any inches to your Height:\"))\n\n#specifing the extra information\nadding_inches = inches / 12\nadding_ounces = ounces / 16\nnew_height = height + adding_inches\nnew_weight = weight + adding_ounces\n\n#convert to kg and meters\nconvert_to_kg = (new_weight * 0.45359237)\nconvert_to_meters = (new_height * 0.3048)\nprint(\"Your weight\", new_weight, \"lbs, is converted to \", convert_to_kg, \"kg\")\nprint(\"Your height\", new_height, \"ft, is converted to \", convert_to_meters, \"m\")\n\n#Calculate the BMI \nBMI = (convert_to_kg/(convert_to_meters**2))\n\n#if statements to see which condition the users input meets\nif BMI >0:\n if BMI < 18.5:\n print(\"You are considered: 'Underweight'\")\n elif BMI < 25:\n print(\"You are considered: 'Normal'\")\n elif BMI < 30:\n print(\"You are considered: 'Overweight'\")\n elif BMI >= 30:\n print(\"You are considered: 'Obese'\")\n","repo_name":"ReggieRay210/BMI-Calculator","sub_path":"BMI_calculator.py","file_name":"BMI_calculator.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33837557020","text":"from dice import Die\n\nclass Layout(object):\n \"\"\"\n A collection of starting dice, health, and armor for a particular\n class' major/minor attributes.\n\n Maybe in the future, starting equipment, and items will be covered too.\n\n This class instance's data is meant to be accumulated. Should a player choose\n a \"Wizard\" major and a \"Fighter\" minor, you should combine each of these\n major/minor attributes to create a complete player profile.\n \"\"\"\n\n def __init__(self, dice=None, health=0, armor=0, agility=0):\n if dice is None:\n dice = []\n\n self.dice = dice\n self.health = health\n self.armor = armor\n self.agility = agility\n\n\nclass Rouge(object):\n major_dice = [Die('white')] * 5 + [Die('red')] + [Die('black')] * 3\n major = Layout(\n dice=major_dice,\n health=1,\n armor=1,\n agility=2\n )\n\n minor_dice = [Die('red')] + [Die('black')]\n minor = Layout(\n dice=dice,\n health=1,\n agility=1\n )\n\n\nclass Wizard(object):\n major_dice = [Die('white')] * 3 + [Die('blue')] * 3 + [Die('green')]\n major = Layout(\n dice=dice,\n health=1\n )\n\n minor_dice = [Die('blue')] + [Die('green')]\n minor = Layout(\n dice=dice\n )\n\nclass Cleric(object):\n major_dice = [Die('white')] * 4 + [Die('blue')] + [Die('green')] * 3\n major = Layout(\n dice=dice,\n health=1\n )\n\n minor_dice = [Die('blue')] + [Die('green')]\n minor = Layout(\n dice=dice\n )\n\n\nclass Fighter(object):\n major_dice = [Die('white')] * 6 + [Die('red')] * 3 + [Die('black')]\n major = Layout(\n dice=dice,\n health=1,\n armor=1,\n agility=1\n )\n\n minor_dice = [Die('red')] + [Die('black')]\n minor = Layout(\n dice=dice,\n armor=1,\n agility=1\n )\n\n\nclass Bard(object):\n major_dice = [Die('white')] * 4 + [Die('red')] + [Die('blue')] + [Die('black')] + [Die('green')]\n major = Layout(\n dice=dice,\n agility=1,\n health=1\n )\n\n minor_dice = [Die('red')] + [Die('blue')]\n minor = Layout(\n dice=dice,\n agility=1\n )\n","repo_name":"PlaytestersKitchen/dungeons-and-dicebags","sub_path":"sim/src/player/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26826604638","text":"import re\nfrom nltk import word_tokenize\nimport unicodedata\nimport string\nimport numpy as np\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nimport pandas as pd\n\nclass PreprocessData:\n\tdef url_elimination(self, text):\n\t\turls = re.findall('(?:(?:https?|ftp):\\/\\/)?[\\w/\\-?=%.]+\\.[\\w/\\-?=%.]+', text)\n\t\toutput = ''\n\t\tfor url in urls:\n\t\t\tx = text.find(url)\n\t\t\tif x > 0:\n\t\t\t\toutput += text[:x]\n\t\t\t\toutput += \"url \"\n\t\t\t\ttext = text[x+len(url) +1:]\n\t\toutput += text\n\t\treturn output\n\n\tdef tokenize(self, text):\n\t\ttext = self.url_elimination(text)\n\t\treturn [w.lower() for w in word_tokenize(text)]\n\t\t\n\tdef remove_non_ascii(self, words):\n\t\t\"\"\"Remove non-ASCII characters from list of tokenized words\"\"\"\n\t\tnew_words = []\n\t\tfor word in words:\n\t\t\tnew_word = unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n\t\t\tnew_words.append(new_word)\n\t\treturn new_words\n\n\tdef remove_punctuation(self, words):\n\t\tnew_words = []\n\t\tfor word in words:\n\t\t\ttemp = word.strip(string.punctuation)\n\t\t\tif temp is not '':\n\t\t\t\tnew_words.append(temp)\n\t\treturn new_words\n\n\tdef replace_numbers(self, words):\n\t\t\"\"\"Replace all interger occurrences in list of tokenized words with textual representation\"\"\"\n\t\treturn [re.sub(r'\\d+', '', word) for word in words]\n\n\tdef normalize_string(self, text):\n\t\treturn re.sub(r'([a-z])\\1+', lambda m: m.group(1).lower(), text, flags=re.IGNORECASE)\n\n\tdef clean_str(self, string):\n\t\tstring = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n\t\tstring = re.sub(r\"\\'s\", \" \\'s\", string)\n\t\tstring = re.sub(r\"\\'ve\", \" \\'ve\", string)\n\t\tstring = re.sub(r\"n\\'t\", \" n\\'t\", string)\n\t\tstring = re.sub(r\"\\'re\", \" \\'re\", string)\n\t\tstring = re.sub(r\"\\'d\", \" \\'d\", string)\n\t\tstring = re.sub(r\"\\'ll\", \" \\'ll\", string)\n\t\tstring = re.sub(r\",\", \" , \", string)\n\t\tstring = re.sub(r\"!\", \" ! \", string)\n\t\tstring = re.sub(r\"\\(\", \" \\( \", string)\n\t\tstring = re.sub(r\"\\)\", \" \\) \", string)\n\t\tstring = re.sub(r\"\\?\", \" \\? \", string)\n\t\tstring = re.sub(r\"\\s{2,}\", \" \", string)\n\t\treturn string.strip().lower()\n\n\tdef clean(self, text):\n\t\ttext = self.clean_str(text)\n\t\ttext = self.normalize_string(text)\n\t\twords = self.tokenize(text)\n\t\twords = self.remove_non_ascii(words)\n\t\twords = self.remove_punctuation(words)\n\t\twords = self.replace_numbers(words)\n\t\treturn ' '.join(words)\n\n\tdef get_modified_data(self, filepath):\n\t\tf = open(filepath, 'r')\n\t\tdata_processed = []\n\t\tfor line in f.readlines():\n\t\t\tline = line.strip()\n\t\t\ttemp = line.split('\\t')\n\t\t\tfor i in range(2):\n\t\t\t\ttemp[i] = self.clean(temp[i])\n\t\t\tdata_processed.append(temp)\n\t\tf.close()\n\t\treturn data_processed\n \n\tdef build_corpus(self, filepath):\n\t\tprint('Loading %s' % filepath)\n\t\tdata_processed = self.get_modified_data(filepath)\n\t\tquestions = []\n\t\tanswers = []\n\t\tlabels = []\n\t\tfor i in range (len(data_processed)):\n\t\t\tquestions.extend([data_processed[i][0]])\n\t\t\tanswers.extend([data_processed[i][1]])\n\t\t\tlabels.append(int(data_processed[i][2]))\n\t\tprint('Done loading %s' % filepath)\n\t\treturn (questions, answers, labels)","repo_name":"vudat1710/CQA_reformat","sub_path":"utils/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41549595937","text":"# https://programmers.co.kr/learn/courses/30/lessons/42578\n\ndef solution(clothes):\n answer = 1\n dic = {}\n for cloth, key in clothes:\n if key in dic.keys():\n dic[key].append(cloth)\n else:\n dic[key] = [cloth]\n for clothes in dic.values():\n answer *= len(clothes)+1\n return answer-1\n\n# 이건 좀 더 느림\n# def solution(clothes):\n# answer = 1\n# dic = {}\n# for cloth, key in clothes:\n# if key in dic.keys():\n# dic[key] += 1\n# else:\n# dic[key] = 1\n# print(dic)\n# for num_clothes in dic.values():\n# print(num_clothes)\n# answer *= num_clothes+1\n# return answer-1\n\nclothes1 = [[\"yellow_hat\", \"headgear\"], [\"blue_sunglasses\", \"eyewear\"], [\"green_turban\", \"headgear\"]]\nclothes2 = [[\"crow_mask\", \"face\"], [\"blue_sunglasses\", \"face\"], [\"smoky_makeup\", \"face\"]]\n\nprint(solution(clothes1))\nprint(solution(clothes2))","repo_name":"hongjy127/TIL","sub_path":"0. coding_test/programmers/practice_hash_3.py","file_name":"practice_hash_3.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13775128052","text":"#!/usr/bin/env python3\n\n\"\"\" \n fb2cal - Facebook Birthday Events to ICS file converter\n Created by: mobeigi\n\n This program is free software: you can redistribute it and/or modify it under\n the terms of the GNU General Public License as published by the Free Software\n Foundation, either version 3 of the License, or (at your option) any later\n version.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n You should have received a copy of the GNU General Public License along with\n this program. If not, see .\n\"\"\"\n\n\nimport os\nimport sys\nimport platform\nimport re\nimport mechanicalsoup\nimport requests\nimport urllib.parse\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\nfrom babel import Locale\nfrom babel.core import UnknownLocaleError\nfrom babel.dates import format_date\nimport html\nimport locale\nimport pytz\nimport json\nimport ics\nfrom ics import Calendar, Event\nimport configparser\nimport logging\nfrom distutils import util\n\n# Classes\n\n\nclass Birthday:\n def __init__(self, uid, name, day, month):\n # Unique identififer for person (required for ics events)\n self.uid = uid\n self.name = name\n self.day = day\n self.month = month\n\n def __str__(self):\n return f'{self.name} ({self.day}/{self.month})'\n\n def __unicode__(self):\n return u'{self.name} ({self.day}/{self.month})'\n\n# Entry point\n\n\ndef get_birthdays(email, password):\n\n browser = mechanicalsoup.StatefulBrowser()\n init_browser(browser)\n\n # Attempt login\n facebook_authenticate(browser, email, password)\n\n # Get birthday objects for all friends via async endpoint\n birthdays = get_async_birthdays(browser)\n\n if len(birthdays) == 0:\n raise SystemError\n\n c = populate_birthdays_calendar(birthdays)\n\n # Remove blank lines\n return ''.join([line.rstrip('\\n') for line in c])\n\n\ndef init_browser(browser):\n \"\"\" Initialize browser as needed \"\"\"\n browser.set_user_agent(\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36')\n\n\ndef facebook_authenticate(browser, email, password):\n \"\"\" Authenticate with Facebook setting up session for further requests \"\"\"\n\n FACEBOOK_LOGIN_URL = 'http://www.facebook.com/login.php'\n FACEBOOK_DATR_TOKEN_REGEXP = r'\\\"_js_datr\\\",\\\"(.*?)\\\"'\n regexp = re.compile(FACEBOOK_DATR_TOKEN_REGEXP, re.MULTILINE)\n\n # Add 'datr' cookie to session for countries adhering to GDPR compliance\n login_page = browser.get(FACEBOOK_LOGIN_URL)\n\n if login_page.status_code != 200:\n raise SystemError\n\n matches = regexp.search(login_page.text)\n\n if not matches or len(matches.groups()) != 1:\n raise SystemError\n\n _js_datr = matches[1]\n\n datr_cookie = requests.cookies.create_cookie(\n domain='.facebook.com', name='datr', value=_js_datr)\n _js_datr_cookie = requests.cookies.create_cookie(\n domain='.facebook.com', name='_js_datr', value=_js_datr)\n browser.get_cookiejar().set_cookie(datr_cookie)\n browser.get_cookiejar().set_cookie(_js_datr_cookie)\n\n # Perform main login now\n login_page = browser.get(FACEBOOK_LOGIN_URL)\n\n if login_page.status_code != 200:\n raise SystemError\n\n login_form = login_page.soup.find('form', {'id': 'login_form'})\n login_form.find('input', {'id': 'email'})['value'] = email\n login_form.find('input', {'id': 'pass'})['value'] = password\n login_response = browser.submit(login_form, login_page.url)\n\n if login_response.status_code != 200:\n raise SystemError\n\n # Check to see if login failed\n if login_response.soup.find('link', {'rel': 'canonical', 'href': 'https://www.facebook.com/login/'}):\n raise SystemError\n\n # Check to see if we hit Facebook security checkpoint\n if login_response.soup.find('button', {'id': 'checkpointSubmitButton'}):\n raise SystemError\n\n\n__cached_async_token = None\n\n\ndef get_async_token(browser):\n \"\"\" Get async authorization token (CSRF protection token) that must be included in all async requests \"\"\"\n\n global __cached_async_token\n\n if __cached_async_token:\n return __cached_async_token\n\n # async token is present on this page\n FACEBOOK_BIRTHDAY_EVENT_PAGE_URL = 'https://www.facebook.com/events/birthdays/'\n FACEBOOK_ASYNC_TOKEN_REGEXP_STRING = r'{\\\"token\\\":\\\".*?\\\",\\\"async_get_token\\\":\\\"(.*?)\\\"}'\n regexp = re.compile(FACEBOOK_ASYNC_TOKEN_REGEXP_STRING, re.MULTILINE)\n\n birthday_event_page = browser.get(FACEBOOK_BIRTHDAY_EVENT_PAGE_URL)\n\n if birthday_event_page.status_code != 200:\n raise SystemError\n\n matches = regexp.search(birthday_event_page.text)\n\n if not matches or len(matches.groups()) != 1:\n raise SystemError\n\n __cached_async_token = matches[1]\n\n return matches[1]\n\n\n__locale = None\n\n\ndef get_facebook_locale(browser):\n \"\"\" Returns users Facebook locale \"\"\"\n\n global __locale\n\n if __locale:\n return __locale\n\n FACEBOOK_LOCALE_ENDPOINT = 'https://www.facebook.com/ajax/settings/language/account.php?'\n FACEBOOK_LOCALE_REGEXP_STRING = r'[a-z]{2}_[A-Z]{2}'\n regexp = re.compile(FACEBOOK_LOCALE_REGEXP_STRING, re.MULTILINE)\n\n # Not all fields are required for response to be given, required fields are fb_dtsg_ag and __a\n query_params = {'fb_dtsg_ag': get_async_token(browser),\n '__a': '1'}\n\n response = browser.get(FACEBOOK_LOCALE_ENDPOINT +\n urllib.parse.urlencode(query_params))\n\n if response.status_code != 200:\n raise SystemError\n\n # Parse json response\n try:\n json_response = json.loads(strip_ajax_response_prefix(response.text))\n current_locale = json_response['jsmods']['require'][0][3][1]['currentLocale']\n except json.decoder.JSONDecodeError as e:\n raise SystemError\n except KeyError as e:\n raise SystemError\n\n # Validate locale\n if not regexp.match(current_locale):\n raise SystemError\n\n __locale = current_locale\n\n return __locale\n\n\ndef get_async_birthdays(browser):\n \"\"\" Returns list of birthday objects by querying the Facebook birthday async page \"\"\"\n\n FACEBOOK_BIRTHDAY_ASYNC_ENDPOINT = 'https://www.facebook.com/async/birthdays/?'\n\n birthdays = []\n\n next_12_months_epoch_timestamps = get_next_12_month_epoch_timestamps()\n\n for epoch_timestamp in next_12_months_epoch_timestamps:\n\n # Not all fields are required for response to be given, required fields are date, fb_dtsg_ag and __a\n query_params = {'date': epoch_timestamp,\n 'fb_dtsg_ag': get_async_token(browser),\n '__a': '1'}\n\n response = browser.get(\n FACEBOOK_BIRTHDAY_ASYNC_ENDPOINT + urllib.parse.urlencode(query_params))\n\n if response.status_code != 200:\n raise SystemError\n\n birthdays_for_month = parse_birthday_async_output(\n browser, response.text)\n birthdays.extend(birthdays_for_month)\n\n return birthdays\n\n\ndef get_next_12_month_epoch_timestamps():\n \"\"\" Returns array of epoch timestamps corresponding to the 1st day of the next 12 months starting from the current month.\n For example, if the current date is 2000-05-20, will return epoch for 2000-05-01, 2000-06-01, 2000-07-01 etc for 12 months \"\"\"\n\n epoch_timestamps = []\n\n # Facebook timezone seems to use Pacific Standard Time locally for these epochs\n # So we have to convert our 00:00:01 datetime on 1st of month from Pacific to UTC before getting our epoch timestamps\n pdt = pytz.timezone('America/Los_Angeles')\n cur_date = datetime.now()\n\n # Loop for next 12 months\n for _ in range(12):\n # Reset day to 1 and time to 00:00:01\n cur_date = cur_date.replace(\n day=1, hour=0, minute=0, second=0, microsecond=0)\n\n # Convert from Pacific to UTC and store timestamp\n utc_date = pdt.localize(cur_date).astimezone(pytz.utc)\n epoch_timestamps.append(int(utc_date.timestamp()))\n\n # Move cur_date to 1st of next month\n cur_date = cur_date + relativedelta(months=1)\n\n return epoch_timestamps\n\n\ndef parse_birthday_async_output(browser, text):\n \"\"\" Parsed Birthday Async output text and returns list of Birthday objects \"\"\"\n BIRTHDAY_STRING_REGEXP_STRING = r'class=\\\"_43q7\\\".*?href=\\\"https://www\\.facebook\\.com/(.*?)\\\".*?data-tooltip-content=\\\"(.*?)\\\">.*?alt=\\\"(.*?)\\\".*?/>'\n regexp = re.compile(BIRTHDAY_STRING_REGEXP_STRING, re.MULTILINE)\n\n birthdays = []\n\n # Fetch birthday card html payload from json response\n try:\n json_response = json.loads(strip_ajax_response_prefix(text))\n birthday_card_html = json_response['domops'][0][3]['__html']\n except json.decoder.JSONDecodeError as e:\n raise SystemError\n except KeyError as e:\n raise SystemError\n\n user_locale = get_facebook_locale(browser)\n\n for vanity_name, tooltip_content, name in regexp.findall(birthday_card_html):\n # Check to see if user has no custom vanity name in which case we'll just take the id directly\n if vanity_name.startswith('profile.php?id='):\n uid = vanity_name[15:]\n else:\n uid = get_entity_id_from_vanity_name(browser, vanity_name)\n\n # Parse tooltip content into day/month\n day, month = parse_birthday_day_month(\n tooltip_content, name, user_locale)\n\n birthdays.append(Birthday(uid, html.unescape(name), day, month))\n\n return birthdays\n\n\ndef parse_birthday_day_month(tooltip_content, name, user_locale):\n \"\"\" Convert the Facebook birthday tooltip content to a day and month number. Facebook will use a tooltip format based on the users Facebook language (locale).\n The date will be in some date format which reveals the birthday day and birthday month.\n This is done for all birthdays expect those in the following week relative to the current date.\n Those will instead show day names such as 'Monday', 'Tuesday' etc for the next 7 days. \"\"\"\n\n birthday_date_str = tooltip_content\n\n # List of strings that will be stripped away from tooltip_content\n # The goal here is to remove all other characters except the birthday day, birthday month and day/month seperator symbol\n strip_list = [\n name, # Full name of user which will appear somewhere in the string\n '(', # Regular left bracket\n ')', # Regular right bracket\n '‏', # Remove right-to-left mark (RLM)\n '‎', # Remove left-to-right mark (LRM)\n '՝' # Backtick character name postfix in Armenian\n ]\n\n for string in strip_list:\n birthday_date_str = birthday_date_str.replace(string, '')\n\n birthday_date_str = birthday_date_str.strip()\n\n # Dict with mapping of locale identifier to month/day datetime format\n locale_date_format_mapping = {\n 'af_ZA': '%d-%m',\n 'am_ET': '%m/%d',\n # 'ar_AR': '', # TODO: parse Arabic numeric characters\n # 'as_IN': '', # TODO: parse Assamese numeric characters\n 'az_AZ': '%d.%m',\n 'be_BY': '%d.%m',\n 'bg_BG': '%d.%m',\n 'bn_IN': '%d/%m',\n 'br_FR': '%d/%m',\n 'bs_BA': '%d.%m.',\n 'ca_ES': '%d/%m',\n # 'cb_IQ': '', # TODO: parse Arabic numeric characters\n 'co_FR': '%m-%d',\n 'cs_CZ': '%d. %m.',\n 'cx_PH': '%m-%d',\n 'cy_GB': '%d/%m',\n 'da_DK': '%d.%m',\n 'de_DE': '%d.%m.',\n 'el_GR': '%d/%m',\n 'en_GB': '%d/%m',\n 'en_UD': '%m/%d',\n 'en_US': '%m/%d',\n 'eo_EO': '%m-%d',\n 'es_ES': '%d/%m',\n 'es_LA': '%d/%m',\n 'et_EE': '%d.%m',\n 'eu_ES': '%m/%d',\n # 'fa_IR': '', # TODO: parse Persian numeric characters\n 'ff_NG': '%d/%m',\n 'fi_FI': '%d.%m.',\n 'fo_FO': '%d.%m',\n 'fr_CA': '%m-%d',\n 'fr_FR': '%d/%m',\n 'fy_NL': '%d-%m',\n 'ga_IE': '%d/%m',\n 'gl_ES': '%d/%m',\n 'gn_PY': '%m-%d',\n 'gu_IN': '%d/%m',\n 'ha_NG': '%m/%d',\n 'he_IL': '%d.%m',\n 'hi_IN': '%d/%m',\n 'hr_HR': '%d. %m.',\n 'ht_HT': '%m-%d',\n 'hu_HU': '%m. %d.',\n 'hy_AM': '%d.%m',\n 'id_ID': '%d/%m',\n 'is_IS': '%d.%m.',\n 'it_IT': '%d/%m',\n 'ja_JP': '%m/%d',\n 'ja_KS': '%m/%d',\n 'jv_ID': '%d/%m',\n 'ka_GE': '%d.%m',\n 'kk_KZ': '%d.%m',\n 'km_KH': '%d/%m',\n 'kn_IN': '%d/%m',\n 'ko_KR': '%m. %d.',\n 'ku_TR': '%m-%d',\n 'ky_KG': '%d-%m',\n 'lo_LA': '%d/%m',\n 'lt_LT': '%m-%d',\n 'lv_LV': '%d.%m.',\n 'mg_MG': '%d/%m',\n 'mk_MK': '%d.%m',\n 'ml_IN': '%d/%m',\n 'mn_MN': '%m-р сар/%d',\n # 'mr_IN': '', # TODO: parse Marathi numeric characters\n 'ms_MY': '%d-%m',\n 'mt_MT': '%m-%d',\n # 'my_MM': '', # TODO: parse Myanmar numeric characters\n 'nb_NO': '%d.%m.',\n # 'ne_NP': '', # TODO: parse Nepali numeric characters\n 'nl_BE': '%d/%m',\n 'nl_NL': '%d-%m',\n 'nn_NO': '%d.%m.',\n 'or_IN': '%m/%d',\n 'pa_IN': '%d/%m',\n 'pl_PL': '%d.%m',\n # 'ps_AF': '', # TODO: parse Afghani numeric characters\n 'pt_BR': '%d/%m',\n 'pt_PT': '%d/%m',\n 'ro_RO': '%d.%m',\n 'ru_RU': '%d.%m',\n 'rw_RW': '%m-%d',\n 'sc_IT': '%m-%d',\n 'si_LK': '%m-%d',\n 'sk_SK': '%d. %m.',\n 'sl_SI': '%d. %m.',\n 'sn_ZW': '%m-%d',\n 'so_SO': '%m/%d',\n 'sq_AL': '%d.%m',\n 'sr_RS': '%d.%m.',\n 'sv_SE': '%d/%m',\n 'sw_KE': '%d/%m',\n 'sy_SY': '%m-%d',\n 'sz_PL': '%m-%d',\n 'ta_IN': '%d/%m',\n 'te_IN': '%d/%m',\n 'tg_TJ': '%m-%d',\n 'th_TH': '%d/%m',\n 'tl_PH': '%m/%d',\n 'tr_TR': '%d/%m',\n 'tt_RU': '%d.%m',\n 'tz_MA': '%m/%d',\n 'uk_UA': '%d.%m',\n 'ur_PK': '%d/%m',\n 'uz_UZ': '%d/%m',\n 'vi_VN': '%d/%m',\n 'zh_CN': '%m/%d',\n 'zh_HK': '%d/%m',\n 'zh_TW': '%m/%d',\n 'zz_TR': '%m-%d'\n }\n\n # Ensure a supported locale is being used\n if user_locale not in locale_date_format_mapping:\n raise SystemError\n\n try:\n # Try to parse the date using appropriate format based on locale\n parsed_date = datetime.strptime(\n birthday_date_str, locale_date_format_mapping[user_locale])\n return (parsed_date.day, parsed_date.month)\n except ValueError:\n # Otherwise, have to convert day names to a day and month\n offset_dict = get_day_name_offset_dict(user_locale)\n cur_date = datetime.now()\n\n # Use beautiful soup to parse special html codes properly before matching with our dict\n day_name = BeautifulSoup(birthday_date_str, 'lxml').get_text().lower()\n\n if day_name in offset_dict:\n cur_date = cur_date + relativedelta(days=offset_dict[day_name])\n return (cur_date.day, cur_date.month)\n\n raise SystemError\n\n\ndef get_day_name_offset_dict(user_locale):\n \"\"\" The day name to offset dict maps a day name to a numerical day offset which can be used to add days to the current date.\n Day names will match the provided user locale and will be in lowercase.\n \"\"\"\n\n offset_dict = {}\n\n # Todays birthdays will be shown normally (as a date) so start from tomorrow\n start_date = datetime.now() + relativedelta(days=1)\n\n # Method 1: Babel\n try:\n babel_locale = Locale.parse(user_locale, sep='_')\n cur_date = start_date\n\n # Iterate through the following 7 days\n for i in range(1, 8):\n offset_dict[format_date(\n cur_date, 'EEEE', locale=babel_locale).lower()] = i\n cur_date = cur_date + relativedelta(days=1)\n\n return offset_dict\n except UnknownLocaleError as e:\n raise SystemError\n\n # Method 2: System locale\n cur_date = start_date\n locale_check_list = [user_locale, user_locale +\n 'UTF-8', user_locale + 'utf-8']\n system_locale = None\n\n # Windows\n if any(platform.win32_ver()):\n for locale_to_check in locale_check_list:\n if locale_to_check in locale.windows_locale.values():\n system_locale = locale_to_check\n break\n # POSIX\n else:\n for locale_to_check in locale_check_list:\n if locale_to_check in locale.locale_alias.values():\n system_locale = locale_to_check\n break\n\n # Check if system locale was found\n if system_locale:\n locale.setlocale(locale.LC_ALL, system_locale)\n\n # Iterate through the following 7 days\n for i in range(1, 8):\n offset_dict[cur_date.strftime('%A').lower()] = i\n cur_date = cur_date + relativedelta(days=1)\n\n return offset_dict\n else:\n\n # Failure\n raise SystemError\n\n\ndef get_entity_id_from_vanity_name(browser, vanity_name):\n \"\"\" Given a vanity name (user/page custom name), try to get the unique identifier entity_id \"\"\"\n\n # Method 1: Composer Query async\n # Loop through entries to see if a valid match is found where alias matches provided vanity name\n composer_query_entries = get_composer_query_entries(browser, vanity_name)\n for entry in composer_query_entries:\n # Skip other render types like commerce pages etc\n if entry['vertical_type'] != 'USER' and entry['render_type'] not in ['friend', 'non_friend']:\n continue\n\n if 'alias' in entry and entry['alias'] == vanity_name:\n # Match found!\n return entry['uid']\n\n # Method 2: Scrape users profile page for entity id (significantly slower)\n entity_id = get_entity_id_from_profile_page(browser, vanity_name)\n if entity_id:\n return entity_id\n\n # Failure\n raise SystemError\n\n\ndef get_composer_query_entries(browser, value):\n \"\"\" Get list of entries from the composer query endpoint \"\"\"\n\n COMPOSER_QUERY_ASYNC_ENDPOINT = \"https://www.facebook.com/ajax/mercury/composer_query.php?\"\n\n # Not all fields are required for response to be given, required fields are value, fb_dtsg_ag and __a\n query_params = {'value': value,\n 'fb_dtsg_ag': get_async_token(browser),\n '__a': '1'}\n\n response = browser.get(COMPOSER_QUERY_ASYNC_ENDPOINT +\n urllib.parse.urlencode(query_params))\n\n if response.status_code != 200:\n return []\n\n # Parse json response\n try:\n json_response = json.loads(strip_ajax_response_prefix(response.text))\n return json_response['payload']['entries']\n except json.decoder.JSONDecodeError as e:\n return []\n except KeyError as e:\n return []\n\n\ndef get_entity_id_from_profile_page(browser, vanity_name):\n \"\"\" Get entity id from a users profile page \"\"\"\n\n FACEBOOK_PROFILE_PAGE_ENTITY_ID_REGEXP_STRING = r'entity_id:(\\d+),ef_page:'\n regexp = re.compile(\n FACEBOOK_PROFILE_PAGE_ENTITY_ID_REGEXP_STRING, re.MULTILINE)\n\n response = browser.get(f'https://m.facebook.com/{vanity_name}')\n if response.status_code != 200:\n return None\n\n matches = regexp.search(response.text)\n\n if not matches or len(matches.groups()) != 1:\n return None\n\n return matches[1]\n\n\ndef strip_ajax_response_prefix(payload):\n \"\"\" Strip the prefix that Facebook puts in front of AJAX responses \"\"\"\n\n if payload.startswith('for (;;);'):\n return payload[9:]\n return payload\n\n\ndef populate_birthdays_calendar(birthdays):\n \"\"\" Populate a birthdays calendar using birthday objects \"\"\"\n\n c = Calendar()\n c.scale = 'GREGORIAN'\n c.method = 'PUBLISH'\n c.creator = f'fb2cal'\n c._unused.append(ics.parse.ContentLine(name='X-WR-CALNAME',\n params={}, value='Facebook Birthdays (fb2cal)'))\n c._unused.append(ics.parse.ContentLine(\n name='X-PUBLISHED-TTL', params={}, value='PT12H'))\n c._unused.append(ics.parse.ContentLine(\n name='X-ORIGINAL-URL', params={}, value='/events/birthdays/'))\n\n cur_date = datetime.now()\n\n for birthday in birthdays:\n e = Event()\n e.uid = birthday.uid\n e.name = f\"{birthday.name}'s Birthday\"\n\n # Calculate the year as this year or next year based on if its past current month or not\n # Also pad day, month with leading zeros to 2dp\n year = cur_date.year if birthday.month >= cur_date.month else (\n cur_date + relativedelta(years=1)).year\n month = '{:02d}'.format(birthday.month)\n day = '{:02d}'.format(birthday.day)\n e.begin = f'{year}-{month}-{day} 00:00:00'\n e.make_all_day()\n e.duration = timedelta(days=1)\n e._unused.append(ics.parse.ContentLine(\n name='RRULE', params={}, value='FREQ=YEARLY'))\n\n c.events.add(e)\n\n return c\n","repo_name":"pmihaly/facebook-bdays","sub_path":"bdays.py","file_name":"bdays.py","file_ext":"py","file_size_in_byte":21183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4598784853","text":"from django.core.management.base import BaseCommand\nfrom django.conf import settings\nimport os\nimport shutil\n\nclass Command(BaseCommand):\n help = \"Import language files previously exported through the 'export_language_files' command from a folder.\"\n\n def add_arguments(self, parser):\n parser.add_argument('-p', '--inpath', type=str, help='The path to the folder from which to import the files.')\n\n def handle(self, *args, **options):\n separator = \"___\"\n\n input_folder_path = options['inpath']\n if not input_folder_path:\n self.stderr.write(\"The input folder path is mandatory!\")\n return\n\n base_folder = str(settings.BASE_DIR / 'g3w-admin/g3w-admin')\n \n print(f\"Looking for tanslation files (*.po) inside: {input_folder_path}\")\n\n for file in os.listdir(input_folder_path):\n if file.endswith(\".po\"):\n rel_file_path = file.replace(separator, \"/\")\n\n from_path = os.path.join(input_folder_path, file)\n to_path = os.path.join(base_folder, rel_file_path)\n print(f\"Copying {from_path}\")\n print(f\" ---> {to_path}\")\n shutil.copyfile(from_path, to_path)\n\n print(\"Done.\")\n \n ","repo_name":"g3w-suite/g3w-admin","sub_path":"g3w-admin/base/management/commands/import_language_files.py","file_name":"import_language_files.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"52"} +{"seq_id":"8899304081","text":"from bootstrapvz.base import Task\nfrom .. import phases\nfrom ..tasks import packages\n\n\nclass AddDKMSPackages(Task):\n\tdescription = 'Adding DKMS and kernel header packages'\n\tphase = phases.package_installation\n\tsuccessors = [packages.InstallPackages]\n\n\t@classmethod\n\tdef run(cls, info):\n\t\tinfo.packages.add('dkms')\n\t\tkernel_pkg_arch = {'i386': '686-pae', 'amd64': 'amd64'}[info.manifest.system['architecture']]\n\t\tinfo.packages.add('linux-headers-' + kernel_pkg_arch)\n\n\nclass UpdateInitramfs(Task):\n\tdescription = 'Rebuilding initramfs'\n\tphase = phases.system_modification\n\n\t@classmethod\n\tdef run(cls, info):\n\t\tfrom bootstrapvz.common.tools import log_check_call\n\t # Update initramfs (-u) for all currently installed kernel versions (-k all)\n\t\tlog_check_call(['chroot', info.root, 'update-initramfs', '-u', '-k', 'all'])\n","repo_name":"null0000/bootstrap-vz","sub_path":"bootstrapvz/common/tasks/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1175646958","text":"from __future__ import unicode_literals\n\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import (DetailView, RedirectView, TemplateView)\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import login_required\nfrom django import http\n\nfrom bluusites.models import BluuSite\n\n\nclass DashboardView(TemplateView, RedirectView):\n template_name = \"dashboard/dashboard.html\"\n\n def get_redirect_url(self, *args, **kwargs):\n last_site = self.request.session.get('last_dashboard_site', None)\n if last_site is not None:\n try:\n BluuSite.objects.get(slug=last_site)\n except BluuSite.DoesNotExist:\n last_site = None\n\n if not last_site:\n sites = self.request.user.get_sites()\n if sites.exists():\n last_site = sites[0].slug\n\n if last_site is None:\n return None\n \n self.url = reverse('bluusite_dashboard', \n kwargs={'site_slug': last_site})\n\n return super(DashboardView, self).get_redirect_url(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n\n url = self.get_redirect_url(**kwargs)\n if url:\n if self.permanent:\n return http.HttpResponsePermanentRedirect(url)\n else:\n return http.HttpResponseRedirect(url)\n else:\n context = self.get_context_data(**kwargs)\n return self.render_to_response(context) \n\n return http.HttpResponseGone() \n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super(DashboardView, self).dispatch(*args, **kwargs)\n\n\nclass BluuSiteDashboardView(DetailView):\n template_name = \"dashboard/dashboard.html\"\n model = BluuSite\n slug_url_kwarg = 'site_slug'\n\n def get_context_data(self, *args, **kwargs):\n kwargs['sites'] = self.request.user.get_sites()\n return super(BluuSiteDashboardView, self).get_context_data(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.request.session['last_dashboard_site'] = self.object.slug\n context = self.get_context_data(object=self.object)\n return self.render_to_response(context) \n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super(BluuSiteDashboardView, self).dispatch(*args, **kwargs)\n\n","repo_name":"bluusystemsinc/bluu","sub_path":"bluu-web/project/apps/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1037959304","text":"import torch as th\nimport torch.nn as nn\nimport torch.nn.functional as tf\n\nfrom queue import PriorityQueue\nfrom typing import Union, List, Dict, Optional\n\n\nclass Node(object):\n \"\"\"\n Node for usage in best-first beam search\n \"\"\"\n\n def __init__(self, score, stats):\n self.score = score\n self.stats = stats\n\n def __getitem__(self, key):\n return self.stats[key]\n\n def __lt__(self, other):\n return self.score >= other.score\n\n\ndef _prep_nbest(container: Union[List, PriorityQueue],\n nbest: int,\n len_norm: bool = True,\n blank: int = 0) -> List[Dict]:\n \"\"\"\n Return nbest hypos from queue or list\n \"\"\"\n # get nbest\n if isinstance(container, PriorityQueue):\n container = container.queue\n beam_hypos = []\n for node in container:\n trans = [t.item() for t in node[\"token\"]]\n beam_hypos.append({\"score\": node.score, \"trans\": trans + [blank]})\n # return best\n nbest_hypos = sorted(beam_hypos,\n key=lambda n: n[\"score\"] / (len(n[\"trans\"]) - 1\n if len_norm else 1),\n reverse=True)\n return nbest_hypos[:nbest]\n\n\ndef greedy_search(decoder: nn.Module,\n enc_out: th.Tensor,\n blank: int = 0) -> List[Dict]:\n \"\"\"\n Greedy search algorithm for RNN-T\n Args:\n enc_out: N x Ti x D\n \"\"\"\n if blank < 0:\n raise RuntimeError(f\"Invalid blank ID: {blank:d}\")\n N, T, _ = enc_out.shape\n if N != 1:\n raise RuntimeError(\n f\"Got batch size {N:d}, now only support one utterance\")\n if not hasattr(decoder, \"step\"):\n raise RuntimeError(\"Function step should defined in decoder network\")\n if not hasattr(decoder, \"pred\"):\n raise RuntimeError(\"Function pred should defined in decoder network\")\n\n blk = th.tensor([[blank]], dtype=th.int64, device=enc_out.device)\n dec_out, hidden = decoder.step(blk)\n score = 0\n trans = []\n for t in range(T):\n # 1 x V\n prob = tf.log_softmax(decoder.pred(enc_out[:, t], dec_out)[0], dim=-1)\n best_prob, best_pred = th.max(prob, dim=-1)\n score += best_prob.item()\n # not blank\n if best_pred.item() != blank:\n dec_out, hidden = decoder.step(best_pred[None, ...], hidden=hidden)\n trans += [best_pred.item()]\n return [{\"score\": score, \"trans\": [blank] + trans + [blank]}]\n\n\ndef beam_search(decoder: nn.Module,\n enc_out: th.Tensor,\n lm: Optional[nn.Module] = None,\n lm_weight: float = 0,\n beam: int = 16,\n blank: int = 0,\n nbest: int = 8,\n len_norm: bool = True) -> List[Dict]:\n \"\"\"\n Beam search (not prefix beam search) algorithm for RNN-T\n Args:\n enc_out: N(=1) x Ti x D\n blank: #vocab_size - 1\n \"\"\"\n if blank < 0:\n raise RuntimeError(f\"Invalid blank ID: {blank:d}\")\n N, T, _ = enc_out.shape\n if N != 1:\n raise RuntimeError(\n f\"Got batch size {N:d}, now only support one utterance\")\n if not hasattr(decoder, \"step\"):\n raise RuntimeError(\"Function step should defined in decoder network\")\n if not hasattr(decoder, \"pred\"):\n raise RuntimeError(\"Function pred should defined in decoder network\")\n if beam > decoder.vocab_size:\n raise RuntimeError(f\"Beam size({beam}) > vocabulary size\")\n if lm and lm.vocab_size < decoder.vocab_size:\n raise RuntimeError(\"lm.vocab_size < am.vocab_size, \"\n \"seems different dictionary is used\")\n if blank != decoder.vocab_size - 1:\n raise RuntimeError(\"Hard code for blank = self.vocab_size - 1 here\")\n\n nbest = min(beam, nbest)\n\n device = enc_out.device\n blk = th.tensor([blank], dtype=th.int64, device=device)\n # B in Sequence Transduction with Recurrent Neural Networks: Algorithm 1\n list_b = []\n init_node = Node(0.0, {\n \"token\": [blk],\n \"trans\": f\"{blank}\",\n \"hidden\": None,\n \"lm_state\": None\n })\n list_b.append(init_node)\n stats = {}\n _, T, _ = enc_out.shape\n for t in range(T):\n # A in Sequence Transduction with Recurrent Neural Networks: Algorithm 1\n list_b = sorted(list_b, key=lambda n: n.score, reverse=True)[:beam]\n\n queue_a = PriorityQueue()\n for node in list_b:\n queue_a.put_nowait(node)\n list_b = []\n while len(list_b) < beam:\n # pop one (queue_a is updated)\n cur_node = queue_a.get_nowait()\n token = cur_node[\"token\"]\n # make a step\n if cur_node[\"trans\"] in stats:\n dec_out, hidden = stats[cur_node[\"trans\"]]\n else:\n dec_out, hidden = decoder.step(token[-1][..., None],\n hidden=cur_node[\"hidden\"])\n stats[cur_node[\"trans\"]] = (dec_out, hidden)\n\n # prediction: N x 1 x V => V\n pred = decoder.pred(enc_out[:, t], dec_out)[0, 0]\n prob = tf.log_softmax(pred, dim=-1)\n\n # add terminal node (end with blank)\n score = cur_node.score + prob[blank].item()\n blank_node = Node(\n score, {\n \"token\": token,\n \"trans\": cur_node[\"trans\"],\n \"hidden\": cur_node[\"hidden\"],\n \"lm_state\": cur_node[\"lm_state\"]\n })\n list_b.append(blank_node)\n\n lm_state = None\n if lm and t:\n # 1 x 1 x V (without blank)\n lm_prob, lm_state = lm(token[-1][..., None],\n cur_node[\"lm_state\"])\n prob[:-1] += tf.log_softmax(lm_prob[0, -1], dim=-1) * lm_weight\n\n # extend other nodes\n topk_score, topk_index = th.topk(prob[:-1], beam)\n for i in range(beam):\n score = cur_node.score + topk_score[i].item()\n node = Node(\n score, {\n \"token\":\n token + [topk_index[None, i]],\n \"trans\":\n cur_node[\"trans\"] + \",\" + str(topk_index[i].item()),\n \"hidden\":\n hidden,\n \"lm_state\":\n lm_state\n })\n queue_a.put_nowait(node)\n\n best_score = queue_a.queue[0].score\n list_b = [n for n in list_b if n.score > best_score]\n\n return _prep_nbest(list_b, nbest, len_norm=len_norm, blank=blank)\n","repo_name":"felixfuyihui/AISHELL-4","sub_path":"asr/cmd/aps/asr/beam_search/transducer.py","file_name":"transducer.py","file_ext":"py","file_size_in_byte":6726,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"52"} +{"seq_id":"73479667366","text":"import pygame, sys\nfrom utils import *\nfrom grid import *\n\nclass Snake:\n def __init__(self, grid:Grid):\n self.grid = grid\n self.rect = pygame.Rect(0,0, grid.cellSize, grid.cellSize)\n \n self.velocity = (0,1)\n self.nextMove = 0\n \n self.isAlive = True\n self.score = 0\n\n self.headSprites = [pygame.transform.scale(pygame.image.load(\"res/SnakeHead_Up.png\"), (self.grid.cellSize, self.grid.cellSize)),\n pygame.transform.scale(pygame.image.load(\"res/SnakeHead_Down.png\"), (self.grid.cellSize, self.grid.cellSize)),\n pygame.transform.scale(pygame.image.load(\"res/SnakeHead_Left.png\"), (self.grid.cellSize, self.grid.cellSize)),\n pygame.transform.scale(pygame.image.load(\"res/SnakeHead_Right.png\"), (self.grid.cellSize, self.grid.cellSize))]\n self.currentSprite = self.headSprites[1]\n self.tails = [self.rect]\n self.Grow()\n self.tailSprite = pygame.transform.scale(pygame.image.load(\"res/SnakeBody.png\"), (self.grid.cellSize, self.grid.cellSize))\n \n def Draw(self):\n screen.blit(self.currentSprite, self.rect)\n\n i = 1\n while i < len(self.tails):\n screen.blit(self.tailSprite, self.tails[i])\n i+=1\n \n def Update(self):\n self.Draw()\n\n if self.isAlive:\n self.GetInput()\n self.Movement()\n\n def GetInput(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n self.velocity = (0, -1)\n self.currentSprite = self.headSprites[0]\n if event.key == pygame.K_DOWN:\n self.velocity = (0, 1)\n self.currentSprite = self.headSprites[1]\n if event.key == pygame.K_LEFT:\n self.velocity = (-1, 0)\n self.currentSprite = self.headSprites[2]\n if event.key == pygame.K_RIGHT:\n self.velocity = (1, 0)\n self.currentSprite = self.headSprites[3]\n \n if event.key == pygame.K_ESCAPE:\n self.isAlive = False\n \n def CheckForApple(self):\n cell = self.grid.GetCellAt(self.rect.topleft)\n\n if cell is not None:\n if cell.isApple:\n self.Grow()\n self.grid.GenApple()\n cell.isApple = False\n\n def Grow(self):\n lastPart = self.tails[len(self.tails)-1].topleft\n self.tails.append(pygame.Rect(lastPart[0]-self.grid.cellSize, lastPart[1], self.grid.cellSize, self.grid.cellSize))\n\n self.score += 1\n\n def CheckForSelfCollision(self):\n i = 1\n while i < len(self.tails):\n if self.rect.colliderect(self.tails[i]):\n self.isAlive = False\n i += 1\n\n def Movement(self):\n self.nextMove += 0.1\n \n if self.nextMove >= 1:\n self.CheckForApple()\n self.CheckForSelfCollision()\n\n i = len(self.tails)-1\n\n while i > 0:\n self.tails[i].topleft = self.tails[i-1].topleft\n i-=1\n \n self.rect.x += self.velocity[0]*self.grid.cellSize\n self.rect.y += self.velocity[1]*self.grid.cellSize\n \n self.nextMove = 0\n \n if self.rect.x <0 or self.rect.x>=width or self.rect.y<0 or self.rect.y>=height:\n self.isAlive = False\n return\n\n \n","repo_name":"QentangifyCodes/SnakeGame","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32447523730","text":"import json\nimport statistics\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\ndata = {}\ndata[\"Celowniki, lunety\"] = [] \ndata[\"Części ASG\"] = [] \ndata[\"Karabinki szturmowe\"] = [] \ndata[\"Karabinki maszynowe\"] = [] \ndata[\"Karabiny snajperskie\"] = [] \ndata[\"Kulki ASG\"] = [] \ndata[\"Magazynki\"] = []\ndata[\"Oporządzenie taktyczne\"] = [] \ndata[\"Osprzęt ASG\"] = [] \ndata[\"Pistolety i rewolwery\"] = [] \ndata[\"Pistolety maszynowe\"] = [] \ndata[\"Strzelby\"] = [] \ndata[\"Pozostałe\"] = [] \n\nwith open('allProductsInCategories.json') as json_file:\n jsonData = json.load(json_file)\n\n for oneCategory in data:\n for p in jsonData[oneCategory]:\n data[oneCategory].append({\n 'nazwa': p['nazwa'],\n 'cena': p['cena'],\n 'cena_z_dostawa': p['cena_z_dostawa'],\n 'licytacja': p['licytacja'],\n 'ile_osob_kupilo': p['ile_osob_kupilo'],\n 'allegro_smart': p['allegro_smart'],\n 'ssprzedawca': p['ssprzedawca'],\n 'cena': p['cena'],\n 'stan': p['stan']\n })\n\nmedianArray = []\n\nfor oneCategory in data:\n oneCategoryPrices = []\n for i in data[oneCategory]:\n arrPrice = []\n for y in i['cena'] :\n if y.isdigit():\n arrPrice.append(y)\n oneCategoryPrices.append(float(''.join(arrPrice))/100)\n\n lowQuantile= np.quantile(oneCategoryPrices, 0.05)\n highQuantile = np.quantile(oneCategoryPrices, 0.95)\n afterQuantile = []\n for price in oneCategoryPrices:\n if lowQuantile <= price <= highQuantile:\n afterQuantile.append(price)\n\n medianArray.append(round(statistics.median(afterQuantile), 2))\n\n \n\n\nprint(medianArray)\n\n\nobjects = [\"Celowniki, lunety\", \n\"Części ASG\",\n\"Karabinki szturmowe\",\n\"Karabinki maszynowe\",\n\"Karabiny snajperskie\",\n\"Kulki ASG\",\n\"Magazynki\",\n\"Oporządzenie taktyczne\",\n\"Osprzęt ASG\",\n\"Pistolety i rewolwery\",\n\"Pistolety maszynowe\" ,\n\"Strzelby\" ,\n\"Pozostałe\"\n]\n\ny_pos = np.arange(len(objects))\nperformance = medianArray\n\nplt.barh(y_pos, performance, align='center', alpha=0.5)\nplt.yticks(y_pos, objects)\nplt.xlabel('Cena [zł]')\nplt.title('Mediana cen w rozrónieniu na kategorie', fontsize=14, fontweight='bold')\n\nfor i, v in enumerate(performance):\n plt.text(v + 5, i - 0.15, str(v), color='blue', fontsize=9, fontweight='bold')\n\nplt.show()\n\n","repo_name":"rafalszymanek/Big-Data-Project","sub_path":"chartCategoriesPriceRange.py","file_name":"chartCategoriesPriceRange.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32562749789","text":"from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.shortcuts import render, get_object_or_404, HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\n\nfrom publications.models import Publication, PublicationLike, PublicationComment\nfrom publications.forms import PublicationForm, PublicationCommentForm\n\nfrom publications.serializers import PublicationSerializer\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\n\nfrom utils import gen_page_list\n\n\n\n\ndef publications(request):\n form = PublicationForm()\n if request.method == \"POST\":\n form = PublicationForm(request.POST, request.FILES)\n if form.is_valid():\n data = form.cleaned_data\n Publication.objects.create(title=data.get(\"title\"),\n body=data.get(\"body\"),\n image=data.get(\"image\"),\n author=request.user)\n publications = Publication.objects.all()\n paginator = Paginator(publications, 2)\n page = request.GET.get('page', 1)\n last_page = paginator.num_pages\n paginator_gen_list = gen_page_list(int(page), paginator.num_pages)\n try:\n publications = paginator.page(page)\n except PageNotAnInteger:\n publications = paginator.page(1)\n except EmptyPage:\n publications = paginator.page(paginator.num_pages)\n\n return render(request, \"publications.html\", {\"publications\": publications,\n \"form\": form,\n \"last_page\": last_page,\n \"paginator_gen_list\": paginator_gen_list})\n\ndef single_publication(request, publication_id):\n publication = get_object_or_404(Publication, pk=publication_id)\n form = PublicationCommentForm()\n if request.method == \"POST\":\n form = PublicationCommentForm(request.POST)\n if form.is_valid():\n PublicationComment.objects.create(comment=form.cleaned_data[\"comment\"],\n user=request.user,\n publication=publication)\n return HttpResponseRedirect(reverse(\"single_publication\", kwargs={\"publication_id\": publication_id}))\n return render(request, \"single_publication.html\", {\"publication\": publication,\n \"form\": form})\n\n\ndef like_single_publication(request, publication_id):\n if request.user.is_authenticated():\n publication = get_object_or_404(Publication, pk=publication_id)\n if PublicationLike.objects.filter(publication=publication, user=request.user).exists():\n PublicationLike.objects.filter(publication=publication, user=request.user).delete()\n else:\n PublicationLike.objects.create(publication=publication, user=request.user)\n return HttpResponseRedirect(reverse(\"single_publication\", kwargs={\"publication_id\": publication_id}))\n else:\n return HttpResponseRedirect(reverse(\"login\"))\n\n@api_view([\"GET\"])\ndef publication_as_json(request, publication_id):\n publication = get_object_or_404(Publication, pk=publication_id)\n publications = Publication.objects.all()\n serializer = PublicationSerializer(publications, many=True)\n return Response(serializer.data)\n","repo_name":"Sprow/Django_mountain","sub_path":"publications/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43056423734","text":"class Cat:\n def __init__(self, name, preferred_food, meal_time):\n self.name = name\n self.preferred_food = preferred_food\n self.meal_time = meal_time\n\n def __str__(self):\n return f\"Name: {self.name} \\nPreferred Food: {self.preferred_food}\"\n\n def eats_at(self):\n if self.meal_time < 12:\n return f\"{self.meal_time} AM\"\n else:\n return f\"{self.meal_time - 12} PM\"\n\n def meow(self):\n return f\"My name is {self.name}, and my favourite food is {self.preferred_food.lower()}. You can feed me at {self.eats_at()}\"\n\ncharlie = Cat('Charlie', 'Tuna', 17)\njazzy = Cat('Jazzy', 'Everything', 8)\n\nprint()\nprint(charlie)\nprint(jazzy)\n\nprint()\nprint(charlie.eats_at())\nprint(jazzy.eats_at())\n\nprint()\nprint(charlie.meow())\nprint(jazzy.meow())","repo_name":"jessiicacmoore/python-cat-exercise","sub_path":"cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26784455114","text":"import sncosmo\nimport numpy as np\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nimport sn_sampling as sns\nimport sn_sampling_extras as snse\n\n\ndef gridcreate(name, y, x, ratio, z, **kwargs):\n # Function that creates a blank axis canvas; each figure gets a name (or alternatively a number\n # if none is given), and gridspec creates an N*M grid onto which you can create axes for plots.\n # This returns a gridspec \"instance\" so you can specific which figure to put the axis on if you\n # have several on the go.\n plt.figure(name, figsize=(z*x, z*ratio*y))\n gs = gridspec.GridSpec(y, x, **kwargs)\n return gs\n\n\nz = 0.2\nbands = np.array(['z087', 'y106', 'w149', 'j129', 'h158', 'f184'])\nsnse.register_filters(bands)\na = sncosmo.models._SOURCES.get_loaders_metadata()\n\ngs = gridcreate('123123', 2, 3, 0.8, 5)\naxs = [plt.subplot(gs[i]) for i in range(0, 6)]\ncs = ['k', 'r', 'b', 'g', 'c', 'm', 'orange', 'brown']\n\ntypings = ['Ia', 'Ib', 'Ic', 'IIP', 'IIL', 'IIn', 'Iat', 'Iabg']\nset_models = [0, 1, 1, 0, 1, 1, 1, 1]\n\nmintime, maxtime = 999, -999\nfor typing in typings:\n sn_model = sns.get_sn_model(typing, 1, t0=0, z=z)\n sn_model.set_source_peakabsmag(-19.0, 'f125w', 'ab')\n mintime, maxtime = min(mintime, sn_model.mintime()), max(maxtime, sn_model.maxtime())\nmintime -= 50\nmaxtime += 50\nt_max = np.linspace(mintime, maxtime, 1000)\n\nfor typing, c, set_model in zip(typings, cs, set_models):\n sn_model = sns.get_sn_model(typing, 1, t0=0, z=z)\n sn_model.set_source_peakabsmag(-19.0, 'f125w', 'ab')\n t = np.linspace(sn_model.mintime(), sn_model.maxtime(), 1000)\n for band, ax in zip(bands, axs):\n f = sn_model.bandflux(band, time=t)\n ax.plot(t, f, ls='-', c=c, label=typing)\n f = sn_model.bandflux(band, time=t_max)\n ax.plot(t_max, f, ls='--', c=c)\n ax.axvline(sn_model.maxtime() if 'L' not in typing and 'n' not in typing else\n 150*(1+z)+np.random.uniform(-5, 5), ls='-', c=c)\n if not set_model:\n print(typing)\n print('===============')\n for i in a:\n if typing in i['type']:\n m = sncosmo.Model(source=i['name'])\n m.set(z=z)\n if m.maxtime() >= 50 and m.maxwave() >= 20000:\n try:\n print(m._source.name, i['type'], m.mintime(), m.maxtime(),\n m.minwave(), m.maxwave(), [m._source.peakphase(band) for band in bands])\n except ValueError:\n pass\n\naxs[0].legend()\nfor ax in axs:\n ax.axvline(150, ls=':', c='k', lw=1.5)\n ax.axhline(0, ls=':', c='k', lw=1.5)\n ax.set_xlabel('time')\n ax.set_ylabel('flux')\nplt.tight_layout()\nplt.savefig('test_model_phases.pdf')\n","repo_name":"Onoddil/WFIRST_SN","sub_path":"SN Sampling/test_sn_cosmo_models.py","file_name":"test_sn_cosmo_models.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"533648779","text":"\nclass Node:\n\tdef __init__(self, chave):\n\t\tself.chave = chave\n\t\tself.pai = None\n\t\tself.direita = None\n\t\tself.esquerda = None\n\nclass Heap:\n\tdef __init__(self, *args):\n\t\tself.node = None\n\n\tdef redefineFilhosPai(pai, esquerda, direita):\n\t\tself.heap.pai = pai\n\t\tself.heap.esquerda = esquerda\n\t\tself.heap.direita = direita\n\n\tdef fator(self):\n\t\tpEsq = 0\n\t\tpDir = 0\n\t\tif self.node:\n\t\t\tpEsq = self.node.esquerda.calculaProfundidade()\n\t\t\tpDir = self.node.direita.calculaProfundidade()\n\t\treturn pDir - pEsq\n\n\tdef calculaProfundidade(self):\n\t\tpEsq = 0\n\t\tpDir = 0\n\t\tif self.node:\n\t\t\tpEsq = self.node.esquerda.calculaProfundidade()\n\t\t\tpDir = self.node.direita.calculaProfundidade()\n\t\tresultado = max(pEsq, pDir) + 1\n\t\treturn resultado\n\t\n\n\tdef inserirHeap(self, chave, noPai = None):\n\t\tno = Node(chave) \n\t\tif not self.node:\n\t\t\tself.node = no\n\t\t\tself.node.esquerda = Heap()\n\t\t\tself.node.direita = Heap()\n\t\t\tself.node.pai = noPai\n\t\telse:\n\t\t\tpai = self.node\n\t\t\tfator = self.fator()\n\t\t\tfatorSAE = self.node.esquerda.fator()\n\t\t\tfatorSAD = self.node.direita.fator()\n\n\t\t\tif fator == 0:\n\t\t\t\tif fatorSAE == 0 and fatorSAD == 0:\n\t\t\t\t\tself.node.esquerda.inserirHeap(chave,pai)\n\t\t\t\telif fatorSAE == 0 and fatorSAD < -1:\t\n\t\t\t\t\tself.node.direita.node.direita.inserirHeap(chave, pai)\n\t\t\t\telif fatorSAE == 0 and fatorSAD > 1:\t\n\t\t\t\t\tself.node.direita.node.esquerda.inserirHeap(chave, pai)\t\n\t\t\telif fator < -1:\n\t\t\t\tself.node.direita.inserirHeap(chave,pai)\n\t\t\telif fator > 1:\t\n\t\t\t\tself.node.esquerda.inserirHeap(chave, pai)\t\t\n\tdef imprimirHeap(self, espaco = 0): # Imprime uma árvore rotacionada 90º no sentido anti-horário\n\t\tif self.node:\n\t\t\tself.node.direita.imprimirHeap(espaco + 2)\n\t\t\tprint(\" \" * espaco + str(self.node.chave))\n\t\t\tself.node.esquerda.imprimirHeap(espaco + 2)\t\t\t\t\n\ndef main():\n\theap = Heap()\n\n\theap.inserirHeap(7)\n\theap.inserirHeap(8)\n\theap.inserirHeap(5)\n\theap.inserirHeap(6)\n\theap.inserirHeap(3)\n\theap.inserirHeap(4)\n\theap.inserirHeap(9)\n\theap.inserirHeap(2)\n\theap.inserirHeap(1)\n\theap.inserirHeap(0)\n\theap.inserirHeap(-1)\n\theap.imprimirHeap()\t\n\nmain()\t\t\t\t\t","repo_name":"CrazyRural/Trabalhos","sub_path":"Arvores e Heap/heapTree.py","file_name":"heapTree.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40050407915","text":"# birth_year = input(\"Enter your birth year: \")\n# age = 2022 - int(birth_year)\n# print(age)\n#\n# int()\n# float()\n# bool()\n# str()\n\n# Exercise\n\nfirst = float(input(\"First: \"))\nsecond = float(input(\"Second: \"))\nsum = first + second\nprint(\"Sum: \" + str(sum))\n","repo_name":"Edufreitass/py-hello-world","sub_path":"type_conversion_example.py","file_name":"type_conversion_example.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"860779766","text":"import math\n#untuk permutasi\ndef P(n, r):\n f = math.factorial\n permutasi = f(n)//f(n-r)//1\n print('P : ' + str(permutasi))\nP(10, 7)\n\n#untuk combinasi\ndef C(n, r):\n f = math.factorial\n kombinasi = f(n)//f(r)//f(n-r)\n print('C : ' + str(kombinasi))\nC(5, 3)","repo_name":"Dzazyy/python_project","sub_path":"Chapter 6/Latihan no.3.py","file_name":"Latihan no.3.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36220170715","text":"class TICKET_BOOK (object):\n \"\"\"docstring for User\"\"\"\n def __init__(self, Class=None, bdg_pt=None, quota=None,usr=None):\n super(TICKET_BOOK, self).__init__()\n self.Class = Class\n self.bdg_pt = bdg_pt\n self.quota=quota\n self.usr=usr\n\n def __str__(self):\n return \"=============================\"+\\\n \"\\nuser : \"+ str(self.usr)+\\\n \"\\nClass : \" + self.Class+\\\n \"\\nbdg_pt: \"+ str(self.bdg_pt)+\\\n \"\\nquota : \"+ str(self.quota)+\\\n \"\\n=============================\"+\\\n \" \"\n\n def display(self):\n print (\"=============================\")\n print (\"USER : \",self.usr)\n print (\" CLASS : \",self.Class)\n print (\" BOARDING PT.: \",self.bdg_pt)\n print (\" QUOTA : \",self.quota)\n print (\"=============================\")\n print (\" \")","repo_name":"tejeswar68/Railway-Reservation-System-Using-Python","sub_path":"tkt_bk.py","file_name":"tkt_bk.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38500400326","text":"#!/usr/bin/python3\nimport pexpect #will need to be installed for this to work\nimport pexpect.popen_spawn\n\nimport sys\nimport random\nimport time\nimport os\nimport pprint\n\nif len(sys.argv) == 3:\n red_player_file = sys.argv[1]\n blue_player_file = sys.argv[2]\n grid_length = 10\nelif len(sys.argv) == 4:\n red_player_file = sys.argv[1]\n blue_player_file = sys.argv[2]\n grid_length = int(sys.argv[3])\nelse:\n red_player_file = 'test_red.py' #hard coded files to be used as bike controls\n blue_player_file = 'test_red.py'\n grid_length = 10\n\ngrid = [['.'] * grid_length for i in range(grid_length)] #first value in 2d list is row then col or y then x\n\n\nclass Bike:\n def __init__(self, start_x,start_y,direction,process,file_name,time_out = 1):\n self.__pos_x = start_x #cars x position in grid\n self.__pos_y = start_y #cars y position in grid\n self.__future_x = start_x #where x position of where car wants to move which is checked to see if valid \n self.__future_y = start_y #where y position of where car wants to move which is checked to see if valid \n self.__direction = direction #the direction car is faceing \n self.__process = process #pexpect object that contains chile process\n self.__file_name = file_name #name of python file related to this cars ai\n self.__time_out = time_out #how lone the process.expect() command is going to wait for responce before giving up\n self.__crashed = False #has the car crashed?\n self.__timeout = False #has the car timed out a process.expect() command?\n self.__next_move = '' #does the car want to go forward, left, or right\n\n def get_next_move(self):\n return self.__next_move \n\n def get_car_state_string(self): #returns direction,x_pos,y_pos in one string so it can be sent to the oppent \n return str(self.__direction) +','+ str(self.__pos_x)+','+ str(self.__pos_y)\n\n def change_pos(self):\n self.__pos_x = self.__future_x\n self.__pos_y = self.__future_y\n\n def state_transaction(self,grid,enemy_state_string): #sends car state string and oppents state string to process and expects next move to be returned\n #i = self.__process.expect(['ready',pexpect.TIMEOUT,pexpect.EOF],timeout = self.__time_out)\n i = self.__process.expect(['ready',pexpect.TIMEOUT,pexpect.EOF])\n if i == 1:\n print('Time out on ' + self.__file_name +'. Ready signal not sent')\n self.__timeout = True\n sys.exit(0)\n elif i == 2:\n print('Program ended in file ' + self.__file_name + ' : Program needs to not end on its own and needs a correct path to file. Try useing an infinite loop and make sure your client doesnt crash')\n sys.exit(0)\n out_put = self.__direction+','+str(self.__pos_x)+','+str(self.__pos_y)+','+enemy_state_string\n\n number_bytes = self.__process.sendline(out_put)\n\n #i = self.__process.expect(['left','right','forward',pexpect.TIMEOUT,pexpect.EOF],timeout = self.__time_out)\n i = self.__process.expect(['left','right','forward',pexpect.TIMEOUT,pexpect.EOF])\n if i == 0:\n self.__next_move = 'left'\n elif i == 1:\n self.__next_move = 'right'\n elif i == 2:\n self.__next_move = 'forward'\n elif i == 3:\n print('Time out on ' + self.__file_name +'. No direction information sent')\n self.__timeout = True\n sys.exit(0)\n elif i == 4:\n print('Program ended in file ' + self.__file_name + ' : Program needs to not end on its own and needs a correct path to file. Try useing an infinite loop and make sure your client doesnt crash')\n sys.exit(0)\n return self.__pos_x, self.__pos_y\n\n def update_position(self): #translates the next_move direction to a possition in the grid\n global grid\n if self.__direction == 'n':\n if self.__next_move == 'right':\n self.__direction = 'e'\n self.__future_x = self.__pos_x + 1\n elif self.__next_move == 'left':\n self.__direction = 'w'\n self.__future_x = self.__pos_x - 1\n else:\n self.__future_y = self.__pos_y - 1\n elif self.__direction == 's':\n if self.__next_move == 'right':\n self.__direction = 'w'\n self.__future_x = self.__pos_x - 1\n elif self.__next_move == 'left':\n self.__direction = 'e'\n self.__future_x = self.__pos_x + 1\n else:\n self.__future_y = self.__pos_y + 1\n elif self.__direction == 'e':\n if self.__next_move == 'right':\n self.__direction = 's'\n self.__future_y = self.__pos_y + 1\n elif self.__next_move == 'left':\n self.__direction = 'n'\n self.__future_y = self.__pos_y - 1\n else:\n self.__future_x = self.__pos_x + 1 \n else: \n if self.__next_move == 'right':\n self.__direction = 'n'\n self.__future_y = self.__pos_y - 1\n elif self.__next_move == 'left':\n self.__direction = 's'\n self.__future_y = self.__pos_y + 1\n else:\n self.__future_x = self.__pos_x - 1\n\n return self.__future_x , self.__future_y\n\n def crashed(self): #sets crashed to True which is bad luck for this car :/\n self.__crashed = True\n def get_crashed(self):\n return self.__crashed\n\ndef referee_light_cycle(red_car,blue_car):\n global grid\n global grid_length\n\n red_current_x, red_current_y = red_car.state_transaction(grid,blue_car.get_car_state_string()) #Sends state information to red car and returns red cars current position\n red_desired_move_x, red_desired_move_y = red_car.update_position() #Translates where the red car wants to go and returns its desired_x and desired_y\n blue_current_x, blue_current_y = blue_car.state_transaction(grid,red_car.get_car_state_string()) #Sends state information to blue car and returns red cars current position\n blue_desired_move_x, blue_desired_move_y = blue_car.update_position() #Translates where the blue car wants to go and returns its desired_x and desired_y\n\n if red_desired_move_x == blue_desired_move_x and red_desired_move_y == blue_desired_move_y:\n print(\"Tie\")\n sys.exit(0)\n\n #print('red_future_x: ',red_desired_move_x,'red_future_y: ',red_desired_move_y)\n #print('blue_future_x: ',blue_desired_move_x,'blue_future_y: ',blue_desired_move_y)\n\n if red_desired_move_x < 0 or red_desired_move_x > (grid_length - 1) or red_desired_move_y < 0 or red_desired_move_y > (grid_length - 1): #checks if red car wants to go off map if so that car has crashed\n red_car.crashed()\n\n\n if blue_desired_move_x < 0 or blue_desired_move_x > grid_length - 1 or blue_desired_move_y < 0 or blue_desired_move_y > grid_length - 1: #checks if blue car wants to go off map if so that car has crashed\n blue_car.crashed()\n\n if not red_car.get_crashed(): #checks if red car wants to move to an open space if not it has crashed \n object_at_red_desired_position = grid[red_desired_move_y][red_desired_move_x]\n if object_at_red_desired_position != '.':\n red_car.crashed()\n if not blue_car.get_crashed(): #checks if blue car wants to move to an open space if not it has crashed \n object_at_blue_desired_position = grid[blue_desired_move_y][blue_desired_move_x]\n if object_at_blue_desired_position != '.':\n blue_car.crashed()\n\n if red_car.get_crashed() and blue_car.get_crashed():\n print('Tie')\n sys.exit(0)\n elif red_car.get_crashed():\n print('Winner',blue_player_file)\n sys.exit(0)\n elif blue_car.get_crashed():\n print('Winner',red_player_file)\n sys.exit(0)\n else:\n grid[red_desired_move_y][red_desired_move_x] = 'R'\n grid[blue_desired_move_y][blue_desired_move_x] = 'B'\n grid[red_current_y][red_current_x] = 'W'\n grid[blue_current_y][blue_current_x] = 'W'\n\n red_car.change_pos()\n blue_car.change_pos()\n\n\n\n\ndef init_cars(time_out = 5):\n global grid\n global grid_length\n coin_flip = random.randint(0,1)\n\n if os.name == 'nt':\n red = pexpect.popen_spawn.PopenSpawn('start ' + red_player_file)\n blue = pexpect.popen_spawn.PopenSpawn('start ' + blue_player_file)\n else:\n # red = pexpect.spawn('python3 ' + red_player_file) #spawn red player process\n # blue = pexpect.spawn('python3 ' + blue_player_file)#spawn blue player process\n red = pexpect.spawn('./' + red_player_file) #spawn red player process\n blue = pexpect.spawn('./' + blue_player_file)#spawn blue player process\n red.timeout = time_out\n blue.timeout = time_out\n #red.logfile_read = sys.stdout.buffer #tells pexpect to write all output to main process stdout should only be uncommited for debuging\n #blue.logfile = sys.stdout.buffer #tells pexpect to write all output to main process stdout should only be uncommited for debuging\n i = red.expect(['ready',pexpect.TIMEOUT,pexpect.EOF]) #wait for red child process to send 'ready' \n\n if i == 1: #reacts on if red expect times out or errors \n print('Time out on ' + red_player_file +'. Ready signal not sent in start transaction')\n sys.exit(0)\n elif i == 2:\n print('Program ended in file ' + red_player_file + ' : Program needs to not end on its own. Try useing an infinite loop and make sure your client doesnt crash')\n sys.exit(0)\n\n red.sendline(str(grid_length)) #sends grid_lenth to red process so it can build its model\n\n i = blue.expect(['ready',pexpect.TIMEOUT,pexpect.EOF]) #wait for blue child process to send 'ready' \n\n if i == 1: #reacts on if blue expect times out or errors \n print('Time out on ' + blue_player_file +'. Ready signal not sent in start transaction')\n sys.exit(0)\n elif i == 2:\n print('Program ended in file ' + blue_player_file + ' : Program needs to not end on its own. Try useing an infinite loop and make sure your client doesnt crash')\n sys.exit(0)\n\n blue.sendline(str(grid_length)) #sends grid_lenth to blue process so it can build its model\n\n\n\n if coin_flip == 0: #starts cars on random corner based of coin_flip value\n red_car = Bike(0,0,'s',red,red_player_file)\n blue_car = Bike(grid_length -1 ,grid_length - 1,'n',blue,blue_player_file)\n grid[0][0] = 'R'\n grid[grid_length - 1][grid_length - 1] = 'B'\n else:\n blue_car = Bike(0,0,'s',blue,blue_player_file)\n red_car = Bike(grid_length -1 ,grid_length - 1,'n',red,red_player_file)\n grid[0][0] = 'B'\n grid[grid_length - 1][grid_length - 1] = 'R'\n return red_car, blue_car\n\n\n\nred_car, blue_car = init_cars(2) #initializes red and blue cars position and sends them information on grid size \nwhile True: \n referee_light_cycle(red_car,blue_car)\n #os.system('cls' if os.name == 'nt' else 'clear')\n #time.sleep(.1)\n pprint.pprint(grid)\n print()\n","repo_name":"jkolecr/light_cycle","sub_path":"light_cycle.py","file_name":"light_cycle.py","file_ext":"py","file_size_in_byte":11332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42920196850","text":"import csv\n\ngotEpisodes = list(range(828419, 828494))\ngotActors = []\n\nprint(gotEpisodes)\n\n#exit()\n\n\noutfile = open('actorsInMoviesGOT.csv', 'w')\nwith open('actorsInMovies.csv', 'r') as csvfile:\n\tspamreader = csv.reader(csvfile, delimiter=';', quotechar='|')\n\tspamwriter = csv.writer(outfile, delimiter=';', quotechar='|')\n\n\thack = True\n\tfor row in spamreader:\n\t\tif hack:\n\t\t\thack = False\n\t\t\tcontinue\n\t\tif (int(row[0]) % 5000 == 0):\n\t\t\tpercentage = (int(row[0]) / 1937893) * 100\n\t\t\tprint(\"actorsInMovies \" + str(percentage) + \"%\")\n\n\t\tif int(row[1]) in gotEpisodes and row[2] == \"False\":\n\t\t\tgotActors.append(int(row[0]))\n\t\t\tspamwriter.writerow(row)\n\t\t\toutfile.flush()\noutfile.close()\n\noutfile = open('actorsGOT.csv', 'w', newline='')\nwith open('actors.csv', 'r') as csvfile:\n\tspamreader = csv.reader(csvfile, delimiter=';', quotechar='|')\n\tspamwriter = csv.writer(outfile, delimiter=';', quotechar='|')\n\n\thack = True\n\tfor row in spamreader:\n\t\tif hack:\n\t\t\thack = False\n\t\t\tcontinue\n\t\tif (int(row[0]) % 5000 == 0):\n\t\t\tpercentage = (int(row[0]) / 3606672) * 100\n\t\t\tprint(\"actors \" + str(percentage) + \"%\")\n\n\t\tif int(row[0]) in gotActors:\n\t\t\tspamwriter.writerow(list(row))\n\t\t\toutfile.flush()\noutfile.close()\n\nprint(\"done :)\")","repo_name":"Gybelle/IMDbDataVisualisation","sub_path":"Preprocessing/GoTExtractor.py","file_name":"GoTExtractor.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25406989508","text":"#!/usr/bin/env python\n\nfrom os import path\n\nfrom setuptools import setup, find_namespace_packages\n\n\n# Fetch the README contents\nrootdir = path.abspath(path.dirname(__file__))\nwith open(path.join(rootdir, \"README.md\"), encoding=\"utf-8\") as f:\n long_description = f.read()\n\n\nsetup(\n name=\"calf\",\n version=\"0.0.0\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=find_namespace_packages(include=[\"calf.*\"]),\n entry_points={\n \"console_scripts\": [\n \"calflex = calf.lexer:main\",\n \"calfp = calf.parser:main\",\n \"calfr = calf.reader:main\",\n \"calffmt = calf.fmt:main\",\n \"calf = calf.server:main\",\n ]\n },\n install_requires=[\n \"pyrsistent~=0.17.0\",\n ]\n)\n","repo_name":"arrdem/calf","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8703275617","text":"from typing import List\n\nEAST = \"E\"\nWEST = \"W\"\n\n\ndef search_apartment(buildings: List[int], direction: str) -> List[int]:\n \"\"\"\n Find and return the indices of those building with\n the desired view: EAST (E) or WEST (W).\n\n See sample inputs / outputs below and in the tests.\n \"\"\"\n highest = 0\n building_list = []\n if direction == \"E\":\n buildings.reverse()\n for index, building in enumerate(buildings):\n if building > highest:\n highest = building\n building_list.append(index)\n if direction == \"E\":\n for index, building in enumerate(building_list):\n building_list[index] = len(buildings)-building-1\n building_list.reverse()\n return building_list\n\n\n\nif __name__ == \"__main__\":\n A = [3, 5, 4, 4, 7, 1, 3, 2] # central tallest\n B = [1, 1, 1, 1, 1, 2] # almost flat\n #\n # W <- -> E(ast)\n #\n print(search_apartment(A, \"W\")) # [0, 1, 4]\n print(search_apartment(A, \"E\")) # [4, 6, 7]\n print(search_apartment(B, \"W\")) # [0, 5]\n print(search_apartment(B, \"E\")) # [5]","repo_name":"syurskyi/Python_Topics","sub_path":"125_algorithms/_examples/_algorithms_challenges/pybites/topics/Algorithms/332/search_apartment.py","file_name":"search_apartment.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8222206873","text":"\nclass Area:\n def __init__(self, area):\n self.area = area\n self.lata = 0\n self.preco = 0\n\n\n def calcular_lata(self):\n self.lata = float(self.area) / 6\n print('Voçê deverá usar: {} latas'.format(self.lata))\n\n def calcular_preco(self):\n self.preco = float(self.lata) * 80\n print('Voçê pagará: {} reais'.format(self.preco))\n\nif __name__ == \"__main__\":\n area1 = input(\"Digite a area pretendida para pintura em m2: \")\n area = Area(area1)\n area.calcular_lata()\n area.calcular_preco()\n","repo_name":"joaopedroAlldax/EstudosPy","sub_path":"Python/class6.py","file_name":"class6.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70608034405","text":"#!/usr/bin/env python -u\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pw2py as pw\nimport glob\nimport scipy.constants\n\n\n# constants for conversions\nhbar = scipy.constants.physical_constants['reduced Planck constant in eV s'][0]\neV2J = scipy.constants.e\natomic_mass = scipy.constants.atomic_mass\n\n\ndef read_full_dat() -> dict:\n ''' read linear extrapolation data '''\n full_dat = {}\n for lin in sorted(glob.glob('lin*/')):\n full_dat[lin] = []\n for rat in sorted(glob.glob(f'{lin}ratio-*/')):\n rloc = rat.find('ratio-')\n ratio = float(rat[rloc+len('ratio-'):-1])\n energy = pw.qeout.final_energy(f'{rat}scf.out')[0]\n full_dat[lin].append([ratio, energy])\n full_dat[lin] = np.array(full_dat[lin])\n\n # shift minimum to zero\n minE = min([dat.min() for _, dat in full_dat.items()])\n for lin, dat in full_dat.items():\n dat[:, 1] -= minE\n np.savetxt(f'{lin}_barrier.dat', dat)\n full_dat\n\n return full_dat\n\n\ndef calc_zpl(full_dat: dict, report=False) -> dict:\n ''' calculate position of minimum for each curve '''\n zpl = {}\n for lin, dat in full_dat.items():\n zpl[lin] = (dat[np.argmin(dat[:, 1]), 0], dat[:, 1].min())\n if report:\n print(\n f'{lin} -> min = {zpl[lin][1]:.4f} at ratio = {zpl[lin][0]:.4f}')\n return zpl\n\n\ndef calc_dQ(full_dat: dict, report=False) -> float:\n ''' calculate dQ from atomic geometry of minimum (units of amu^1/2 Ang) '''\n lins = list(full_dat.keys())\n geo0 = pw.atomgeo.from_file(\n f'{lins[0]}/ratio-{zpl[lins[0]][0]:.4f}/scf.out')\n geo1 = pw.atomgeo.from_file(\n f'{lins[1]}/ratio-{zpl[lins[1]][0]:.4f}/scf.out')\n dQ = geo0.calc_dQ(geo1)\n if report:\n print(f'dQ = {dQ:.4f}')\n return dQ\n\n\ndef calc_polyfit(full_dat: dict) -> dict:\n ''' calculate degree 2 polynomial fit around the minimum '''\n polyfit = {}\n for lin, dat in full_dat.items():\n fit_dat = dat[:6] if zpl[lin][0] < 0.5 else dat[-6:]\n polyfit[lin] = np.polyfit(*fit_dat.T, 2)\n return polyfit\n\n\ndef calc_hw_and_S(polyfit: dict, dQ: float, report=False) -> tuple:\n ''' calculate hbar*omega (hw) in eV and the Huang-Rhys factor (S) '''\n dQ_SI = dQ * (atomic_mass)**(1/2) * 1e-10\n hw, S = {}, {}\n for lin, fit in polyfit.items():\n # hbar omega in eV\n hw[lin] = hbar * (fit[0] * 2 * eV2J / (dQ_SI**2))**(1/2)\n # HR factor (unitless)\n S[lin] = hw[lin] * (dQ_SI**2) / hbar**2 / 2 / eV2J\n if report:\n print(f'{lin} -> hw = {hw[lin]:.4f}, S = {S[lin]:.4f}')\n return hw, S\n\n\ndef make_plot(full_dat: dict, polyfit: dict, zpl: dict, dQ: float, filename: str = 'config.png'):\n ''' make configuration plot '''\n plt.figure(dpi=300, figsize=(4, 4))\n xlim = np.array([-0.5, 1.5])\n colors = {k: c for k, c in zip(full_dat, ['red', 'blue'])}\n\n # plot scatter data\n for lin, dat in full_dat.items():\n qvals = dat[:, 0]*dQ\n yvals = dat[:, 1]\n plt.scatter(qvals, yvals, color=colors[lin])\n # plot fit lines\n for lin, fit in polyfit.items():\n qvals = np.linspace(-0.5, 1.5)\n yvals = fit[0] * qvals**2 + fit[1] * qvals + fit[2]\n qvals *= dQ\n plt.plot(qvals, yvals, color=colors[lin])\n\n # labels and such\n plt.ylabel('Energy [eV]')\n plt.xlabel(r'$\\rm \\Delta Q$ [$\\sqrt{\\rm amu}$ $\\rm \\AA$]')\n plt.xlim(xlim*dQ)\n # keep default ylim\n ax = plt.gca()\n ylim = ax.get_ylim()\n plt.ylim(ylim)\n\n # extract zpl for annotating\n z0, z1 = list(zpl.values())\n # lines\n kwargs = {'color': 'grey', 'linestyle': 'dotted', 'zorder': 0}\n plt.hlines((z0[1], z1[1]), *(xlim*dQ), **kwargs)\n plt.vlines((z0[0]*dQ, z1[0]*dQ), *(ylim), **kwargs)\n\n # save fig\n plt.tight_layout()\n plt.savefig('config.png')\n plt.close()\n\n\nif __name__ == '__main__':\n full_dat = read_full_dat()\n zpl = calc_zpl(full_dat, report=True)\n dQ = calc_dQ(full_dat, report=True)\n polyfit = calc_polyfit(full_dat)\n hw, S = calc_hw_and_S(polyfit, dQ, report=True)\n make_plot(full_dat, polyfit, zpl, dQ)\n","repo_name":"Ping-Group-UCSC/NonRad","sub_path":"scripts/config_helper.py","file_name":"config_helper.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"29860895136","text":"class Cell(object):\n def __init__(self, row_num, col_num):\n self.row_num = row_num\n self.col_num = col_num\n self.value = 0\n self.visited = False\n\n\nclass DynamicGrid(object):\n def __init__(self, rows, columns):\n self.rows = rows\n self.columns = columns\n self.table = []\n for i in range(rows):\n self.table.append([])\n for j in range(columns):\n self.table[i].append(Cell(i, j))\n\n def operation_m(self, row_num, col_num, value):\n \"\"\"Change a number in one cell of the grid to 0 or 1\"\"\"\n self.table[row_num][col_num].value = value\n\n def operation_q(self):\n \"\"\"Determine the number of different connected regions of 1s\"\"\"\n # reset the board every time preform the q operation\n for i in range(self.rows):\n for j in range(self.columns):\n self.table[i][j].visited = False\n\n regions_count = 0\n for row_num in range(self.rows):\n for col_num in range(self.columns):\n cell = self.table[row_num][col_num]\n if cell.value == 1 and not cell.visited:\n regions_count += 1\n self._visit_region(row_num, col_num)\n\n print(regions_count)\n\n def _visit_region(self, row_num, col_num):\n cell = self.table[row_num][col_num]\n cell.visited = True\n # find all the neighbor cells\n neighbours = filter(None, [\n self._get_cell_left(cell),\n self._get_cell_top(cell),\n self._get_cell_right(cell),\n self._get_cell_below(cell),\n ])\n\n for neighbour in neighbours:\n if neighbour.value == 1 and not neighbour.visited:\n self._visit_region(neighbour.row_num, neighbour.col_num)\n\n def _get_cell_top(self, cell):\n upper_row_num = cell.row_num - 1\n upper_col_num = cell.col_num\n\n if upper_row_num >= 0:\n return self.table[upper_row_num][upper_col_num]\n\n return None\n\n def _get_cell_left(self, cell):\n left_row_num = cell.row_num\n left_col_num = cell.col_num - 1\n\n if left_col_num >= 0:\n return self.table[left_row_num][left_col_num]\n\n return None\n\n def _get_cell_right(self, cell):\n right_row_num = cell.row_num\n right_col_num = cell.col_num + 1\n\n if right_col_num < self.columns:\n return self.table[right_row_num][right_col_num]\n\n return None\n\n def _get_cell_below(self, cell):\n below_row_num = cell.row_num + 1\n below_col_num = cell.col_num\n\n if below_row_num < self.rows:\n return self.table[below_row_num][below_col_num]\n\n return None\n\n\ndef main():\n file_name = \"A-large-practice.in\"\n file = open(file_name)\n\n total_cases = int(file.readline())\n\n for case_number in range(total_cases):\n print(\"Case #%s: \" % (case_number + 1))\n rows, columns = list(map(int, file.readline().split()))\n grid = DynamicGrid(rows, columns)\n\n # initialize the grid with default values\n for row_num in range(rows):\n line = file.readline()\n for col_num in range(columns):\n if line[col_num] == \"1\":\n grid.operation_m(row_num, col_num, 1)\n\n num_operations = int(file.readline())\n\n for _ in range(num_operations):\n line = file.readline()\n if line.startswith(\"Q\"):\n grid.operation_q()\n else:\n params = line.split()\n grid.operation_m(int(params[1]), int(params[2]), int(params[3]))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"victor-guoyu/CodeJam","sub_path":"DynamicGrid/dynamic_grid.py","file_name":"dynamic_grid.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2610794242","text":"\"\"\"\nTests of the neuron responses to current steps of different amplitudes match experimental data.\n\nThe responses are quantified by extracting features from the voltage traces using eFEL.\n\nReference data (features extracted from experimental recordings) and experimental protocol configurations\n are extracted from .zip files produced by BluePyOpt.\n\nAndrew Davison, UNIC, CNRS.\nMarch 2017\n\"\"\"\n\nimport os.path\nfrom datetime import datetime\nimport json\nfrom zipfile import ZipFile\nimport numpy as np\nimport sciunit\nfrom sciunit.scores import ZScore\nfrom neuronunit.capabilities import ProducesMembranePotential, ReceivesSquareCurrent\nimport neo\nimport efel\nimport matplotlib.pyplot as plt\nfrom urllib import urlopen\nfrom StringIO import StringIO\nfrom quantities import ms\n\n\nclass RMSZScore(ZScore):\n \"\"\"\n Calculates the z-score for one or more variables and returns the root mean square\n \"\"\"\n\n @classmethod\n def compute(cls, observation, prediction):\n \"\"\"\n Computes a z-score from an observation and a prediction.\n \"\"\"\n scores = []\n table = [] # store intermediate results\n for obs, pred in zip(observation, prediction):\n assert obs.keys() == pred.keys()\n assert len(obs) == 1\n #print(\"O\" + str(obs))\n #print(\"P\" + str(pred))\n scores.append(ZScore.compute(list(obs.values())[0],\n list(pred.values())[0]).score)\n #print(\"Z\" + str(scores[-1]) + \"\\n\")\n key = obs.keys()[0]\n table.append((key, obs[key][\"mean\"], obs[key][\"std\"], pred[key][\"value\"], scores[-1]))\n sc = np.sqrt(np.mean(np.square(scores)))\n print(\"RMS(Z) \" + str(sc))\n score = cls(sc, related_data={'score_table': table})\n return score\n\n _description = ('The root-mean-square of the z-scores for multiple variables')\n\n\nclass MultipleCurrentStepTest(sciunit.Test):\n \"\"\"\n Tests of the neuron responses to current steps of different amplitudes match\n experimental data.\n\n The responses are quantified by extracting features from the voltage traces\n using eFEL.\n \"\"\"\n required_capabilities = (ProducesMembranePotential, ReceivesSquareCurrent)\n score_type = RMSZScore\n\n def __init__(self, observation=None, name=None, protocol=None, plot_figure=False):\n sciunit.Test.__init__(self, observation, name)\n self.plot_figure = plot_figure\n if protocol is None:\n raise ValueError(\"Must provide a stimulation protocol\")\n self.protocol = protocol\n self.timestamp = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n self.figures = []\n\n def validate_observation(self, observation):\n \"\"\"\n Checks that the observation has the correct format, i.e.\n\n - a top-level dict with one entry per current step.\n - the key should be a label for the step\n - the value should be a dict containing one entry per feature of the voltage trace\n - the key of the feature dict should be a label for the feature\n - the value should be a dict with keys 'mean' and 'value'\n \"\"\"\n pass # todo\n\n def generate_prediction(self, model, verbose=False):\n use_cache = True\n cache_filename = \"./\"+model.working_dir+\"/results.pkl\"\n if use_cache and os.path.exists(cache_filename):\n io = neo.io.get_io(cache_filename)\n self.recordings = io.read_block()\n else:\n self.recordings = self._run_simulations(model)\n io = neo.io.PickleIO(cache_filename)\n io.write_block(self.recordings)\n if self.plot_figure:\n for i, seg in enumerate(self.recordings.segments):\n plt.plot(seg.analogsignals[0].times.rescale('ms'),\n seg.analogsignals[0].rescale('mV').magnitude + i * 110.0,\n label=seg.name)\n plt.legend()\n self.figure_path = \"./{}/{}_{}_{}.png\".format(model.working_dir, self.name, model.name, self.timestamp)\n plt.savefig(self.figure_path)\n self.figures.append(self.figure_path)\n return self._calculate_features(self.recordings)\n\n def _run_simulations(self, model):\n \"\"\"For each step in the protocol, run simulation and store recordings\"\"\"\n recordings = neo.Block()\n for step_name, step in self.protocol.items():\n segment = neo.Segment(name=step_name)\n recordings.segments.append(segment)\n segment.block = recordings\n\n model.inject_current(step[\"stimuli\"])\n model.run(tstop=step[\"total_duration\"])\n signal = model.get_membrane_potential()\n stimulus_on = neo.Epoch(times=step[\"stimuli\"][\"delay\"]*ms,\n durations=step[\"stimuli\"][\"duration\"]*ms,\n labels=\"stimulus\")\n segment.analogsignals.append(signal)\n segment.epochs.append(stimulus_on)\n return recordings\n\n def _calculate_features(self, recordings):\n \"\"\"For each recorded step, calculate the features.\"\"\"\n features_from_simulation = {}\n for segment in recordings.segments:\n step_name = segment.name\n feature_names = self.observation[step_name].keys()\n trace = {\n 'T': segment.analogsignals[0].times.rescale('ms').magnitude,\n 'V': segment.analogsignals[0].rescale('mV').magnitude,\n 'stim_start': [segment.epochs[0].times],\n 'stim_end': [segment.epochs[0].times + segment.epochs[0].durations]\n }\n\n features = efel.getFeatureValues([trace], feature_names)[0]\n features_from_simulation[step_name] = dict([(k, {'value': v[0]})\n for k, v in features.items()])\n return features_from_simulation\n\n def compute_score(self, observation, prediction, verbose=False):\n \"\"\"\n Generates a score given the observations provided in the constructor\n and the prediction generated by generate_prediction.\n \"\"\"\n # reformat the observations and predictions into the form needed by RMSZScore\n # i.e. from dict of dicts into a flat list of dicts\n observation_list = []\n prediction_list = []\n for step_name in observation:\n for feature_name in observation[step_name]:\n key = \"{}_{}\".format(step_name, feature_name)\n observation_list.append({key: observation[step_name][feature_name]})\n prediction_list.append({key: prediction[step_name][feature_name]})\n return self.score_type.compute(observation_list, prediction_list)\n\n def bind_score(self, score, model, observation,\n prediction):\n \"\"\"\n For the user to bind additional features to the score.\n \"\"\"\n if hasattr(self, \"figure_path\"):\n score.related_data[\"figures\"] = self.figures\n return score\n\n\n\nclass BluePyOpt_MultipleCurrentStepTest(MultipleCurrentStepTest):\n \"\"\"\n Tests if the neuron responses to current steps of different amplitudes match\n experimental data.\n\n The responses are quantified by extracting features from the voltage traces\n using eFEL.\n\n Experimental protocol definitions and experimental features obtained from\n zip files produced by BluePyOpt\n \"\"\"\n\n def __init__(self, observation=None, name=None, plot_figure=False):\n url = urlopen(observation)\n with ZipFile(StringIO(url.read())) as zf:\n top_level_directory = os.path.splitext(os.path.basename(observation))[0]\n # load the protocol definition and the reference data\n with zf.open(top_level_directory + \"/config/protocols.json\") as fp:\n protocols = json.load(fp)\n assert len(protocols) == 1\n protocol_name = protocols.keys()[0]\n\n with zf.open(top_level_directory + \"/config/features.json\") as fp:\n reference_features = json.load(fp)\n assert reference_features.keys()[0] == protocol_name\n\n # reformat the reference_features dict into the necessary form\n observations = {}\n for step, value in reference_features[protocol_name].items():\n observations[step] = {}\n for feature_name, (mean, std) in value[\"soma\"].items():\n observations[step][feature_name] = {\"mean\": mean, \"std\": std}\n\n # reformat the protocol definition into the form requested by NeuronUnit\n protocol = {}\n for step_name, content in protocols[protocol_name].items():\n stim = content[\"stimuli\"][0]\n stim[\"amplitude\"] = stim[\"amp\"]\n protocol[step_name] = {\n \"stimuli\": stim,\n \"total_duration\": stim[\"totduration\"]\n }\n del stim[\"amp\"]\n del stim[\"totduration\"]\n\n MultipleCurrentStepTest.__init__(self,\n observation=observations,\n name=name,\n protocol=protocol,\n plot_figure=plot_figure)\n","repo_name":"apdavison/hippounit","sub_path":"hippounit/tests/test_bpopt.py","file_name":"test_bpopt.py","file_ext":"py","file_size_in_byte":9298,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"43216766477","text":"from anytree import Node, PreOrderIter, LevelOrderGroupIter\n\nTOTAL_SIZE = 100_000\nTOTAL_SPACE = 70_000_000\nUNUSED_SPACE = 30_000_000\n\n\nclass FileNode(Node):\n def __init__(self, path, size, parent=None):\n super(FileNode, self).__init__(path, parent)\n self.size = size\n\n\ndef calc_size(parent):\n size = sum([node.size for node in PreOrderIter(parent)])\n return size\n\n\ndef task1(lines):\n root = FileNode('/', 0)\n cwd = root\n for line in lines:\n if line[:4] == '$ cd' and line[5] != '/':\n if line[5] != '.':\n cwd = FileNode(line[5:], 0, parent=cwd)\n elif line[5] == '.':\n cwd = cwd.parent\n elif line[0].isnumeric():\n cmd = line.split()\n FileNode(cmd[1], int(cmd[0]), parent=cwd)\n levels = [[{'node': node,\n 'size': node.size} for node in children] for children in LevelOrderGroupIter(root)]\n sizes = []\n for level in levels:\n for node_dict in level:\n if node_dict['size'] == 0:\n sizes.append(calc_size(node_dict['node']))\n print(sum([s for s in sizes if s <= TOTAL_SIZE]))\n return sizes\n\n\ndef task2(sizes):\n c_unused_space = TOTAL_SPACE - sizes[0]\n desired_size = UNUSED_SPACE - c_unused_space\n print(min([s for s in sizes if s >= desired_size]))\n\n\nif __name__ == '__main__':\n with open('input.txt', 'r') as f:\n lines = f.read().splitlines()\n sizes = task1(lines)\n task2(sizes)","repo_name":"eera-l/AoC22","sub_path":"day7/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"6946657290","text":"# Quick script to infer a gtr model using treetime\n\nimport sys\nimport json\nimport numpy as np\nfrom Bio import AlignIO\nfrom treetime import TreeAnc\n\ndef output_JSON(gtr_model, output_file):\n gtr = gtr_model.__dict__\n save_dict = {}\n for key in [\"_mu\", \"_Pi\", \"_W\"]:\n if isinstance(gtr[key], np.ndarray):\n save_dict[key.replace(\"_\", \"\")] = gtr[key].tolist()\n else:\n save_dict[key.replace(\"_\", \"\")] = gtr[key]\n\n with open(output_file, 'w') as output:\n json.dump(save_dict, output)\n\n\nalignment_file = sys.argv[1]\ntree_file = sys.argv[2]\noutput_file = sys.argv[3]\n\nalignment = AlignIO.read(alignment_file, \"fasta\")\ntt = TreeAnc(tree=tree_file, aln=alignment_file)\ngtr = tt.infer_gtr(marginal=True, normalized_rate=False)\noutput_JSON(gtr, output_file)\n","repo_name":"vdruelle/BH_hiv_seq","sub_path":"scripts/infer_gtr.py","file_name":"infer_gtr.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28172602543","text":"import willie\nimport re\n\n@willie.module.rule('.*(?:^| )/?r/([A-Za-z0-9][A-Za-z0-9_]{2,20})/?(?:$| ).*')\ndef sublink(bot, trigger):\n \"\"\"Gives a subreddit url and title when the abreviation r/subreddit is posted to the channel\"\"\"\n\n url = 'https://www.reddit.com/r/' + trigger.group(1) + '/'\n data = willie.web.get(url, limit_bytes=1024)\n title = re.match('.*(.+).*', data).group(1)\n \n if title == 'search results' : bot.reply('r/' + trigger.group(1) + ' doesn\\'t seem to exist')\n else : bot.say('\\x02r/' + trigger.group(1) + '\\x02 [' + title + '] ' + url)\n","repo_name":"Llamatron2112/Llamatron-Willie-Modules","sub_path":"sublink.py","file_name":"sublink.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74020024806","text":"import argparse\nimport pathlib\n\ndef main():\n # Parse command-line\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path\", nargs=1, help=\"folder path\")\n args = parser.parse_args()\n\n script_path = pathlib.Path(__file__).parent\n input_folder = pathlib.Path(args.path[0])\n\n # --------------------------------------\n if not input_folder.is_dir():\n raise NotADirectoryError(\"input_folder does not exist \"\n f\"or is not a directory ('{input_folder}')\")\n output_path = (script_path / input_folder.name).with_suffix(\".art\")\n\n i = 0\n with open(output_path, mode=\"wb\") as f:\n for x in sorted(input_folder.glob(\"*.[tT][gG][aA]\")):\n print(f\"File = {x}\")\n buf = x.read_bytes()\n\n tga_id_length = int(buf[0])\n tga_width = int.from_bytes(buf[12:14], \"little\")\n tga_height = int.from_bytes(buf[14:16], \"little\")\n tga_data_size = 4 * tga_width * tga_height\n hdr_len = 0x12 + tga_id_length\n\n if len(buf) < tga_data_size:\n print(\"Skipping... TGA format error (missing alpha channel?)\")\n continue\n\n # print(\"header:\", buf[:hdr_len])\n # print(buf[hdr_len:hdr_len + tga_data_size])\n # print(\"footer:\", buf[hdr_len + tga_data_size:])\n print(f\"id_len={tga_id_length} w={tga_width} h={tga_height} \"\n f\"in_size={tga_data_size} out_size={len(buf)}\")\n # print(tga_width.to_bytes(4, \"little\"))\n # print(tga_height.to_bytes(4, \"little\"))\n\n f.write(tga_width.to_bytes(4, \"little\"))\n f.write(tga_height.to_bytes(4, \"little\"))\n f.write(buf[hdr_len:hdr_len + tga_data_size])\n\n i += 1\n\n print(f\"created file {output_path} (contains {i} TGA files)\")\n if i < 1:\n raise Warning(\"empty ART archive\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bfut/PyScripts","sub_path":"bfut_Art2Tga/bfut_Tga2Art.py","file_name":"bfut_Tga2Art.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2706095557","text":"class Solution:\n def combinationSum(self, nums: List[int], target: int) -> List[List[int]]:\n def backtrack(tmp: List[int], target: int, start: int):\n if target < 0:\n return\n elif target == 0:\n res.append(tmp[:])\n \n for i in range(start, len(nums)):\n tmp.append(nums[i])\n backtrack(tmp, target - nums[i], i)\n tmp.pop()\n \n res = []\n nums.sort()\n backtrack([], target, 0)\n return res\n","repo_name":"cvpriccvnips/coding-challenge","sub_path":"leetcode/backtracking/39.comb.py","file_name":"39.comb.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43445142275","text":"import yaml\nimport os\nimport re\n\n\nclass ConfigParser:\n\n \"\"\"\n A parser to parse the config files. The parameters can be accessed as attributes\n Eg. For the below config.yml file\n \n train:\n batch_size: 8\n epochs: 100\n optim:\n lr: 0.0004\n type: 'adam'\n\n config = ConfigParser('config/train.yml', None).config\n \n You can access the parameters form the config file as shown below\n config.train.optim\n config.train.optim.lr\n config.train.batch_size\n\n which is not possible with a standard python dictionary.\n \n Note: Values such as 1e-4 are considered as strings instead of float\n \"\"\"\n\n class ConfigObject(dict):\n \"\"\"\n Represents configuration options' group, works like a dict\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n\n def __getattr__(self, name):\n return self[name]\n\n def __setattr__(self, name, val):\n self[name] = val\n\n def __init__(self, config_file, args=None):\n\n \"\"\"\n :param config_file: Path to the config file\n :param args: Optional. Arguments passed via command line\n \"\"\"\n\n self.config_file = config_file\n self._check_files()\n\n self.pattern = re.compile(r\"^([0-9a-zA-Z]+_*[0-9a-zA-Z]*.)*([0-9a-zA-Z]+_*[0-9a-zA-Z]*)+$\")\n\n with open(self.config_file) as file:\n self.config_dict = yaml.load(file, Loader=yaml.FullLoader)\n\n self._update_with_args(args)\n\n self.config = self._create_config_object(self.config_dict)\n\n def _create_config_object(self, config_dict):\n\n if isinstance(config_dict, dict):\n out = self.ConfigObject()\n for key in config_dict:\n out[key] = self._create_config_object(config_dict[key])\n return out\n else:\n return config_dict\n\n def _update_dict_for_nested_key(self, dictionary, key: str, value):\n\n if \".\" not in key:\n dictionary[key] = value\n else:\n key_1, key_2 = key.split('.', 1)\n if key_1 not in dictionary:\n dictionary[key_1] = {}\n\n self._update_dict_for_nested_key(dictionary[key_1], key_2, value)\n\n def _update_with_args(self, args):\n\n if args is None:\n return\n\n for param, value in args.items():\n if value is None:\n continue\n if self.pattern.fullmatch(param):\n self._update_dict_for_nested_key(self.config_dict, param, value)\n\n def _check_files(self):\n \"\"\"\n Checks if the config and schema files exist\n \"\"\"\n\n if self.config_file is not None and not os.path.exists(self.config_file):\n return FileNotFoundError('%s file does not exist' % self.config_file)\n","repo_name":"harinandan1995/csm","sub_path":"src/utils/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"4918235975","text":"# escape refers to \\\ntabby_cat = \"\\tI'm tabbed!\"\nprint(tabby_cat)\n\npersian_cat = \"I'm split\\non a line.\"\nprint(persian_cat)\n\nbackslash_cat = \"I'm \\\\ a \\\\ cat.\"\nprint(backslash_cat)\n\nprint(\"\"\"\nThis is my list:\n\\t- Cat food\n\\t- Fishies\n\\t- Catnip\\n\\t- Grass\n\"\"\")\n\n","repo_name":"UpCode-Academy/Python-Bootcamp-October","sub_path":"06 - escape sequence.py","file_name":"06 - escape sequence.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37818996514","text":"from django.urls import path\nfrom users import views\nfrom django.contrib.auth.views import LoginView, LogoutView\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('register/', views.register, name='register'),\n path('login/', LoginView.as_view(template_name='users/login.html'), name='login'),\n path('logout/', LogoutView.as_view(), name='logout'),\n path('post/', views.create_post, name='post'),\n path('profile//', views.user_profile, name='profile'),\n path('like/post//', views.like_post, name='like-post'),\n path('post//', views.get_full_post, name='full_post'),\n path('delete/comment//', views.delete_comment, name='delete_comment'),\n path('posts/filtered//', views.search_post, name='search_posts'),\n path('follow//', views.follow_user, name='follow')\n]","repo_name":"ismailPervez/pictogram","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30166298904","text":"#!/usr/bin/python\r\n#_*_coding:UTF-8_*_\r\n# 全部?取\r\nprint(\"#######全ての取込む#######\")\r\nfile0 = open(\"File/test.txt\",\"r\")\r\ncontent1 = file0.read()\r\nprint(content1)\r\n\r\n# ??文件?取\r\nfile0.close()\r\n# 按照字?数?取\r\nprint(\"#######Byteによって、取込む#######\")\r\nfile1 = open(\"File/test.txt\",\"r\")\r\ncontent2 = file1.read(3)\r\nprint(content2)\r\n# 剩下直到?尾的内容?取\r\ncontent3 = file1.read()\r\nprint(content3)\r\n# ??文件?取\r\nfile1.close()\r\n# 按行?取\r\nprint(\"#######全ての取込む(行目によって(readlines))#######\")\r\nfile2 = open(\"File/test.txt\",\"r\")\r\ncontent4 = file2.readlines()\r\nprint(content4)\r\ni = 1 \r\nfor temp in content4:\r\n print(temp)\r\n i += 1\r\nfile2.close()\r\n# 按行?取\r\nprint(\"#######全ての取込む(一つの行目のみ(毎readline))#######\")\r\nfile3 = open(\"File/test.txt\",\"r\")\r\ncontent5 = file3.readline()\r\nprint(\"1:%s\" % content5)\r\ncontent5 = file3.readline()\r\nprint(\"2:%s\" % content5)\r\nfile3.close()\r\n","repo_name":"qiaokeli2022/zhangxu","sub_path":"test/huayu.liu/readFileTxt.py","file_name":"readFileTxt.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6858949754","text":"#!/usr/bin/env python\n# Socket io ROS wrapper\nfrom socketIO_client import SocketIO, LoggingNamespace\nimport rospy\nimport time\nfrom budspeech.msg import speech\nfrom std_msgs.msg import String\n\ndef on_publish_test():\n message = speech()\n message.text=str(msg)\n message.confidence=1\n message.interface_id=2\n self.pub.publish(message)\n\nclass socketio_wrapper_node(object):\n\n def __init__(self):\n self.socketIO = SocketIO('localhost', 3000, LoggingNamespace)\n rospy.init_node('socketio_wrapper')\n self.socketIO.emit('it_works','yeah')\n # Init Ros Publisher\n self.pub = rospy.Publisher('speech', speech,queue_size=100)\n # Init Ros Subcriber\n rospy.Subscriber(\"budrep\", String, self.process_response)\n self.socketIO.on('user_demand', self.on_publish)\n\n def spin(self):\n self.socketIO.wait()\n\n def process_response(self,data):\n self.socketIO.emit('resp',data.data)\n\n def on_publish(self,*msg):\n message = speech()\n message.text=str('buddy '+msg[0])\n message.confidence=1\n message.interface_id=3\n self.pub.publish(message)\n\nif __name__ == '__main__':\n wrap=socketio_wrapper_node()\n wrap.spin()\n","repo_name":"SimBil91/FlatBuddy","sub_path":"budspeech/src/socketio_wrapper.py","file_name":"socketio_wrapper.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"37518448195","text":"import requests\nfrom telegram import (KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove,\n Update, error)\nfrom telegram.ext import (CallbackContext, CallbackQueryHandler,\n CommandHandler, ConversationHandler, Filters,\n MessageHandler)\n\nfrom modules.dialogs_shortcuts.start_shortcuts import (\n CONF_LOCATION, END, PATIENT_REGISTRATION_ACTION, START_OVER,\n START_SELECTORS, STOPPING)\nfrom tools.prepared_answers import BAD_GEOCODER_RESP\nfrom tools.tools import get_from_env\n\n\nclass Location:\n def __init__(self, tz=None, location: dict = None):\n self._time_zone = self.validate_tz(tz) if tz else tz\n self._location = location # {'address': [lat, lon]}\n\n def time_zone(self):\n return self._time_zone\n\n @staticmethod\n def validate_tz(tz):\n if type(tz) is str and (tz[0] not in ('+', '-') or not tz[1:].isdigit()\n or not (-10 <= int(tz[1:]) <= 10)):\n raise ValueError(f'Not correct tz: {tz}')\n return tz\n\n def location(self):\n return self._location\n\n def get_coords(self):\n if self._location:\n return list(self._location.values())[0]\n return None\n\n def __str__(self):\n if self._location and not self._time_zone:\n address = list(self._location.keys())[0]\n return f'{address} - ({self._location[address][0]}, ' \\\n f'{self._location[address][1]})'\n elif self._time_zone and not self._location:\n return f'{\"+\" if int(self._time_zone) >= 0 else \"\"}' \\\n f'{int(self._time_zone)}'\n\n def __ne__(self, other):\n if other:\n return (int(self.time_zone()) if self.time_zone() else None,\n self.location()) \\\n != (int(other.time_zone()) if self.time_zone() else None,\n other.location())\n return True\n\n\nclass FindLocationDialog(ConversationHandler):\n def __init__(self, *args, **kwargs):\n from modules.start_dialogs import StartDialog\n super().__init__(\n name=self.__class__.__name__,\n entry_points=[CallbackQueryHandler(\n self.start, pattern=f'^{CONF_LOCATION}$')]\n if not kwargs.get('e_points') else kwargs.get('e_points'),\n\n states={\n 1: [MessageHandler(Filters.regex('^Найти адрес$'),\n self.input_address),\n MessageHandler(Filters.location, self.location_response,\n run_async=False),\n MessageHandler(Filters.regex('^Назад$'),\n self.back_to_prev_level, run_async=False)],\n 2: [MessageHandler(Filters.text & ~Filters.command,\n self.find_response)],\n 3: [MessageHandler(Filters.regex('^Да, верно$|^Нет, неверно$'),\n self.location_response, run_async=False)],\n },\n fallbacks=[\n CommandHandler('stop', StartDialog.stop_nested,\n run_async=False),\n CommandHandler('start', StartDialog.restart, run_async=False)\n ] if not kwargs.get('fallbacks') else kwargs.get('fallbacks'),\n map_to_parent={\n START_SELECTORS: START_SELECTORS,\n PATIENT_REGISTRATION_ACTION: END,\n STOPPING: STOPPING,\n }\n )\n\n @staticmethod\n def start(update: Update, context: CallbackContext):\n kboard = ReplyKeyboardMarkup(\n [\n [KeyboardButton(text='Отправить геолокацию',\n request_location=True)],\n ['Назад']\n ],\n row_width=1, resize_keyboard=True, one_time_keyboard=True)\n\n if not context.user_data.get(START_OVER):\n update.callback_query.delete_message()\n if context.chat_data.get('st_msg'):\n context.chat_data['st_msg'] = None\n try:\n msg = context.bot.send_message(\n update.effective_chat.id,\n text='Выберите способ добавления местоположения',\n reply_markup=kboard)\n context.chat_data['st_msg'] = msg.message_id\n context.user_data[START_OVER] = False\n return 1\n except error.Unauthorized:\n return STOPPING\n\n @staticmethod\n def input_address(update: Update, context: CallbackContext):\n try:\n context.bot.send_message(update.effective_chat.id,\n text='Введите Ваш адрес или '\n 'ближайший населенный пункт.',\n reply_markup=ReplyKeyboardRemove())\n return 2\n except error.Unauthorized:\n return STOPPING\n\n @staticmethod\n def find_response(update: Update, context: CallbackContext):\n static_api_request = FindLocationDialog.find_location(update, context)\n try:\n if static_api_request is not None:\n keyboard = ReplyKeyboardMarkup(\n [['Да, верно'], ['Нет, неверно']],\n row_width=1, resize_keyboard=True, one_time_keyboard=True)\n context.bot.send_photo(\n update.message.chat_id,\n static_api_request,\n caption='Пожалуйста, убидетесь, что мы правильно '\n 'определили Ваше местоположение.',\n reply_markup=keyboard)\n return 3\n return FindLocationDialog.input_address(update, context)\n except error.Unauthorized:\n return STOPPING\n\n @staticmethod\n def location_response(update: Update, context: CallbackContext, ret=None):\n \"\"\"\n Проверка результата поиска через апи.\n Сохранение позиции, полученной через геометку ТГ.\n \"\"\"\n from modules.start_dialogs import PatientRegistrationDialog\n\n response = update.message.text\n location = update.message.location\n\n context.user_data[START_OVER] = True\n if response and 'Нет, неверно' in response:\n return FindLocationDialog.start(update, context)\n\n elif (response and 'Да, верно' in response) or location:\n if location:\n context.user_data['user'].p_loc.location = Location(\n location={'Нет адреса': [location.longitude,\n location.latitude]})\n if ret:\n context.user_data[START_OVER] = False\n return ret(update, context)\n return PatientRegistrationDialog.start(update, context)\n\n @staticmethod\n def back_to_prev_level(update: Update, context: CallbackContext):\n # Переход на предыдущий уровень в диалоге\n context.user_data[START_OVER] = True\n if not context.user_data['user'].registered():\n from modules.start_dialogs import ConfigureTZDialog\n ConfigureTZDialog.start(update, context)\n else:\n from modules.settings_dialogs import SettingsConfTZDialog\n SettingsConfTZDialog.start(update, context)\n return END\n\n @staticmethod\n def find_location(update: Update, context: CallbackContext):\n \"\"\"Поиск локации в яндексе\"\"\"\n\n # Получние ответа от геокодера о поиске адреса\n geocoder_uri = 'http://geocode-maps.yandex.ru/1.x/'\n response = requests.get(geocoder_uri, params={\n 'apikey': get_from_env('GEOCODER_T'),\n 'format': 'json',\n 'geocode': update.message.text\n })\n if not response:\n update.message.reply_text(\n BAD_GEOCODER_RESP +\n f'Http статус: {response.status_code} ({response.reason})')\n return None\n\n json_response = response.json()\n\n # На основе ответа геокодера получаем координаты объекта\n if json_response['response']['GeoObjectCollection'][\n 'metaDataProperty']['GeocoderResponseMetaData']['found'] == '0':\n update.message.reply_text('Мы не смогли найти указанный адрес. '\n 'Попробуйте снова.')\n return None\n\n toponym = json_response['response']['GeoObjectCollection'][\n 'featureMember'][0]['GeoObject']\n toponym_coodrinates = toponym['Point']['pos']\n\n # Долгота и широта\n toponym_longitude, toponym_lattitude = toponym_coodrinates.split(' ')\n delta = '0.3'\n ll = ','.join([toponym_longitude, toponym_lattitude])\n spn = ','.join([delta, delta])\n\n # Ищем объект на карте, чтобы определить что правильно нашли место\n static_api_request = \\\n f'http://static-maps.yandex.ru/1.x/?ll={ll}' \\\n f'&spn={spn}&l=map&' \\\n f'pt={\",\".join([toponym_longitude, toponym_lattitude])},vkbkm'\n\n # Запоминаем положение\n context.user_data['user'].p_loc.location = \\\n Location(location={update.message.text: [toponym_longitude,\n toponym_lattitude]})\n\n return static_api_request\n\n\nclass ChangeLocationDialog(FindLocationDialog):\n def __init__(self):\n from modules.settings_dialogs import SETTINGS_ACTION, SettingsDialog\n super().__init__(\n fallbacks=[\n CommandHandler('stop', SettingsDialog.stop_nested,\n run_async=False),\n MessageHandler(Filters.regex('Настройки$'),\n SettingsDialog.restart, run_async=False)\n ]\n )\n self.map_to_parent.update({\n SETTINGS_ACTION: SETTINGS_ACTION,\n STOPPING: STOPPING\n })\n\n @staticmethod\n def location_response(update: Update, context: CallbackContext, *args):\n from modules.settings_dialogs import SettingsDialog\n return FindLocationDialog.location_response(\n update, context, SettingsDialog.start)\n","repo_name":"gg-master/VISDOM_Tg-bot","sub_path":"modules/location.py","file_name":"location.py","file_ext":"py","file_size_in_byte":10757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71877686566","text":"from os import listdir, path, remove\nfrom PIL import Image\n\nprint(\"(WARNING: Images in the input folder will be moved(deleted) to the output folder with exif data modified)\")\n\ntry:\n ending_num = int(input('Enter the highest file number ending (E.g. 63) : '))\nexcept ValueError:\n print('Make sure to input an integer\\nExiting...')\n\n# Adds the exif data to a variable called metadata\nwith open('sample.exif','rb') as exif_file:\n metadata = exif_file.read()\n\n\nif path.exists('./input'): # Checks if input folder exists\n for image_file in listdir('./input'): # Loops over every file in input\n if image_file.split('.')[-1].lower() in ['jpg','jpeg','png']: # Checks for supported extensions\n tmp_image = Image.open(f'./input/{image_file}') # Loads the image into an Image object\n x,y = tmp_image.size # Assigns the height and width of the image to variables\n\n if x > 640 or y > 480: # Checks if the image is too large\n print(f'Image \"{image_file}\" is too big. Limited to 640 x 480.')\n else:\n ending_num+=1\n tmp_image.save(f'{\"./output/\" if path.exists(\"./output\") else \"\"}HNI_{str(ending_num).zfill(4)}.JPG', exif=metadata) # Creates the file with metadata to be read by 3DS\n remove(f'./input/{image_file}')\n else:\n if image_file == \"PUT IMAGES HERE\":\n pass # Ignores the basic file placeholder\n else:\n print(f'\"{image_file}\" has an unsupported file extension.')\n","repo_name":"Zekaroni/3DS_Image_Conversion","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3972709048","text":"import time\nimport datetime\nimport os\nimport numpy\nimport av\nimport cv2\nfrom ball_tracker import ball_tracker\nfrom myTello import myTello\nfrom cv2 import dnn\nfrom face_tracker import face_tracker\n\nclass TelloCV(object):\n \"\"\"\n TelloTracker builds keyboard controls on top of TelloPy as well\n as generating images from the video stream and enabling opencv support\n \"\"\"\n\n def __init__(self,Tello:myTello):\n self.prev_flight_data = None\n self.record = False\n self.tracking = False\n self.keydown = False\n self.date_fmt = '%Y-%m-%d_%H%M%S'\n self.speed = 20\n self.speed2 = 10\n self.drone = Tello\n # self.init_drone()\n\n self.caffe_prototxt_path = \"../Face_Distance/model/RFB-320.prototxt\"\n self.caffe_model_path = \"../Face_Distance/model/RFB-320.caffemodel\"\n self.net = dnn.readNetFromCaffe(self.caffe_prototxt_path, self.caffe_model_path)\n\n # container for processing the packets into frames\n # self.container = av.open(self.drone.get_video_stream())\n # self.vid_stream = self.drone.container.streams.video[0]\n self.out_file = None\n self.out_stream = None\n self.out_name = None\n self.start_time = time.time()\n\n # tracking a color\n green_lower = (30, 50, 50)\n green_upper = (80, 255, 255)\n #red_lower = (0, 50, 50)\n # red_upper = (20, 255, 255)\n # blue_lower = (110, 50, 50)\n # upper_blue = (130, 255, 255)\n self.track_cmd = \"\"\n self.ball_tracker = ball_tracker(self.drone.height,\n self.drone.width,\n green_lower, green_upper)\n\n self.face_tracker = face_tracker(self.drone.height,\n self.drone.width,)\n\n # def init_drone(self):\n # \"\"\"Connect, uneable streaming and subscribe to events\"\"\"\n # # self.drone.log.set_level(2)\n # # self.drone.connect()\n # # self.drone.start_video()\n # self.drone.subscribe(self.drone.EVENT_FLIGHT_DATA,\n # self.flight_data_handler)\n # self.drone.subscribe(self.drone.EVENT_FILE_RECEIVED,\n # self.handle_flight_received)\n\n\n def ball_process_frame(self, frame):\n \"\"\"convert frame to cv2 image and show\"\"\"\n image = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n # image = self.write_hud(image)\n if self.record:\n self.record_vid(frame)\n\n xoff, yoff, zoff = self.ball_tracker.track(image)\n image = self.ball_tracker.draw_arrows(image)\n\n distance = 100\n cmd = \"\"\n if self.tracking:\n if xoff < -distance:\n cmd = \"counter_clockwise\"\n elif xoff > distance:\n cmd = \"clockwise\"\n elif yoff < -distance:\n cmd = \"down\"\n elif yoff > distance:\n cmd = \"up\"\n elif zoff < -25:\n cmd = \"backward\"\n elif zoff > 25:\n cmd = \"forward\"\n else:\n if self.track_cmd is not \"\":\n getattr(self.drone, self.track_cmd)(0)\n self.track_cmd = \"\"\n\n if cmd is not self.track_cmd:\n if cmd is not \"\":\n if cmd == \"forward\" or cmd == \"backward\":\n print(\"track command forward:\", cmd)\n getattr(self.drone, cmd)(self.speed2)\n self.track_cmd = cmd\n else:\n print(\"track command other:\", cmd)\n getattr(self.drone, cmd)(self.speed)\n self.track_cmd = cmd\n return image\n\n def face_process_frame(self, frame):\n \"\"\"convert frame to cv2 image and show\"\"\"\n image = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n # image = self.write_hud(image)\n # cv2.imshow(\"test\",image)\n # cv2.waitKey(1)\n if self.record:\n self.record_vid(frame)\n\n xoff, yoff, zoff = self.face_tracker.track(image, self.net)\n # image = self.tracker_face.draw_arrows(image)\n #print(zoff)\n\n distance = 80\n cmd = \"\"\n # if count!=0:\n # if self.track_cmd is not \"\":\n # getattr(self.drone, self.track_cmd)(0)\n # self.track_cmd = \"\"\n # return image\n if self.tracking:\n if xoff < -distance:\n cmd = \"counter_clockwise\"\n elif xoff > distance:\n cmd = \"clockwise\"\n elif yoff < -distance:\n cmd = \"down\"\n elif yoff > distance:\n cmd = \"up\"\n elif zoff < -15:\n cmd = \"backward\"\n # self.backtimes = self.backtimes + 1\n # print(\"backtimes={}\".format(self.backtimes))\n elif zoff > 15:\n cmd = \"forward\"\n # self.fortimes = self.fortimes + 1\n # print(\"fortimes={}\".format(self.fortimes))\n else:\n if self.track_cmd is not \"\":\n getattr(self.drone, self.track_cmd)(0)\n self.track_cmd = \"\"\n\n if cmd is not self.track_cmd:\n if cmd is not \"\":\n if cmd == \"forward\" or cmd == \"backward\":\n print(\"track command forward:\", cmd)\n getattr(self.drone, cmd)(self.speed2)\n self.track_cmd = cmd\n else:\n print(\"track command other:\", cmd)\n getattr(self.drone, cmd)(self.speed)\n self.track_cmd = cmd\n\n return image\n\n\n def write_hud(self, frame):\n \"\"\"Draw drone info, tracking and record on frame\"\"\"\n stats = self.prev_flight_data.split('|')\n stats.append(\"Tracking:\" + str(self.tracking))\n if self.drone.zoom:\n stats.append(\"VID\")\n else:\n stats.append(\"PIC\")\n if self.record:\n diff = int(time.time() - self.start_time)\n mins, secs = divmod(diff, 60)\n stats.append(\"REC {:02d}:{:02d}\".format(mins, secs))\n\n for idx, stat in enumerate(stats):\n text = stat.lstrip()\n cv2.putText(frame, text, (0, 30 + (idx * 30)),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1.0, (255, 0, 0), lineType=30)\n return frame\n\n def toggle_recording(self, speed):\n \"\"\"Handle recording keypress, creates output stream and file\"\"\"\n if speed == 0:\n return\n self.record = not self.record\n\n if self.record:\n datename = [os.getenv('HOME'), datetime.datetime.now().strftime(self.date_fmt)]\n self.out_name = '{}/Pictures/tello-{}.mp4'.format(*datename)\n print(\"Outputting video to:\", self.out_name)\n self.out_file = av.open(self.out_name, 'w')\n self.start_time = time.time()\n self.out_stream = self.out_file.add_stream(\n 'mpeg4', self.drone.vid_stream.rate)\n self.out_stream.pix_fmt = 'yuv420p'\n self.out_stream.width = self.drone.vid_stream.width\n self.out_stream.height = self.drone.vid_stream.height\n\n if not self.record:\n print(\"Video saved to \", self.out_name)\n self.out_file.close()\n self.out_stream = None\n\n def record_vid(self, frame):\n \"\"\"\n convert frames to packets and write to file\n \"\"\"\n new_frame = av.VideoFrame(\n width=frame.width, height=frame.height, format=frame.format.name)\n for i in range(len(frame.planes)):\n new_frame.planes[i].update(frame.planes[i])\n pkt = None\n try:\n pkt = self.out_stream.encode(new_frame)\n except IOError as err:\n print(\"encoding failed: {0}\".format(err))\n if pkt is not None:\n try:\n self.out_file.mux(pkt)\n except IOError:\n print('mux failed: ' + str(pkt))\n\n def take_picture(self, speed):\n \"\"\"Tell drone to take picture, image sent to file handler\"\"\"\n if speed == 0:\n return\n self.drone.take_picture()\n\n def palm_land(self, speed):\n \"\"\"Tell drone to land\"\"\"\n if speed == 0:\n return\n self.drone.palm_land()\n\n def toggle_tracking(self, speed):\n \"\"\" Handle tracking keypress\"\"\"\n if speed == 0: # handle key up event\n return\n self.tracking = not self.tracking\n print(\"tracking:\", self.tracking)\n return\n\n def toggle_zoom(self, speed):\n \"\"\"\n In \"video\" mode the self.drone sends 1280x720 frames.\n In \"photo\" mode it sends 2592x1936 (952x720) frames.\n The video will always be centered in the window.\n In photo mode, if we keep the window at 1280x720 that gives us ~160px on\n each side for status information, which is ample.\n Video mode is harder because then we need to abandon the 16:9 display size\n if we want to put the HUD next to the video.\n \"\"\"\n if speed == 0:\n return\n self.drone.set_video_mode(not self.drone.zoom)\n\n def flight_data_handler(self, event, sender, data):\n \"\"\"Listener to flight data from the drone.\"\"\"\n text = str(data)\n if self.prev_flight_data != text:\n self.prev_flight_data = text\n\n def handle_flight_received(self, event, sender, data):\n \"\"\"Create a file in ~/Pictures/ to receive image from the drone\"\"\"\n path = '%s/Pictures/tello-%s.jpeg' % (\n os.getenv('HOME'),\n datetime.datetime.now().strftime(self.date_fmt))\n with open(path, 'wb') as out_file:\n out_file.write(data)\n print('Saved photo to %s' % path)\n","repo_name":"zhengyinloong/MyTello","sub_path":"tello2/myScripts/TelloCV_ball_people.py","file_name":"TelloCV_ball_people.py","file_ext":"py","file_size_in_byte":9834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"423713952","text":"album_1 = {\"Thriller\", \"AC/DC\", \"BackinBlack\"}\nalbum_2 = {\"DarkSide of Moon\", \"AC/DC\", \"BackinBlack\"}\n\nprint(album_1&album_2)\n\nsinger = [\"MJ\", 60, \"Thriller\", \"Dance\"]\nprint(\"MJ\" in singer)\nsinger_set = set(singer)\nprint(singer_set)\n\nS={'A','B','C'}\n\nU={'A','Z','C'}\n\nprint(U.union(S))","repo_name":"srinidhi82/python-bootcamp","sub_path":"learnSets.py","file_name":"learnSets.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32163629198","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport sympy as sym\nh=0.0001\nL = (lambda x: 0.5*x*(x-1), lambda x: -(x-1)*x, lambda x: 0.5*x(x+1))\nprint(L[0](-1))\nprint([])\n\ndef multiplicador(funcion_1, funcion_2):\n def funcion(x,y):\n return funcion_1(x,y)*funcion_2(x,y)\n return funcion\n \n \n\"\"\" def polinomio(lista_valores):\n n=len(lista_valores)\n polinomios_base = [1]*n\n for i in range(n):\n lista_i = []\n for j in range(n):\n if i != j:\n lista_i.append(lista_valores[j])\n lista_monomios = []\n for j in range(n-1):\n lista_monomios.append(lambda x: (x-lista_i[j]))\n for j in range(n-1):\n def polinomio_base_j(x,y):\n lista_monomios(x,y)\n polinomios_base[i]= lambda x: (polinomios_base[i])*(lista_monomios[j])\n return polinomios_base\n\npolinomio_1 = polinomio((-1,0,0))\nprint(polinomio_1[0](-1)) \"\"\"\n\n\ndef Lagrange(x,X,i):\n L = 1.\n for j in range(X.shape[0]):\n if i != j:\n L*=(x-X[j])/(X[i]-X[j])\n return L\n\ndef Interpolate(x,X,Y):\n \n Poly = 0.\n for i in range(X.shape[0]):\n Poly += Lagrange(x,X,i)*Y[i]\n return Poly\n \nX=np.array([-2,-1,0,1])\nY=np.array([0.5,10,5,8])\nx0=np.linspace(-2,1,10)\ny0=Interpolate(x0,X,Y)\nplt.scatter(X,Y)\nplt.scatter(x0,y0)\n#plt.show()\n\n\nx=sym.Symbol('x', real=True)\nf=Interpolate(x,X,Y)\nf=sym.simplify(f)\nprint(f)\n\n\n \n\ndef funcion(x):\n return (3.75*x**3)+(4*x**2)-(4.75*x)+5\n\ndef index_xn_cercano(xn,X):\n index=0\n for i in range(X.shape[0]):\n df = xn-x[i]\n if df<0:\n index=i\n break\n return index\n\ndef f_xn_cercano(xn,X,Y):\n index = index_xn_cercano(xn,X)\n return Y[index]\n\ndef derivada_central_discreta(x,X,Y,h):\n index_x_X=index_xn_cercano(x,X)\n xf=X[index_x_X+1]\n xi=X[index_x_X-1]\n h=xf-xi\n derivada_x = (Y[index_x_X+1]-Y[index_x_X-1])/(2*h)\n return derivada_x\n\ndef derivada_central(funcion, x, h):\n derivada_x = ((funcion(x+h)-funcion(x-h))/(2*h))\n return derivada_x\n\ndef GetNewtonMethod(f,df,xn,itmax=100000,precision=1e-5):\n error = 1.\n it=0\n \n while error > precision and it precision and it= n:\r\n ret = True\r\n break\r\n if n > len(img_urls) == c:\r\n ret = True\r\n return ret\r\n\r\n def process(self, data):\r\n # detect whether one picture downloaded at least\r\n # 只有图片队列还有值的时候才有必要判断本条数据的图片是否已经抓完\r\n img_urls = [url for url in re.split('#+', data['car_images']) if url]\r\n if self.rdb3.exists('image:queue'):\r\n if data.get('car_images') or data.get('car_img_thumb'):\r\n # 下载的图片少于4张\r\n if not self.atlstNImagesCrawled(img_urls, 4):\r\n self.logger.debug('%s still in image crawling, ignore it.' % data['url'])\r\n if int(time.time()*1000) - data['updated'] >= 1000*3600*24*3:\r\n self.logger.debug('%s picture crawling expired!' % data['url'])\r\n data['car_images'] = ''; data['car_img_thumb'] = ''\r\n else:\r\n self.logger.debug('%s still in image crawling, ignore it.' % data['url'])\r\n data['updated'] = int(time.time()*1000)\r\n self.sendMyself.send(data)\r\n return\r\n else:\r\n self.logger.debug('%s has picture . nice ~' % data['url'])\r\n else:\r\n self.logger.debug('%s has no image. ' % data['url'])\r\n else:\r\n self.logger.debug(\"Queue(image:queue) no exists, url: %s.\" % data['url'])\r\n\r\n # 临时增补\r\n data['car_img_server'] = 'AUTO'\r\n #real_img_count = len([img for img in img_urls if self.mdb.exists(md5(url).hexdigest().upper())])\r\n real_img_count = len(img_urls)\r\n data['integrity'] = get_integrity(data, real_img_count)\r\n\r\n return data\r\n","repo_name":"hw20686832/worker_queue","sub_path":"worker/process990.py","file_name":"process990.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10010039957","text":"import os\nimport configargparse\n\n\nclass ConfigParser(configargparse.ArgParser):\n def __init__(self):\n super().__init__(default_config_files=[\n os.path.join(os.path.dirname(__file__), 'default_config.yml')\n ],\n conflict_handler='resolve')\n\n # yapf:disable\n # Default arguments\n self.add(\n '--name', type=str,\n help='Name of the config for the offline reconsturction system.')\n self.add(\n '--device', type=str,\n help='Device to run the system.')\n\n input_parser = self.add_argument_group('input')\n input_parser.add(\n '--path_dataset', type=str,\n help='Path to the dataset folder. It should contain a folder with pcd and a folder with sensor pose.')\n\n integration_parser = self.add_argument_group('integration')\n integration_parser.add(\n '--voxel_size', type=float,\n help='Voxel size in meter for volumetric integration.')\n integration_parser.add(\n '--block_resolution', type=int,\n help='Voxel block resolution to construction resolution^3 local blocks')\n integration_parser.add(\n '--sdf_trunc_multiplier', type=float,\n help='Truncation distance for signed distance.')\n integration_parser.add(\n '--block_count', type=int,\n help='Pre-allocated voxel block count for volumetric integration.')\n integration_parser.add(\n '--step_size', type=int,\n help='Ray marching step size along the ray.')\n integration_parser.add(\n '--tangential_step_size', type=int,\n help='Ray marching tangential plane step size.')\n\n def get_config(self):\n config = self.parse_args()\n return config\n\n\nif __name__ == '__main__':\n # Priority: command line > custom config file > default config file\n parser = ConfigParser()\n parser.add(\n '--config',\n is_config_file=True,\n help='YAML config file path. Please refer to default_config.yml as a '\n 'reference. It overrides the default config file, but will be '\n 'overridden by other command line inputs.')\n config = parser.get_config()\n print(config)\n","repo_name":"xyaoab/RealityModelingPCD","sub_path":"scripts/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33721362467","text":"import urllib\nimport json\nimport requests\nimport os\nimport db_orphaned_spaces\nfrom jira import JIRA\nfrom dotenv import load_dotenv\nproject_folder = os.path.expanduser('/home/project_archive') #change as necessary\nload_dotenv(os.path.join(project_folder, '.env'))\n\norphaned_spaces = db_orphaned_spaces.confluence_spaces() #get json from SQL query\n#print inactive_projects\nHEADERS = {\n 'project': {'key': 'TOOL'},\n 'issuetype': {'name': 'issuetype'},\n 'reporter': {'name': 'user_name'},\n 'assignee': {'name': 'user_name'}\n }\njira = JIRA(basic_auth=(os.environ.get(\"JIRA_LOGIN\"), os.environ.get(\"JIRA_PASS\")), options={'server': os.environ.get(\"JIRA_SERVER\")})\nif orphaned_spaces: #json is not empty\n scope_of_projects = ''\n for spaces in inactive_projects:\n# I have two extra loops, because I didn't find a way to convert json from sql in right format\n for i in spaces:\n for a in i:\n summary = a['spacename'] + ' ' + 'Space Archive'\n search_string = \"summary ~\\\"{}\\\" and statuscategory!=done \".format(summary)\n issues = jira.search_issues(search_string, maxResults=25)\n if issues: #if issue already exist on jira server - ignore creation.\n break\n else:\n\n url_spacename = urllib.quote_plus( a['spacename'])\n url = 'https://confluence_url.com/confluence/display' + '/' + a['spacekey'] +'/' + url_spacename\n issue_dict = HEADERS\n issue_dict['summary'] = a['spacename'] + ' ' + 'Space Archive'\n issue_dict['description'] = 'Please, approve space archive' + ' ' + a['spacename'] + ' ' + url\n new_issue = jira.create_issue(fields=issue_dict) # create new jira issue with predifined variables\n scope_of_projects += a['spacename'] + ' - ' + 'https://jira_url.com/jira/browse/' + new_issue.key + '\\n' #generate payload to Slack\n print (new_issue.key)\n if scope_of_projects: #if string is not empty - send notification to slack. \n payload = {'text': \"Orphaned Confleunce Space(s) without activity for 180 days: \\n {} \".format(scope_of_projects) }\n r = requests.post(\"https://hooks.slack.com/services/channel/incomming/webhook_here\", data=json.dumps(payload))\n","repo_name":"CyberObiOne/python","sub_path":"project_archive/confluence/orphaned_confluence_slack_jira_notifications.py","file_name":"orphaned_confluence_slack_jira_notifications.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"14496774442","text":"numbs=[2,5,6,9,12,15,21,27]\n\nwhile True:\n ch=input('Please guess a number or type q to quit')\n if ch == 'q':\n break\n try:\n ch=int(ch)\n except ValueError:\n print('Please type a number')\n if ch in numbs:\n print('you have guessed right')\n \n else:\n print('You guessed wrong')\n \n\n\n","repo_name":"Cherub-Mike/container","sub_path":"2ndguess.py","file_name":"2ndguess.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31943511970","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import connections\nfrom django.db import transaction\n\nfrom django.core.management.base import BaseCommand\nfrom oms.views import *\nfrom oms.const import *\nimport logging\nimport datetime\nfrom django.db.models import Q\n\nfrom django.http import HttpRequest\nfrom oms.controllers.order_controller import *\nfrom oms.models.post_models import Prescription\nfrom oms.models.product_models import PgProduct\n\nfrom tracking.models import ai_log_control\n\n\nclass Command(BaseCommand):\n AI_CODE = 'AI_80919_90528'\n # 记录LOG 的开关\n write_log = True\n\n def handle(self, *args, **options):\n logging.critical('start generate lab orders ....')\n\n '''\n 81001:增加对订单中包含特别说明或包含测试用的COUPON_CODE的过滤\n 81008:修复订单中包含特别说明,影响其他单光订单下单的BUG\n '''\n\n index = 0\n\n ailog = ai_log_control() # AI操作日志\n\n try:\n # Pg Order List:\n\n pgos = PgOrder.objects.filter(is_enabled=True,\n is_inlab=False,\n status='processing').filter(~Q(status_control='APPROVED'),\n ~Q(status_control='REVIEWED'))\n\n logging.critical(pgos.query)\n\n msg = '(%s):%s: %s'\n\n '''\n AI_CODE:AI_80919\n \n 检索所有状态正常,Not Inlab,Status=processing的订单\n 检索:\n 1.该订单下的所有Pg Order Item中的镜片为单光库存片\n 2.所有验光单中散光度<=200\n 3.ADD为0\n 4.PRISM为0\n \n 理论上讲,如果是单光,上述的验光单数据一定为0,但仍需验证\n '''\n '''\n 2019.07.27 --by gaoyu\n 每个渐进订单,重新调用接口查询,pupils_position\n '''\n approved_pgos = []\n\n for pgo in pgos:\n logging.critical(msg % (str(index), pgo.order_number, pgo.status))\n index += 1\n is_can_auto = True\n\n # 筛选生成不足一小时的订单\n now_time = datetime.datetime.now()\n pg_time = pgo.create_at\n dt = pg_time.replace(tzinfo=None)\n dt = dt + datetime.timedelta(hours=+8)\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单-时间筛选1', str(now_time), str(pg_time),\n str(dt),\n str((now_time - dt).seconds), '', 'YES', ' 时间')\n if (now_time - dt).seconds < 3600:\n logging.critical('订单创建不足一小时 不开始自动下单')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单-时间筛选2', str(now_time), str(pg_time),\n str(dt), str((now_time - dt).seconds), '', 'YES', ' 时间')\n is_can_auto = False\n continue\n\n if pgo.is_inst:\n logging.critical('包含特别说明 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', 'is_inst', str(pgo.is_inst), '', '',\n '', 'YES', '包含特别说明 无法自动生成')\n\n is_can_auto = False\n continue\n\n if pgo.coupon_code == 'PG-INTERNAL':\n logging.critical('内部测试订单 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', 'coupon_code', pgo.coupon_code, '',\n '',\n '', 'YES', '内部测试订单 无法自动生成')\n\n is_can_auto = False\n continue\n\n if pgo.coupon_code:\n if bool(re.search('REPLACE', pgo.coupon_code, re.IGNORECASE)):\n logging.critical('替换订单 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', 'coupon_code', pgo.coupon_code,\n '',\n '', '', 'YES', '替换订单 无法自动生成')\n\n is_can_auto = False\n continue\n # 包含instruction不过\n if not pgo.instruction == '' and not pgo.instruction == 'null' and pgo.instruction is not None:\n is_can_auto = False\n logging.critical('PGO包含特别说明 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', 'instruction', pgo.instruction, '',\n '',\n '', 'YES', 'PGO包含特别说明 无法自动生成')\n is_can_auto = False\n continue\n if is_can_auto:\n for pgi in pgo.get_items:\n try:\n lens = PgProduct.objects.get(sku=pgi.lens_sku)\n if bool(pgi.is_has_imgs):\n logging.critical('包含图片 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', str(pgi.id), pgi.order_number, '自动下单', 'is_has_imgs',\n str(pgi.is_has_imgs), '', '', '', 'YES', '包含图片 无法自动生成')\n\n is_can_auto = False\n break\n if not pgi.instruction == '' and not pgi.instruction == 'null' and pgi.instruction is not None:\n logging.critical('行数据包含特别说明 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', str(pgi.id), pgi.order_number, '自动下单', 'instruction',\n str(pgi.instruction), '', '', '', 'YES', '行数据包含特别说明 无法自动生成')\n\n is_can_auto = False\n break\n\n if lens.is_rx_lab:\n logging.critical('车房片转入车房片判断方法')\n # 转入车房片判断并生成LBO的分支\n self.__rx_orders_handel(pgo)\n is_can_auto = False\n break\n # 库存单单光验证\n is_can_auto = self.__single_vision(pgi)\n\n except Exception as e:\n logging.critical(str(e))\n is_can_auto = False\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', '', '', '', '-1', str(e),\n 'NO', '164异常报错')\n logging.critical('generate lab orders completed ....')\n break\n\n if is_can_auto:\n self.__generate_lab_orders_address_verify(pgo, '')\n else:\n logging.critical('验证规则未通过或进入车房处理')\n except Exception as e:\n logging.critical(str(e))\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', '', '', '', '-1', str(e), 'NO', '177异常报错')\n logging.critical('generate lab orders completed ....')\n\n # 生成订单并校验地址\n def __generate_lab_orders_address_verify(self, pgo, comments):\n\n ailog = ai_log_control() # AI操作日志\n\n pgo.status_control = 'AI'\n pgo.comments = comments\n pgo.save()\n # 写入LOG\n if self.write_log:\n ailog.add('pgorderitem', str(pgo.id), pgo.order_number, '自动下单-生成工厂订单', 'comments',\n comments, '', '', '', 'YES', '写入备注')\n\n try:\n for pgi in pgo.get_items:\n pgi.comments_inner = comments\n pgi.save()\n # 写入LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-生成工厂订单', 'comments',\n comments, '', '', '', 'YES', '写入备注')\n\n except Exception as e:\n logging.critical(str(e))\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', '', '', '', '-1', str(e), 'NO', '205异常报错')\n\n poc = PgOrderController()\n res = poc.generate_lab_orders(pgo.order_number)\n # 写入LOG\n if self.write_log:\n ailog.add('pgorderitem', str(pgo.id), pgo.order_number, '自动下单-生成工厂订单', 'res',\n res, '', '', '', 'YES', '生成工厂订单')\n\n logging.critical(res)\n\n # 地址校验\n ods = []\n ods.append(pgo.order_number)\n poc = PgOrderController()\n res = poc.pgorder_address_verified(ods)\n logging.critical(res)\n\n # 库存单单光验证\n def __single_vision(self, pgi):\n\n ailog = ai_log_control() # AI操作日志\n\n pre = pgi.get_prescritpion\n # pre = Prescription()\n if abs(float(pre.rcyl)) > 2.00 or abs(float(pre.lcyl)) > 2.00:\n logging.critical('散光度高于200 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'cyl',\n 'od_%s' % str(pre.rcyl), 'os_%s' % str(pre.lcyl), '', '', 'YES', '散光度高于200 不过')\n return False\n\n if float(pre.radd) > 0 or float(pre.ladd) > 0:\n logging.critical('验光单包含ADD 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'add',\n 'od_%s' % str(pre.radd), 'os_%s' % str(pre.ladd), '', '', 'YES', '验光单包含ADD 不过')\n\n return False\n\n if float(pre.rpri) > 0 or float(pre.lpri) > 0:\n logging.critical('验光单包含PRISM 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'PRISM',\n 'od_%s' % str(pre.rpri), 'os_%s' % str(pre.lpri), '', '', 'YES', '验光单包含PRISM 不过')\n\n return False\n\n if float(pre.rpri1) > 0 or float(pre.lpri1) > 0:\n logging.critical('验光单包含PRISM1 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'PRISM1',\n 'od_%s' % str(pre.rpri1), 'os_%s' % str(pre.rpri1), '', '', 'YES', '验光单包含PRISM1 不过')\n\n return False\n\n if pre.used_for is not None and not pre.used_for == '':\n logging.critical('验光单包含 Used For 无法自动生成')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'Used For',\n pre.used_for, '', '', '', 'YES', '验光单包含Used For 不过')\n\n return False\n\n return True\n\n # 狭义渐进单处理方法,不包括平顶双光\n def __progressive_handle(self, pgi):\n\n ailog = ai_log_control() # AI操作日志\n\n seg_height = 0 # 加工瞳高\n standard_seg_hight = 0.5 * float(pgi.lens_height) + 3\n # 有鼻托\n if int(pgi.is_has_nose_pad) == 1:\n # 桥长大于20\n if float(pgi.bridge) > 20:\n # 框高小于等于30\n if float(pgi.lens_height) <= 30:\n seg_height = standard_seg_hight\n else:\n seg_height = 0.5 * float(pgi.lens_height) + 4\n # 桥长小于等于20\n else:\n seg_height = standard_seg_hight\n # 无鼻托\n else:\n # 桥大于20\n if float(pgi.bridge) > 20:\n seg_height = 0.5 * float(pgi.lens_height) + 5\n # 桥小于等于20\n else:\n # 框高小于等于37\n if float(pgi.lens_height) <= 37:\n seg_height = standard_seg_hight\n else:\n if float(pgi.lens_height) <= 43:\n seg_height = 0.5 * float(pgi.lens_height) + 4\n else:\n seg_height = 0.5 * float(pgi.lens_height) + 5\n # 因为直接取PGI的pupils_position为0,所以重新查询一遍\n pgi_positions = PgOrderItem.objects.filter(order_number=pgi.order_number).values('pupils_position')\n pgi_position = pgi_positions[0]\n v_pgi_position = pgi_position['pupils_position']\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'lab_seg_height',\n str(seg_height), '用户选:' + str(pgi.pupils_position), '二次查询结果=' + str(v_pgi_position), '', 'YES',\n '计算狭义渐进瞳高,不写入PGI')\n\n # 根据用户习惯修正瞳高\n diff_lab_seg_hight_and_std = seg_height - standard_seg_hight # 加工瞳高和标准瞳高差值\n # 用户选3\n if v_pgi_position == 3:\n seg_height = seg_height + 1\n diff_lab_seg_hight_and_std = seg_height - standard_seg_hight\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'lab_seg_height',\n '用户选:' + str(v_pgi_position), str(seg_height), '', '', 'YES', '根据用户选择调整狭义渐进瞳高,计算结果')\n # 用户选1\n if v_pgi_position == 1:\n # 不是标准瞳高时修改,否则不修改\n if not diff_lab_seg_hight_and_std == 0:\n seg_height = seg_height - 1\n diff_lab_seg_hight_and_std = seg_height - standard_seg_hight\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'lab_seg_height',\n '用户选:' + str(v_pgi_position), str(seg_height), '', '', 'YES', '根据用户选择调整狭义渐进瞳高,计算结果')\n # 生成加工要求\n ass_str = 'STD'\n if not diff_lab_seg_hight_and_std == 0:\n ass_str = 'STD+' + str(diff_lab_seg_hight_and_std)\n # 加工瞳高写入pgorderitem,并写入备注\n pgi.lab_seg_height = seg_height\n pgi.assemble_height = ass_str\n pgi.comments += '加工瞳高%smm;' % seg_height\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'lab_seg_height',\n '用户选:' + str(v_pgi_position), str(seg_height), '', '', 'YES', '根据用户选择调整狭义渐进瞳高,写入PGI')\n # 通道选择,渐进单\n if pgi.lens_height == 30: # 框高等于 30\n pgi.channel = 'FH15'\n pgi.comments += '车房加工采用短通道(7mm);'\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'lens_height',\n pgi.lens_height, 'FH15', '加备注:车房加工采用短通道(7mm)', '', 'YES', '通道选择,渐进单')\n\n # 平顶双光计算子镜高度方法\n def __flat_double_light_handle(self, pgi):\n ailog = ai_log_control() # AI操作日志\n sub_mirrors_height = 0 # 子镜高度\n # 有鼻托\n if int(pgi.is_has_nose_pad) == 1:\n # 桥长大于20\n if float(pgi.bridge) > 20:\n if float(pgi.lens_height) <= 30: # 框高小于等于30\n sub_mirrors_height = 0.5 * float(pgi.lens_height) - 3\n else:\n sub_mirrors_height = 0.5 * float(pgi.lens_height) - 2\n else:\n sub_mirrors_height = 0.5 * float(pgi.lens_height) - 3\n # 无鼻托\n else:\n # 桥长大于20\n if float(pgi.bridge) > 20:\n sub_mirrors_height = 0.5 * float(pgi.lens_height) - 1\n else:\n if float(pgi.lens_height) <= 37: # 框高小于等于37\n sub_mirrors_height = 0.5 * float(pgi.lens_height) - 3\n else:\n sub_mirrors_height = 0.5 * float(pgi.lens_height) - 2\n # 超出范围按最大值算\n if sub_mirrors_height < 13:\n sub_mirrors_height = 13\n if sub_mirrors_height > 19:\n sub_mirrors_height = 19\n # 子镜高度写入PGI,并写入备注\n pgi.sub_mirrors_height = sub_mirrors_height\n pgi.comments += '子镜高度%smm;' % sub_mirrors_height\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'sub_mirrors_height',\n str(sub_mirrors_height), '', '', '', 'YES', '计算子镜高度,写入PGI')\n\n # 带有车房单的订单验证处理\n def __rx_orders_handel(self, pgo):\n logging.critical('开始 车房单审单')\n ailog = ai_log_control()\n\n is_can_auto = True\n progressive_num = 0 # 渐进单数量\n comments = '' # 备注\n # 判断有无历史单查找历史单\n order_history = PgOrder.objects.filter(customer_id=pgo.customer_id, id__lt=pgo.id).only(\n 'order_number').order_by('-id')[:5]\n if len(order_history) > 0: # 有历史单数据\n logging.critical('有历史单,不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', 'order_history',\n order_history[0].order_number, '', '', '', 'YES', '有历史单,不过')\n\n return False\n\n # 重新遍历这个pgo,来做判断\n for pgi in pgo.get_items:\n try:\n lens = PgProduct.objects.get(sku=pgi.lens_sku)\n\n # 如果不是车房单\n if not lens.is_rx_lab:\n is_can_auto = self.__single_vision(pgi) # 单光验证\n if not is_can_auto: # 如果有库存单单光验证未通过,直接跳出\n break\n # 是车房单\n else:\n # 只有渐进片更新PGI的pupils_position和pupils_position_name\n self.__update_pgi_pp(pgi)\n\n # pgi = PgOrderItem()\n # 如果是渐进,记录数量\n if float(pgi.od_add) > 0 or float(pgi.os_add) > 0:\n progressive_num += 1\n iteam_id_str = ''\n iteam_id_str += ',%s' % pgi.item_id\n # 一单中渐进数量大于1\n if progressive_num > 1:\n logging.critical('渐进单数量大于1 不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', 'item_id',\n iteam_id_str, '', '', '', 'YES', '渐进单数量大于1 不过')\n is_can_auto = False\n break\n # 车房单光和渐进都做以下验证\n # 偏光镜\n if bool(re.search('polarized', pgi.lens_name, re.IGNORECASE)): # 平顶双光,计算子镜高度\n logging.critical('偏光镜不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'lens_name',\n pgi.lens_name, '', '', '', 'YES', '偏光镜不过')\n\n is_can_auto = False\n break\n # 有棱镜不过\n if float(pgi.od_prism) > 0 or float(pgi.os_prism) > 0:\n logging.critical('有棱镜不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'prism',\n 'od_%s' % pgi.od_prism, 'os_%s' % pgi.os_prism, '', '', 'YES', '有棱镜不过')\n\n is_can_auto = False\n break\n if float(pgi.od_prism1) > 0 or float(pgi.os_prism1) > 0:\n logging.critical('有棱镜不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'prism1',\n 'od_%s' % pgi.od_prism1, 'os_%s' % pgi.os_prism1, '', '', 'YES', '有棱镜1不过')\n is_can_auto = False\n break\n # 单一瞳距\n if pgi.is_singgle_pd == '1':\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单',\n 'what_pd=' + pgi.is_singgle_pd,\n 'pd_%s' % pgi.pd, '', '', '', 'YES', '成人镜框,瞳距小于等于45或大于75 不过')\n # 儿童\n if pgi.frame[0] == '3':\n if float(pgi.pd) <= 40:\n logging.critical('儿童镜框瞳距小于等于40 不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'pd',\n 'pd_%s' % pgi.pd, '', '', '', 'YES', '儿童镜框瞳距小于等于40 不过')\n\n is_can_auto = False\n break\n # 成年人\n else:\n if float(pgi.pd) <= 45 or float(pgi.pd) > 75:\n logging.critical('成人镜框,瞳距小于等于45或大于75 不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'pd',\n 'pd_%s' % pgi.pd, '', '', '', 'YES', '成人镜框,瞳距小于等于45或大于75 不过')\n\n is_can_auto = False\n break\n # 双瞳距\n else:\n if abs(abs(pgi.od_pd) - abs(pgi.os_pd)) >= 5:\n logging.critical('双瞳距,左右瞳距差大于等于5 不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'pd',\n 'od_pd_%s' % pgi.od_pd, 'os_pd_%s' % pgi.os_pd, '', '', 'YES',\n '双瞳距,左右瞳距差大于等于5 不过')\n is_can_auto = False\n break\n # 左右ADD不同\n if not pgi.os_add == pgi.od_add:\n logging.critical('左右ADD不同 不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'add',\n 'od_add_%s' % pgi.od_add, 'os_add_%s' % pgi.os_add, '', '', 'YES', '左右ADD不同 不过')\n is_can_auto = False\n break\n # 度数差大于500\n if abs(float(pgi.os_sph) - float(pgi.od_sph)) >= 5.0:\n logging.critical('两眼度数差大于等于500 不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'sph',\n 'od_add_%s' % pgi.od_sph, 'os_add_%s' % pgi.os_sph, '', '', 'YES',\n '两眼度数差大于等于500 不过')\n is_can_auto = False\n break\n # 散光差大于500\n if abs(float(pgi.os_cyl) - float(pgi.od_cyl)) >= 5.0:\n logging.critical('两眼散光差大于等于500 不过')\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单', 'cyl',\n 'od_add_%s' % pgi.od_cyl, 'os_add_%s' % pgi.os_cyl, '', '', 'YES',\n '两眼散光差大于等于500 不过')\n is_can_auto = False\n break\n except Exception as e:\n logging.critical(str(e))\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', '', '', '', '-1', str(e), 'NO',\n '551异常报错')\n # 上面验证都通过才做以下处理\n if is_can_auto:\n # 重新遍历这个pgo,来做处理,不区分渐进与单光\n for pgi in pgo.get_items:\n try:\n # 做处理,不区分渐进与单光\n if abs(float(pgi.os_sph) - float(pgi.od_sph)) >= 3.0:\n logging.critical('左右��度数差大于等于300 添加备注及特殊说明')\n pgi.special_handling = '注意平衡配重'\n pgi.comments += '注意平衡配重;'\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'sph',\n 'od_add_%s' % pgi.od_sph, 'os_add_%s' % pgi.os_sph, '', '', 'YES',\n '左右眼度数差大于等于300 添加备注及特殊说明')\n if abs(float(pgi.os_cyl) - float(pgi.od_cyl)) >= 3.0:\n logging.critical('左右眼散光差大于等于300 添加备注及特殊说明')\n pgi.special_handling = '注意平衡配重'\n pgi.comments += '注意平衡配重;'\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'cyl',\n 'od_add_%s' % pgi.od_cyl, 'os_add_%s' % pgi.os_cyl, '', '', 'YES',\n '左右眼散光差大于等于300 添加备注及特殊说明')\n if pgi.tint_sku[:2] == 'TS':\n logging.critical('实色染色85% 添加备注及特殊说明')\n pgi.special_handling = pgi.special_handling + '实色染色85%;'\n pgi.comments += '实色染色85%;'\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'sku',\n pgi.tint_sku, '', '', '', 'YES',\n '实色染色85% 添加备注及特殊说明')\n if pgi.tint_sku[:2] == 'TG':\n logging.critical('渐变染色70% 添加备注及特殊说明')\n pgi.special_handling = pgi.special_handling + '渐变染色70%;'\n pgi.comments += '渐变染色70%;'\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'sku',\n pgi.tint_sku, '', '', '', 'YES',\n '渐变染色70% 添加备注及特殊说明')\n # 设计加备注\n if not pgi.pal_design_name == '' and pgi.pal_design_name is not None:\n design_comments = ''\n if pgi.pal_design_name == 'No Line Computer Progressive':\n design_comments = '车房采用 办公设计1.3米 渐进设计;'\n elif pgi.pal_design_name == 'No Line Office Progressive':\n design_comments = '车房采用 办公设计4米 渐进设计;'\n elif pgi.pal_design_name == 'Easy Adapt Progressive':\n design_comments = '车房采用 IOT Alpha S35 渐进设计;'\n elif pgi.pal_design_name == 'Drive Progressive':\n design_comments = '车房采用 IOT Drive Progressive 渐进设计;'\n elif pgi.pal_design_name == 'Sport Progressive':\n design_comments = '车房采用 IOT Sport Progressive 渐进设计;'\n elif pgi.pal_design_name == 'Premium Progressive':\n design_comments = '车房采用 IOT Alpha H45 渐进设计;'\n elif pgi.pal_design_name == 'Mobile Enhanced Progressive':\n design_comments = '车房采用 IOT Alpha Mobile 渐进设计;'\n elif pgi.pal_design_name == 'Near Enhanced Progressive':\n design_comments = '车房采用 IOT Alpha H25 渐进设计;'\n else:\n design_comments = ''\n pgi.comments += design_comments\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'sku',\n pgi.pal_design_sku, pgi.pal_design_name, design_comments, '', 'YES',\n '设计加备注')\n # 做处理,根据框型瞳高修正,区分广义渐进与单光\n if float(pgi.od_add) > 0 or float(pgi.os_add) > 0: # 广义渐进\n if bool(re.search('Lined Bifocal', pgi.lens_name, re.IGNORECASE)):\n self.__flat_double_light_handle(pgi) # 平顶双光处理\n else: # 狭义渐进,计算瞳高\n self.__progressive_handle(pgi) # 狭义渐进处理\n else: # 单光给出瞳高并添加备注\n pgi.lab_seg_height = 0.5 * float(pgi.lens_height) + 4\n pgi.assemble_height = 'STD+1.0'\n pgi.comments += '加工瞳高%smm;' % str(0.5 * float(pgi.lens_height) + 4)\n pgi.save()\n # 记录LOG\n if self.write_log:\n ailog.add('pgorderitem', pgi.order_number, str(pgi.item_id), '自动下单-处理', 'assemble_height',\n str(pgi.lab_seg_height), '', '', '', 'YES', '非渐进给出瞳高')\n\n except Exception as e:\n logging.critical(str(e))\n if self.write_log:\n ailog.add('pgorder', str(pgo.id), pgo.order_number, '自动下单', '', '', '', '-1', str(e), 'NO',\n '646异常报错')\n # 生成工厂订单\n if is_can_auto:\n self.__generate_lab_orders_address_verify(pgo, comments)\n else:\n logging.critical('车房单验证规则未通过')\n\n # 更新PGI的pupils_position和pupils_position_name\n def __update_pgi_pp(self, pgi):\n ailog = ai_log_control()\n dict_poi = {\n \"order_entity\": pgi.pg_order_entity.base_entity,\n \"profile_entity\": pgi.profile_id,\n \"order_item_entity\": pgi.item_id,\n \"profile_prescription_entity\": pgi.profile_prescription_id,\n \"prescription_entity\": pgi.prescription_id\n }\n poc = PgOrderController()\n rb = poc.get_order_image(dict_poi)\n try:\n if rb.code == 0:\n body = rb.body\n pgi.pupils_position = body['pupils_position']\n pgi.pupils_position_name = body['pupils_position_name']\n pgi.save()\n\n # entity_pgis.order_image_urls = json.dumps(body['image_urls'])\n except Exception as e:\n logging.exception('exception: %s' % str(e))\n if self.write_log:\n ailog.add('pgorder', str(pgi.id), pgi.order_number, '自动下单', '', '', '', '-1', str(e), 'NO',\n '677异常报错')\n","repo_name":"qiaozhizt/OMS","sub_path":"oms/management/commands/generate_lab_order_cron_ai_80919.py","file_name":"generate_lab_order_cron_ai_80919.py","file_ext":"py","file_size_in_byte":35377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73178168165","text":"import time\n\nlarge1 = ['nemo' for i in range(100000)]\nlarge2 = ['nemo' for i in range(100000)]\n\ndef find_nemo(array1, array2):\n\n t0 = time.time() #O(1)\n for i in range(0,len(array1)): #O(m)\n if array1[i] == 'nemo': #m*O(1)\n print(\"Found Nemo!!\") #k1*O(1) where k1 <= m because this statement will be executed only if the if statement returns True, which can be k1(<=m) times\n t1 = time.time() #O(1)\n print(f'The search took {t1-t0} seconds.') #O(1)\n\n t0 = time.time() #O(1)\n for i in range(0, len(array2)): #O(n)\n if array2[i] == 'nemo': #n*O(1)\n print(\"Found Nemo!!\") #k2*O(1) where k2 <= m because this statement will be executed only if the if statement returns True, which can be k2(<=m) times\n t1 = time.time() #O(1)\n print(f'The search took {t1 - t0} seconds.') #O(1)\n\nfind_nemo(large1, large2)\n\n# O(m + n)","repo_name":"Buzonxxxx/python-learning","sub_path":"ds_algorithm/bigO/O(m+n).py","file_name":"O(m+n).py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4022799538","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.manifold import TSNE\n\n\ndef TSNE_scatterplot(model, word, neg_word, save=False):\n close_words = np.array(model.wv.most_similar([word]))\n neg_words = np.array(model.wv.most_similar(negative=[neg_word]))\n\n arrays = np.vstack((model.wv[[word]], model.wv[close_words[:, 0]], model.wv[neg_words[:, 0]]))\n word_labels = [word] + list(close_words[:, 0]) + list(neg_words[:, 0])\n\n color_list = ['blue'] * len(close_words) + ['green'] * len(neg_words)\n\n Y = TSNE(n_components=2, random_state=0, perplexity=15).fit_transform(arrays)\n\n x = Y[1:, 0]\n y = Y[1:, 1]\n plt.figure(figsize=(11, 4))\n plt.scatter(Y[0, 0], Y[0, 1], marker=\"*\", c='blue', s=120)\n plt.scatter(x, y, c=color_list)\n plt.grid()\n\n annotations = []\n\n for line in range(len(word_labels)):\n annotations.append(plt.text(Y[line, 0], Y[line, 1], word_labels[line].title()))\n\n if save:\n plt.savefig(f\"{str(model)}.png\", bbox_inches='tight')\n","repo_name":"jonatanvm/nlp-project","sub_path":"notebooks/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25730652905","text":"\nimport vtk\nimport numpy as np \nimport os\nimport pandas as pd\nimport argparse\nimport json\nimport utils\nfrom tqdm import tqdm\n\ndef main(args):\n surf_scales = []\n\n df = pd.read_csv(args.csv)\n\n pbar = tqdm(df.iterrows(), total=len(df))\n\n for idx, row in pbar:\n surf = utils.ReadSurf(row[args.surf_column])\n\n unit_surf, surf_mean, surf_scale = utils.ScaleSurf(surf)\n surf_scales.append(surf_scale)\n\n pbar.set_description('surf_scale={surf_scale}'.format(surf_scale=surf_scale))\n\n surf_scales = np.array(surf_scales)\n\n df['surf_scale'] = surf_scales\n\n min_scale = np.min(surf_scales)\n\n if args.out:\n df.to_csv(args.out, index=False)\n\n print(\"MinScale:\", min_scale)\n return min_scale\n\ndef get_argparse():\n parser = argparse.ArgumentParser(description='Computes the minimum magnitude/scaling factor for all shapes after centering each at 0.')\n parser.add_argument('--csv', type=str, help='CSV file with column surf', required=True)\n parser.add_argument('--surf_column', help='Surface column name', type=str, default=\"surf\")\n parser.add_argument('--out', type=str, default=None, help='Output json filename')\n return parser\n\nif __name__ == \"__main__\":\n \n parser = get_argparse()\n args = parser.parse_args()\n\n main(args)\n","repo_name":"DCBIA-OrthoLab/ShapeAXI","sub_path":"src/compute_min_scale.py","file_name":"compute_min_scale.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"29608500334","text":"# How many Thursdays were there between 1990 - 2000?\n\nfrom datetime import date\n\nstart_date = date(1990, 1, 1)\n# StartDate\nend_date = date(2000, 12, 31)\n# EndDate\ndays_middle = end_date - start_date\n\nprint(int(days_middle.days / 7 + 1))\n#Adding 1 for remainder value, if not properly divisible\n","repo_name":"jagannathsrs/gramenerTasks","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70132621606","text":"import logging\nlogger = logging.getLogger('athenataf')\nfrom athenataf.lib.functionality.test.ConfigurationTest import ConfigurationTest\n\nclass MultiVersion(ConfigurationTest):\n\t'''\n\tTest class for services test cases of configuration module.\n\t'''\n\n\tdef test_ath_11318_calea(self):\n\t\tself.take_s1_snapshot()\n\t\tservices_page = self.LeftPanel.go_to_services()\n\t\tservices_page.conifgure_calea_settings()\n\t\tself.take_s2_snapshot()\n\t\tservices_page.reset_calea_fields() \n\t\tself.take_s3_snapshot()\n\t\tself.assert_s1_s2_diff(0)\n\t\tself.assert_s1_s3_diff()\n\t\tself.clear()\n\t\t\n\tdef test_ath_11328_airgroup_fields_in_multiversion(self):\n\t\tservices_page = self.LeftPanel.go_to_services()\n\t\tservices_page.assert_airgroup_checkbox_disabled()\n\t\tservices_page.enable_airgroup()\n\t\tservices_page.assert_air_group_fields()\n\t\t\n\tdef test_ath_11327_analytics_and_location_engine(self):\n\t\tself.take_s1_snapshot()\n\t\tconf = self.config.config_vars\n\t\tservices_page = self.LeftPanel.go_to_services()\n\t\tservices_page.rtls_click()\n\t\tservices_page.click_analytics_location_engine_checkbox()\n\t\tservices_page.assert_analytics_and_location_engine_fields()\n\t\tservices_page.set_rtls_analytics_location_engine_fields(conf.service_server,conf.report_interval_location)\n\t\tservices_page.save_settings()\n\t\tself.take_s2_snapshot()\n\t\tservices_page.set_rtls_analytics_location_engine_fields(conf.empty,conf.report_interval_location)\n\t\tservices_page.save_settings()\n\t\tservices_page.click_analytics_location_engine_checkbox()\n\t\tself.take_s3_snapshot()\n\t\tself.assert_s1_s2_diff(0)\n\t\tself.assert_s1_s3_diff()\n\t\tself.clear()\n\t\n\tdef test_ath_11319_network_integration(self):\n\t\tself.take_s1_snapshot()\n\t\tservices_page = self.LeftPanel.go_to_services()\n\t\tservices_page.click_on_network_integration_accordion()\n\t\tservices_page.edit_network_integration()\n\t\tservices_page.assert_override_flag_button('False')\n\t\tself.take_s2_snapshot()\n\t\tservices_page.reset_network_integration_fields()\n\t\tself.take_s3_snapshot()\n\t\tself.assert_s1_s2_diff(0)\n\t\tself.assert_s1_s3_diff()\n\t\tself.clear()","repo_name":"cash2one/reautomation_handoff","sub_path":"athena_automation/athenataf/tests/configuration/services/multiversion/MultiVersion.py","file_name":"MultiVersion.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74895327843","text":"from time import sleep\nimport shutil\nimport logging\nfrom pathlib import Path\n\nfrom t_helpers import write_text_to_file, main_with_log, parse_results\n\nlogger = logging.getLogger(__name__)\n\n\ndef test_continuation():\n addn_options = [\"--v\", \"--detail-files\"]\n\n this_dir = Path(__file__).parent\n resources_path = this_dir / \"resources\"\n temp_path_A = this_dir / \"tempA\"\n temp_path_B = this_dir / \"tempB\"\n if temp_path_A.exists():\n shutil.rmtree(temp_path_A)\n if temp_path_B.exists():\n shutil.rmtree(temp_path_B)\n try:\n shutil.copytree(resources_path, temp_path_A)\n shutil.copytree(resources_path, temp_path_B)\n sleep(1)\n\n ###\n ### Test 'continuation mode' where we start from a previous calculation\n ###\n\n # Continuation mode will skip any folder for which the MD5 has already been\n # computed, including all subfolders. So to test the mode, we calculate a\n # first-pass and then modify it.\n\n main_with_log([\"--calculate\", str(temp_path_A), \"--new\"] + addn_options)\n main_with_log([\"--calculate\", str(temp_path_B), \"--new\"] + addn_options)\n test = main_with_log(\n [\"--compare\", str(temp_path_A / \"Folder_C\" / \"Folder_C2\"), str(temp_path_B / \"Folder_C\" / \"Folder_C2\")]\n + addn_options\n )\n assert \"No differences\" in test\n\n # Write a file into the temp_path and run continuation on only temp_path, which should\n # cause a delta between A and B. However, to verify that it actually ran as a continuation,\n # let's also introduce a change that should go unnoticed in continuation mode because that\n # folder is already scanned.\n continue_text = \"This file should be added by continuation.\"\n write_text_to_file(temp_path_A / \"Continuation_Folder_A\" / \"File_A.txt\", continue_text)\n write_text_to_file(\n temp_path_A / \"Folder_C\" / \"Ignored_file_A.txt\", \"This file should go unnoticed in continuation.\"\n )\n main_with_log([\"--calculate\", str(temp_path_A), \"--continue\"] + addn_options)\n\n # Calculate path B without continuation mode but also without the ignored file.\n write_text_to_file(temp_path_B / \"Continuation_Folder_A\" / \"File_A.txt\", continue_text)\n main_with_log([\"--calculate\", str(temp_path_B)] + addn_options)\n\n test = main_with_log([\"--compare\", str(temp_path_A), str(temp_path_B)] + addn_options)\n assert \"No differences\" in test\n\n # Finally, recompute A without continuation to make sure the 'unnoticed' file is now observed and breaks\n # the match between A and B.\n main_with_log([\"--calculate\", str(temp_path_A)] + addn_options)\n test = main_with_log([\"--compare\", str(temp_path_A), str(temp_path_B)] + addn_options)\n file_mismatches, missing_A, missing_B = parse_results(test, temp_path_A, temp_path_B)\n assert file_mismatches == [\"Folder_C\"]\n assert len(missing_A) == 0\n assert len(missing_B) == 0\n\n finally:\n shutil.rmtree(temp_path_A)\n shutil.rmtree(temp_path_B)\n\n\nif __name__ == \"__main__\":\n test_continuation()\n","repo_name":"WileEMan/tree-inventory","sub_path":"tests/test_continuation.py","file_name":"test_continuation.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9644834889","text":"# CS 582 - Search Engine Project\n# Author - Sanjay Ramachandran\n# email - sramac22@uic.edu\n# UIN - 671035289\n\nimport string\nfrom typing import Callable\nfrom nltk.stem.api import StemmerI\nfrom nltk.corpus import stopwords\n\n# globals\n#lets check how the results are when numbers are not removed in data and queries like courses,phone numbers,addresses\ntable = str.maketrans('', '', string.punctuation)# + \"0123456789\") \ntable2 = str.maketrans('\\\\/-', ' ')\n\nstopWords = set(stopwords.words('english'))\n\nclass PreProcessor:\n # tokenizes the text based on whitespaces, removes the punctuations and converts to lowercase\n # If a stemmer is passed, then stems the non stop-words as well\n def tokenize(self, file, target: list, stemmer: StemmerI=None):\n # stemmer is not gonna change within the loop so makes sense to do the check only once\n if stemmer is None:\n for line in file:\n # for stopwords - not anymore since we are using nltks stopwords\n line = line.translate(table2).strip()\n target.extend([word.lower() for word in line.translate(table).strip().split()\n if (len(word) > 1 and\n word.lower() not in stopWords)])\n else:\n for line in file:\n # map() might look cleaner\n # for query\n line = line.translate(table2).strip()\n target.extend([stemmer.stem(word.lower()) for word in line.translate(table).strip().split() \n if (word.lower() not in stopWords and \n stemmer.stem(word.lower()) not in stopWords and \n len(word) > 1)])\n\n # function that tokenizes and constructs the vocabulary\n def preprocess(self, files, source: list, aggregator: Callable[..., None], dataset=None, stemmer: StemmerI=None):\n for i, file in enumerate(files):\n url = ''\n with open(file, 'r', encoding='ascii', errors='ignore') as f:\n url = f.readline().strip()\n self.tokenize(f, source, stemmer)\n aggregator(url, source)\n # for topic modelling, we need docs as list of tokens\n if dataset != None:\n dataset.append(source.copy())\n source.clear()","repo_name":"sanjayr93/noogle","sub_path":"source code/PreProcessor.py","file_name":"PreProcessor.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39189669704","text":"# -*- coding:utf-8 -*-\nimport json\n\nimport requests\n\nimport re\n\n\ndef handler(event, context):\n \"\"\"\n 基于华为云的bilibili反向代理\n\n :param event: see \n :param context: see \n :return:\n \"statusCode\": 200,\n \"isBase64Encoded\": False,\n \"body\": json.dumps(result),\n \"headers\": {\n \"Content-Type\": \"application/json\"\n }\n \"\"\"\n\n result = {}\n\n params = event['queryStringParameters']\n headers = event['headers']\n path = re.sub('/bilihub', '', event['path'])\n\n match = False\n if 'bilihost' in event['headers'].keys():\n bili_host = event['headers']['bilihost']\n match = re.match(\".*.bilibili.com\", bili_host)\n else:\n bili_host = 'api.bilibili.com'\n\n if match:\n bili_headers = {}\n\n def set_header(key):\n if key in headers.keys():\n bili_headers[key] = headers[key]\n\n url = f'https://{bili_host}{path}'\n set_header('cookie')\n set_header('origin')\n set_header('referer')\n set_header('user-agent')\n\n response = requests.request(method='GET', url=url, params=params, headers=bili_headers)\n\n result['code'] = response.status_code\n if response.status_code == 200:\n result['data'] = json.loads(response.text)\n else:\n result['data'] = 'error'\n\n else:\n result['code'] = 500\n result['msg'] = 'Host Error.'\n\n return {\n \"statusCode\": 200,\n \"isBase64Encoded\": False,\n \"body\": json.dumps(result),\n \"headers\": {\n \"Content-Type\": \"application/json\"\n }\n }\n","repo_name":"LeonNOV/BiliHubProxy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75311767203","text":"from math import log, sqrt\n\nclass fractal:\n\t'''iterator that manages the creation of a fractal image'''\n\t\n\toptions = {\n\t\t'width': 500,\t#width in pixels of the fractal area\n\t\t'height': 100,\t#height in pixels of the fractal area\n\t\t'max_iterations': 300,\t#maximum number of iterations to perform for each point\n\t\t'color_range_repeats': 7\t#the amount of times to repeat the color pattern\n\t}\n\t\n\tzoom = {\n\t\t'x': -2.3,\n\t\t'y': 1.5,\n\t\t'width': 3,\n\t\t'height': 3\n\t}\n\t\n\timage = []\n\t\n\t\n\tdef __init__(self, options):\n\t\t'''init function sets up the options'''\n\t\tself.options.update(options)\n\t\n\tdef change_options(self, options):\n\t\t'''overrides current options with the newly-supplied set'''\n\t\tself.options.update(options)\n\t\n\tdef draw_fractal(self):\n\t\t'''this draws the fractal and returns the image list'''\n\t\tz = complex()\n\t\tc = complex()\n\t\ti = 0\n\t\tpixel = 0\n\t\tx = 0\n\t\ty = 0\n\t\titminus = 0\n\t\tcolors = {'r':0, 'g':0, 'b':0}\n\t\tover_iterated = False\n\t\titeration_divider = self.options['max_iterations'] / self.options['color_range_repeats']\n\t\torig_zoom_height = self.zoom['height']\n\t\t\n\t\tself.image = [] #reset the image array\n\t\t\n\t\t#adjust for non-square viewports\n\t\tself.zoom['height'] = self.zoom['width'] * (self.options['height'] / self.options['width'])\n\t\tself.zoom['y'] = self.zoom['y'] - (orig_zoom_height - self.zoom['height'])/2\n\t\t\n\t\t#for each vertical row in the viewport\n\t\tfor y in range(self.options['height']):\n\t\t\t#for each horizontal pixel in the row\n\t\t\tfor x in range(self.options['width']):\n\t\t\t\tz = complex()\n\t\t\t\tc = self.convert_pixel_to_point(x, y)\n\t\t\t\ti = 0\n\t\t\t\tover_iterated = False\n\t\t\t\t\n\t\t\t\twhile abs(z) < 4 and not over_iterated:\n\t\t\t\t\tz = z**2 + c\n\t\t\t\t\ti += 1\n\t\t\t\t\t\n\t\t\t\t\tif i > self.options['max_iterations']:\n\t\t\t\t\t\t#if abs(z) is still less than 4 and we're past our max_iterations counter, assume the point is in the set and color it black\n\t\t\t\t\t\ti = 0\n\t\t\t\t\t\tself.image.extend([0, 0, 0, 255])\n\t\t\t\t\t\tpixel += 4\n\t\t\t\t\t\t\n\t\t\t\t\t\tover_iterated = True\n\t\t\t\t\n\t\t\t\tif not over_iterated:\n\t\t\t\t\t#if the point is outside the set, color it\n\t\t\t\t\titminus = log(log(sqrt(z.real**2 + z.imag**2), 2), 2)\n\t\t\t\t\tcolors = self.rainbow_color((i - itminus) / iteration_divider)\n\t\t\t\t\t\n\t\t\t\t\tself.image.extend([colors['r'], colors['g'], colors['b'], 255])\n\t\t\t\t\tpixel += 4\n\t\t\n\t\treturn self.image\n\t\t\n\t\n\tdef convert_pixel_to_point(self, x, y):\n\t\t'''takes an x and a y position and converts it to a complex point\n\t\t@param int\t\tx\n\t\t@param int\t\ty\n\t\t\n\t\t@return complex\n\t\t'''\n\t\tstepx = self.zoom['width'] / self.options['width']\n\t\tstepy = self.zoom['height'] / self.options['height']\n\t\t\n\t\treturn complex(self.zoom['x'] + x * stepx, self.zoom['y'] - y * stepy)\n\t\n\tdef rainbow_color(self, position):\n\t\t'''takes a value calculated from the coloring algorithm and assigns an r, g, b value to it depending on how high it is\n\t\t@param float\t\tposition\n\t\t\n\t\t@return dict {r, g, b}\n\t\t'''\n\t\tcols = []\n\t\tnbars = 6 #number of color bars\n\t\tposition_int = int(position)\n\t\tposition_frac = position - position_int\n\t\tm = nbars * position_frac\n\t\tn = int(m) #integer portion of m\n\t\tf = m - n #fraction portion of m\n\t\tt = int(f * 255)\n\t\tcolor_vals = {\n\t\t\t0: {'r':255, 'g': t, 'b': 0},\n\t\t\t1: {'r':255 - t, 'g': 255, 'b': 0},\n\t\t\t2: {'r':0, 'g': 255, 'b': t},\n\t\t\t3: {'r':0, 'g': 255 - t, 'b': 255},\n\t\t\t4: {'r':t, 'g': 0, 'b': 255},\n\t\t\t5: {'r':255, 'g': 0, 'b': 255 - t}\n\t\t}\n\t\t\n\t\treturn color_vals[n]","repo_name":"janhartigan/FractalPython","sub_path":"fractal.py","file_name":"fractal.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"40178435870","text":"\"\"\"\n Nom ......... : game.py\n Rôle ........ : structure en dictionnaire regroupant les informations à un jeu complet et fonctions auxiliaires d'accès et modifications.\n Auteur ...... : Mickaël D. Pernet\n Version ..... : 29/05/2022\n Licence ..... : chapître 10: interpretation et compilation - projet\n\"\"\"\n\n\"\"\"\nnote: \n DMAP:\n matrice ou chaque ligne représente un étage et chaque sous liste une pièce:\n [, , ]\n note: utiliser le caractère ’ et non '.\n\"\"\"\ngame = {\n \"combine\": {\n \"rondins\": {\n \"echelle cassee\": \"échelle\"\n },\n \"verre\": {\n \"wiskey\": \"verre de wiskey\"\n },\n \"wiskey\": {\n \"verre\": \"verre de wiskey\"\n },\n \"verre de wiskey\": {\n \"buldog\": \"buldog endormis\"\n },\n \"clef en fer\": {\n \"porte de fer\": \"porte ouverte\"\n },\n \"clef en argent\": {\n \"porte en argent\": \"porte ouverte\"\n },\n \"hache\": {\n \"arbustes\": \"rondins\"\n },\n \"coffret a code\": {\n \"codes\": \"clef en argent\"\n } },\n \"current\": {\n \"RUN\": 1,\n \"ETAGE\": 1,\n \"PIECE\": 6, },\n \"damage\": {\n \"saucissons\": 2 },\n \"DMAP\": [\n [ [0, \"l’escalier vers le haut\", [0,1,0,0,1,0]], [1, \"salle à manger nord\" , [0,2,1,1,0,0]], [2, \"la cuisine\" , [0,0,0,1,0,0]], # rez de chaussée\n [3, \"accés nord\" , [0,1,1,0,0,0]], [4, \"salle à manger sud\" , [1,0,0,1,0,0]], [5, \"La serre nord\" , [0,0,1,0,0,0]],\n [6, \"accés sud\" , [1,1,0,0,0,0]], [7, \"Hall d’entrée\" , [0,1,2,1,0,0]], [8, \"La serre sud\" , [1,0,0,1,0,0]] ],\n [ [0, \"l’escalier vers le bas\" , [0,1,0,0,0,1]], [1, \"le hall du premier étage\", [0,2,1,2,0,0]], [2, \"la chambre du maitre\", [0,0,1,1,0,0]], # 1er étage\n [3, \"le bureau\" , [0,1,0,0,0,0]], [4, \"le couloir nord\" , [1,0,1,1,2,0]], [5, \"le lit du maitre\" , [1,0,0,0,0,0]],\n [6, \"la chambre d’ami\" , [0,1,0,0,0,0]], [7, \"le couloir sud\" , [1,1,0,1,0,0]], [8, \"la réserve\" , [0,0,0,1,0,0]] ],\n [ ['X'], ['X'] , ['X'], # Second étage\n ['X'], [4, \"L’observatoire\" , [0,0,0,0,0,1]] , ['X'],\n ['X'], ['X'] , ['X'] ] ],\n \"description\": { #Utilisation de lambda pour de la \"lazy evaluation\":\n # ETAGE 0 PIECE 0:\n \"l’escalier vers le haut\": lambda:\"Un escalier en colimaçon de marbre blanc et poli permettant d'accéder à l'étage supérieur, il mène vers une salle à manger à l'est\",\n # ETAGE 0 PIECE 1:\n \"salle à manger nord\": lambda:\"Une salle à manger se poursuivant sur le sud, cette partie et le bout de la table réserver au maitre de maison. Il y a également un [buffet] contre le mur. Un escalier vers l'étage supérieur à l'ouest et une [porte de fer] à l'est.\", \n # ETAGE 0 PIECE 2:\n \"la cuisine\": lambda:f\"\"\"Vous pénetrez dans une pièce avec un grand [âtre] éteind contenant une énormem marmite, des ustensiles de cuisines{', un [couteau]' if 'couteau' in piece_inventaire(position()[1]) else ''}{' et même une [hache]' if 'hache' in piece_inventaire(position()[1]) else ''}.\"\"\",\n # ETAGE 0 PIECE 3:\n \"accés nord\": lambda:\"Vous accédez à un long corridor avec une [baie vitrée] remplaçant le mur ouest et des [tableaux] et une porte ornant le mur est, il se prolonge vers le sud.\",\n # ETAGE 0 PIECE 4:\n \"salle à manger sud\": lambda:\"Vous longez une table de réception longue de plusieurs mètres entourée de chaises lourdes en bois, au nord la place en bout de table de maitre de maison, dans la partie sud une porte sur le mur ouest.\",\n # ETAGE 0 PIECE 5:\n \"La serre nord\": lambda:\"Vous arrivez au fond de la serre qui est beaucoup plus sauvage que la partie sud, ici nombre de petits arbres et [arbustes] poussent à leur guise.\", \n # ETAGE 0 PIECE 6:\n \"accés sud\": lambda:\"Un long corridor avec sur le mur est une [baie vitrée], sur le mur est une porte et il se prolonge vers le nord.\",\n # ETAGE 0 PIECE 7:\n \"Hall d’entrée\": lambda:\"Un hall d'entrée dallé de pierre compétement vide à l'exception des accès est et ouest, et d'une [porte en argent] au sud\",\n # ETAGE 0 PIECE 8:\n \"La serre sud\": lambda:\"Vous vous trouvez dans une sorte de serre relié au hall d'entrée par une petite porte à l'ouest et qui se prolonge au nord, ici des [fleurs] sont disposées esthétiquement de manière à produire des formes géométriques.\", \n # ETAGE 1 PIECE 0:\n \"l’escalier vers le bas\": lambda:\"Un escalier en colimaçon de marbre blanc et poli permettant d'accéder à l'étage inférieur, il mène vers une sorte de hall à l'est.\",\n # ETAGE 1 PIECE 1:\n \"le hall du premier étage\": lambda:f\"\"\"{\"Un [buldog] de bonne taille vous fixe avec insistance, il vous bloque le passage allongé sur \" if pnj(\"le hall du premier étage\", \"buldog\") else \" \"}un tapis plutôt défraichis et rogné sur tous ses bord trônant au milieu d'un hall d'entrer permettant de rejoindre un escalier de marbre à l'ouest, un couloir s'enfonçant vers le sud ou une porte particuliérement vernis à l'est.\"\"\",\n # ETAGE 1 PIECE 2:\n \"la chambre du maitre\": lambda:\"Une grande pièce séparée par une semi-Alcôve, dans la partie où vous trouvez une [bibliothèque] ainsi qu'un beau [fauteuil] de cuir meuble la pièce, une porte permet de sortir à l'ouest, tandis qu'au sud trône le lit de la chambre\",\n # ETAGE 1 PIECE 3:\n \"le bureau\": lambda:\"L'unique [fenêtre] de la pièce est obstruée par des planches et ne laisse filtrer que quelques rayons de lumière détourant un lourd [bureau] à tiroirs et une chaise face à la porte du mur est\",\n # ETAGE 1 PIECE 4:\n \"le couloir nord\": lambda:f\"Un couloir ornée d'un [tapis] rouge en mauvais état permettant de relier le fond de celui-ci au sud à une sorte de hall au nord. {'Une [échelle cassée] avec des barreaux manquants' if 'echelle cassee' in piece_inventaire(position()[1]) else 'Une [échelle]'} est posée contre le mur est et semble mener à une trappe au plafond, tandis que sur le mur ouest se trouve une porte\",\n # ETAGE 1 PIECE 5:\n \"le lit du maitre\": lambda:\"Cette partie de la pièce est séparée de la partie nord, un grand [lit] à deux place occupe presque tout l'espace.\",\n # ETAGE 1 PIECE 6:\n \"la chambre d’ami\": lambda:f\"Une petite pièce contenant un [lit] assez sommaire et une [table] de chevet{' sur laquelle repose un [verre]' if 'verre' in piece_inventaire(position()[1]) else ''}, une lumière pâle filtrant entre les rideaux obstruant l'unique fenêtre de la pièce donne à l'ensemble une humeur triste. Une porte sur le mur Est permet d'entrer et de sortir\",\n # ETAGE 1 PIECE 7:\n \"le couloir sud\": lambda:\"Vous découvrez un long couloir qui se poursuit vers le nord dans un long [tapis] poussièreux d'une couleur qui avait surement été une variante de rouge, le tout éclairé par une [fenêtre] sur le mur sud. A l'est et à l'ouest se trouve une porte.\",\n # ETAGE 1 PIECE 8:\n \"la réserve\": lambda:f\"Cette pièce sans fenêtre n'a qu'une entrée la porte de l'ouest. Grâce à la lumière vous devinez une reserve de [bric à brac]{', vous remarquez tout particulièrement une bouteille de [wiskey]' if 'wiskey' in piece_inventaire(position()[1]) else ''}{' et des [saucissons] au plafond' if 'saucissons' in piece_inventaire(position()[1]) else ''} .\",\n # ETAGE 2 PIECE 4:\n \"L’observatoire\": lambda:f\"En prenant l'échelle vous arrivez dans une petite tour avec un [télescope] pointer sur une montagne.\" }, \n \"hero\": {\n \"VIE_PERSONNAGE\": 10,\n \"INV_PERSONNAGE\": [],\n \"DEGAT_PERSONNAGE\": 1, },\n # {\"piece\": [element, option] - 1 prenable, 0 fixe, 2 fixe mais le résultat d'une utilisation dans l'inventaire du joueur, 3 pnj}\n \"inventaire\": { \n \"la chambre d’ami\": [\"verre\", 1, \"lit\", 0, \"fenetre\", 0, \"table\", 0],\n \"la réserve\": [\"wiskey\", 1, \"saucissons\", 1, \"bric a brac\", 0],\n \"le couloir sud\": [\"fenetre\", 0, \"tapis\", 0],\n \"le couloir nord\": [\"echelle cassee\", 2, \"tapis\", 0],\n \"le bureau\": [\"coffret a code\", 1, \"fenetre\", 0, \"bureau\", 0],\n \"le hall du premier étage\": [\"buldog\", 3],\n \"la chambre du maitre\": [\"bibliotheque\", 0, \"fauteuil\", 0],\n \"le lit du maitre\": [\"lit\", 0, \"clef en fer\", 1],\n \"salle à manger nord\": [\"buffet\", 0, \"porte de fer\", 2],\n \"la cuisine\": [\"atre\", 0, \"couteau\", 1, \"hache\", 1],\n \"accés nord\": [\"baie vitree\", 0, \"tableaux\", 0],\n \"accés sud\": [\"baie vitree\", 0],\n \"Hall d’entrée\": [\"porte en argent\", 2],\n \"La serre sud\": [\"fleurs\", 0],\n \"La serre nord\": [\"arbustes\", 1],\n \"L’observatoire\": [\"telescope\", 0, \"codes\", 1] },\n\n \"personnage\": { \n # ETAGE 1 PIECE 1:\n \"le hall du premier étage\":{\n 'buldog': {\n \"vie\": 5,\n \"degats\": 5,\n \"inv\": [],\n \"faible\": '\"verre de wiskey\"'\n }\n } },\n \"useCase\": {\n \"coffret a code\": {\n \"telescope\": lambda: f\"Vous regardez dans le télescope et testez les séries de chiffres sur la serrure à code jusqu'à réussir à le déverrouiller. Il contient une clé en argent.\"\n },\n \"verre\": {\n \"seul\": lambda: f\"Bien que le verre soit propre, il reste complètement vide et sans utilité.\",\n \"wiskey\": lambda: f\"Vous remplissez le verre avec le wiskey.\"\n },\n \"wiskey\": {\n \"seul\": lambda: f\"Vous ouvrez la bouteille et prenez une petite lampé, il faut peut-être en garder pour plus tard.\",\n \"verre\": lambda: f\"Vous remplissez le verre avec le wiskey.\"\n },\n \"verre de wiskey\": {\n \"seul\": lambda: f\"Vous prenez une lampé pour vous imprégner du goût agréable de la boisson.\",\n \"buldog\": lambda: f\"Vous présentez le verre au buldog et il se dépêche de venir le boire goulument. Une fois le verre vide il s'effondre endormis.\"\n },\n \"rondins\": {\n \"echelle cassee\": lambda: f\"Vous consolidez l'échelle en insérant les rondins dans les encoches des marches manquantes.\"\n },\n \"clef en fer\": {\n \"porte de fer\": lambda: f\"Vous entrez la lourde clef en fer dans la serrure et la tourné doucement, un click prévient que la porte est à présent ouverte.\"\n },\n \"hache\": {\n \"arbustes\": lambda: f\"Vous tranchez les branches des arbustes à coup de hache et faites un petit tas de rondins, quand soudain le fer de la hache se détache et vole jusqu'à se planter au plafond.\"\n },\n \"clef en argent\": {\n \"porte en argent\": lambda: f\"Vous introduisez la délicate clef d'argent dans la porte en argent!\"\n },\n \"coffret a code\": {\n \"codes\": lambda: f\"Vous essayez les différentes combinaisons sur le coffret jusqu'à ce que l'une d'elle le déverrouille, il contient une [clef en argent].\"\n } },\n \"special\": {\n \"la chambre d’ami\": { \n \"voir\": {\n \"lit\": lambda: \"Le lit dans lequel vous vous êtes réveillé, les draps sont défaits.\",\n \"fenetre\": lambda: f\"En écartant les rideaux une nature pastoral sous une aube levant se révèle devant vos yeux légèrement éblouie.\",\n \"table\": lambda: f\"C'est une table de chevet simple {',Un verre vide repose dessus' if 'verre' in piece_inventaire(position()[1]) else ''}.\"\n\n },\n \"util\": {\n \"lit\": lambda: \"Vous avez dormi il y a peu et ne ressentez pas le besoin de dormir à nouveau.\",\n \"fenetre\": lambda: \"Vous avez beau forcer impossible d'ouvrir la fenêtre.\",\n \"table\": lambda: \"Vous déplacez la table, mais rien ne se trouve en dessous ou derrière elle.\"\n } }, \n \"le couloir sud\": {\n \"voir\": {\n \"fenetre\": lambda: \"En écartant les rideaux une nature pastoral sous une aube levant se révèle devant vos yeux légèrement éblouie.\",\n \"tapis\": lambda: \"Ce tapis a connus des jours meilleurs, sa couleur est passée et il est envahi de poussière.\"\n },\n \"util\": {\n \"fenetre\": lambda: \"Vous avez beau forcer impossible d'ouvrir la fenêtre.\",\n \"tapis\": lambda: \"Vous remuez le tapis, la poussière s'élève doucement, mais non ... ce tapis n'a décidément rien de magique.\"\n } },\n \"le couloir nord\": {\n \"voir\": {\n \"tapis\": lambda: \"Ce tapis a connus des jours meilleurs, sa couleur est passée et il est envahi de poussière.\"\n },\n \"util\": {\n \"tapis\": lambda: \"Vous remuez le tapis, la poussière s'élève doucement, mais non ... ce tapis n'a décidément rien de magique.\"\n },\n \"special\": lambda: \"Pour accéder au niveau supérieur il va falloir utiliser l'échelle, mais son état ne permet pas d'utiliser pour le moment.\" \n },\n \"la réserve\": {\n \"voir\": {\n \"bric a brac\": lambda: \"Des sacs de farines et de riz, des petits outils cassées, du foin... bref tout un tas de chose sans utilitée.\"\n },\n \"util\": {\n \"bric a brac\": lambda: \"Hors de question de remuer tous ces trucs, d'autant plus qu'on risquerait de nous demander de les ranger plus tard...\"\n } },\n \"le bureau\": { \n \"voir\": {\n \"bureau\": lambda: f\"le bureau est bien rangé, une ramette de papier avec une plume et un encrier sur le plateau.{' Après avoir rapidement vérifié les tiroirs, un seul contient un [coffret à code] dont la serrure attend une combinaison de six chiffres pour être déverrouillée.' if 'coffret a code' in piece_inventaire(position()[1]) else ''}\",\n \"fenetre\": lambda: \"Cette fenêtre a été étrangement barrée par de solide planche, mais pourquoi faire?\"\n },\n \"util\": {\n \"bureau\": lambda: \"C'est pas vraiment le moment de se pencher sur ses exercices.\",\n \"fenetre\": lambda: \"Les planches empêchent d'actionner la fenêtre.\" \n } },\n \"le hall du premier étage\": {\n \"special\": lambda: \"Vous essayez de vous avancer, mais dès que vous approchez le [buldog] se redresse et grogne bien décidé à ne pas vous laissez passer\" \n },\n \"la chambre du maitre\": {\n \"voir\":{\n \"bibliotheque\": lambda: \"Une collection de livres ancien à reliure de cuir, ces bibliothèques sont des bien précieux!\",\n \"fauteuil\": lambda: \"Le fauteuil semble si confortable que la forme de son propriétaire est incrustée à l'intérieur\"\n },\n \"util\":{\n \"bibliotheque\": lambda: \"Vous déplacez plusieurs livres, mais non rien, pas de passage secret.\",\n \"fauteuil\": lambda: \"Une petite pause bien méritée, il faut trouver la sortie à présent.\"\n } },\n \"le lit du maitre\": {\n \"voir\":{\n \"lit\": lambda: \"Ce lit est bien plus moelleux et luxueux que celui dans lequel vous avez dormi.\"\n },\n \"util\":{\n \"lit\": lambda: f\"\"\"Vous défaites les couvertures et retournez les oreillers. {'Vous découvrez parmi les draps une [clef en fer].' if \"clef en fer\" in piece_inventaire(position()[1]) else ''}\"\"\" \n } },\n \"salle à manger nord\":{\n \"voir\":{\n \"buffet\": lambda: \"C'est un beau meuble remplit d'une vaisselle luxueuse.\"\n },\n \"util\":{\n \"buffet\": lambda: \"Le buffet est beaucoup trop lourd pour être déplacer.\"\n },\n \"special\": lambda: \"La porte de fer est verouillée et vous empêche de rejoindre la pièce suivante.\"\n },\n \"la cuisine\": {\n \"voir\": {\n \"atre\": lambda: \"c'est un grand âtre en pierre recueillant une marmite et beaucoup de cendre, manifestement il n'a pas été nettoyé récemment.\"\n },\n \"util\": {\n \"atre\": lambda: \"Non non ce n'est pas l'heure de manger!\"\n } },\n \"accés nord\": {\n \"voir\": {\n \"baie vitree\": lambda: \"La grande baie vitrée ne permet pas de voir très loin puisqu'une haie d'au moins deux mètres de haut se trouve à 3 mètres de celle-ci, sans compter d'épais barreau de fer la protégeant\",\n \"tableaux\": lambda: \"Un triptyque de portraits représentant un homme à trois âges différents.\"\n },\n \"util\": {\n \"baie vitree\": lambda: \"Non même en parvenant à briser la vitre sans se blesser, les barreaux empêcheraient tout de même de sortir.\",\n \"tableaux\": lambda: \"Vous faites balancez les tableaux qui restent bien accrochés, rien ne semble caché derrière.\"\n } },\n \"accés sud\": {\n \"voir\": {\n \"baie vitree\": lambda: \"La grande baie vitrée ne permet pas de voir très loin puisqu'une haie d'au moins deux mètres de haut se trouve à 3 mètres de celle-ci, sans compter d'épais barreau de fer la protégeant\"\n },\n \"util\": {\n \"baie vitree\": lambda: \"Non même en parvenant à briser la vitre sans se blesser, les barreaux empêcheraient tout de même de sortir.\"\n } },\n \"La serre sud\": {\n \"voir\": {\n \"fleurs\": lambda: \"Aconit, bergénie, camélia, fleur d'arlequin... mmm visiblement le maitre de maison à une passion pour la botanique.\"\n },\n \"util\": {\n \"fleurs\": lambda: \"la fleur en bouquet fâne et jamais ne renait! laissons les vivres.\"\n } },\n \"L’observatoire\": {\n \"voir\": {\n \"telescope\": lambda: \"Il semble fonctionnel et est pointé dans une direction un peu singulière.\"\n },\n \"util\": {\n \"telescope\": lambda: \"Vous utilisez le télescope et apercevez la montagne de plus près, il semblerait qu'il soit réglé ainsi pour permettre de distinguer des panneaux de bois sur lesquels est inscrit des sortes de [codes] à six chiffres\"\n } },\n \"Hall d’entrée\": {\n \"special\": lambda: f\"La porte est solide et sa serrure en argent semble bien fermée!\"\n } },\n \"welcome\": \"\"\"\nAIDE DES DIFFERENTES ACTIONS POSSIBLES: \nAide aide\nSe deplacer allez/va au/à (nord, surd, est, ouest)\nAttaquer attaquer \n attaquer avec \nPrendre prendre \nUtiliser utiliser \n utiliser avec <élément>\nRegarder regarder \nAfficher son inventaire inventaire\nnote: les \"objets\" en plusieurs mots doivent obligatoirement être entre guillemet \"\" les autres non.\n\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\\n\nVous ne vous souvenez pas de la nuit dernière et lorsque vous ouvrez les yeux vous n'êtes manifestement pas dans votre lit, vous vous levez et vous trouvez dans \n\"\"\"\n}\n\n\ndef combine(E1, E2):\n \"\"\"\n combine: \n Retourne la valeur pour la combinaison entre E1 et E2\n Args:\n E1 sting: un objet\n E2 string: un objet\n Returns:\n string: résultat de la combinaison.\n \"\"\"\n return game.get(\"combine\", {\"vide\": 0}).get(str(E1), {\"vide\": 0}).get(str(E2), 0)\n\ndef RUN():\n \"\"\"\n RUN: \n Reroutne la valeur actuel de RUN dans la structure.\n Returns:\n int: 0 ou 1\n \"\"\"\n return game.get(\"current\", {\"vide\", 0}).get(\"RUN\", -1)\n\ndef position():\n \"\"\"\n position: \n retourne la position actuel dans la matrice DMAP\n Returns:\n string: résultat\n \"\"\"\n return game.get(\"DMAP\", 0)[game.get(\"current\").get(\"ETAGE\")][game.get(\"current\").get(\"PIECE\")]\n\ndef description(E1):\n \"\"\"\n description: \n retourne la description pour E1 de la structure\n Args:\n E1 string: \"nom de piece\"\n Returns:\n string: résultat\n \"\"\"\n return game.get(\"description\", {\"vide\": 0}).get(E1,lambda: 0)\n\ndef hero_inventaire():\n \"\"\"\n hero_inventaire: \n Récupére l'inventaire dans la structure \"hero\"\n Returns:\n list: liste d'inventaire\n \"\"\"\n return game.get(\"hero\", {\"vide\": 0}).get(\"INV_PERSONNAGE\", 0)\n\ndef hero_vie():\n \"\"\"\n hero_vie: \n retourne la valeur de vie du hero dans la structure \"hero\"\n Returns:\n int: point de vie\n \"\"\"\n return game.get(\"hero\", {\"vide\": 0}).get(\"VIE_PERSONNAGE\", 0)\n\ndef hero_damage():\n \"\"\"\n hero_damage: \n retourne le montant de dommages dans la structure \"hero\"\n Returns:\n ind: dommages\n \"\"\"\n return game.get(\"hero\", {\"vide\": 0}).get(\"DEGAT_PERSONNAGE\", 0)\n\ndef piece_inventaire(piece):\n \"\"\"\n Exec: \n fonction qui reçoit les arbres à partir de la grammaire et applique les actions nécessaires.\n Args:\n tree(arbre): arbre d'instruction\n Returns:\n string: résultat\n \"\"\"\n return game.get(\"inventaire\", {\"vide\":0}).get(piece, 0)\n\ndef pnj(PIECE, E1):\n \"\"\"\n pnj: \n récupére la structure pour un personnage donné\n Args:\n PIECE string: \"nom de la piece\"\n E1 string: \"nom du pnj\"\n Returns:\n dict: structure du personnage\n \"\"\"\n return game.get(\"personnage\", {\"vide\": 0}).get(PIECE, {\"vide\": 0}).get(E1, 0)\n\ndef use(E1, E2):\n \"\"\"\n use: \n Retourne le résultat d'utilisation entre E1 et E12\n Args:\n E1 string: \"objet1\"\n E2 string: \"objet2\"\n Returns:\n string: résultat\n \"\"\"\n return game.get(\"useCase\", {\"vide\": 0}).get(E1, {\"vide\": 0}).get(E2, lambda: 0)\n\ndef special(PIECE, E1, E2):\n \"\"\"\n special: \n retourne le résultat des actions par rapport à un objet\n Args:\n PIECE string: \"nom de la piece\"\n E1 string: \"action\"\n E2 string: \"objet\"\n Returns:\n string: résultat\n \"\"\"\n return game.get(\"special\", {\"vide\": 0}).get(PIECE, {\"vide\": 0}).get(E1, {\"vide\": 0}).get(E2, lambda: 0)\n\ndef styleFormat(E):\n \"\"\"\n styleFormat: \n fonction pour intégrer un resultat dans un standard \"graphique\"\n Args:\n E string: chaîne de caractère à décorer.\n Returns:\n string: résultat\n \"\"\"\n return f\"\"\"\n\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\\n\n{E}\n\\n\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\"`-._,-'\n\"\"\"","repo_name":"MickaelDP/Lang_jeu_textuel","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":27382,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70063026086","text":"from __future__ import print_function\nfrom functools import reduce\nfrom .git_lint import load_config, run_linters, git_base\nimport operator\nimport gettext\n_ = gettext.gettext\n\n\ndef print_report(results, unlintable_filenames, cant_lint_filenames,\n broken_linter_names, unfindable_filenames, options={'bylinter': True}):\n\n def base_file_cleaner(files):\n return [file.replace(git_base + '/', '', 1) for file in files]\n\n # ICK. Mutation, references, and hidden assignment.\n def group_by(iterable, field_id):\n results = []\n keys = {}\n for obj in iterable:\n key = obj[field_id]\n if key in keys:\n keys[key].append(obj)\n continue\n keys[key] = [obj]\n results.append((key, keys[key]))\n return results\n\n sort_position = 1\n grouping = _('Linter: {}')\n if 'byfile' in options:\n sort_position = 0\n grouping = _('Filename: {}')\n grouped_results = group_by(results, sort_position)\n\n for group in grouped_results:\n messages = reduce(operator.add, [item[3] for item in group[1]], [])\n if len(messages) == 0:\n continue\n print(grouping.format(group[0]))\n for (filename, lintername, returncode, text) in group[1]:\n if text:\n print('\\n'.join(base_file_cleaner(text)))\n print('')\n print ('')\n\n if len(broken_linter_names) and (len(cant_lint_filenames) or ('verbose' in options)):\n print(_('Linters not found:'), ','.join(broken_linter_names))\n if len(cant_lint_filenames):\n print(' ' + _('Files not linted:'))\n print('\\n'.join([' {}'.format(f) for f in cant_lint_filenames]))\n print('')\n\n if len(unlintable_filenames) and ('verbose' in options):\n print(_('No recognizeable linters for:'))\n print('\\n'.join([' {}'.format(f) for f in unlintable_filenames]))\n print('')\n\n if len(unfindable_filenames):\n print(_('Files not found:'))\n print('\\n'.join([' {}'.format(f) for f in unfindable_filenames]))\n print('')\n\n \ndef print_help(options, name):\n print(_('Usage: {} [options] [filenames]').format(name))\n for item in options:\n print(' {:<2} --{:<12} {}'.format((item[0] and ('-' + item[0])) or '', item[1], item[3]))\n\n\ndef print_version(name, version):\n print(_('{} {} Copyright (c) 2009, 2016 Kennth M. \"Elf\" Sternberg').format(name, version))\n\n\ndef print_linters(config, broken_linter_names):\n print(_('Currently supported linters:'))\n for linter in config:\n print('{:<14} {}'.format(linter.name,\n ((linter.name in broken_linter_names and\n _('(WARNING: executable not found)') or\n linter.linter.get('comment', '')))))\n\n\n","repo_name":"elfsternberg/git-linter","sub_path":"git_lint/reporters.py","file_name":"reporters.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"44789553077","text":"def naive_get_gift_for_house(_house):\n gifts_total = 1\n for h in range(2, _house):\n if _house % h == 0:\n gifts_total += h\n\n return gifts_total * 10\n\ndef get_gifts_for_house_solution_1(_house, target=0):\n tail = _house\n gift_total = 0\n start = 1\n gift_factors = 0\n\n while tail > start:\n if _house % start == 0:\n tail = _house / start\n\n if tail > start:\n gift_total = gift_total + tail\n\n gift_total = gift_total + start\n gift_factors += start\n start+=1\n\n if start > 8 and gift_factors < 36:\n return 0\n\n return int(gift_total * 10)\n\ndef get_gifts_for_house_solution_2(_house, target_score):\n tail = _house\n gift_total = 0\n start = 1\n gift_factors = 0\n\n discard = []\n prime=0\n\n while tail > start:\n if _house % start == 0:\n tail = _house / start\n\n if tail * 50 <= _house:\n discard.append(tail)\n\n if tail * 50 >= _house and tail > start:\n gift_total = gift_total + tail\n\n if start * 50 >= _house:\n gift_total = gift_total + start\n gift_factors += start\n else:\n discard.append(start)\n else:\n prime+=1\n\n if (10 < start < 15) and prime > 5:\n return 0\n\n start+=1\n\n return int(gift_total * 11)\ndef find_best_house(gift_target, getGiftForHouseFn):\n _house = 1\n while True:\n _gifts = getGiftForHouseFn(_house, gift_target)\n if _gifts >= gift_target:\n return _house\n\n if _house % 1000000 == 0:\n print(\"1 Million\")\n\n _house += 1\n\n return -1\n\n\ndef factors50(h):\n r = []\n for n in range(1, h):\n if h % n == 0 and n*50 >= h:\n r.append(n)\n\n r.append(h)\n return r\ndef factors(h):\n r = []\n\n for n in range(1, h):\n if h % n == 0:\n r.append(n)\n\n r.append(h)\n return r\n\ndef test1(_house, expected_res):\n _best = find_best_house(_house)\n status = \"Pass\" if _best==expected_res else \"Fail\"\n print(\"Best house after house: \", _house, \" =>\", _best, \" =>\", status)\n print(\"gifts on house target: \", get_gifts_for_house_solution_1(_house))\n print(\"gifts on best house: \", get_gifts_for_house_solution_1(_best))\n\n\n\nP = 29000000\nbest_house = find_best_house(P, get_gifts_for_house_solution_1)\nprint(\"solution 1: \", best_house)\nbest_house_solution_2 = find_best_house(P, get_gifts_for_house_solution_2)\nprint(\"solution 2: \", best_house_solution_2)\n","repo_name":"cesarvr/puzzlz","sub_path":"aoc_2015/day20/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4287220980","text":"from flask import Flask\nfrom flask import render_template, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/estimate')\ndef estimate():\n return render_template('estimate.html')\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n@app.route('/TotalPrice', methods=['POST'])\ndef TotalPrice():\n if request.method == 'POST':\n form = request.form\n radius = float(form['radius'])\n height = float(form['height'])\n pi = 3.14\n areaOfTankTop = pi * (radius**2)\n areaOfTankSide = 2 * (pi*(radius*height))\n totalPrice = 35 * (areaOfTankSide + areaOfTankTop)\n formattedTotalPrice = \"${:,.2f}\".format(totalPrice)\n \n print(radius)\n print(height)\n print(areaOfTankTop)\n print(areaOfTankSide)\n print(totalPrice)\n\n return render_template('estimate.html', TotalPrice = formattedTotalPrice)\n \n return render_template('estimate.html')\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"hoangtnguyen-github/vtm_site","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25588599390","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport scipy.optimize as op\nimport matplotlib.pyplot as plt\nimport models\n\n# --------------------------------------------------------------------------- #\n# Load public EDGS data from Bowman et al. 2018 Figure 1\n# G:\\My Drive\\Publications\\Papers\\2017_EDGES_Low\\PublicData\n# --------------------------------------------------------------------------- #\n\ndata = np.genfromtxt('G:/My Drive/Publications/Papers/2017_EDGES_Low/PublicData/figure1_plotdata.csv', delimiter=',', skip_header=1);\nf = data[:,0];\nw = data[:,1];\nd = data[:,2];\n\n# Extract frequency coordinates from the data file for small and large subbands\nv = [data[(data[:,1]>0),0], data[(data[:,0]>63) & (data[:,0]<99),0]];\n\n# Extract the data for the same ranges\nd = [data[(data[:,1]>0),2], data[(data[:,0]>63) & (data[:,0]<99),2]];\n\n\n# Thermal uncertainty estimate per channel\nthermalUncertainty = 0.025;\nderr = [thermalUncertainty * np.ones_like(x) for x in v];\n\n\n# Arguments for functions\nvc = 75;\nbeta = -2.5;\nfrange = 1;\nknown_signal = [models.flattenedGaussian(v[i], 79, 19, 6.5, -0.5) for i in range(0,len(v))];\nargs_vc = [(v[i], d[i], derr[i], vc) for i in range(0,len(v))];\nargs_vc_beta = [(v[i], d[i] - known_signal[i], derr[i], vc, beta) for i in range(0,len(v))];\n\n# Find solutions\n\n#theta_prime = [1700, -2.5, 0, 0, 79, 19, 7, -0.5]; # exponentLogExpansion_FlattenedGaussian\n#result = op.minimize(models.optExponentLogExpansion_FlattenedGaussian, theta_prime, args=args_vc[frange]);\n\n#theta_prime = [1700, -2.5, 0, 0, 0]; # exponentLogExpansion\n#result = op.minimize(models.optExponentLogExpansion, theta_prime, args=args_vc[frange]);\n\nnterms = 5;\ntheta_prime = [1792, 127, -276, 123, -16, 79, 19, 7, -0.5]; # linearPolynomial_FlattenedGaussian\nbounds = [[None, None], [None, None], [None, None], [None, None], [None, None], [75, 83], [10, 30], [1, 10], [-2, -0.1]];\nresult = op.minimize(models.optLinearPolynomial_FlattenedGaussian, theta_prime, \n args=args_vc_beta[frange],\n tol = 1e-6,\n method='Nelder-Mead');\n\n#theta_prime = [1700, 0, 0, 0, 0]; # linearPolynomial\n#result = op.minimize(models.optLinearPolynomial, theta_prime, args=args_vc_beta[frange]);\n\n#nterms = 5;\n#theta_prime = [1700, 0, 0, 0, 0, 79, 19, 7, -0.5]; # linearLogExpansion_FlattenedGaussian\n#bounds = [[1000, 2000], [-5000, 10], [-5000, 10], [-5000, 10], [-5000, 1000], [75, 83], [10, 30], [5, 10], [-0.8, -0.3]];\n#result = op.minimize(models.optLinearLogExpansion_FlattenedGaussian, \n# theta_prime, \n# bounds = bounds,\n# args=args_vc_beta[frange],\n# tol = 1e-10,\n# method='L-BFGS-B',\n# options={'eps':1e-8, 'maxcor': 100, 'gtol':1e-9, 'ftol':1e-12, 'maxls':1000, 'maxiter': 100000, 'disp': True});\n\n#nterms = 5;\n#theta_prime = [1500, 0.1, 0.1, 0.1, 0.1]; # linearLogExpansion\n#result = op.minimize(models.optLinearLogExpansion, theta_prime, args=args_vc_beta[frange]);\n\n# Extract the fit\n\nfit_min = result[\"x\"];\nfit_lin, rms_lin_o = models.fitLinear(d[frange] - known_signal[frange], models.linearPolynomialComponents(v[frange],vc,beta,nterms));\nfit_linc, cov_linc = models.fitLinearCov(d[frange], np.diag(derr[frange]*derr[frange]), models.linearPolynomialComponents(v[frange],vc,beta,nterms));\n\n#signal = np.zeros_like(v[frange]);\nsignal = models.flattenedGaussian(v[frange], fit_min[-4], fit_min[-3], fit_min[-2], fit_min[-1]);\n\nmodel_min = models.linearPolynomial(v[frange], vc, beta, fit_min) + signal;\nmodel_lin = models.linearPolynomial(v[frange], vc, beta, fit_lin);\nmodel_linc = models.linearPolynomial(v[frange], vc, beta, fit_linc);\n\nresiduals_min = d[frange] - model_min;\nresiduals_lin = d[frange] - model_lin;\nresiduals_linc = d[frange] - model_linc;\n\nrms_min = np.std(residuals_min);\nrms_lin = np.std(residuals_lin);\nrms_linc = np.std(residuals_linc);\n\nprint(\"RMS minimize fit: {}\".format(rms_min));\nprint(\"RMS linear fit: {}\".format(rms_lin));\nprint(\"RMS linear cov fit: {}\".format(rms_linc));\n\n\nplt.figure(1);\nplt.clf();\nplt.plot(v[frange], residuals_min, v[frange], residuals_lin, v[frange], residuals_linc);\nplt.show();\n\nplt.figure(2);\nplt.clf();\nplt.plot(v[frange], signal);\nplt.show();\n\nplt.figure(3);\nplt.clf();\nplt.plot(v[frange], model_min, v[frange], model_lin, v[frange], model_linc);\nplt.show();\n","repo_name":"jdbowman/edges","sub_path":"src/py/exp/testmcmc.py","file_name":"testmcmc.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11311822512","text":"from flask import render_template,Flask ,url_for, flash, redirect, request\nfrom forms import EmotionForm\nfrom emo_detext import predict_emo\nimport os\n\n\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = os.environ.get(\"SECRET_KEY\")\n\n\n@app.route('/')\n@app.route('/home')\ndef home():\n return render_template(\"home.html\")\n\n\n@app.route('/about')\ndef about():\n return render_template(\"about.html\")\n\n\n@app.route('/emodetext', methods=['GET', 'POST'])\ndef emodetext():\n form = EmotionForm()\n if form.validate_on_submit():\n text = form.text_sentiment.data\n emotion = predict_emo([text])\n return render_template(\"emotion.html\", form= form , emotion = emotion)\n\n return render_template(\"emodetext.html\", form = form)\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n\n\n","repo_name":"idrissa-mgs/emotion-detection-npl","sub_path":"emodetext-app.py","file_name":"emodetext-app.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37283062258","text":"#\n# @lc app=leetcode id=1680 lang=python3\n#\n# [1680] Concatenation of Consecutive Binary Numbers\n#\n# https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/description/\n#\n# algorithms\n# Medium (43.99%)\n# Likes: 55\n# Dislikes: 81\n# Total Accepted: 6.8K\n# Total Submissions: 15.4K\n# Testcase Example: '1'\n#\n# Given an integer n, return the decimal value of the binary string formed by\n# concatenating the binary representations of 1 to n in order, modulo 10^9 +\n# 7.\n# \n# \n# Example 1:\n# \n# \n# Input: n = 1\n# Output: 1\n# Explanation: \"1\" in binary corresponds to the decimal value 1. \n# \n# \n# Example 2:\n# \n# \n# Input: n = 3\n# Output: 27\n# Explanation: In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\n# After concatenating them, we have \"11011\", which corresponds to the decimal\n# value 27.\n# \n# \n# Example 3:\n# \n# \n# Input: n = 12\n# Output: 505379714\n# Explanation: The concatenation results in\n# \"1101110010111011110001001101010111100\".\n# The decimal value of that is 118505380540.\n# After modulo 10^9 + 7, the result is 505379714.\n# \n# \n# \n# Constraints:\n# \n# \n# 1 <= n <= 10^5\n# \n# \n#\n\n# @lc code=start\nimport math\n\nclass Solution:\n def concatenatedBinary(self, n: int) -> int:\n # Time complexity: O(nlogn)\n # Space complexity: O(nlogn)\n # MOD = 10**9 + 7\n # concatenation = \"\".join(bin(i)[2:] for i in range(n + 1))\n # return int(concatenation, 2) % MOD\n\n # Time complexity: O(nlogn)\n # Space complexity: O(1)\n # MOD = 10**9 + 7\n # length, result = 0, 0\n # for i in range(1, n + 1):\n # # when meets power of 2, increase the bit length\n # if math.log(i, 2).is_integer():\n # length += 1\n # result = ((result * (2 ** length)) + i) % MOD\n # return result\n\n\n # Time complexity: O(n)\n # Space complexity: O(1)\n MOD = 10**9 + 7\n length, result = 0, 0\n for i in range(1, n + 1):\n # when meets power of 2, increase the bit length\n if i & (i - 1) == 0:\n length += 1\n result = ((result << length) | i) % MOD\n return result\n\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"1680.concatenation-of-consecutive-binary-numbers.py","file_name":"1680.concatenation-of-consecutive-binary-numbers.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"71323759526","text":"\"\"\"\nCSCI-603: Trees (week 10)\nAuthor: Sean Strout @ RIT CS\n\nThis is an implementation of a binary search tree.\n\"\"\"\nimport random\nfrom typing import Any\n\nfrom btnode import BTNode\n\n\nclass BST:\n \"\"\"\n A binary search tree consists of:\n :slot root: The root node of the tree (BTNode)\n :slot size: The size of the tree (int)\n \"\"\"\n __slots__ = 'root', 'size'\n root: BTNode\n size: int\n\n def __init__(self, root: BTNode = None) -> None:\n \"\"\"\n Initialize the tree.\n :return: None\n \"\"\"\n self.root = root\n self.size = 0\n\n def __str__(self) -> str:\n \"\"\"\n Return a string representation of the tree. By default this will\n be a string with the values in order.\n :return:\n \"\"\"\n # call the recursive helper function with the root node\n return self.inorder(self.root)\n\n def __insert(self, val: int, node: BTNode) -> None:\n \"\"\"\n The recursive helper function for inserting a new value into the tree.\n :param val: The value to insert\n :param node: The current node in the tree (BTNode)\n :return: None\n \"\"\"\n if val < node.val:\n if node.left is None:\n node.left = BTNode(val)\n else:\n self.__insert(val, node.left)\n elif val > node.val:\n if node.right is None:\n node.right = BTNode(val)\n else:\n self.__insert(val, node.right)\n\n def insert(self, val: int) -> None:\n \"\"\"\n Insert a new value into the tree\n :param val: The value to insert\n :return: None\n \"\"\"\n if self.root is None:\n self.root = BTNode(val)\n else:\n self.__insert(val, self.root)\n self.size += 1\n\n def __contains(self, val: int, node: BTNode) -> bool:\n \"\"\"\n The recursive helper function for checking if a value is in the tree.\n :param val: The value to search for\n :param node: The current node (BTNode)\n :return: True if val is present, False otherwise\n \"\"\"\n if val < node.val:\n if node.left is None:\n return False\n else:\n return self.__contains(val, node.left)\n elif val > node.val:\n if node.right is None:\n return False\n else:\n return self.__contains(val, node.right)\n elif val == node.val:\n return True\n\n def contains(self, val: int) -> bool:\n \"\"\"\n Returns whether a value is in the tree or not.\n :param val: The value to search for\n :return: True if val is present, False otherwise\n \"\"\"\n # call the recursive helper function with the root node\n if self.root is None:\n return False\n elif self.root.val == val:\n return True\n else:\n return self.__contains(val, self.root)\n\n def __height(self, node: BTNode) -> int:\n \"\"\"\n The recursive helper function for computing the height of a node\n :param node: The current node (BTNode)\n :return: The height of node (int)\n \"\"\"\n if node is None:\n return -1\n else:\n return 1 + max(self.__height(node.right), self.__height(node.left))\n\n def height(self) -> int:\n \"\"\"\n Return the height of a tree. Recall:\n - The height of an empty tree is -1\n - The height of a tree with one node is 0\n - Otherwise the height is one plus the larger of the heights of\n the left or right children.\n :return: The height (int)\n \"\"\"\n # just call the recursive helper function with the root node\n return self.__height(self.root)\n\n def inorder(self, node: BTNode) -> str:\n \"\"\"\n The recursive inorder traversal function that builds a string\n representation of the tree.\n :param node: The current node (BTNode)\n :return: A string of the tree, e.g. \"1 2 5 9 \"\n \"\"\"\n if node is None:\n return \"\"\n else:\n return self.inorder(node.left) + \" \" + str(node.val) + \" \" + self.inorder(node.right)\n\n def preorder(self, node: BTNode) -> str:\n \"\"\"\n The recursive inorder traversal function that builds a string\n representation of the tree.\n :param node: The current node (BTNode)\n :return: A string of the tree, e.g. \"1 2 5 9 \"\n \"\"\"\n if node is None:\n return \"\"\n else:\n return str(node.val) + \" \" + self.inorder(node.left) + \" \" + self.inorder(node.right)\n\n def postorder(self, node: BTNode) -> str:\n \"\"\"\n The recursive inorder traversal function that builds a string\n representation of the tree.\n :param node: The current node (BTNode)\n :return: A string of the tree, e.g. \"1 2 5 9 \"\n \"\"\"\n if node is None:\n return \"\"\n else:\n return self.inorder(node.left) + \" \" + self.inorder(node.right) + \" \" + str(node.val)\n\n\ndef testBST() -> None:\n # tree with a parent (20), left child (10) and right child (30)\n random.seed(42)\n t2 = BST()\n list_asd = [random.randint(0, 10) for i in range(10)]\n for val in list_asd: t2.insert(val)\n print('t2:', t2)\n\n # a larger tree\n t3 = BST()\n for val in (17, 5, 35, 2, 16, 29, 38, 19, 33): t3.insert(val)\n print('t3:', t3)\n print('t3 size (9):', t3.size)\n print('t3 contains 16 (True)?', t3.contains(16))\n print('t3 contains 0 (False)?', t3.contains(0))\n print('t3 height (3)?', t3.height())\n\n\nif __name__ == '__main__':\n testBST()\n","repo_name":"Bardhitoo/CSCI.603-Computational-Problem-Solving","sub_path":"Week 10/midterm_prep/bst.py","file_name":"bst.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27546776906","text":"# -*- coding: utf-8 -*-\n# @author WuJing\n# @created 2023/4/10\nimport tensorlayerx as tlx\nfrom gammagl.sparse import SparseGraph\nfrom gammagl.sparse.storage import SparseStorage\n\n\ndef t(src: SparseGraph) -> SparseGraph:\n csr2csc = src.storage.csr2csc()\n\n row, col, value = src.coo()\n\n if value is not None:\n value = tlx.gather(value, csr2csc)\n\n sparse_sizes = src.storage.sparse_sizes()\n\n storage = SparseStorage(\n row=tlx.gather(col, csr2csc),\n rowptr=src.storage._colptr,\n col=tlx.gather(row, csr2csc),\n value=value,\n sparse_sizes=(sparse_sizes[1], sparse_sizes[0]),\n rowcount=src.storage._colcount,\n colptr=src.storage._rowptr,\n colcount=src.storage._rowcount,\n csr2csc=src.storage._csc2csr,\n csc2csr=csr2csc,\n is_sorted=True,\n )\n\n return src.from_storage(storage)\n\n\nSparseGraph.t = lambda self: t(self)\n","repo_name":"BUPT-GAMMA/GammaGL","sub_path":"gammagl/sparse/transpose.py","file_name":"transpose.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"52"} +{"seq_id":"22712846814","text":"#WhatsApp Server Aplication.\n#We use Twilio as a \"Man in the middle\" between client and WA server. \nfrom flask import Flask, request\nfrom twilio.twiml.messaging_response import MessagingResponse\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello():\n return \"I'm The Server for WhatsApp ChatBot :3...\"\n\n@app.route('/sms', methods=['POST'])\ndef sms_reply():\n \"\"\"Aquí se responde con cualquier mensaje\"\"\"\n #Fetching\n msg = request.form.get('Body')\n\n #Replying\n resp = MessagingResponse()\n resp.message(\"I'm working on development mode!\")\n\n return str(resp)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"J-HenriqueDev/WhatsApp-ChatBot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12365834449","text":"from os import listdir\nfrom numpy import zeros\nfrom numpy import ones\nfrom numpy import loadtxt\nfrom numpy import append\nfrom numpy import expand_dims\nfrom numpy import savetxt\nfrom numpy import loadtxt\nfrom numpy.random import randint\nimport json\n\ndef load_from_directory(path):\n files = listdir(path)\n X = loadtxt(open(path+\"/\"+ files[0], \"rb\"), delimiter=\",\")\n vector_size = X.shape[0]\n if len(X.shape) > 1:\n rows_size, columns_size = X.shape\n # get samples\n for i in range(1, len(files)):\n new = loadtxt(open(path+\"/\"+ files[i], \"rb\"), delimiter=\",\")\n X = append(X, new, axis =0)\n # reshape the ndarray\n if len(X.shape) > 1:\n X = X.reshape(len(files),rows_size,columns_size)\n else:\n X = X.reshape(len(files),vector_size)\n # expand dimension \n X = expand_dims(X, axis=-1)\n # convert from ints to floats\n X = X.astype('float32')\n return X\n\n# load the labeled data\ndef load_labeled_samples(path):\n X_0 = load_from_directory(path+'/DF')\n X_1 = load_from_directory(path+'/SD')\n return [X_0, X_1]\n\n# load the unlabeled data\ndef load_unlabeled_samples(path):\n return load_from_directory(path)\n\n# Simply randomly split an array in two\n# There is a bug here and the test is not 100% garanted balanced, but for now it is close enough\ndef split_test_data(data, test_size, random, file_path):\n mask = zeros(data.shape[0],dtype=bool)\n if(random):\n ix = randint(0, data.shape[0], size=test_size)\n else:\n ix = loadtxt(file_path).astype(int)\n mask[ix] = True\n X_training = data[~mask]\n X_test = data[mask]\n return X_training , X_test, ix\n\n# Generates Training and Test data. The test dataset is always balanced.\ndef generate_supervised_datasets(X, log_path, random, relative_test_size=0.2):\n filepath_0 = log_path+'/test_indices_labeled_0'\n filepath_1 = log_path+'/test_indices_labeled_1'\n total_size = len(X[0]) + len(X[1])\n half_test_size = int((total_size * relative_test_size) / 2 )\n X_training_0, X_test_0, indices_0 = split_test_data(X[0], half_test_size, random, filepath_0)\n X_training_1, X_test_1, indices_1 = split_test_data(X[1], half_test_size, random, filepath_1)\n X_training = append(X_training_0, X_training_1, axis=0)\n y_training = append(zeros((len(X_training_0), 1 )), ones((len(X_training_1), 1 )), axis=0)\n X_test = append(X_test_0, X_test_1, axis=0)\n y_test = append(zeros((len(X_test_0), 1 )), ones((len(X_test_1), 1 )), axis=0)\n if(random):\n savetxt(filepath_0, indices_0, delimiter=',', fmt='%-7.0f')\n savetxt(filepath_1, indices_1, delimiter=',', fmt='%-7.0f')\n return [X_training , y_training] , [X_test , y_test]\n\ndef generate_unsupervised_datasets(X, log_path, random, relative_test_size=0.05):\n filepath = log_path+'/test_indices_unlabeled'\n test_size = half_test_size = int((X.shape[0] * relative_test_size))\n X_training, X_test, indices = split_test_data(X, test_size, random, filepath)\n if(random):\n savetxt(filepath, indices, delimiter=',', fmt='%-7.0f')\n return X_training, X_test\n","repo_name":"caio-davi/gGAN","sub_path":"src/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"25990219076","text":"import requests\nimport json\nimport sys\nimport os\n\n\n# constants\n\ngqlUrl = \"https://gql.twitch.tv/gql\"\n\n\n# for whatever reason these arent unique to 1 person, grabbed from somewhere online\nclientId = \"\"\n\n\n# getVideoUrls constants\n\n# from what i can tell, this is some sort of unique instruction for getting clip information\nsha256HashClipUrl = \"9bfcc0177bffc730bd5a5a89005869d2773480cf1738c592143b5173634b7d15\"\nversionClipUrl = 1\noperationNameClipUrl = \"VideoAccessToken_Clip\"\n\n\n\n# what quality wish to return\nmaxQuality = \"\"\nminQuality = \"\"\n\n\nsha256HashTopClips = \"b73ad2bfaecfd30a9e6c28fada15bd97032c83ec77a0440766a56fe0bd632777\"\nversionTopClips = 1\noperationNameTopClips = \"ClipsCards__User\"\n\n\nlimitMax = 100\n\n\n\ndurations = [\"LAST_WEEK\", \"LAST_DAY\", \"LAST_MONTH\", \"ALL_TIME\"]\n\n\ndef getVideoUrls(slug):\n jsonRequest = {\n \"extensions\": {\n \"persistedQuery\": {\n \"sha256Hash\": sha256HashClipUrl, \n \"version\": versionClipUrl\n }\n }, \n \"operationName\": operationNameClipUrl, \n \"variables\": {\n \"slug\": slug\n }\n }\n\n response = requests.post(gqlUrl \\\n , data=json.dumps(jsonRequest), headers={'Client-ID': clientId})\n\n if (response.status_code == 200):\n response = response.json()\n \n \n maxFoundQuality = -1\n maxFoundQualityUrl = \"\"\n for x in range(0, len(response[\"data\"][\"clip\"][\"videoQualities\"])):\n\n \n\n clipQuality = response[\"data\"][\"clip\"][\"videoQualities\"][x][\"quality\"]\n \n\n if(clipQuality == maxQuality):\n return response[\"data\"][\"clip\"][\"videoQualities\"][x][\"sourceURL\"]\n\n elif int(clipQuality) > int(maxFoundQuality) and int(clipQuality) < int(maxQuality) and int(clipQuality) > int(minQuality):\n maxFoundQuality = clipQuality\n maxFoundQualityUrl = response[\"data\"][\"clip\"][\"videoQualities\"][x][\"sourceURL\"]\n\n\n if maxFoundQuality != -1 and maxFoundQualityUrl != \"\":\n print(\"returned max quality url\")\n return maxFoundQualityUrl\n else:\n print(\"error, statusCode = \" + response.status_code)\n\n \n \n return False \n\n\ndef getSlugs(channel, timeFilter, limit):\n jsonRequest = {\n \"operationName\": operationNameTopClips,\n \"variables\": {\n \"login\": channel,\n \"limit\": limit,\n \"criteria\": {\n \"filter\": timeFilter\n }\n },\n \"extensions\": {\n \"persistedQuery\": {\n \"version\": versionTopClips,\n \"sha256Hash\": sha256HashTopClips\n }\n }\n }\n\n\n response = requests.post(gqlUrl \\\n , data=json.dumps(jsonRequest), headers={'Client-ID': clientId})\n\n slugs = []\n if (response.status_code == 200):\n response = response.json()\n\n # print(json.dumps(response, sort_keys=True, indent=4))\n\n clips = response[\"data\"][\"user\"][\"clips\"][\"edges\"]\n \n for i in range(0, len(clips)):\n clipSlug = clips[i][\"node\"][\"slug\"]\n\n \n\n slugs.append(clipSlug)\n \n else:\n print(\"reponse code = \" + str(response.status_code))\n print(json.dumps(response.json(), sort_keys=True, indent=4))\n\n \n return slugs\n\n\ndef setSettings():\n \n\n with open('settings.json') as json_file:\n data = json.load(json_file)\n\n global clientId\n clientId = data[\"clientId\"]\n global maxQuality\n maxQuality = data[\"maxQuality\"]\n global minQuality\n minQuality = data[\"minQuality\"]\n\n\ndef downloadClips(videoUrls):\n \n\n for videoUrl in videoUrls:\n\n file_name = videoUrl.split('/')[-1] \n\n \n\n # create response object \n r = requests.get(videoUrl, stream = True) \n\n # download started \n print(os.getcwd())\n with open(os.getcwd()+\"/clips/\" + file_name, 'wb') as f: \n for chunk in r.iter_content(chunk_size = 1024*1024): \n if chunk: \n f.write(chunk) \n\n \n\n\n\n\ndef main():\n\n if(len(sys.argv) == 4):\n channel = sys.argv[1]\n duration = sys.argv[2]\n limit = int(sys.argv[3])\n\n if limit > limitMax:\n print(\"limit too high\")\n return\n\n durationFound = False\n for i in range(0, len(durations)):\n if(duration == durations[i]):\n durationFound = True\n break\n \n if durationFound == False:\n print(\"incorrect duration\")\n return\n\n else:\n print(\"too few arguments\")\n return\n\n\n setSettings()\n\n\n slugs = getSlugs(channel, duration, limit)\n\n \n videoUrls = []\n for i in range(0, len(slugs)):\n videoUrls.append(getVideoUrls(slugs[i]))\n \n print(videoUrls)\n\n downloadClips(videoUrls)\n\n\n \n\n \n\n \n\n \n\nmain()","repo_name":"johnslewis/TwitchClipDownloader","sub_path":"twitchClips.py","file_name":"twitchClips.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17688058716","text":"import urllib\nfrom bs4 import BeautifulSoup\nURL = \"https://en.wikipedia.org/wiki/List_of_beat_%27em_ups\"\nsource = urllib.request.urlopen(URL)\ndata = source.read().decode().strip()\nsoup = BeautifulSoup(data, 'html.parser')\nlist_games = soup.find_all('i')\nfor elem in list_games:\n for string in elem.parent.strings:\n print(string, end = \"\")\n print(\"\\n\")\n","repo_name":"DmytroIvakhnenkov/GamerSight","sub_path":"FetchingGameNames.py","file_name":"FetchingGameNames.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4356945785","text":"from bs4 import BeautifulSoup\nimport requests\nimport smtplib\nimport time\nimport datetime\nimport csv\n\nurl = \"https://www.amazon.in/SIDRUM-Shoulder-Adjustable-Compatible-Mirrorless/dp/B09P74TZY8/ref=sr_1_47?crid=2M096C61O4MLT&keywords=bags&qid=1675451564&sprefix=ba%2Caps%2C283&sr=8-47\"\n\n\nheaders = { \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\" }\n\npage = requests.get(url,headers=headers)\n\nsoup1 = BeautifulSoup(page.content,\"html.parser\")\n\nsoup2 = BeautifulSoup(soup1.prettify(),\"html.parser\")\ntitle = soup2.find(id=\"productTitle\").get_text().strip()\nprice = soup2.find(class_ = \"a-offscreen\").get_text().strip()\nrating = soup2.find(id = \"acrPopover\").get_text().strip()\nreviews = soup2.find(id = \"acrCustomerReviewText\").get_text().strip()\ndecription = soup2.find(id = \"feature-bullets\").get_text().strip()\nproduct = soup2.find(id = \"aplus_feature_div\").get_text().strip()\n# print(title.strip() )\n# print(price.strip())\n# print(rating.strip())\n# print(reviews.strip())\n# print(product.strip())\n\ndata = [url,title, price, rating,reviews,decription,product]\n\n# # Write the list to a CSV file\nwith open('product_data.csv', 'a', newline='',encoding=\"UTF8\") as file:\n writer = csv.writer(file)\n # writer.writerow([\"URL\",\"Title\", \"Price\",\"Rating\",\"Reviews\",\"DeSription\",\"Product\"]) \n writer.writerow(data)\n\n\n\n\n\n\n\n","repo_name":"ShriyanshiSharma/scrap","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15532930161","text":"def check_if_product_is_pos(n1, n2, n3):\n if (num1 < 0 and num2 > 0 and num3 > 0) \\\n or (num2 < 0 and num1 > 0 and num3 > 0) \\\n or (num3 < 0 and num1 > 0 and num2 > 0) \\\n or (num1 < 0 and num2 < 0 and num3 < 0): # all three are neg\n return \"negative\"\n elif num1 == 0 or num2 == 0 or num3 == 0:\n return \"zero\"\n else:\n return \"positive\"\n\n\nnum1 = int(input())\nnum2 = int(input())\nnum3 = int(input())\nprint(check_if_product_is_pos(num1, num2, num3))\n","repo_name":"karalkal/SoftUni_Python_Fundamentals","sub_path":"04_Functions/3_more_exercises/more5_multiplication_sign.py","file_name":"more5_multiplication_sign.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"45194707428","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sqlite3 as db\nimport sys\nimport utils\nfrom debug import *\n\nhelp_mes = \"./show.py [top_n, all by default]\"\n#may add find by string\n\ndef show(table_name, number = None):\n conn = db.connect('bookmarks.s3db')\n cur = conn.cursor()\n \n query = \"SELECT title, addit_info FROM {0} ORDER BY will DESC\".format(table_name)\n if not number is None:\n utils.validate(number)\n query += \" LIMIT {0}\".format(number)\n \n start_log()\n log_print(query)\n \n cur.execute(query)\n print(\"Your top currently:\\n\")\n for row in cur:\n print(row[0], row[1])\n #Verification of table name must be done outside\n conn.commit()\n conn.close()\n \nif __name__ == \"__main__\": \n cl_args = sys.argv[1:]\n length = len(cl_args)\n if length > 1:\n print(\"Wrong number of parameters\")\n quit()\n \n number = None\n if length:\n number = int(cl_args[0])\n #try\n show('films', number)\n #except\n #print possible reasons\n end_log()\n","repo_name":"GubanovSergey/Learning","sub_path":"bookmarks/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74448516003","text":"from shapeops import valid_shape_id\n\n\ndef read_input_file(filename):\n \"\"\"Read input file and populate a list of recognised pieces.\"\"\"\n\n # An empty list to contain our input numbers\n numbers = []\n\n # Open input file in read only mode\n with open(filename, 'r') as f:\n # Iterate through each line in the file\n for line in f:\n # Use list comprehension to filter only character digits\n # Then convert each character to an integer\n digitsonly = [int(char) for char in line if char.isdigit()]\n\n # Strip out zeros\n nozeros = [i for i in digitsonly if valid_shape_id(i)]\n\n # And add these numbers to the list\n numbers.extend(nozeros)\n\n return numbers\n\n\ndef write_output_file(filename, output):\n\n # Open output file in write mode\n with open(filename, 'wb') as f:\n f.write(output)\n","repo_name":"alexlouden/tetris-ai","sub_path":"fileops.py","file_name":"fileops.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7446623469","text":"from django.contrib import admin\nfrom .models import Country, State, City\n\n# Register your models here.\n\nclass StateAdminInine(admin.TabularInline):\n\tmodel = State\n\nclass CityAdminInline(admin.TabularInline):\n\tmodel = City\n\n@admin.register(Country)\nclass CountryAdmin(admin.ModelAdmin):\n\tlist_display = [\"id\",\"name\", \"slug\", \"created_time\"] \n\tlist_editable = (\"name\",\"slug\")\n\tinlines = [StateAdminInine]\n\n@admin.register(State)\nclass StateAdmin(admin.ModelAdmin):\n\tlist_display = [\"id\",\"name\", \"slug\", \"created_time\"] \n\tlist_editable = (\"name\",\"slug\")\n\tinlines = [CityAdminInline]\n\n@admin.register(City)\nclass CityAdmin(admin.ModelAdmin):\n\tlist_display = [\"id\",\"name\", \"slug\", \"created_time\"] \n\tlist_editable = (\"name\",\"slug\")\n","repo_name":"mehdi1361/E_Shop","sub_path":"location/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36093425901","text":"'''\nUseful functions for pext files.\n'''\nimport numpy as np;\nimport itertools as itools;\nimport numpy.lib.recfunctions as rfn;\n\ndef add_quantities(d, coords=None, massE=0.511e6):\n '''\n Add physically interesting quantities to\n pext data.\n\n Parameters:\n -----------\n d : pext array\n\n Keywords:\n ---------\n coords : sequence of positions for angle calculation. None\n or by default, calculate no angles.\n For 2D, takes the angle depending on the order passed,\n so this can be used for left-handed coordinate systems\n like LSP's xz.\n massE : rest mass energy of particles.\n Returns a copy with the quantities appended.\n '''\n keys,items = zip(*calc_quantities(d,coords=coords,massE=massE).items());\n return rfn.rec_append_fields(\n d, keys, items);\n\ndef calc_quantities(d, coords=None, massE=0.511e6):\n '''\n Calculate physically interesting quantities from pext\n\n Parameters:\n -----------\n d : pext array\n\n Keywords:\n ---------\n coords : sequence of positions for angle calculation. None\n or by default, calculate no angles.\n For 2D, takes the angle depending on the order passed,\n so this can be used for left-handed coordinate systems\n like LSP's xz.\n massE : rest mass energy of particles.\n Returns a dictionary of physical quantities.\n '''\n quants = dict();\n quants['u_norm'] = np.sqrt(d['ux']**2+d['uy']**2+d['uz']**2)\n quants['KE'] =(np.sqrt(quants['u_norm']**2+1)-1)*massE;\n coords[:] = ['u'+coord for coord in coords];\n if not coords:\n pass;\n elif len(coords) == 3:\n quants['theta'] = np.arccos(d[coords[2]]/quants['u_norm']);\n quants['phi'] = np.arctan2(d[coords[1]],d[coords[0]]);\n quants['phi_n'] = np.arctan2(d[coords[2]],d[coords[0]]);\n elif len(coords) == 2:\n quants['phi'] = np.arctan2(d[coords[1]],d[coords[0]]);\n return quants;\n","repo_name":"noobermin/lspreader","sub_path":"lspreader/pext.py","file_name":"pext.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2446556377","text":"from qcode.qcodeParser import qcodeParser\nfrom qcodeHandleUtils import qcodeFileManager\nfrom qcodeVisitorHandle import qcodeVisitorHandle\nimport string\n\n\n\n#CppParseTreeVisitor\nclass qcodeCppVisitorHandle(qcodeVisitorHandle):\n\n def __init__(self, fileManager:qcodeFileManager):\n self.fn = fileManager\n self.fn.createCppImport()\n\n self.inline_get = 0\n self.is_func_paras = 0#是否添加进函数参数\n self.func_paras = []#函数参数\n self.FUNCTION_RETURN_TYPE_DECLARATOR = None#返回类型\n self.GET_INSIDE_EXP = None#insert方法使用\n self.is_call_back_construct = 0\n self.qif_determine = {'is_fist_qif':0,'qif_parent_count':0,'qif_true_branch_name':'','qif_false_branch_name':'',\n 'qif_branch_name':''\\\n ,'qif_node_name':'','qif_parent_name':''}#qif语句判断使用\n self.qwhile_determine = {'is_fist_qwhile':0,'qwhile_parent_count':0,\n 'qif_false_branch_name':'',\n 'qwhile_branch_name':''\\\n ,'qwhile_parent_name':''}#qwhile语句判断使用\n self.qif_or_qwhile = 0 #qif为0qwhile为1\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.fn.createCppEnd()\n\n # Visit a parse tree produced by qcodeParser#declaration.\n def visitDeclaration(self, ctx:qcodeParser.DeclarationContext):\n if ctx.include_declaration() is not None:\n self.visitInclude_declaration(ctx.include_declaration())\n elif ctx.variable_declaration() is not None:\n self.visitVariable_declaration(ctx.variable_declaration())\n elif ctx.function_declaration() is not None:\n self.visitFunction_declaration(ctx.function_declaration())\n\n\n # Visit a parse tree produced by qcodeParser#include_declaration.\n def visitInclude_declaration(self, ctx:qcodeParser.Include_declarationContext):\n if ctx.INCLUDE() is not None:\n self.fn.write(str(ctx.INCLUDE()))\n self.visitInclude_sign(ctx.include_sign())\n self.visitSingle_expression(ctx.single_expression(),0)\n self.visitInclude_sign(ctx.include_sign())\n\n\n # Visit a parse tree produced by qcodeParser#include_sign.\n def visitInclude_sign(self, ctx:qcodeParser.Include_signContext):\n if ctx.getText() is not None:\n self.fn.write(str(ctx.getText()))\n\n\n # Visit a parse tree produced by qcodeParser#variable_declaration.\n def visitVariable_declaration(self, ctx:qcodeParser.Variable_declarationContext):\n if ctx.declaration_variable() is not None:\n self.visitDeclaration_variable(ctx.declaration_variable(),0)\n elif ctx.parameter_declaration() is not None:\n self.visitParameter_declaration(ctx.parameter_declaration())\n\n\n # Visit a parse tree produced by qcodeParser#parameter_declaration.\n def visitParameter_declaration(self, ctx:qcodeParser.Parameter_declarationContext):\n self.visitParameter_specifier(ctx.parameter_specifier())\n self.fn.createBlank()\n self.fn.write(str(ctx.Identifier()))\n if self.is_func_paras == 1:\n self.func_paras.append(str(ctx.Identifier()))\n\n\n # Visit a parse tree produced by qcodeParser#parameter_specifier.\n def visitParameter_specifier(self, ctx:qcodeParser.Parameter_specifierContext):\n if ctx.auxiliary_primary_type() is not None:\n self.visitAuxiliary_primary_type(ctx.auxiliary_primary_type())\n elif ctx.quantum_primary_type() is not None:\n self.visitQuantum_primary_type(ctx.quantum_primary_type())\n elif ctx.classical_primary_type() is not None:\n self.visitClassical_primary_type(ctx.classical_primary_type())\n elif ctx.array_construct_type() is not None:\n if ctx.array_construct_type().getText() == 'vector':\n self.fn.write('QVec')\n else:\n self.visitArray_construct_type(ctx.array_construct_type())\n elif ctx.call_back_construct_type() is not None:\n self.is_call_back_construct = 0\n self.visitCall_back_construct_type(ctx.call_back_construct_type())\n elif ctx.quantum_alg_built_in_type() is not None:\n self.visitQuantum_alg_built_in_type(ctx.quantum_alg_built_in_type())\n\n\n # Visit a parse tree produced by qcodeParser#quantum_alg_built_in_type.\n def visitQuantum_alg_built_in_type(self, ctx:qcodeParser.Quantum_alg_built_in_typeContext):\n if ctx.HAMILTONIAN() is not None:\n self.fn.write(str(ctx.HAMILTONIAN()))\n elif ctx.AVAR() is not None:\n self.fn.write(str(ctx.AVAR()))\n\n\n\n # Visit a parse tree produced by qcodeParser#auxiliary_primary_type.\n def visitAuxiliary_primary_type(self, ctx:qcodeParser.Auxiliary_primary_typeContext):\n if ctx.INT() is not None:\n self.fn.write(str(ctx.INT()))\n self.fn.createBlank()\n elif ctx.DOUBLE() is not None:\n self.fn.write(str(ctx.DOUBLE()))\n self.fn.createBlank()\n elif ctx.BOOL() is not None:\n self.fn.write(str(ctx.BOOL()))\n self.fn.createBlank()\n\n\n # Visit a parse tree produced by qcodeParser#quantum_circuit_type.\n def visitQuantum_circuit_type(self, ctx:qcodeParser.Quantum_circuit_typeContext):\n if ctx.CIRCUIT() is not None:\n self.FUNCTION_RETURN_TYPE_DECLARATOR = 'circuit'\n self.fn.write('QCircuit ')\n elif ctx.VARIATIONALCIRCUIT() is not None:\n self.FUNCTION_RETURN_TYPE_DECLARATOR = 'variationalCircuit'\n self.fn.write(str(ctx.VARIATIONALCIRCUIT()))\n\n\n # Visit a parse tree produced by qcodeParser#quantum_prog_type.\n def visitQuantum_prog_type(self, ctx:qcodeParser.Quantum_prog_typeContext):\n if ctx.QPROG() is not None:\n self.fn.write(str(ctx.QPROG()))\n\n\n # Visit a parse tree produced by qcodeParser#quantum_primary_type.\n def visitQuantum_primary_type(self, ctx:qcodeParser.Quantum_primary_typeContext):\n if ctx.QUBIT() is not None:\n self.fn.write('Qubit* ')\n\n\n # Visit a parse tree produced by qcodeParser#classical_primary_type.\n def visitClassical_primary_type(self, ctx:qcodeParser.Classical_primary_typeContext):\n if ctx.CBIT() is not None:\n self.fn.write('ClassicalCondition')\n\n # Visit a parse tree produced by qcodeParser#array_construct_type.\n def visitArray_construct_type(self, ctx:qcodeParser.Array_construct_typeContext):\n if ctx.VECTOR() is not None:\n self.fn.write(str(ctx.VECTOR()))\n self.fn.write(str(ctx.LT()))\n self.visitConstruct_primary_type(ctx.construct_primary_type())\n self.fn.write(str(ctx.GT()))\n self.fn.createBlank()\n elif ctx.MAP() is not None:\n self.fn.write(str(ctx.MAP()))\n self.fn.createBlank()\n\n\n # Visit a parse tree produced by qcodeParser#construct_primary_type.\n def visitConstruct_primary_type(self, ctx:qcodeParser.Construct_primary_typeContext):\n if ctx.auxiliary_primary_type() is not None:\n self.visitAuxiliary_primary_type(ctx.auxiliary_primary_type())\n elif ctx.quantum_primary_type() is not None:\n self.visitQuantum_primary_type(ctx.quantum_primary_type())\n elif ctx.classical_primary_type() is not None:\n self.visitClassical_primary_type(ctx.classical_primary_type())\n elif ctx.MAP() is not None:\n self.fn.write(str(ctx.MAP()))\n\n\n # Visit a parse tree produced by qcodeParser#call_back_construct_type.\n def visitCall_back_construct_type(self, ctx:qcodeParser.Call_back_construct_typeContext):\n if self.is_call_back_construct == 1:\n self.fn.write('using QGEN = ')\n self.fn.write('Oracle')\n self.fn.write('<')\n self.visitCall_back_primary_type_list(ctx.call_back_primary_type_list())\n self.fn.write('>;')\n self.fn.createline()\n self.fn.createline()\n self.fn.createline()\n self.fn.write('QGEN ')\n\n else:\n self.fn.write('QCircuit')\n self.visitCall_back_primary_type_list(ctx.call_back_primary_type_list())\n self.fn.write(str(ctx.GT()))\n # Visit a parse tree produced by qcodeParser#call_back_primary_type_list.\n def visitCall_back_primary_type_list(self, ctx:qcodeParser.Call_back_primary_type_listContext):\n if ctx.call_back_primary_type_list() is not None:\n self.visitCall_back_primary_type_list(ctx.call_back_primary_type_list())\n self.fn.write(str(ctx.COMMA()))\n self.visitCall_back_primary_type(ctx.call_back_primary_type())\n else:\n self.visitCall_back_primary_type(ctx.call_back_primary_type())\n\n # Visit a parse tree produced by qcodeParser#call_back_primary_type.\n def visitCall_back_primary_type(self, ctx:qcodeParser.Call_back_primary_typeContext):\n if ctx.auxiliary_primary_type() is not None:\n self.visitAuxiliary_primary_type(ctx.auxiliary_primary_type())\n elif ctx.quantum_primary_type() is not None:\n self.visitQuantum_primary_type(ctx.quantum_primary_type())\n elif ctx.classical_primary_type() is not None:\n self.visitClassical_primary_type(ctx.classical_primary_type())\n elif ctx.array_construct_type() is not None:\n if ctx.array_construct_type().getText() == 'vector':\n self.fn.write('QVec')\n else:\n self.visitArray_construct_type(ctx.array_construct_type())\n elif ctx.call_back_construct_type() is not None:\n self.is_call_back_construct = 0\n self.visitCall_back_construct_type(ctx.call_back_construct_type())#+++\n\n\n # Visit a parse tree produced by qcodeParser#declaration_variable.\n def visitDeclaration_variable(self, ctx:qcodeParser.Declaration_variableContext,scope_ident):\n ident = scope_ident\n self.visitVariable_decl_specifier(ctx.variable_decl_specifier())\n self.visitInit_declaratorlist(ctx.init_declaratorlist(),ident)\n self.fn.write(str(ctx.SEMI()))\n\n\n # Visit a parse tree produced by qcodeParser#variable_decl_specifier.\n def visitVariable_decl_specifier(self, ctx:qcodeParser.Variable_decl_specifierContext):\n if ctx.common_specifier() is not None:\n self.visitCommon_specifier(ctx.common_specifier())\n elif ctx.array_construct_type() is not None:\n if ctx.array_construct_type().getText() == 'vector':\n self.fn.write('QVec ')\n else:\n self.visitArray_construct_type(ctx.array_construct_type())\n\n\n # Visit a parse tree produced by qcodeParser#common_specifier.\n def visitCommon_specifier(self, ctx:qcodeParser.Common_specifierContext):\n self.fn.write('auto ')\n\n\n\n # Visit a parse tree produced by qcodeParser#init_declaratorlist.\n def visitInit_declaratorlist(self, ctx:qcodeParser.Init_declaratorlistContext,scope_ident):\n ident = scope_ident\n if ctx.variable_declarator() is not None:\n if ctx.init_declaratorlist() is not None:\n self.visitInit_declaratorlist(ctx.init_declaratorlist(),ident)\n self.fn.write(str(ctx.COMMA()))\n self.visitVariable_declarator(ctx.variable_declarator(),ident)\n else:\n self.visitVariable_declarator(ctx.variable_declarator(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#variable_declarator.\n def visitVariable_declarator(self, ctx:qcodeParser.Variable_declaratorContext,scope_ident):\n ident = scope_ident\n # self.fn.createIdent(ident)\n self.fn.write(str(ctx.Identifier()))\n if ctx.ASSIGN() is not None:\n self.fn.write(str(ctx.ASSIGN()))\n self.visitVariableInitializer(ctx.variableInitializer(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#variableInitializer.\n def visitVariableInitializer(self, ctx:qcodeParser.VariableInitializerContext,scope_ident):\n ident = scope_ident\n if ctx.single_expression() is not None:\n if ctx.variableInitializer() is not None:\n self.visitVariableInitializer(ctx.variableInitializer(),ident)\n self.fn.write(str(ctx.COMMA()))\n self.visitSingle_expression(ctx.single_expression(),ident)\n else:\n self.visitSingle_expression(ctx.single_expression(),ident)\n\n\n\n # Visit a parse tree produced by qcodeParser#function_declaration.\n def visitFunction_declaration(self, ctx:qcodeParser.Function_declarationContext):\n self.visitDeclarate_function(ctx.declarate_function())\n self.fn.write(str(ctx.SEMI()))\n\n\n # Visit a parse tree produced by qcodeParser#declarate_function.\n def visitDeclarate_function(self, ctx:qcodeParser.Declarate_functionContext):\n if ctx.function_return_type_declarator() is not None:\n self.visitFunction_return_type_declarator(ctx.function_return_type_declarator())\n if self.is_call_back_construct == 1:\n self.is_func_paras = 1\n self.visitFunction_declarator(ctx.function_declarator())\n self.fn.write(';')\n self.fn.createline()\n self.fn.createline()\n self.fn.write('QGEN ')\n else:\n self.fn.write('QProg ')\n self.is_func_paras = 0\n self.visitFunction_declarator(ctx.function_declarator())\n\n # Visit a parse tree produced by qcodeParser#function_return_type_declarator.\n def visitFunction_return_type_declarator(self, ctx:qcodeParser.Function_return_type_declaratorContext):\n if ctx.quantum_prog_type() is not None:\n self.FUNCTION_RETURN_TYPE_DECLARATOR = 'quantum_prog'\n self.visitQuantum_prog_type(ctx.quantum_prog_type())\n elif ctx.quantum_circuit_type() is not None:\n self.visitQuantum_circuit_type(ctx.quantum_circuit_type())\n elif ctx.auxiliary_primary_type() is not None:\n self.FUNCTION_RETURN_TYPE_DECLARATOR = 'auxiliary'\n self.visitAuxiliary_primary_type(ctx.auxiliary_primary_type())\n elif ctx.classical_primary_type() is not None:\n self.FUNCTION_RETURN_TYPE_DECLARATOR = 'classical'\n self.visitClassical_primary_type(ctx.classical_primary_type())\n elif ctx.array_construct_type() is not None:\n self.FUNCTION_RETURN_TYPE_DECLARATOR = 'array'\n if ctx.array_construct_type().getText() == 'vector':\n self.fn.write('QVec')\n else:\n self.visitArray_construct_type(ctx.array_construct_type())\n elif ctx.call_back_construct_type() is not None:\n self.is_call_back_construct = 1\n self.FUNCTION_RETURN_TYPE_DECLARATOR = 'call_back_construct'\n self.visitCall_back_construct_type(ctx.call_back_construct_type())\n\n\n # Visit a parse tree produced by qcodeParser#function_declarator.\n def visitFunction_declarator(self, ctx:qcodeParser.Function_declaratorContext):\n self.visitFunction_name(ctx.function_name())\n self.fn.write(str(ctx.LPAREN()))\n self.visitParameter_decl_list(ctx.parameter_decl_list())\n self.fn.write(str(ctx.RPAREN()))\n\n\n\n\n # Visit a parse tree produced by qcodeParser#function_name.\n def visitFunction_name(self, ctx:qcodeParser.Function_nameContext):\n self.fn.write(str(ctx.Identifier()))\n\n\n # Visit a parse tree produced by qcodeParser#parameter_decl_list.\n def visitParameter_decl_list(self, ctx:qcodeParser.Parameter_decl_listContext):\n if ctx.parameter_declaration() is not None:\n if ctx.parameter_decl_list() is not None:\n self.visitParameter_decl_list(ctx.parameter_decl_list())\n self.fn.write(str(ctx.COMMA()))\n self.visitParameter_declaration(ctx.parameter_declaration())\n else:\n self.visitParameter_declaration(ctx.parameter_declaration())\n\n\n\n # Visit a parse tree produced by qcodeParser#expression_list.\n def visitExpression_list(self, ctx:qcodeParser.Expression_listContext,scope_ident):\n ident = scope_ident\n if ctx.single_expression() is not None:\n if ctx.expression_list() is not None:\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(str(ctx.COMMA()))\n self.visitSingle_expression(ctx.single_expression(),ident)\n # Visit a parse tree produced by qcodeParser#vector_expression.\n def visitVector_expression(self, ctx:qcodeParser.Vector_expressionContext,scope_ident):\n ident = scope_ident\n if ctx.single_expression() is not None:\n self.visitSingle_expression(ctx.single_expression(),ident)\n elif ctx.vector_slice() is not None:\n self.visitVector_slice(ctx.vector_slice(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#vector_slice.\n def visitVector_slice(self, ctx:qcodeParser.Vector_sliceContext,scope_ident):\n ident = scope_ident\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(',')\n self.visitSingle_expression(ctx.single_expression(1),ident)\n\n\n # Visit a parse tree produced by qcodeParser#single_expression.\n def visitSingle_expression(self, ctx:qcodeParser.Single_expressionContext,scope_ident):\n ident = scope_ident\n if list == type(ctx.single_expression()):\n if 2 == len(ctx.single_expression()):\n if ctx.DOT() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(str(ctx.DOT()))\n self.visitSingle_expression(ctx.single_expression(1),ident)\n\n elif ctx.multiplicative_op() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.visitMultiplicative_op(ctx.multiplicative_op())\n self.visitSingle_expression(ctx.single_expression(1),ident)\n elif ctx.additive_op() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.visitAdditive_op(ctx.additive_op())\n self.visitSingle_expression(ctx.single_expression(1),ident)\n elif ctx.shift_op() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.visitShift_op(ctx.shift_op())\n self.visitSingle_expression(ctx.single_expression(1),ident)\n elif ctx.relationship_op() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.visitRelationship_op(ctx.relationship_op())\n self.visitSingle_expression(ctx.single_expression(1),ident)\n elif ctx.equal_op() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.createBlank()\n self.visitEqual_op(ctx.equal_op())\n self.visitSingle_expression(ctx.single_expression(1),ident)\n self.fn.createBlank()\n elif ctx.logic_op() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.visitLogic_op(ctx.logic_op())\n self.visitSingle_expression(ctx.single_expression(1),ident)\n elif ctx.QUE_MARK() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(str(ctx.QUE_MARK()))\n self.visitSingle_expression(ctx.single_expression(1),ident)\n self.fn.write(str(ctx.COLON()))\n self.visitSingle_expression(ctx.single_expression(2),ident)\n elif ctx.assign_op() is not None:\n # self.fn.createIdent(ident)\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.visitAssign_op(ctx.assign_op())\n self.visitSingle_expression(ctx.single_expression(1),ident)\n\n\n elif 1 == len(ctx.single_expression()):\n if ctx.LBRACK() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(str(ctx.LBRACK()))\n self.visitVector_expression(ctx.vector_expression(),ident)\n self.fn.write(str(ctx.RBRACK()))\n elif ctx.LPAREN() is not None:\n print(ctx.function_call_exp.getText()[-6:])\n if ctx.function_call_exp.getText()[-5:] == '.size':\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(str(ctx.LPAREN()))\n if ctx.expression_list() is not None:\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(str(ctx.RPAREN()))\n elif ctx.function_call_exp.getText()[-7:] == '.length':\n self.fn.write(ctx.function_call_exp.getText()[:-7]+'.size')\n self.fn.write(str(ctx.LPAREN()))\n if ctx.expression_list() is not None:\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(str(ctx.RPAREN()))\n elif ctx.function_call_exp.getText()[-4:] == '.add':\n self.fn.write(ctx.function_call_exp.getText()[:-4]+'.push_back')\n self.fn.write(str(ctx.LPAREN()))\n if ctx.expression_list() is not None:\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(str(ctx.RPAREN()))\n elif ctx.function_call_exp.getText()[-7:] == '.append':\n self.fn.write(ctx.function_call_exp.getText()[:-7]+'.push_back')\n self.fn.write(str(ctx.LPAREN()))\n if ctx.expression_list() is not None:\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(str(ctx.RPAREN()))\n elif ctx.function_call_exp.getText()[-7:] == '.insert':\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(str(ctx.LPAREN()))\n if ctx.expression_list() is not None:\n new_str = ctx.expression_list().getText()\n str_arr = new_str.split(',')\n func_name = new_str[0]\n self.fn.write(ctx.function_call_exp.get_inside_exp.getText() + '.begin(), ')\n self.fn.write(func_name + '.begin()+'+ str_arr[1] + ', ')\n self.fn.write(func_name + '.begin()+'+ str_arr[2] + ')')\n elif ctx.function_call_exp.getText()[-7:] == '.dagger':\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write('()')\n elif ctx.function_call_exp.getText()[-9:] == '.getFirst':\n self.fn.write(ctx.function_call_exp.getText()[:-9]+'.fist')\n elif ctx.function_call_exp.getText()[-10:] == '.getSecond':\n self.fn.write(ctx.function_call_exp.getText()[:-10]+'.second')\n elif ctx.function_call_exp.getText()[-6:] == '.first':\n self.visitSingle_expression(ctx.single_expression(0),ident)\n elif ctx.function_call_exp.getText()[-7:] == '.second':\n self.visitSingle_expression(ctx.single_expression(0),ident)\n elif ctx.function_call_exp.getText()[-7:] == '.remove':\n self.fn.write(ctx.function_call_exp.getText()[:-7]+'.erase')\n self.fn.write(str(ctx.LPAREN()))\n if ctx.expression_list() is not None:\n new_str = ctx.expression_list().getText()\n str_arr = new_str.split(',')\n self.fn.write(ctx.function_call_exp.get_inside_exp.getText() + '.begin()+' + str_arr[0] + ', ')\n self.fn.write(ctx.function_call_exp.get_inside_exp.getText()+ '.begin()+' + str_arr[0] + '+1)')\n else:\n if self.inline_get==0:\n if self.qif_determine['is_fist_qif'] > 0 or self.qwhile_determine['is_fist_qwhile'] > 0:\n if self.qif_or_qwhile == 0:\n self.fn.write(self.qif_determine['qif_branch_name']+' << ')\n elif self.qif_or_qwhile == 1:\n self.fn.write(self.qwhile_determine['qwhile_branch_name']+' << ')\n else:\n if self.FUNCTION_RETURN_TYPE_DECLARATOR == 'circuit' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'call_back_construct' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'variationalCircuit':\n self.fn.write('qCircuit << ')\n elif self.FUNCTION_RETURN_TYPE_DECLARATOR == 'quantum_prog' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR is None:\n self.fn.write('prog << ')\n self.inline_get = 1\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.inline_get = 0\n else:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n if ctx.expression_list() is not None:\n self.fn.write(str(ctx.LPAREN()))\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(')')\n\n\n\n elif ctx.INC() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(str(ctx.INC()))\n elif ctx.DEC() is not None:\n self.visitSingle_expression(ctx.single_expression(0),ident)\n self.fn.write(str(ctx.DEC()))\n elif ctx.unary_op() is not None:\n self.visitUnary_op(ctx.unary_op())\n self.visitSingle_expression(ctx.single_expression(0),ident)\n\n\n else:\n if ctx.LBRACK() is not None:\n self.fn.write(str(ctx.LBRACK()))\n if ctx.expression_list() is not None:\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(str(ctx.RBRACK()))\n elif ctx.LPAREN() is not None:\n self.fn.write(str(ctx.LPAREN()))\n if ctx.expression_list() is not None:\n self.visitExpression_list(ctx.expression_list(),ident)\n self.fn.write(str(ctx.RPAREN()))\n elif ctx.lambda_exp() is not None:\n self.visitLambda_exp(ctx.lambda_exp())\n elif ctx.Identifier() is not None:\n identifierText = str(ctx.Identifier())\n self.fn.write(identifierText)\n elif ctx.constant() is not None:\n self.visitConstant(ctx.constant())\n elif ctx.key_words() is not None:\n self.visitKey_words(ctx.key_words())\n elif ctx.PI() is not None:\n self.fn.write('3.14159265358979')\n\n\n # Visit a parse tree produced by qcodeParser#lambda_exp.\n def visitLambda_exp(self, ctx:qcodeParser.Lambda_expContext):\n if ctx.LAMBDA() is not None:\n self.fn.write('[')\n func_paras_str = ''\n for parameters in self.func_paras:\n func_paras_str+=','+parameters\n func_paras_str = func_paras_str.strip(string.punctuation)\n self.fn.write(func_paras_str)\n self.fn.write(']')\n self.fn.write(str(ctx.LPAREN()))\n self.visitParameter_decl_list(ctx.parameter_decl_list())\n self.fn.write(str(ctx.RPAREN()))\n self.visitLambda_body(ctx.lambda_body())\n\n\n\n # Visit a parse tree produced by qcodeParser#lambda_body.\n def visitLambda_body(self, ctx:qcodeParser.Lambda_bodyContext):\n ident = 1\n self.fn.write('{')\n self.fn.createline()\n self.fn.createIdent(2)\n if self.FUNCTION_RETURN_TYPE_DECLARATOR == 'call_back_construct':\n self.fn.write('QCircuit qCircuit;')\n self.visitCompound_statement(ctx.compound_statement(),ident)\n self.fn.createline()\n self.fn.createIdent(2)\n self.fn.write('return qCircuit;')\n self.fn.createLineTab()\n self.fn.write('}')\n\n # Visit a parse tree produced by qcodeParser#additive_op.\n def visitAdditive_op(self, ctx:qcodeParser.Additive_opContext):\n if ctx.SUB() is not None:\n self.fn.write(str(ctx.SUB()))\n elif ctx.ADD() is not None:\n self.fn.write(str(ctx.ADD()))\n\n\n # Visit a parse tree produced by qcodeParser#multiplicative_op.\n def visitMultiplicative_op(self, ctx:qcodeParser.Multiplicative_opContext):\n if ctx.MUL() is not None:\n self.fn.write(str(ctx.MUL()))\n elif ctx.DIV() is not None:\n self.fn.write(str(ctx.DIV()))\n elif ctx.MOD() is not None:\n self.fn.write(str(ctx.MOD()))\n\n # Visit a parse tree produced by qcodeParser#shift_op.\n def visitShift_op(self, ctx:qcodeParser.Shift_opContext):\n if ctx.SHIFT_LEFT() is not None:\n self.fn.write(str(ctx.SHIFT_LEFT()))\n elif ctx.SHIFT_RIGHT() is not None:\n self.fn.write(str(ctx.SHIFT_RIGHT()))\n\n\n # Visit a parse tree produced by qcodeParser#assign_op.\n def visitAssign_op(self, ctx:qcodeParser.Assign_opContext):\n if ctx.ASSIGN() is not None:\n self.fn.write(str(ctx.ASSIGN()))\n elif ctx.ADD_ASSIGN() is not None:\n self.fn.write(str(ctx.ADD_ASSIGN()))\n elif ctx.SUB_ASSIGN() is not None:\n self.fn.write(str(ctx.SUB_ASSIGN()))\n elif ctx.MUL_ASSIGN() is not None:\n self.fn.write(str(ctx.MUL_ASSIGN()))\n elif ctx.DIV_ASSIGN() is not None:\n self.fn.write(str(ctx.DIV_ASSIGN()))\n elif ctx.MOD_ASSIGN() is not None:\n self.fn.write(str(ctx.MOD_ASSIGN()))\n\n\n # Visit a parse tree produced by qcodeParser#equal_op.\n def visitEqual_op(self, ctx:qcodeParser.Equal_opContext):\n if ctx.EQUAL() is not None:\n self.fn.createBackSpace(str(ctx.EQUAL()))\n elif ctx.NOTEQUAL() is not None:\n self.fn.createBackSpace(str(ctx.NOTEQUAL()))\n\n\n # Visit a parse tree produced by qcodeParser#relationship_op.\n def visitRelationship_op(self, ctx:qcodeParser.Relationship_opContext):\n if ctx.LT() is not None:\n self.fn.write(str(ctx.LT()))\n elif ctx.LE() is not None:\n self.fn.write(str(ctx.LE()))\n elif ctx.GT() is not None:\n self.fn.write(str(ctx.GT()))\n elif ctx.GE() is not None:\n self.fn.write(str(ctx.GE()))\n\n\n # Visit a parse tree produced by qcodeParser#logic_op.\n def visitLogic_op(self, ctx:qcodeParser.Logic_opContext):\n if ctx.LOGIC_AND() is not None:\n self.fn.createBackSpace(str(ctx.LOGIC_AND()))\n elif ctx.LOGIC_OR() is not None:\n self.fn.createBackSpace(str(ctx.LOGIC_OR() ))\n\n\n # Visit a parse tree produced by qcodeParser#unary_op.\n def visitUnary_op(self, ctx:qcodeParser.Unary_opContext):\n if ctx.TILDE() is not None:\n self.fn.write(str(ctx.TILDE()))\n elif ctx.BANG() is not None:\n self.fn.write(str(ctx.BANG()))\n elif ctx.INC() is not None:\n self.fn.write(str(ctx.INC()))\n elif ctx.DEC() is not None:\n self.fn.write(str(ctx.DEC()))\n elif ctx.SUB() is not None:\n self.fn.write(str(ctx.SUB()))\n\n\n # Visit a parse tree produced by qcodeParser#statement.\n def visitStatement(self, ctx:qcodeParser.StatementContext,scope_ident):\n ident = scope_ident\n if ctx.expression_statement() is not None:\n self.visitExpression_statement(ctx.expression_statement(),ident)\n elif ctx.empty_statement() is not None:\n self.visitEmpty_statement(ctx.empty_statement(),ident)\n elif ctx.declaration_variable_statement() is not None:\n self.visitDeclaration_variable_statement(ctx.declaration_variable_statement(),ident)\n elif ctx.compound_statement() is not None:\n self.visitCompound_statement(ctx.compound_statement(),ident)\n elif ctx.select_statement() is not None:\n ident += 1\n self.visitSelect_statement(ctx.select_statement(),ident)\n ident -= 1\n elif ctx.iterate_statement() is not None:\n ident += 1\n self.visitIterate_statement(ctx.iterate_statement(),ident)\n ident += 1\n elif ctx.qif_statement() is not None:\n self.visitQif_statement(ctx.qif_statement(),ident)\n elif ctx.qwhile_statement() is not None:\n self.visitQwhile_statement(ctx.qwhile_statement(),ident)\n elif ctx.return_statement() is not None:\n self.visitReturn_statement(ctx.return_statement(),ident)\n\n\n\n # Visit a parse tree produced by qcodeParser#return_statement.\n def visitReturn_statement(self, ctx:qcodeParser.Return_statementContext,scope_ident):\n ident = scope_ident\n self.fn.createBackSpace(str(ctx.RETURN()))\n self.visitStatement(ctx.statement(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#qif_statement.\n def visitQif_statement(self, ctx:qcodeParser.Qif_statementContext,scope_ident):\n ident = scope_ident\n if ctx.QELSE() is not None:\n is_fist_qif = self.qif_determine['is_fist_qif']\n\n qif_parent_name = self.qif_determine['qif_parent_name']\n qwhile_parent_name = self.qwhile_determine['qwhile_parent_name']\n if qwhile_parent_name != '' :\n qif_parent_name = qwhile_parent_name\n if qif_parent_name == '':\n if self.FUNCTION_RETURN_TYPE_DECLARATOR == 'circuit' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'call_back_construct' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'variationalCircuit':\n qif_parent_name = 'qCircuit'\n elif self.FUNCTION_RETURN_TYPE_DECLARATOR == 'quantum_prog' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR is None:\n qif_parent_name = 'prog'\n\n if is_fist_qif==0:\n self.qif_determine['qif_parent_count'] = self.qif_determine['qif_parent_count']+1\n self.qif_determine['qif_true_branch_name']= 'qif_true_branch'+str(self.qif_determine['qif_parent_count'])\n self.qif_determine['qif_false_branch_name']= 'qif_false_branch'+str(self.qif_determine['qif_parent_count'])\n self.qif_determine['qif_node_name']= 'qif_node_prog'+str(self.qif_determine['qif_parent_count'])\n else:\n self.qif_determine['qif_true_branch_name'] = self.qif_determine['qif_true_branch_name']+'_1'\n self.qif_determine['qif_false_branch_name'] = self.qif_determine['qif_false_branch_name']+'_1'\n self.qif_determine['qif_node_name'] = self.qif_determine['qif_node_name']+'_1'\n\n qif_true_branch_name = self.qif_determine['qif_true_branch_name']\n self.qif_determine['qif_parent_name'] = qif_true_branch_name\n self.qif_determine['qif_branch_name'] = qif_true_branch_name\n qif_node_name = self.qif_determine['qif_node_name']\n self.fn.write('QProg '+qif_true_branch_name+' = CreateEmptyQProg();')\n self.visitQif_true_branch(ctx.qif_true_branch(),ident)\n\n self.fn.createline()\n self.fn.createIdent(ident+1)\n qif_false_branch_name = self.qif_determine['qif_false_branch_name']\n self.qif_determine['qif_parent_name'] = qif_false_branch_name\n self.qif_determine['qif_branch_name'] = qif_false_branch_name\n self.fn.write('QProg '+qif_false_branch_name+' = CreateEmptyQProg();')\n self.visitQif_false_branch(ctx.qif_false_branch(),ident)\n\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.fn.write('QIfProg '+qif_node_name+' = CreateIfProg(')\n self.visitSingle_expression(ctx.single_expression(),ident)\n self.fn.write(',' +qif_true_branch_name+',' +qif_false_branch_name+');')\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.fn.write(qif_parent_name+' << '+qif_node_name+';')\n\n\n\n\n else:\n is_fist_qif = self.qif_determine['is_fist_qif']\n\n qif_parent_name = self.qif_determine['qif_parent_name']\n qwhile_parent_name = self.qwhile_determine['qwhile_parent_name']\n if qwhile_parent_name != '' :\n qif_parent_name = qwhile_parent_name\n if qif_parent_name == '':\n if self.FUNCTION_RETURN_TYPE_DECLARATOR == 'circuit' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'call_back_construct' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'variationalCircuit':\n qif_parent_name = 'qCircuit'\n elif self.FUNCTION_RETURN_TYPE_DECLARATOR == 'quantum_prog' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR is None:\n qif_parent_name = 'prog'\n\n if is_fist_qif==0:\n self.qif_determine['qif_parent_count'] = self.qif_determine['qif_parent_count']+1\n self.qif_determine['qif_true_branch_name']= 'qif_true_branch'+str(self.qif_determine['qif_parent_count'])\n self.qif_determine['qif_false_branch_name']= 'qif_false_branch'+str(self.qif_determine['qif_parent_count'])\n self.qif_determine['qif_node_name']= 'qif_node_prog'+str(self.qif_determine['qif_parent_count'])\n else:\n self.qif_determine['qif_true_branch_name'] = self.qif_determine['qif_true_branch_name']+'_1'\n self.qif_determine['qif_false_branch_name'] = self.qif_determine['qif_false_branch_name']+'_1'\n self.qif_determine['qif_node_name'] = self.qif_determine['qif_node_name']+'_1'\n\n qif_true_branch_name = self.qif_determine['qif_true_branch_name']\n self.qif_determine['qif_parent_name'] = qif_true_branch_name\n self.qif_determine['qif_branch_name'] = qif_true_branch_name\n qif_node_name = self.qif_determine['qif_node_name']\n self.fn.write('QProg '+qif_true_branch_name+' = CreateEmptyQProg();')\n\n self.visitQif_true_branch(ctx.qif_true_branch(),ident)\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.fn.write('QIfProg '+qif_node_name+' = CreateIfProg(')\n self.visitSingle_expression(ctx.single_expression(),ident)\n self.fn.write(',' +qif_true_branch_name+');')\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.fn.write(qif_parent_name+' << '+qif_node_name+';')\n self.qif_determine['qif_parent_name'] = ''\n # Visit a parse tree produced by qcodeParser#qif_true_branch.\n def visitQif_true_branch(self, ctx:qcodeParser.Qif_true_branchContext,scope_ident):\n ident = scope_ident\n self.qif_or_qwhile = 0\n self.qif_determine['is_fist_qif'] = self.qif_determine['is_fist_qif'] + 1\n self.visitStatement_list(ctx.statement_list(),ident)\n self.qif_determine['is_fist_qif'] = self.qif_determine['is_fist_qif'] - 1\n\n # Visit a parse tree produced by qcodeParser#qif_false_branch.\n def visitQif_false_branch(self, ctx:qcodeParser.Qif_false_branchContext,scope_ident):\n ident = scope_ident\n self.qif_or_qwhile = 0\n self.qif_determine['is_fist_qif'] = self.qif_determine['is_fist_qif'] + 1\n self.visitStatement_list(ctx.statement_list(),ident)\n self.qif_determine['is_fist_qif'] = self.qif_determine['is_fist_qif'] - 1\n\n # Visit a parse tree produced by qcodeParser#qwhile_statement.\n def visitQwhile_statement(self, ctx:qcodeParser.Qwhile_statementContext,scope_ident):\n ident = scope_ident\n is_fist_qwhile = self.qwhile_determine['is_fist_qwhile']\n qwhile_parent_name = self.qwhile_determine['qwhile_parent_name']\n qif_parent_name = self.qif_determine['qif_parent_name']\n if qif_parent_name != '' :\n qwhile_parent_name = qif_parent_name\n if qwhile_parent_name == '':\n if self.FUNCTION_RETURN_TYPE_DECLARATOR == 'circuit' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'call_back_construct' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR == 'variationalCircuit':\n qwhile_parent_name = 'qCircuit'\n elif self.FUNCTION_RETURN_TYPE_DECLARATOR == 'quantum_prog' or \\\n self.FUNCTION_RETURN_TYPE_DECLARATOR is None:\n qwhile_parent_name = 'prog'\n\n if is_fist_qwhile==0:\n self.qwhile_determine['qwhile_parent_count'] = self.qwhile_determine['qwhile_parent_count']+1\n self.qwhile_determine['qwhile_branch_name'] = 'qwhile_branch_prog'+str(self.qwhile_determine['qwhile_parent_count'])\n self.qwhile_determine['qwhile_node_name']= 'qwhile_node_prog'+str(self.qwhile_determine['qwhile_parent_count'])\n else:\n self.qwhile_determine['qwhile_branch_name'] = self.qwhile_determine['qwhile_branch_name']+'_1'\n self.qwhile_determine['qwhile_node_name']= self.qwhile_determine['qwhile_node_name']+'_1'\n qwhile_branch_name = self.qwhile_determine['qwhile_branch_name']\n self.qwhile_determine['qwhile_parent_name'] = qwhile_branch_name\n qwhile_node_name = self.qwhile_determine['qwhile_node_name']\n self.fn.write('QProg '+qwhile_branch_name+' = CreateEmptyQProg();')\n self.qif_or_qwhile = 1\n self.qwhile_determine['is_fist_qwhile'] = self.qwhile_determine['is_fist_qwhile'] + 1\n self.visitStatement_list(ctx.statement_list(),ident)\n self.qwhile_determine['is_fist_qwhile'] = self.qwhile_determine['is_fist_qwhile'] - 1\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.fn.write('auto '+qwhile_node_name+' = CreateWhileProg(')\n self.visitSingle_expression(ctx.single_expression(),ident)\n self.fn.write(',' +qwhile_branch_name+');')\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.fn.write(qwhile_parent_name+' << '+qwhile_node_name+';')\n self.qwhile_determine['qwhile_parent_name'] = ''\n\n # Visit a parse tree produced by qcodeParser#expression_statement.\n def visitExpression_statement(self, ctx:qcodeParser.Expression_statementContext,scope_ident):\n ident = scope_ident\n self.visitSingle_expression(ctx.single_expression(),ident)\n self.fn.write(';')\n\n\n\n # Visit a parse tree produced by qcodeParser#empty_statement.\n def visitEmpty_statement(self, ctx:qcodeParser.Empty_statementContext):\n self.fn.write(str(ctx.SEMI()))\n\n\n # Visit a parse tree produced by qcodeParser#declaration_variable_statement.\n def visitDeclaration_variable_statement(self, ctx:qcodeParser.Declaration_variable_statementContext,scope_ident):\n ident = scope_ident\n self.visitDeclaration_variable(ctx.declaration_variable(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#compound_statement.\n def visitCompound_statement(self, ctx:qcodeParser.Compound_statementContext,scope_ident):\n ident = scope_ident\n if ctx.statement_list() is not None:\n self.visitStatement_list(ctx.statement_list(),ident)\n\n # Visit a parse tree produced by qcodeParser#select_statement.\n def visitSelect_statement(self, ctx:qcodeParser.Select_statementContext,scope_ident):\n ident = scope_ident\n self.fn.createBackSpace(str(ctx.IF()))\n self.fn.write(str(ctx.LPAREN()))\n self.visitSingle_expression(ctx.single_expression(),ident)\n self.fn.write(str(ctx.RPAREN())+'{')\n self.visitStatement(ctx.statement(0),ident)\n self.fn.createline()\n self.fn.createIdent(ident)\n self.fn.write('}')\n if ctx.ELSE() is not None:\n ident = ident-1\n if ctx.statement(1).select_statement() is not None:\n self.fn.write('else ')\n self.visitStatement(ctx.statement(1),ident)\n else:\n if len(ctx.statement(1).getText()) > 2:\n ident = ident+1\n self.fn.write(str(ctx.ELSE()))\n self.fn.write('{')\n self.visitStatement(ctx.statement(1),ident)\n self.fn.createline()\n self.fn.createIdent(ident)\n self.fn.write('}')\n\n\n # Visit a parse tree produced by qcodeParser#iterate_statement.\n def visitIterate_statement(self, ctx:qcodeParser.Iterate_statementContext,scope_ident):\n ident = scope_ident\n # self.fn.createIdent(ident-1)\n if ctx.for_stmt() is not None:\n self.fn.createBackSpace(str(ctx.FOR()))\n self.fn.write('(')\n self.visitFor_stmt(ctx.for_stmt(),ident)\n self.fn.write('){')\n self.visitStatement(ctx.statement(),ident)\n self.fn.createline()\n self.fn.createIdent(ident)\n self.fn.write('}')\n elif ctx.inhanced_for_stmt() is not None:\n self.fn.createBackSpace(str(ctx.FOR()))\n self.fn.write('(')\n self.visitInhanced_for_stmt(ctx.inhanced_for_stmt(),ident)\n self.fn.write('){')\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.visitStatement(ctx.statement(),ident)\n self.fn.createline()\n self.fn.createIdent(ident)\n self.fn.write('}')\n\n # Visit a parse tree produced by qcodeParser#for_stmt.\n def visitFor_stmt(self, ctx: qcodeParser.For_stmtContext, scope_indent):\n indent = scope_indent\n if ctx.for_start() is not None:\n self.visitFor_start(ctx.for_start(),indent)\n self.fn.write(';')\n if ctx.for_condition() is not None:\n self.fn.write(str(ctx.for_start().Identifier()))\n self.fn.write('<')\n self.visitFor_condition(ctx.for_condition(),indent)\n self.fn.write(';')\n if ctx.for_step() is not None:\n self.fn.write(str(ctx.for_start().Identifier()))\n self.fn.write('+=')\n self.visitFor_step(ctx.for_step(),indent)\n else:\n self.fn.write(str(ctx.for_start().Identifier()))\n self.fn.write('++')\n\n # Visit a parse tree produced by qcodeParser#for_start.\n def visitFor_start(self, ctx:qcodeParser.For_startContext,scope_ident):\n ident = scope_ident\n if ctx.LET() is not None:\n self.fn.write('auto ')\n self.fn.createBackSpace(str(ctx.Identifier()))\n if ctx.ASSIGN() is not None:\n self.fn.write(str(ctx.ASSIGN()))\n self.visitSingle_expression(ctx.single_expression(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#for_step.\n def visitFor_step(self, ctx:qcodeParser.For_stepContext,scope_ident):\n ident = scope_ident\n self.visitSingle_expression(ctx.single_expression(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#for_condition.\n def visitFor_condition(self, ctx:qcodeParser.For_conditionContext,scope_ident):\n ident = scope_ident\n self.visitSingle_expression(ctx.single_expression(),ident)\n\n\n # Visit a parse tree produced by qcodeParser#inhanced_for_stmt.\n def visitInhanced_for_stmt(self, ctx:qcodeParser.Inhanced_for_stmtContext,scope_ident):\n ident = scope_ident\n self.visitConstruct_primary_type(ctx.construct_primary_type())\n self.fn.createBackSpace(str(ctx.Identifier()))\n self.fn.createBackSpace(':')\n self.visitSingle_expression(ctx.single_expression(),ident)#\n\n\n # Visit a parse tree produced by qcodeParser#statement_list.\n def visitStatement_list(self, ctx:qcodeParser.Statement_listContext,scope_ident):\n ident = scope_ident\n for index in range(len(ctx.statement())):\n self.fn.createline()\n self.fn.createIdent(ident+1)\n self.visitStatement(ctx.statement(index),ident)\n\n def visitFunction_definition(self, ctx:qcodeParser.Function_definitionContext):\n indent = 0\n self.func_paras = []\n self.FUNCTION_RETURN_TYPE_DECLARATOR =None\n self.is_call_back_construct = 0\n self.fn.createline()\n self.qif_determine['qif_parent_count'] = 0\n self.qwhile_determine['qwhile_parent_count'] = 0\n self.visitDeclarate_function(ctx.declarate_function())\n self.visitFunction_body(ctx.function_body())\n\n\n # Visit a parse tree produced by qcodeParser#function_body.\n def visitFunction_body(self, ctx:qcodeParser.Function_bodyContext):\n self.fn.write('{')\n if self.FUNCTION_RETURN_TYPE_DECLARATOR == None:\n self.fn.createLineTab()\n self.fn.write('QProg prog = CreateEmptyQProg();')\n self.visitCompound_statement(ctx.compound_statement(),0)\n self.fn.createLineTab()\n self.fn.write('return prog;')\n self.fn.createline()\n self.fn.write('}')\n\n elif self.FUNCTION_RETURN_TYPE_DECLARATOR == 'circuit':\n self.fn.createLineTab()\n self.fn.write('QCircuit qCircuit = CreateEmptyCircuit();')\n self.visitCompound_statement(ctx.compound_statement(),0)\n self.fn.createLineTab()\n self.fn.write('return qCircuit;')\n self.fn.createline()\n self.fn.write('}')\n\n elif self.FUNCTION_RETURN_TYPE_DECLARATOR == 'variationalCircuit':\n self.fn.createLineTab()\n self.fn.write('QCircuit qCircuit = CreateEmptyQProg();')\n self.visitCompound_statement(ctx.compound_statement(),0)\n self.fn.createLineTab()\n self.fn.write('return qCircuit;')\n self.fn.createline()\n self.fn.write('}')\n else:\n self.visitCompound_statement(ctx.compound_statement(),0)\n self.fn.createline()\n self.fn.write('}')\n\n # Visit a parse tree produced by qcodeParser#key_words.\n def visitKey_words(self, ctx:qcodeParser.Key_wordsContext):\n key_words_text = str(ctx.getText())\n if key_words_text == 'VQG_NOT':\n key_words_text = 'VariationalQuantumGate_NOT'\n if key_words_text == 'VQG_RZ':\n key_words_text = 'VariationalQuantumGate_RZ'\n if key_words_text == 'VQG_RX':\n key_words_text = 'VariationalQuantumGate_RX'\n self.fn.write(key_words_text)\n\n\n\n # Visit a parse tree produced by qcodeParser#constant.\n def visitConstant(self, ctx:qcodeParser.ConstantContext):\n if ctx.Integer_Literal() is not None:\n self.fn.write(str(ctx.Integer_Literal()))\n elif ctx.Double_Literal() is not None:\n self.fn.write(str(ctx.Double_Literal()))\n\n","repo_name":"OriginQ/qurator-vscode","sub_path":"client/resources/qrunesScripts/qcodeCppVisitorHandle.py","file_name":"qcodeCppVisitorHandle.py","file_ext":"py","file_size_in_byte":52325,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"52"} +{"seq_id":"12131059228","text":"import requests\nimport time\nimport pprint\nimport Connect_database\nimport create_fig\nimport get_from_web\n\n# 用来获取 时间戳\ndef gettime():\n return int(round(time.time() * 1000))\n\nif __name__ == '__main__':\n datanodes = get_from_web.nation_stat('A0301')\n\n\n # total = []\n # man = []\n # woman = []\n # city = []\n # countryside = []\n d = ['year','total','man','woman','city','countryside']\n for i in range(len(d)):\n cmd = d[i]+' = []'\n exec(cmd)\n\n for num,ele in enumerate(datanodes):\n for i in range(len(d)-1):\n if num//20 == i:\n cmd = d[i+1]+\".append(ele['data']['data'])\"\n # print(cmd)\n eval(cmd)\n else:\n # print('overflow')\n pass\n\n # 连接数据库预信息\n f = open('ps.txt','r')\n ps = f.readline()\n tablename = 'Population_num'\n yearspan = 20\n db = Connect_database.Cnect_Database(\"127.0.0.1\", \"root\", \"population\", 'utf8')\n # 连接,登记\n db.connect(ps)\n db.register([[],total,man,woman,city,countryside],d,tablename,yearspan)\n # 连接,查询\n db.connect(ps)\n result = db.retrieval('*',tablename)\n pprint.pprint(result)\n\n create_fig.drawHW1(result)\n\n","repo_name":"KiritoHugh/Nation_statistic_crawler","sub_path":"mysql_HW1.py","file_name":"mysql_HW1.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12488285851","text":"amount = int(input(\"introduce el valor del producto: \"))\n\n\"\"\"en ingles amount es Monto.\n invoice es factura\n vat es Iva\"\"\"\ndef iva(amount, vat=0.19):\n only_vat = amount * vat\n price_with_vat= only_vat +amount\n return print(\"el iva es: \"+ str(int(only_vat)) +\"\\n\" +\n \" monto total: \"+ str(int(price_with_vat)))\n \niva(amount)","repo_name":"deManrrique/Python","sub_path":"iva.py","file_name":"iva.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40144071118","text":"\"\"\"\r\nExample script for testing the Forest theme\r\n\r\nAuthor: rdbende\r\nLicense: MIT license\r\nSource: https://github.com/rdbende/ttk-widget-factory\r\n\"\"\"\r\n\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom tkinter import *\r\nfrom openpyxl import *\r\nimport openpyxl\r\n\r\n\r\n# IDEAS A PROBAR\r\n# PONER 2 LISTBOX, UNA PARA EL NEGOCIO DE DONDE PROVIENE EL PRODUCTO A COMPRAR\r\n# Y LA OTRA LA BASE DE DATOS DE DONDE LA EXTRAE\r\n#\r\n# AÑADIR DEL WIDGET # BASE DE DATOS # AL TREEVIEW\r\n#\r\n# AÑADIR EL WHATSAPP\r\n#\r\n\r\n\r\n# JERARQUIA\r\n#\r\n# ORDEN #XXX\r\n# TIENDA A \r\n# PRODUCTO A $XXX\r\n# PRODUCTO B $XXX\r\n# PRODUCTO C $XXX\r\n# PRODUCTO D $XXX\r\n#-------------------------SUBTOTAL\r\n# $XXXA\r\n## TIENDA B \r\n# PRODUCTO A $XXX\r\n# PRODUCTO B $XXX\r\n#-------------------------SUBTOTAL\r\n# $XXXB\r\n#-------------------------TOTAL\r\n# $XXXT\r\n#\r\n# \r\n\r\n\r\n\r\n# Update the listbox\r\ndef update(data):\r\n # Clear the listbox\r\n # limpia la listbox\r\n my_list.delete(0,END)\r\n\r\n # Add lreyes to listbox\r\n # se añaden los elementos de una lista en la listbox\r\n for item in data:\r\n my_list.insert(END,item)\r\n\r\ndef fillout(e):\r\n # borrar todo lo que haya en la entry\r\n my_entry.delete(0,END)\r\n # inserta el elemento seleccionado del listbox en el entry\r\n my_entry.insert(0,my_list.get(ACTIVE))\r\n\r\ndef check(e):\r\n # pide el valor de la entrada\r\n typed = my_entry.get()\r\n # si es un string vacio\r\n if typed == '':\r\n data = lreyes\r\n # la listbox permanece igual\r\n else:\r\n # se borra toda la lista de data\r\n data = []\r\n for item in lreyes:# para cada elemento de nuestra lista\r\n if typed.lower() in item.lower():\r\n # si la entrada en minusculas\r\n # es igual a un valor dentro de la lista en minusculas\r\n # se añade a la lista\r\n data.append(item)\r\n\r\n update(data)# MIUESTRA LOS VALORES ACTUALES\r\n\r\n# Valores de los botones\r\ndef seleccionar():\r\n print(my_entry.get())\r\n\r\n# Valores \r\ndef nuevo_pedido(treeview_data):\r\n total_items \r\n treeview.insert(parent=item[0], index=item[1], iid=item[2], text=item[3], values=item[4])\r\n\r\ndef selectbox(e):\r\n comboactual = menu_tiendas.get()\r\n if comboactual == 'Tienda de Reyes': # PRODUCTOS DEFINIDOS\r\n # PRODUCTOS DEFINIDOS \r\n tienda1 = wb['Reyes']\r\n ltienda1 = loaddb(tienda1)\r\n update(ltienda1)\r\n elif comboactual == 'Carniceria':\r\n tienda2 = wb['Carniceria']\r\n ltienda2 = loaddb(tienda2)\r\n update(ltienda2)\r\n elif comboactual == 'Papeleria de José':\r\n tienda3 = wb['Papeleria de José']\r\n ltienda3 = loaddb(tienda3)\r\n update(ltienda3)\r\n else:\r\n pass\r\n## print(comboactual)\r\nroot = tk.Tk()\r\nroot.title(\"Forest\")\r\nroot.option_add(\"*tearOff\", False) # This is always a good idea\r\n\r\ng = tk.DoubleVar(value=75.0)\r\n\r\n# Make the app responsive\r\nroot.columnconfigure(index=0, weight=1)\r\nroot.columnconfigure(index=1, weight=1)\r\nroot.columnconfigure(index=2, weight=1)\r\nroot.rowconfigure(index=0, weight=1)\r\nroot.rowconfigure(index=1, weight=1)\r\nroot.rowconfigure(index=2, weight=1)\r\n\r\n# Create a style\r\nstyle = ttk.Style(root)\r\n\r\n# Import the tcl file\r\nroot.tk.call(\"source\", \"forest-dark.tcl\")\r\n\r\n# Set the theme with the theme_use method\r\nstyle.theme_use(\"forest-dark\")\r\n\r\nbotones_frame = ttk.LabelFrame(root, text=\"Que desea hacer?\", padding=(20, 10))\r\nbotones_frame.grid(row=0, column=0, padx=(20, 10), pady=(20, 10), sticky=\"nsew\")\r\n\r\nbutton = ttk.Button(botones_frame, text=\"Nueva orden\",command=nuevo_pedido)\r\nbutton.grid(row=0, column=0, padx=5, pady=10, sticky=\"nsew\")\r\n\r\n# Panedwindow\r\npaned = ttk.PanedWindow(root)\r\npaned.grid(row=1, column=1, pady=(25, 5), sticky=\"nsew\", rowspan=3)\r\n\r\n# Pane #1\r\npane_1 = ttk.Frame(paned)\r\npaned.add(pane_1, weight=1)\r\n\r\n# Create a Frame for the Treeview\r\ntreeFrame = ttk.Frame(pane_1)\r\ntreeFrame.pack(expand=True, fill=\"both\", padx=5, pady=5)\r\n\r\n# Scrollbar\r\ntreeScroll = ttk.Scrollbar(treeFrame)\r\ntreeScroll.pack(side=\"right\", fill=\"y\")\r\n\r\n# Treeview\r\ntreeview = ttk.Treeview(treeFrame, selectmode=\"extended\", yscrollcommand=treeScroll.set, columns=(1, 2), height=12)\r\ntreeview.pack(expand=True, fill=\"both\")\r\ntreeScroll.config(command=treeview.yview)\r\n\r\n# Treeview columns\r\ntreeview.column(\"#0\", width=120)\r\ntreeview.column(1, anchor=\"w\", width=120)\r\ntreeview.column(2, anchor=\"w\", width=120)\r\n\r\n# Treeview headings\r\ntreeview.heading(\"#0\", text=\"Column 1\", anchor=\"center\")\r\ntreeview.heading(1, text=\"Column 2\", anchor=\"center\")\r\ntreeview.heading(2, text=\"Column 3\", anchor=\"center\")\r\n\r\n# Define treeview data\r\ntreeview_data = [\r\n (\"\", \"end\", 1, \"Orden 1\", (\"\", \"\")),\r\n (1, \"end\", 2, \"Tienda reyes\", (\"\", \"\")),\r\n (2, \"end\", 3, \"producto 1\", (\"xxxx Kg\", \"$xx.xx\")),\r\n (1, \"end\", 4, \"Tienda Mandrake\", (\"\", \"\")),\r\n (4, \"end\", 5, \"producto 1\", (\"xxxx Kg\", \"$xx.xx\")),\r\n (\"\", \"end\", 6, \"Copias Edgar\", (\"\", \"\")),\r\n (6, \"end\", 7, \"Child\", (\"Subitem 2.1\", \"Value 2.1\")),\r\n (6, \"end\", 8, \"Sub-parent\", (\"Subitem 2.2\", \"Value 2.2\")),\r\n (8, \"end\", 9, \"Child\", (\"Subitem 2.2.1\", \"Value 2.2.1\")),\r\n (8, \"end\", 10, \"Child\", (\"Subitem 2.2.2\", \"Value 2.2.2\")),\r\n (8, \"end\", 11, \"Child\", (\"Subitem 2.2.3\", \"Value 2.2.3\")),\r\n (6, \"end\", 12, \"Child\", (\"Subitem 2.3\", \"Value 2.3\")),\r\n (6, \"end\", 13, \"Child\", (\"Subitem 2.4\", \"Value 2.4\")),\r\n ]\r\n # Item\r\n # (parent, index, iid, text, values)\r\n\r\n# Insert treeview data\r\nfor item in treeview_data:\r\n treeview.insert(parent=item[0], index=item[1], iid=item[2], text=item[3], values=item[4])\r\n if item[0] == \"\" or item[2] in (8, 12):\r\n treeview.item(item[2], open=True) # Open parents\r\n\r\n# Select and scroll\r\ntreeview.selection_set(10)\r\ntreeview.see(7)\r\n\r\n# Panedwindow\r\npaned2 = ttk.PanedWindow(root)\r\npaned2.grid(row=1, column=0, pady=(25, 5), sticky=\"nsew\", rowspan=3)\r\n\r\n# Pane #2\r\npane_2 = ttk.Frame(paned2)\r\npaned2.add(pane_2, weight=3)\r\n\r\n# Notebook\r\nnotebook = ttk.Notebook(pane_2)\r\n\r\n# Tab #1\r\ntab_1 = ttk.Frame(notebook)\r\ntab_1.columnconfigure(index=0, weight=1)\r\ntab_1.columnconfigure(index=1, weight=1)\r\ntab_1.rowconfigure(index=0, weight=1)\r\ntab_1.rowconfigure(index=1, weight=1)\r\nnotebook.add(tab_1, text=\"Productos\")\r\n\r\n# Fill_3\r\n\r\n\r\nwb = load_workbook('Lista_Reyes.xlsx')\r\nreyes = wb['Reyes']\r\n\r\ndef loaddb(reyes):\r\n m_row = reyes.max_row\r\n## print(reyes)\r\n## print(m_row)\r\n lreyes = []\r\n for i in range(1,m_row+1):\r\n cell_obj = reyes.cell(row=i, column=1)# Se obtiene el la celda por completp\r\n print(cell_obj.value)# se imprime el valor dentro de la celda\r\n lreyes.append(cell_obj.value)# se agrega el valor a la lista lreyes\r\n return lreyes\r\n\r\nlreyes = loaddb(reyes)\r\n\r\n# Fill_5\r\n\r\nlista_tiendas = [\r\n 'Tienda de Reyes', # PRODUCTOS DEFINIDOS\r\n 'Carniceria', # PRODUCTOS DEFINIDOS \r\n 'Papeleria de José', # PRODUCTOS DEFINIDOS\r\n 'Café internet Edgar Online', # SERVICIOS DE COPIAS\r\n 'Antojitos CETIS 33', # PRODUCTOS DEFINIDOS\r\n 'Liconsa',# PRODUCTO DEFINIDO\r\n 'Tortilleria',# PRODUCTO DEFINIDO\r\n 'Purificadora de Agua',# PRODUCTOS DEFINIDO\r\n 'Plomeria Y Electricista Memo'# SERVICIOS\r\n 'OXXO',# PRODUCTOS DEFINIDOS\r\n ]\r\n\r\nSeleccionado = StringVar()\r\nSeleccionado.set(lista_tiendas[0])\r\n\r\n\r\n##my_label = Label(tab_1, text=\"Start Typing...\", font=(\"Helvetica\",14),fg=\"grey\")\r\n##my_label.grid(row=0, column=0, padx=(20, 10), pady=(20, 0), sticky=\"ew\")\r\n\r\n##sel_prod_frame = ttk.LabelFrame(tab_1, text=\"Checkbuttons\", padding=(20, 10))\r\n##sel_prod_frame.grid(row=1, column=0, padx=10, pady=(30, 10), sticky=\"nsew\", rowspan=3)\r\n\r\n# Combobox\r\nmenu_tiendas = ttk.Combobox(tab_1, values=lista_tiendas)\r\nmenu_tiendas.current(0)\r\nmenu_tiendas.grid(row=0, column=0, padx=5, pady=10, sticky=\"ew\")\r\n\r\nmy_entry = ttk.Entry(tab_1,font=(\"Helvetica\",20))\r\nmy_entry.grid(row=1, column=0, padx=(10, 20), pady=(20, 0), sticky=\"ew\")\r\n\r\nmy_list = Listbox(tab_1,width=50)\r\nmy_list.grid(row=2, column=0, padx=(10, 20), pady=(20, 0), sticky=\"ew\")\r\n\r\nbutton = ttk.Button(tab_1, text=\">>\",command=seleccionar)\r\nbutton.grid(row=3, column=0, padx=5, pady=10, sticky=\"nsew\")\r\n\r\n# Button\r\n##button = ttk.Button(tab_1, text=\"seleccionar Producto\",command=seleccionar)\r\n##button.grid(row=3, column=0, padx=5, pady=10, sticky=\"nsew\")\r\n\r\n##lreyes = [\"Peperoni\",\"Peppers\",\"Mushrooms\",\"Cheese\",\"Onions\",\"Ham\",\"Taco\"]\r\n\r\n\r\nupdate(lreyes)\r\n\r\nmy_list.bind(\"<>\",fillout)\r\n\r\nmy_entry.bind(\"\",check)\r\n\r\nmenu_tiendas.bind(\"<>\",selectbox)\r\n\r\n### Scale\r\n##scale = ttk.Scale(tab_1, from_=100, to=0, variable=g, command=lambda event: g.set(scale.get()))\r\n##scale.grid(row=0, column=0, padx=(20, 10), pady=(20, 0), sticky=\"ew\")\r\n##\r\n### Progressbar\r\n##progress = ttk.Progressbar(tab_1, value=0, variable=g, mode=\"determinate\")\r\n##progress.grid(row=0, column=1, padx=(10, 20), pady=(20, 0), sticky=\"ew\")\r\n##\r\n### Label\r\n##label = ttk.Label(tab_1, text=\"Forest ttk theme\", justify=\"center\")\r\n##label.grid(row=1, column=0, pady=10, columnspan=2)\r\n\r\n# Tab #2\r\ntab_2 = ttk.Frame(notebook)\r\nnotebook.add(tab_2, text=\"Tab 2\")\r\n\r\n# Tab #3\r\ntab_3 = ttk.Frame(notebook)\r\nnotebook.add(tab_3, text=\"Tab 3\")\r\n\r\nnotebook.pack(expand=True, fill=\"both\", padx=5, pady=5)\r\n\r\n# Sizegrip\r\nsizegrip = ttk.Sizegrip(root)\r\nsizegrip.grid(row=100, column=100, padx=(0, 5), pady=(0, 5))\r\n\r\n# Center the window, and set minsize\r\nroot.update()\r\nroot.minsize(root.winfo_width(), root.winfo_height())\r\nx_cordinate = int((root.winfo_screenwidth()/2) - (root.winfo_width()/2))\r\ny_cordinate = int((root.winfo_screenheight()/2) - (root.winfo_height()/2))\r\nroot.geometry(\"+{}+{}\".format(x_cordinate, y_cordinate))\r\n\r\n# Start the main loop\r\nroot.mainloop()\r\n","repo_name":"PolitropicMX/AUTOFILL1","sub_path":"fill_5.py","file_name":"fill_5.py","file_ext":"py","file_size_in_byte":9806,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7606960736","text":"\"\"\" This module collects all loaders. That is, all utils which allow to setup a particular model from an external file.\n\"\"\"\n\nimport xml.etree.ElementTree as ET\n\nimport abc\nimport importlib\n\nfrom panacea.core.Coordinates import Coordinates2D, Coordinates3D\nfrom panacea.core.Schedule import Schedule\n\n\nclass Loader(object):\n \"\"\" Blueprint of the loader object.\n \"\"\"\n\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def setupFromExternal(self, model):\n \"\"\" Sets up from the external file. Note that the path and type of the loader have to be specified\n when instantiating the model.\n\n Args:\n model (Model): The model instance we are setting up.\n \"\"\"\n pass\n\nclass XMLLoader(Loader):\n \"\"\" Loader from our XML format.\n \"\"\"\n def __init__(self, model):\n \"\"\" Constructor method to avoid explicitly having to call setupFromExternal.\n\n Args:\n model (Model): The model we are setting up.\n \"\"\"\n xmlPath = model.setupPath\n self.setupFromExternal(xmlPath, model)\n\n def setupFromExternal(self, xmlPath, model):\n tree = ET.parse(xmlPath)\n root = tree.getroot()\n\n modelProperties = root.attrib\n\n # setting epochs\n model.setEpochs(int(modelProperties[\"epochs\"]))\n\n modelParameters = root.findall(\"modelParameters/*\")\n\n for m in modelParameters:\n model.addOptionalParameter(m.attrib)\n\n # grid index, that is all possible types of grids\n gridIndex = root.findall(\"grids/gridIndex/*\")\n\n # getting all grids which are actually instantiated\n modelGrid = root.findall(\"grids/modelGrids/*\")\n\n # looping through all grids\n for m in modelGrid:\n # getting the reference to the actual grid class which we will instantiate\n g = filter(lambda x : x.attrib[\"ref\"] == m.attrib[\"type\"], gridIndex)[0].attrib\n\n # getting parameters for this specific instance\n instanceParameters = m.findall(\"parameters/*\")\n\n parameters = []\n\n for p in instanceParameters:\n parameters.append(p.attrib[\"value\"])\n\n # And finally actually instantiating the class\n module = importlib.import_module(g[\"module\"])\n my_class = getattr(module, g[\"class\"])\n grid = my_class(parameters)\n\n model.addGrid(grid)\n\n # NumericalGrid2D objects can have coordinate values\n # defined in xml\n if(g[\"class\"] == \"NumericalGrid2D\"):\n coordinateValues = m.findall(\"coordinateValues/*\")\n\n for cv in coordinateValues:\n cv = cv.attrib\n\n grid.setGridValue(Coordinates2D(int(cv[\"x\"]), int(cv[\"y\"])), float(cv[\"value\"]))\n\n schedule = Schedule()\n\n # helper index, that is all possible types of helpers\n helperIndex = root.findall(\"helpers/helperIndex/*\")\n\n # getting all the helpers which are actually instantiated\n modelHelpers = root.findall(\"helpers/modelHelpers/*\")\n\n #looping through all helpers\n for m in modelHelpers:\n # getting reference to the actual helper class\n h = filter(lambda x : x.attrib[\"ref\"] == m.attrib[\"type\"], helperIndex)[0].attrib\n\n # getting parameters for this specific instance\n instanceParameters = m.findall(\"parameters/*\")\n\n parameters = []\n\n for p in instanceParameters:\n parameters.append(p.attrib[\"value\"])\n\n\n # And finally actually instantiating the class\n module = importlib.import_module(h[\"module\"])\n my_class = getattr(module, h[\"class\"])\n helper = my_class(parameters)\n\n schedule.addHelper(helper)\n\n # agent index, that is all possible types of agents\n agentIndex = root.findall(\"agents/agentIndex/*\")\n\n # getting all agents which are actually instantiated\n modelAgents = root.findall(\"agents/modelAgents/*\")\n\n # looping through agents\n for m in modelAgents:\n # getting reference to the actual agent class\n a = filter(lambda x : x.attrib[\"ref\"] == m.attrib[\"type\"], agentIndex)[0].attrib\n\n # getting parameters for this specific instance\n instanceParameters = m.findall(\"parameters/*\")\n\n parameters = []\n\n for p in instanceParameters:\n parameters.append(p.attrib[\"value\"])\n\n\n # And finally actually instantiating the class\n module = importlib.import_module(a[\"module\"])\n my_class = getattr(module, a[\"class\"])\n agent = my_class(parameters)\n\n schedule.addAgent(agent)\n\n # Now we have to add the agent to the appropriate grids\n gridPositions = m.findall(\"gridPositions/*\")\n\n for g in gridPositions:\n\n # getting the grid\n gridName = g.attrib[\"grid\"]\n grid = model.getGridFromName(gridName)\n\n # now we get the agent's coordinates for this grid\n coords = g.findall(\"coordinate\")\n\n # and add them\n if(len(coords) == 2):\n c = Coordinates2D(int(coords[0].attrib[\"value\"]), int(coords[1].attrib[\"value\"]))\n else:\n c = Coordinates3D(int(coords[0].attrib[\"value\"]), int(coords[1].attrib[\"value\"]), int(coords[2].attrib[\"value\"]))\n\n grid.moveAgent(c, agent)\n\n model.addSchedule(schedule)\n\n","repo_name":"DarioPanada/Panacea","sub_path":"core/utils/SetupLoader.py","file_name":"SetupLoader.py","file_ext":"py","file_size_in_byte":5576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34568464987","text":"import pandas as pd\nimport os\nimport sys\nimport datasets\nimport nltk\nfrom nltk.tokenize import word_tokenize\n# from nltk.corpus import stopwords\nimport docx\nimport numpy as np\nimport datetime\nfrom box import Box\nimport yaml\nfrom tqdm import tqdm\nfrom prompts import *\nfrom config_parser import *\n\n\n# nltk.download()\n\ndef calc_rouge(sen_a, sen_b):\n rouge = datasets.load_metric('rouge')\n # if one of the sentences is empty, return 0\n if sen_a == \"\" or sen_b == \"\":\n rouge_score = rouge.compute(predictions=\"1\", references=\"0\")\n else:\n # fix mismatch by length by cut:\n # match in the number of len prediction and len reference :len(sen_b)\n if len(sen_a) >= len(sen_b):\n rouge_score = rouge.compute(predictions=sen_a[:len(sen_b)], references=sen_b)\n else:\n rouge_score = rouge.compute(predictions=sen_a, references=sen_b[:len(sen_a)])\n # low, mid, high - \"\"\"Tuple containing confidence intervals for scores.\"\"\"\n precentile = 1 # 'mid'\n score_type = 2 # 'fmeasure' # recall, precision\n rouge1 = rouge_score['rouge1'][precentile][score_type]\n rouge2 = rouge_score['rouge2'][precentile][score_type]\n return rouge1, rouge2\n\n\ndef calc_cosine_similarity_2_sentences(sen_a, sen_b):\n \"\"\"\n calculates cosine similarity of 2 sentences -\n counting vector (histogram) per each word for each sentence\n :param sen_a:\n :param sen_b:\n :return:\n \"\"\"\n # splits to words\n a_list = word_tokenize(sen_a)\n b_list = word_tokenize(sen_b)\n # remove stop words\n # sw = stopwords.words('english')\n # a_set = {w for w in a_list if not w in sw}\n # b_set = {w for w in b_list if not w in sw}\n a_set = {w for w in a_list}\n b_set = {w for w in b_list}\n\n l1 = []\n l2 = []\n # form a set containing keywords of both strings\n rvector = a_set.union(b_set) # all words\n for w in rvector:\n if w in a_set:\n l1.append(1) # create a vector\n else:\n l1.append(0)\n if w in b_set:\n l2.append(1)\n else:\n l2.append(0)\n c = 0\n # cosine formula\n for i in range(len(rvector)):\n c += l1[i] * l2[i]\n\n try:\n cosine = c / float((sum(l1) * sum(l2)) ** 0.5)\n except:\n cosine = 0\n return cosine\n\n\n# todo: remove splitting the prediction - duplicated ( already done in funetunings_scripts)\ndef fix_columns(df):\n predicted_meaning = []\n gt_meaning = []\n for in_prompt, pred in zip(df['input_prompt'], df['predicted_text']):\n pred_splitted = pred.split(in_prompt)\n\n if len(pred_splitted) <= 1:\n pred = \"Empty\"\n elif len(pred_splitted) == 2:\n pred = pred_splitted[1]\n # else:\n # pred = \"More than one repetition: \" + pred\n predicted_meaning.append(pred)\n\n df['predicted_meaning'] = predicted_meaning\n\n df['gt_meaning'] = predicted_meaning # TODO: delete\n df['lyrics'] = df['input_prompt'] # TODO: delete\n return df\n\n\ndef post_eval(pickle_path, fix_flag=0):\n # Load pickle as a dataframe\n df = pd.read_pickle(pickle_path)\n # pickle_name = os.path.split(pickle_path)[1]\n pickle_name = pickle_path.split('/')[-2] + datetime.datetime.today().strftime('_%d%m%y_%H%M')\n\n if fix_flag:\n df = fix_columns(df)\n\n # calculate eval_metrices - (input, prediction), (label, prediction)\n cos_pred_lyrics_l, cos_pred_label_l, rouge1_l, rouge2_l = [], [], [], []\n total_score_l = []\n weights_per_metric = {'cos_pred_lyrics': 0.5, 'cos_pred_label': 0.5, 'rouge1': 0.5, 'rouge2': 0}\n for lyrics, pred, label in tqdm(zip(df['lyrics'], df['predicted_meaning'], df['gt_meaning'])):\n # cosine similarity - LSA\n cos_pred_lyrics = calc_cosine_similarity_2_sentences(pred, lyrics)\n cos_pred_label = calc_cosine_similarity_2_sentences(pred, label)\n # rouge\n rouge1, rouge2 = calc_rouge(pred, label)\n\n scores = {'cos_pred_lyrics': cos_pred_lyrics, 'cos_pred_label': cos_pred_label, 'rouge1': rouge1,\n 'rouge2': rouge2}\n weighted_scores = [scores[k] * v for k, v in weights_per_metric.items()]\n total_score = max(0, sum(weighted_scores) - 2 * weighted_scores[0]) # sum of all minus similarity to lyrics\n\n # appends\n cos_pred_lyrics_l.append(cos_pred_lyrics)\n cos_pred_label_l.append(cos_pred_label)\n rouge1_l.append(rouge1)\n rouge2_l.append(rouge2)\n total_score_l.append(total_score)\n\n df['rouge1'] = rouge1_l\n df['rouge2'] = rouge2_l\n df['cos_pred_label'] = cos_pred_label_l\n df['cos_pred_lyrics'] = cos_pred_lyrics_l\n df['total_score'] = total_score_l\n new_pickle_path = \"post_eval/example_to_analysis_\" + pickle_name + \".pkl\"\n df.to_pickle(new_pickle_path)\n print('done')\n return df, new_pickle_path\n\n\ndef analysis(df: pd.DataFrame, compare_params: list, score_name: str,\n new_pickle_path, post_eval_path, run_all=1):\n \"\"\"\n\n :param df:\n :param compare_param: list of strings - order - hirrechy - column - model, prompt, decode, any other...\n :return:\n \"\"\"\n\n df = pd.read_pickle(new_pickle_path) #TODO: remove\n df_analysis = pd.DataFrame()\n df_analysis_std = pd.DataFrame()\n\n # creat docx file\n doc = docx.Document()\n doc.add_heading('Analysis', 0)\n\n if run_all:\n compare_params_lists = [['model', 'prompt_type', 'decode_method'],\n ['prompt_type', 'model', 'decode_method'],\n ['decode_method', 'model', 'prompt_type']]\n score_name_list = ['total_score', 'rouge1', 'cos_pred_label', 'cos_pred_lyrics']\n\n for compare_list in compare_params_lists:\n for score in score_name_list:\n para = doc.add_paragraph('Compare_list: \\n{}\\nMean score by:{}'.format(compare_list, score))\n print('Compare_list:', compare_list, '\\nMean score by:', score)\n h = len(compare_list) # hierarchies\n for ind_param in range(h):\n gk = df.groupby(compare_list[:ind_param + 1])\n mean_gk = gk[score].mean()\n std_gk = gk[score].std()\n # save as df\n mean_gk_df = mean_gk.to_frame()\n # TODO: add std\n std_gk_df = std_gk.to_frame()\n\n # # concat to analysis df\n # df_analysis = pd.concat([df_analysis, mean_gk_df], axis=1)\n # df_analysis_std = pd.concat([df_analysis_std, std_gk_df], axis=1)\n\n # save pickle\n curr_pickle_path = os.path.join(post_eval_path, 'analysis_{}_{}.pkl'.format(\n score, compare_list[:ind_param + 1]))\n mean_gk_df.to_pickle(curr_pickle_path)\n\n curr_std_pickle_path = os.path.join(post_eval_path, 'analysis_std_{}_{}.pkl'.format(\n score, compare_list[:ind_param + 1]))\n\n std_gk_df.to_pickle(curr_std_pickle_path)\n\n # append to docx\n para.add_run('Mean Hierarchy \\n{}:\\n'.format(ind_param))\n para.add_run('Mean:\\n{}\\n'.format(mean_gk))\n para.add_run('\\n')\n\n print('Mean Hierarchy {}:\\n'.format(ind_param), mean_gk)\n\n else:\n h = len(compare_params) # hierarchies\n for ind_param in range(h):\n gk = df.groupby(compare_params[:ind_param+1])\n mean_gk = gk[score_name].mean()\n std_gk = gk[score_name].std()\n\n # save as df\n mean_gk_df = mean_gk.to_frame()\n std_gk_df = std_gk.to_frame()\n\n # concat to analysis df\n # df_analysis = pd.concat([df_analysis, mean_gk_df], axis=1)\n # df_analysis_std = pd.concat([df_analysis_std, std_gk_df], axis=1)\n\n # save pickle\n curr_pickle_path = os.path.join(post_eval_path, 'analysis_{}_{}.pkl'.format(\n score_name, compare_params[:ind_param+1]))\n mean_gk_df.to_pickle(curr_pickle_path)\n\n curr_std_pickle_path = os.path.join(post_eval_path, 'analysis_std_{}_{}.pkl'.format(\n score_name, compare_params[:ind_param + 1]))\n\n std_gk_df.to_pickle(curr_std_pickle_path)\n # append to docx\n doc.add_paragraph('Mean:\\n{}\\n'.format(mean_gk))\n\n print('Mean:\\n', mean_gk)\n\n # save the docx file\n doc.save(os.path.join(post_eval_path, 'analysis_{}.docx'.format(score_name)))\n\n # save pickle\n # df_analysis.to_pickle(os.path.join(post_eval_path, 'analysis_{}.pkl'.format(score_name)))\n # df_analysis_std.to_pickle(os.path.join(post_eval_path, 'analysis_std_{}.pkl'.format(score_name)))\n\n # save as csv\n df_analysis.to_csv(os.path.join(post_eval_path, 'analysis_{}.csv'.format(score_name)))\n\n print('done')\n\n\nif __name__ == '__main__':\n state = 1 # [0 - 'eval_before_training', 1 - 'eval_after_training']\n run_post_eval = True # set True for regular running - post_eval + analysis\n\n # path to evaluate pickle\n before_folder = training_args.path_args.pretraining_folder\n after_folder = training_args.path_args.after_training_folder\n results_folder = training_args.path_args.results_path\n\n pickle_list = []\n pickle_names = ['question_context_with_metadata_bs_32']\n new_pickle_path_list = []\n if state == 1:\n path_to_predictions = private_args.path.path_to_predictions_after_training\n # iterate over folders in path_to_predictions\n for folder in os.listdir(path_to_predictions):\n pickle_list.append(os.path.join(path_to_predictions, folder, 'inference_results.pkl'))\n pickle_names.append(folder)\n else: # state 0 - before\n path_to_predictions = private_args.path.path_to_predictions_before_training\n pickle_list.append(os.path.join(path_to_predictions, 'inference_results.pkl'))\n pickle_names.append('before_training')\n\n if state == 1 and not run_post_eval:\n new_pickles_path = '/home/tok/TRBLLmaker/post_eval/'\n compare_params = ['model', 'prompt_type', 'decode_method']\n score_name = 'total_score'\n # iterate over pickles in new_pickles_path that starts with 'example_to_analysis'\n for file_path in os.listdir(new_pickles_path):\n if file_path.startswith('example_to_analysis') and file_path.endswith('.pkl'):\n new_pickle_path = os.path.join(new_pickles_path, file_path)\n df = pd.read_pickle(new_pickle_path)\n main_path = private_args.path.main_path\n curr_name = file_path.split('example_to_analysis_trained_model_checkpoint_')[1]\n curr_name = curr_name.split('.')[0]\n post_eval_path = os.path.join(main_path, 'post_eval', 'analysis_results', curr_name)\n # if path does not exist, create it\n if not os.path.exists(post_eval_path):\n os.makedirs(post_eval_path)\n analysis(df, compare_params, score_name, new_pickle_path, post_eval_path)\n else: # regular running\n for pickle_path, curr_name in zip(pickle_list, pickle_names):\n main_path = private_args.path.main_path\n post_eval_path = os.path.join(main_path, 'post_eval', 'analysis_results', curr_name)\n # if path does not exist, create it\n if not os.path.exists(post_eval_path):\n os.makedirs(post_eval_path)\n\n # to run analysis only - please fill new_pickle path!!!!\n if run_post_eval:\n df, new_pickle_path = post_eval(pickle_path)\n else:\n new_pickle_path = '/home/mor.ventura/trbll_maker/post_eval/post_eval/example_to_analysis_inference_results.pkl'\n df = pd.read_pickle(new_pickle_path)\n\n # --- run analysis -----\n # those params relvant only if run_all = 0 !!!\n compare_params = ['model', 'prompt_type', 'decode_method']\n score_name = 'total_score'\n analysis(df, compare_params, score_name, new_pickle_path, post_eval_path)\n\n# #---------------------------------------------------------------\n# # create a doc file to write the generated prompts\n# doc = docx.Document()\n# doc.add_heading('Predicted annotations compare {}', 0)\n#\n# # compare the same prompt and decode method with different models\n# # print the input prompt and the predicted text for each model\n# input_prompt = df.loc[0, 'input_prompt']\n# df_input_prompt = df[df['input_prompt'] == input_prompt]\n# for index, row in df_input_prompt.iterrows():\n# para = doc.add_paragraph(\"model: {}\\n\".format(row['model']))\n# para.add_run(\"decode method: {}\\n\".format(row['decode_method']))\n# para.add_run(\"predicted text: {}\\n\".format(row['predicted_text'])).font.bold = True\n#\n#\n#\n# input_prompt = df.loc[5, 'input_prompt']\n# df_input_prompt = df[df['input_prompt'] == input_prompt]\n# for index, row in df_input_prompt.iterrows():\n# para = doc.add_paragraph(\"model: {}\\n\".format(row['model']))\n# para.add_run(\"decode method: {}\\n\".format(row['decode_method']))\n# para.add_run(\"predicted text: {}\\n\".format(row['predicted_text'])).font.bold = True\n#\n# doc.save('/home/tok/TRBLLmaker/results/{}/{}.docx'.format(folder, pickle_name.split('.')[0]))\n#\n# # compare the same prompt and model with different decode methods\n#\n# # compare the same model and decode method with different prompts\n","repo_name":"venturamor/TRBLLmaker-NLP","sub_path":"post_evaluation.py","file_name":"post_evaluation.py","file_ext":"py","file_size_in_byte":13548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31338600905","text":"import sys\nimport spacy\nimport json\nfrom tqdm import tqdm\nimport sys\nfrom candidate_generation.to_json.nltk_extract import validate_nps\nfrom candidate_generation.to_term_list.extract import METHOD_TEXTRANK, METHOD_RAKE, method_name2suffix as method_name2suffix_termlist\nfrom spacy.tokens import Doc\nimport argparse\n\nfrom spacy.matcher import PhraseMatcher\n\ntry:\n unicode\nexcept Exception as e:\n # python 3\n unicode = str\n\n\nVALIDATE = True\nTHRESHOLD = 0.0\n\ndef method_name2suffix(method):\n return \"_\" + method + '.json'\n\nclass WhitespaceTokenizer(object):\n def __init__(self, vocab):\n self.vocab = vocab\n\n def __call__(self, text):\n words = text.split(' ')\n # All tokens 'own' a subsequent space character in this tokenizer\n spaces = [True] * len(words)\n return Doc(self.vocab, words=words, spaces=spaces)\n\n\ndef get_line_count(inFile):\n count = -1\n for count, line in enumerate(open(inFile, 'r')):\n pass\n count += 1\n return count\n\n\nnlp = spacy.load('en', disable=['ner', 'parser', 'tagger'])\nnlp.tokenizer = WhitespaceTokenizer(nlp.vocab)\n\n\ndef read_phrase_list(inFile, threshold=0.5):\n # unified phrase file format\n # input is already ranked and cut off\n # runtime complexity \\t 0.7805276116\n with open(inFile, 'r') as fin:\n phrase_list = []\n for line in fin:\n phrase = line.split('\\t')[0].strip()\n score = float(line.split('\\t')[1])\n if score < threshold:\n break\n phrase_list.append(phrase)\n return phrase_list\n\n\ndef writeToJson(inFile, outFile, matcher, validate=False):\n global nlp\n total = get_line_count(inFile)\n with open(inFile, 'r') as fin, open(outFile, 'w') as fout:\n\n for line in tqdm(fin, total=total):\n text = unicode(line).strip('\\r\\n')\n tokens = text.split(' ')\n\n if text:\n # text may be empty when line is \\n\n doc = nlp(text.lower())\n matches = matcher(doc)\n '''\n matches:\n [(1826470356240629538, 0, 1),\n (4451351154198579052, 0, 2),\n (7342778914265824300, 1, 2),\n (3411606890003347522, 2, 3)]\n '''\n nps = []\n for m in matches:\n st = m[1]\n ed = m[2]\n np = {'st':st, 'ed':ed, 'text': ' '.join(tokens[st:ed])}\n nps.append(np)\n else:\n nps = []\n\n if validate:\n nps = validate_nps(nps, tokens)\n\n fout.write(json.dumps(nps))\n fout.write('\\n')\n\n\ndef extract_by_phrase_list(inFile, phraseinFile, outFile):\n with open(phraseinFile, 'r') as fin:\n phrase_list = read_phrase_list(phraseinFile, THRESHOLD)\n matcher = PhraseMatcher(nlp.vocab)\n for v in phrase_list:\n matcher.add(v, None, nlp(unicode(v))) # python3 is unicode\n writeToJson(inFile, outFile, matcher, validate=VALIDATE)\n\nimport os\n\nif __name__ == '__main__':\n\n # if not threshold\n # threshold = 0.0\n parser = argparse.ArgumentParser(\"\")\n parser.add_argument('arg1', nargs='?', default=\"cs\", help=\"1st Positional arg\")\n parser.add_argument('arg2', nargs='?', default=METHOD_RAKE, help=\"1st Positional arg\")\n args = parser.parse_args()\n method = args.arg2\n\n inFile = args.arg1\n\n phraseinFile = inFile + method_name2suffix_termlist(method)\n\n if os.path.exists(phraseinFile):\n outFile = inFile + method_name2suffix(method)\n extract_by_phrase_list(inFile, phraseinFile, outFile)\n","repo_name":"kleeeeea/ECON","sub_path":"candidate_generation/to_term_list/seg_with_vocab.py","file_name":"seg_with_vocab.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"24220107615","text":"import json\nfrom .right import encodeToken\nfrom .fcutils import dataToJson, dict2xml\nfrom .constant import getConfByName, FC_START_RESPONSE\n\n__all__ = ['ResponseEntity']\n\nclass ResponseEntity:\n\n def __init__(self, statusCode, res=None, token=None):\n ''' 返回数据封装\n --\n @param statusCode: http代码\n @param res: 返回的数据【dict, list, str】\n @param token: token\n '''\n self.statusCode = statusCode\n self.res = res\n self.response_headers = [('Content-type', 'application/json')]\n self.token = token\n self.num = -1\n self.resType = 'json'\n self._kw = None\n\n @staticmethod\n def status(statusCode):\n ''' 自定义状态\n --\n '''\n return ResponseEntity(statusCode)\n\n @staticmethod\n def ok(res):\n ''' 200,成功\n --\n '''\n return ResponseEntity('200', res)\n\n @staticmethod\n def responseXml(res):\n ''' 返回xml\n --\n '''\n return ResponseEntity('200', res, resType='xml')\n\n @staticmethod\n def badRequest(res):\n ''' 400,错误请求\n --\n '''\n return ResponseEntity('400', res)\n\n @staticmethod\n def unauthorized(res):\n ''' 401,权限不足\n --\n '''\n return ResponseEntity('401', res)\n\n @staticmethod\n def notFound(res):\n ''' 404,未找到\n --\n '''\n return ResponseEntity('404', res)\n\n @staticmethod\n def serverError(res):\n ''' 500, 服务器错误\n --\n '''\n return ResponseEntity('500', res)\n \n @staticmethod\n def strResponseEntity(statusCode, res):\n ''' 返回原始字符串给前端\n --\n '''\n response = StrResponseEntity(statusCode, res)\n response.setResType('html')\n return response\n\n def setResType(self, resType):\n ''' 设置返回值类型\n --\n '''\n if resType == 'json':\n self.header([('Content-type', 'application/json')])\n elif resType == 'xml':\n self.header([('Content-type', 'text/xml')])\n elif resType == 'html':\n self.header([('Content-type', 'text/html')])\n else:\n self.resType = resType\n\n return self\n\n def header(self, response_headers=[('Content-type', 'application/json')]):\n ''' 自定义HTTP头\n --\n '''\n if isinstance(response_headers, list):\n return self\n if len(response_headers) < 1:\n return self\n if isinstance(response_headers[0], tuple):\n return self\n\n for h in response_headers:\n if h[0] == 'Content-type':\n if 'json' in h[1]:\n self.resType = 'json'\n elif 'xml' in h[1]:\n self.resType = 'xml'\n elif 'html' in h[1]:\n self.resType = 'html'\n else:\n return self\n self.response_headers = response_headers\n return self\n return self\n \n def body(self, res):\n ''' 自定义Data内容\n --\n '''\n self.res = res\n return self\n\n def setToken(self, token):\n ''' 自定义token\n --\n '''\n self.token = token\n return self\n \n def setKW(self, **kw):\n ''' 自定义返回值,此处定义的参数与data同级\n --\n '''\n self._kw = kw\n return kw\n \n def setNum(self, num):\n ''' 自定义num,data数据为list时有效\n --\n '''\n self.num = num\n return self\n \n def build(self, token = None):\n ''' 生成请求\n :param token 返回给用户的token\n '''\n start_response = getConfByName(FC_START_RESPONSE)\n start_response(self.statusCode, self.response_headers)\n \n response = {}\n data = {}\n \n if self._kw:\n response.update(self._kw)\n \n if isinstance(self.res, str):\n # html直接编码返回\n if self.resType == 'html':\n return [self.res.encode()]\n data = self.res\n elif isinstance(self.res, list):\n data = {'sum':len(self.res) if self.num == -1 else self.num, 'list':self.res}\n elif isinstance(self.res, tuple):\n data = {'sum':len(self.res) if self.num == -1 else self.num, 'list':list(self.res)}\n elif isinstance(self.res, dict) :\n if self.resType == 'json':\n data = self.res\n elif self.resType == 'xml':\n xml = dict2xml.Dict2XML()\n data = xml.parse(self.res)\n else:\n data = str(self.res)\n\n if self.statusCode == '200':\n # 优先使用自定义Token\n if self.token:\n response['token'] = encodeToken(self.token)\n elif token:\n response['token'] = encodeToken(token)\n \n response['data'] = data\n\n codeRes = dataToJson(response)\n return [json.dumps(codeRes).encode()]\n\n def __str__(self):\n return json.dumps({'status':self.statusCode, 'res':str(self.res)}) \n\n\nclass StrResponseEntity(ResponseEntity):\n def build(self, token = None):\n start_response = getConfByName(FC_START_RESPONSE)\n start_response(self.statusCode, self.response_headers)\n if not isinstance(self.res, str):\n self.res = str(self.res)\n return [self.res.encode()]","repo_name":"somnusmo/ali-fc-web","sub_path":"AliFCWeb/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"28936083812","text":"import time\nimport numpy as np\nimport adi\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n\nsample_rate = 40e6 #Hz\nfc = 2450e6 #Hz\n\nsdr = adi.Pluto(\"ip:192.168.2.1\")\nsdr.gain_control_mode = 'manual' \nsdr.sample_rate = int(sample_rate) \nsdr.rx_rf_bandwidth = int(sample_rate) \nsdr.rx_lo = int(fc) \nsdr.rx_hardwaregain_chan0 = 70.0\nsdr.rx_buffer_size = 8192\n\ncounter = 0\n\ndata_array = sdr.rx()\n\nf, t, Sxx = signal.spectrogram(data_array, sample_rate, return_onesided=False)\nf = np.fft.fftshift(f)+fc\nSxx = np.fft.fftshift(Sxx, axes=0,)\nSxx = np.transpose(Sxx)\nSxx = np.flipud(Sxx)\n# data = np.abs(data_array)\n# phase = np.angle(data_array)\n\n# #doesn't work becasue you're changing the whole data array\n# for i in phase:\n# if i < 0:\n# data = np.abs(data_array)*(-1)\n# else:\n# data = np.abs(data_array)*(+1)\n\n# for i in range(len(phase)):\n# if phase[i] < 0:\n# data[i] = data[i] * -1\n# else:\n# data[i] = data[i] * 1\n\n# for i in range(len(phase)):\n# if phase[i] < 0:\n# data[i] = data[i] * -1\n \n# out_data = []\n# for i in data_array:\n# out_data.append(np.abs(i)*np.sign(np.phase(i)))\n\nout_data = [np.abs(x)*np.sign(np.angle(x)) for x in data_array]\ntime_domain = np.linspace(0,sdr.rx_buffer_size/sample_rate,len(data_array))\n\nplt.subplot(2,1,1)\nplt.plot(time_domain, out_data)\nplt.xlabel(\"Time [sec]\")\nplt.ylabel(\"Magnitude\")\n\nplt.subplot(2,1,2)\nplt.pcolormesh(f, t, Sxx, shading=\"gouraud\")\nplt.xlabel(\"Freqeuency [Hz]\")\nplt.ylabel(\"Time [sec]\")\nplt.show()\n","repo_name":"jorgogushi/wpi-ece4305-C22-Team1","sub_path":"ece4305_rev1.py","file_name":"ece4305_rev1.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4410129775","text":"import argparse # هي الوحدة التي تجعل التطبيق يعمل على سطر الاوامر\nfrom argparse import (\n ArgumentParser,\n) # هذا الصنف يحول ما يدخله المستخدم الى كائن تقدر تتعامل معه للغة بايثون\nfrom taskaty.TaskController import TaskController\n\n\ndef main():\n controller = TaskController(\"tasks.txt\")\n\n parser = ArgumentParser(\n description=\"Simple CLI task manger\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n # يقوم بعملية التحليل للمدخلات من المستخدم\n # use decrcription to descripe the project\n # و الا المحلل لن يتعرف عليهاparse_args() يجب استدعى كل الوسائط قبل استداع\n # parser.add_argument('add') # to add some thing\n parser.set_defaults(func=None)\n subparser = parser.add_subparsers()\n\n # add tas\n add_task = subparser.add_parser(\"add\", help=\"Add the given task: \")\n add_task.add_argument(\"title\", help=\"Title of the task\", type=str)\n add_task.add_argument(\n \"-d\",\n \"--description\",\n help=\"Short description of the task\",\n type=str,\n default=None,\n ) # use default use to set value if the user note enter\n add_task.add_argument(\n \"-s\", \"--start_date\", help=\"Date to begin the task\", type=str, default=None\n )\n add_task.add_argument(\n \"-e\", \"--end_date\", help=\"Date to end the task\", type=str, default=None\n )\n add_task.add_argument(\n \"--done\", help=\"Check whether the task is done or not\", default=False\n )\n add_task.set_defaults(func=controller.add_task)\n\n # list task\n list_tasks = subparser.add_parser(\"list\", help=\" List unfinished tasks\")\n list_tasks.add_argument(\n \"-a\", \"--all\", help=\"List all the tasks\", action=\"store_true\"\n )\n # use action to know what action will done\n list_tasks.set_defaults(func=controller.tabulate)\n\n # check task\n do_task = subparser.add_parser(\"check\", help=\"Check the given task\")\n do_task.add_argument(\n \"-t\",\n \"--task\",\n help=\"Number of the task to be done. If not specified, last task will be removed.\",\n type=int,\n )\n do_task.set_defaults(func=controller.do_task)\n\n # remove task\n remove = subparser.add_parser(\"remove\", help=\" Remove a task \")\n remove.add_argument(\n \"-t\", \"--task\", help=\"The task to be removed ( Number )\", type=int\n )\n remove.set_defaults(func=controller.remove)\n\n # reset\n reset = subparser.add_parser(\"reset\", help=\"Remove all tasks.\")\n reset.set_defaults(func=controller.reset)\n\n args = parser.parse_args() # يحول التطبيع الى تطبيق في سطر الاورامر\n if not args.func:\n return\n args.func(args)\n\n\nif __name__ == \"__main__\": # لتجنب عمل الشفره عند استدعاها في ملف اخر\n main()\n","repo_name":"EngAbdurabu/taskaty_Project","sub_path":"taskaty/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"ar","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11990318434","text":"from django.core.management.base import BaseCommand\r\nfrom core.models import Book,Author\r\n\r\nclass Command(BaseCommand):\r\n help = 'Load book data'\r\n\r\n def handle(self,*args,**kwargs):\r\n #create authours\r\n orwell = Author.objects.get_or_create(name='George Orwell')[0]\r\n\r\n #create books\r\n Book.objects.get_or_create(\r\n name='1981',\r\n author=orwell,\r\n price=10.99,\r\n genre=Book.GenreChoices.SCI_FI,\r\n number_in_stock=4\r\n )\r\n","repo_name":"goeych/dj_filter","sub_path":"core/createData.py","file_name":"createData.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10095926372","text":"'''\r\nФункция roundrobin() 🌶️\r\nРеализуйте функцию roundrobin(), которая принимает произвольное количество позиционных \r\nаргументов, каждый из которых является итерируемым объектом.\r\n\r\nФункция должна возвращать итератор, генерирующий последовательность из элементов всех переданных \r\nитерируемых объектов: сначала первый элемент первого итерируемого объекта, затем первый элемент второго \r\nитерируемого объекта, и так далее; после второй элемент первого итерируемого объекта, затем второй элемент второго \r\nитерируемого объекта, и так далее.\r\n\r\nПримечание 1. Элементы итерируемых объектов в возвращаемом функцией итераторе должны располагаться в своем исходном порядке.\r\n\r\nПримечание 2. Гарантируется, что итерируемый объект, передаваемый в функцию, не является множеством.\r\n\r\nПримечание 3. В тестирующую систему сдайте программу, содержащую только необходимую функцию roundrobin(), но не код, вызывающий ее.\r\n\r\nПримечание 4. Тестовые данные доступны по ссылкам:\r\n'''\r\nimport itertools as it\r\n\r\ndef roundrobin(*args):\r\n\r\n iterators_list :list = [iter(sequence) for sequence in args] \r\n \r\n cycle_gen_list :list = it.cycle(iterators_list)\r\n \r\n while iterators_list:\r\n curent_sec = next(cycle_gen_list)\r\n try:\r\n yield next(curent_sec)\r\n except:\r\n iterators_list = [iter for iter in iterators_list if iter!=curent_sec]\r\n\r\n \r\n \r\n \r\n\r\n\r\n# INPUT DATA:\r\n\r\n# TEST_1:\r\nprint(*roundrobin('abc', 'd', 'ef'))\r\n\r\n# TEST_2:\r\nnumbers = [1, 2, 3]\r\nletters = iter('beegeek')\r\n\r\nprint(*roundrobin(numbers, letters))\r\n\r\n# TEST_3:\r\nprint(list(roundrobin()))\r\n\r\n# TEST_4:-ошибка (1 0 b 2 1 e 3 2 e 4 3 g 5 4 e 6 e 7 k 8 9 10)\r\nnumbers1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\r\nnumbers2 = range(5)\r\nletters = iter('beegeek')\r\n\r\nprint(*roundrobin(numbers1, numbers2, letters))\r\n\r\n# TEST_5:\r\nletters = iter('stepik')\r\n\r\nprint(*roundrobin(letters))\r\n\r\n# TEST_6:\r\nnumbers = roundrobin(map(abs, range(-10, 10)))\r\n\r\nprint(next(numbers))\r\nprint(next(numbers))\r\nprint(next(numbers))\r\nprint(next(numbers))\r\nprint(next(numbers))\r\nprint(next(numbers))\r\n\r\n\r\n# TEST_7: -ошибка (10 -10 5 -5 1 -1 9 -9 4 -4 0 8 -8 3 -3 7 -7 2 -2 6 -6 1 -1 5 -5 0 1 4 -4 1 2 3 -3 2 3 2 -2 3 4 1 -1 4 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9)\r\nnumbers1 = map(abs, range(-10, 10))\r\nnumbers2 = filter(None, range(-10, 10))\r\nnumbers3 = map(abs, range(-5, 5))\r\nnumbers4 = filter(None, range(-5, 5))\r\nnumbers5 = map(abs, range(-1, 1))\r\nnumbers6 = filter(None, range(-1, 1))\r\n\r\nprint(*roundrobin(numbers1, numbers2, numbers3, numbers4, numbers5, numbers6))\r\n\r\n# TEST_8:\r\nprint(list(roundrobin([], [], [], [])))\r\n\r\n# TEST_9:\r\nnumbers = iter([1, 2, 3])\r\nnones = iter([None, None, None, None])\r\n\r\nprint(*roundrobin(numbers, nones))\r\n\r\n","repo_name":"GolosCD/python_gen_professional","sub_path":"10.8.4.py","file_name":"10.8.4.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7874422146","text":"import anndata as ad\nimport numpy as np\nfrom params import Params\nimport utils.common as cm\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('macosx')\n\np = Params()\nadata = ad.read_h5ad(p.file_path)\n\nunique_individuals = np.unique(adata.obs['individual'])\nnormalized_expression = {}\nfor ind in unique_individuals:\n print(ind)\n indices = adata.obs['individual'] == ind\n gene_expression = np.sum(adata[indices, 'RPS4Y1'].X)\n total_expression = np.sum(adata[indices, :].X)\n normalized_expression[ind] = gene_expression / total_expression\n\nplt.hist(normalized_expression.values(), bins=20, range=(0, 0.0005))\nplt.xlabel(\"Values\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Histogram\")\nplt.show()\n\ngender_mapping = {\"Male\": [], \"Female\": []}\nfor ind, expr in normalized_expression.items():\n if expr > 0.0001:\n gender_mapping[\"Male\"].append(ind)\n else:\n gender_mapping[\"Female\"].append(ind)\n\n# sorted_expression_sum = sorted(normalized_expression.items(), key=lambda x: x[1])\n# split_point = len(sorted_expression_sum) // 2\n# gender_mapping = {\"Female\": [item[0] for item in sorted_expression_sum[:split_point]],\n# \"Male\": [item[0] for item in sorted_expression_sum[split_point:]]}\nprint(gender_mapping)\nadata.obs[\"gender\"] = adata.obs[\"individual\"].map(lambda x: \"Male\" if x in gender_mapping[\"Male\"] else \"Female\")\ncm.safe_save(adata, p.file_path)\n","repo_name":"umarov90/ALS","sub_path":"STAGE_1/4_gender_select.py","file_name":"4_gender_select.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27384421783","text":"from argparse import ArgumentParser\nfrom bokeh.models import Legend, NumeralTickFormatter, ColumnDataSource\nfrom bokeh.plotting import figure\nfrom bokeh.models.tools import HoverTool\nfrom bokeh.embed import json_item\nfrom bokeh.palettes import grey\n\nimport pandas as pd\nimport sys\n\n# GridPath modules\nfrom db.common_functions import connect_to_database\nfrom gridpath.auxiliary.db_interface import get_scenario_id_and_name\nfrom viz.common_functions import (\n show_hide_legend,\n show_plot,\n get_parent_parser,\n get_unit,\n)\n\n\ndef create_parser():\n \"\"\"\n\n :return:\n \"\"\"\n parser = ArgumentParser(add_help=True, parents=[get_parent_parser()])\n parser.add_argument(\n \"--scenario_id\",\n help=\"The scenario ID. Required if \" \"no --scenario is specified.\",\n )\n parser.add_argument(\n \"--scenario\",\n help=\"The scenario name. Required if \" \"no --scenario_id is specified.\",\n )\n parser.add_argument(\n \"--project\", required=True, type=str, help=\"The name of the project. Required\"\n )\n parser.add_argument(\n \"--period\",\n required=True,\n type=int,\n help=\"The desired modeling period. Required\",\n )\n parser.add_argument(\n \"--stage\", default=1, type=int, help=\"The stage ID. Defaults to 1.\"\n )\n parser.add_argument(\n \"--horizon_start\",\n type=int,\n help=\"The desired starting horizon. Assumes horizons\"\n \"are a set of increasing numbers. Optional\",\n )\n parser.add_argument(\n \"--horizon_end\",\n type=int,\n help=\"The desired ending horizon. Assumes horizons are\"\n \"a set of increasing numbers. Optional\",\n )\n\n return parser\n\n\ndef parse_arguments(arguments):\n \"\"\"\n\n :return:\n \"\"\"\n parser = create_parser()\n parsed_arguments = parser.parse_args(args=arguments)\n\n return parsed_arguments\n\n\ndef get_plotting_data(\n conn, scenario_id, project, period, stage, horizon_start, horizon_end, **kwargs\n):\n \"\"\"\n Get operations by timepoint for a given scenario/project/period/stage and\n horizon range.\n\n **kwargs needed, so that an error isn't thrown when calling this\n function with extra arguments from the UI.\n\n :param conn:\n :param scenario_id:\n :param project:\n :param period:\n :param stage:\n :param horizon_start:\n :param horizon_end:\n :return:\n \"\"\"\n\n # TODO: this is probably not needed anymore, as commitment decisions for\n # projects with no commit decisions will simply be NULL\n # Get operational type to determine table\n c = conn.cursor()\n sql = \"\"\"SELECT operational_type from inputs_project_operational_chars\n INNER JOIN scenarios\n USING (project_operational_chars_scenario_id)\n WHERE scenario_id = ?\n AND project = ?\n ;\"\"\"\n operational_type = c.execute(sql, (scenario_id, project)).fetchone()[0]\n\n if operational_type not in [\"gen_commit_cap\", \"gen_commit_bin\", \"gen_commit_lin\"]:\n raise ValueError(\n \"Selected project does not have commitment decisions.\"\n \"Please select a project of one of the operational types with \"\n \"commitment decisions: 'distpachable_capacity_commit', \"\n \"'gen_commit_bin' or 'gen_commit_lin'\"\n )\n\n # TODO: Could avoid SQL insertions by addding the WHERE clause anywhere\n # but changing the value we check\n # (default would be start = 0 and end = 999999999)\n # However, the table insertion is unavoidable with this approach\n if horizon_start is not None:\n horizon_start_slice = \"AND horizon >= {}\".format(horizon_start)\n else:\n horizon_start_slice = \"\"\n\n if horizon_end is not None:\n horizon_end_slice = \"AND horizon <= {}\".format(horizon_end)\n else:\n horizon_end_slice = \"\"\n\n # Project operations (commitment, power, and reserves)\n sql = \"\"\"\n SELECT scenario_id, project, period, horizon, timepoint,\n SUM(number_of_hours_in_timepoint) \n OVER (PARTITION BY horizon ORDER BY timepoint) AS hour_on_horizon,\n SUM(number_of_hours_in_timepoint) \n OVER (PARTITION BY period ORDER BY timepoint) AS hour_on_period,\n committed_mw, power_mw, \n (min_stable_level_fraction * committed_mw) AS min_stable_level_mw,\n spin_mw, reg_up_mw, reg_down_mw, lf_up_mw, lf_down_mw, frq_resp_mw\n FROM\n (SELECT scenario_id, project, period, stage_id, horizon, timepoint, \n number_of_hours_in_timepoint,\n committed_mw, power_mw\n FROM results_project_timepoint\n WHERE operational_type = '{}'\n AND scenario_id = ?\n {} \n {}\n AND project = ?\n AND period = ?\n AND stage_id = ?) AS commitment_table\n \n LEFT JOIN\n \n (SELECT scenario_id, project, period, stage_id, horizon, timepoint,\n spinning_reserves_reserve_provision_mw as spin_mw \n FROM results_project_timepoint) AS spin_tbl\n USING (scenario_id, project, period, stage_id, horizon, timepoint)\n \n LEFT JOIN\n \n (SELECT scenario_id, project, period, stage_id, horizon, timepoint,\n regulation_up_reserve_provision_mw as reg_up_mw \n FROM results_project_timepoint) AS reg_up_tbl\n USING (scenario_id, project, period, stage_id, horizon, timepoint)\n \n LEFT JOIN\n \n (SELECT scenario_id, project, period, stage_id, horizon, timepoint,\n regulation_down_reserve_provision_mw as reg_down_mw \n FROM results_project_timepoint) AS reg_down_tbl\n USING (scenario_id, project, period, stage_id, horizon, timepoint)\n \n LEFT JOIN\n \n (SELECT scenario_id, project, period, stage_id, horizon, timepoint,\n lf_reserves_up_reserve_provision_mw as lf_up_mw \n FROM results_project_timepoint) AS lf_up_tbl\n USING (scenario_id, project, period, stage_id, horizon, timepoint)\n \n LEFT JOIN\n \n (SELECT scenario_id, project, period, stage_id, horizon, timepoint,\n lf_reserves_down_reserve_provision_mw as lf_down_mw \n FROM results_project_timepoint) AS lf_down_tbl\n USING (scenario_id, project, period, stage_id, horizon, timepoint)\n \n LEFT JOIN\n \n (SELECT scenario_id, project, period, stage_id, horizon, timepoint,\n frequency_response_reserve_provision_mw as frq_resp_mw \n FROM results_project_timepoint) AS frq_resp_tbl\n USING (scenario_id, project, period, stage_id, horizon, timepoint)\n \n LEFT JOIN\n \n (SELECT scenario_id, project, min_stable_level_fraction\n FROM inputs_project_operational_chars\n JOIN scenarios\n USING (project_operational_chars_scenario_id)\n ) as op_table\n USING (scenario_id, project)\n \n ORDER BY horizon, timepoint\n ;\"\"\".format(\n operational_type, horizon_start_slice, horizon_end_slice\n )\n\n df = pd.read_sql(sql, con=conn, params=(scenario_id, project, period, stage))\n\n # Add additional info for hovers\n df[\"power_pct_of_committed\"] = df[\"power_mw\"] / df[\"committed_mw\"]\n df[\"min_stable_level_pct_of_committed\"] = (\n df[\"min_stable_level_mw\"] / df[\"committed_mw\"]\n )\n\n # Add helper columns for reserves\n df[\"bottom_reserves\"] = df[\"power_mw\"] - df[[\"reg_down_mw\", \"lf_down_mw\"]].sum(\n axis=1\n )\n\n # Rename columns for cleaner plotting\n rename_dict = {\n \"power_mw\": \"Power\",\n \"committed_mw\": \"Committed Capacity\",\n \"min_stable_level_mw\": \"Minimum Output\",\n \"reg_down_mw\": \"Regulation Down\",\n \"lf_down_mw\": \"Load Following Down\",\n \"lf_up_mw\": \"Load Following Up\",\n \"reg_up_mw\": \"Regulation Up\",\n \"frq_resp_mw\": \"Frequency Response\",\n \"spin_mw\": \"Spinning Reserves\",\n }\n df.rename(columns=rename_dict, inplace=True)\n\n return df\n\n\ndef create_plot(df, title, power_unit, ylimit=None):\n \"\"\"\n\n :param df:\n :param title: string, plot title\n :param power_unit: string, the unit of power used in the database/model\n :param ylimit: float/int, upper limit of y-axis; optional\n :return:\n \"\"\"\n\n # Set up data source\n source = ColumnDataSource(data=df)\n\n # Determine column types for plotting, legend and colors\n x_col = \"hour_on_period\"\n power_col = \"Power\"\n commitment_col = \"Committed Capacity\"\n stable_level_col = \"Minimum Output\"\n all_reserves = [\n \"bottom_reserves\",\n \"Regulation Down\",\n \"Load Following Down\",\n \"Load Following Up\",\n \"Regulation Up\",\n \"Frequency Response\",\n \"Spinning Reserves\",\n ]\n active_reserves = list(\n df[all_reserves].columns[\n df[all_reserves].notna().all() & df[all_reserves].mean() > 0\n ]\n )\n\n # Setup the reserve colors\n colors = grey(len(active_reserves) + 2)[1:-1] # skip the white/black colors\n alphas = [0] + [1] * (len(active_reserves) - 1) if active_reserves else []\n\n # Set up the figure\n plot = figure(\n plot_width=800,\n plot_height=500,\n tools=[\"pan\", \"reset\", \"zoom_in\", \"zoom_out\", \"save\", \"help\"],\n title=title,\n )\n\n # Add reserve area renderers\n area_renderers = plot.vbar_stack(\n stackers=active_reserves,\n x=x_col,\n source=source,\n fill_color=colors,\n fill_alpha=alphas,\n line_color=colors,\n line_alpha=alphas,\n width=1,\n )\n\n # Add operations to plot\n power_renderer = plot.step(\n name=\"Power\",\n source=source,\n x=x_col,\n y=power_col,\n color=\"black\",\n mode=\"center\",\n )\n commitment_renderer = plot.step(\n name=\"Committed Capacity\",\n source=source,\n x=x_col,\n y=commitment_col,\n color=\"black\",\n line_dash=\"dashed\",\n mode=\"center\",\n )\n stable_level_renderer = plot.step(\n name=\"Minimum Output\",\n source=source,\n x=x_col,\n y=stable_level_col,\n color=\"black\",\n line_dash=\"dotted\",\n mode=\"center\",\n )\n\n # Add legend items\n legend_items = [\n (commitment_renderer.name, [commitment_renderer]),\n (power_renderer.name, [power_renderer]),\n (stable_level_renderer.name, [stable_level_renderer]),\n ] + list(reversed([(r.name, [r]) for r in area_renderers[1:]]))\n\n # Add Legend\n legend = Legend(items=legend_items)\n plot.add_layout(legend, \"right\")\n plot.legend.click_policy = \"hide\" # Add interactivity to the legend\n # Note: Doesn't rescale the graph down, simply hides the area\n # Note2: There's currently no way to auto-size legend based on graph size(?)\n # except for maybe changing font size automatically?\n show_hide_legend(plot=plot) # Hide legend on double click\n\n # Format Axes (labels, number formatting, range, etc.)\n plot.xaxis.axis_label = \"Hour\"\n plot.yaxis.axis_label = power_unit\n plot.yaxis.formatter = NumeralTickFormatter(format=\"0,0\")\n plot.y_range.end = ylimit # will be ignored if ylimit is None\n\n # Add HoverTools\n # Note: stepped lines or varea charts not yet supported (lines/bars OK)\n # Note: skip bottom renderer for vbars/areas since it's just a helper\n hover_renderers = area_renderers[1:] + [\n commitment_renderer,\n power_renderer,\n stable_level_renderer,\n ]\n for r in hover_renderers:\n tooltips = [(\"Hour\", \"@%s\" % x_col), (r.name, \"@$name{0,0} %s\" % power_unit)]\n if r.name == \"Power\":\n tooltips.append((\"% of Committed\", \"@power_pct_of_committed{0%}\"))\n elif r.name == \"Minimum Output\":\n tooltips.append(\n (\"% of Committed\", \"@min_stable_level_pct_of_committed{0%}\")\n )\n hover = HoverTool(tooltips=tooltips, renderers=[r], toggleable=False)\n plot.add_tools(hover)\n\n return plot\n\n\ndef main(args=None):\n \"\"\"\n Parse the arguments, get the data in a df, and create the plot\n\n :return: if requested, return the plot as JSON object\n \"\"\"\n if args is None:\n args = sys.argv[1:]\n parsed_args = parse_arguments(arguments=args)\n\n conn = connect_to_database(db_path=parsed_args.database)\n c = conn.cursor()\n\n scenario_id, scenario = get_scenario_id_and_name(\n scenario_id_arg=parsed_args.scenario_id,\n scenario_name_arg=parsed_args.scenario,\n c=c,\n script=\"project_operations_plot\",\n )\n\n power_unit = get_unit(c, \"power\")\n\n plot_title = \"{}Operations Plot - {} - {} - Stage {}\".format(\n \"{} - \".format(scenario) if parsed_args.scenario_name_in_title else \"\",\n parsed_args.project,\n parsed_args.period,\n parsed_args.stage,\n )\n plot_name = \"OperationsPlot-{}-{}-{}\".format(\n parsed_args.project, parsed_args.period, parsed_args.stage\n )\n\n start = parsed_args.horizon_start\n end = parsed_args.horizon_end\n if start is not None and end is not None:\n appendix = \" - Horizon {}-{}\".format(start, end)\n elif start is not None and end is None:\n appendix = \" - Horizon {}-end\".format(start)\n elif start is None and end is not None:\n appendix = \" - Horizon start-{}\".format(end)\n else:\n appendix = \"\"\n\n plot_title += appendix\n\n df = get_plotting_data(\n conn=conn,\n scenario_id=scenario_id,\n project=parsed_args.project,\n period=parsed_args.period,\n stage=parsed_args.stage,\n horizon_start=parsed_args.horizon_start,\n horizon_end=parsed_args.horizon_end,\n )\n\n plot = create_plot(\n df=df, title=plot_title, power_unit=power_unit, ylimit=parsed_args.ylimit\n )\n\n # Show plot in HTML browser file if requested\n if parsed_args.show:\n show_plot(\n plot=plot,\n plot_name=plot_name,\n plot_write_directory=parsed_args.plot_write_directory,\n scenario=scenario,\n )\n\n # Return plot in json format if requested\n if parsed_args.return_json:\n return json_item(plot, \"plotHTMLTarget\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"blue-marble/gridpath","sub_path":"viz/project_operations_plot.py","file_name":"project_operations_plot.py","file_ext":"py","file_size_in_byte":14145,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"52"} +{"seq_id":"9809869081","text":"import logging\n\nfrom django.core.exceptions import ValidationError\nfrom django.core.management import BaseCommand\n\nfrom signals.apps.reporting.csv.horeca import create_csv_files\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument('isoweek', type=int)\n parser.add_argument('isoyear', type=int)\n\n def _validate_arguments(self, options):\n logger.info('Validate given arguments')\n if options['isoweek'] and (options['isoweek'] < 1 or options['isoweek'] > 53):\n raise ValidationError('Given week must be between 0 or 53')\n\n def handle(self, *args, **options):\n logger.info('Dump Horeca CSV files per sub category')\n\n self._validate_arguments(options)\n\n csv_files = create_csv_files(isoweek=options['isoweek'],\n isoyear=options['isoyear'])\n\n for csv_file in csv_files:\n logger.info('Created file \"{}\"'.format(csv_file))\n","repo_name":"Amsterdam/signals","sub_path":"app/signals/apps/reporting/management/commands/dump_horeca_csv_files.py","file_name":"dump_horeca_csv_files.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"1893849972","text":"from __version__ import __version__\n\nimport setuptools\n\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\nsetuptools.setup(\n name=\"smartfit_booking\",\n version=__version__,\n author=\"Stiven Ramírez Arango\",\n author_email=\"stivenramireza@gmail.com\",\n description=\"Smart Fit gym booking package\",\n packages=setuptools.find_packages(),\n python_requires=\">=3.6\",\n install_requires=required\n)","repo_name":"stivenramireza/smartfit-booking","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"40255878102","text":"from uuid import uuid4\n\nfrom django.test import TestCase\n\nfrom actor.apps import ActorConfig\nfrom actor.models import Actor, GenderTypes, Specie\n\n\nclass ActorTestCase(TestCase):\n actor_name = \"Keir Dullea\"\n\n def setUp(self):\n super().setUp()\n self.human_specie = Specie.objects.create(name=\"Human\", classification=\"Mammal\")\n self.dog_specie = Specie.objects.create(name=\"Dog\", classification=\"Mammal\")\n\n def test_apps(self):\n self.assertEqual(ActorConfig.name, \"actor\")\n\n def test_actor_model(self):\n actor_id = uuid4()\n Actor.objects.create(id=actor_id, name=self.actor_name, specie=self.human_specie)\n actor = Actor.objects.get(id=actor_id)\n self.assertEqual(actor.gender, GenderTypes.UNKNOWN)\n for field in [\"age\", \"eye_color\", \"hair_color\"]:\n self.assertEqual(getattr(actor, field), \"Unspecified\")\n self.assertEqual(actor.specie.id, self.human_specie.id)\n self.assertEqual(str(actor), self.actor_name)\n\n def test_specie_model(self):\n self.assertEqual(str(self.dog_specie), self.dog_specie.name)\n","repo_name":"mastizada/ghiblimovies","sub_path":"actor/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"6096127621","text":"import random\n\n#calcula o dano médio da arma.\nmin_dmg = random.randint(1,10)\nmax_dmg = random.randint(10,50)\ndamage = random.randint(min_dmg, max_dmg)\navg_damage = (min_dmg + max_dmg) / 2\n\n#velocidade de ataque.\nspd_dmg = max(2, round(random.random() * 7.5,1))\n\nfire_sts = 0 \nice_sts = 0\n\n#função para atribuir dano de fogo.\ndef fire_atr ():\n min_fire_sts = round(damage * 0.1)\n max_fire_sts = round(damage * 0.5)\n fire_sts = random.randint(min_fire_sts, max_fire_sts)\n return fire_sts\n\n#função para atribuir dano de gelo.\ndef ice_atr ():\n min_ice_sts = round(damage * 0.1)\n max_ice_sts = round(damage * 0.5)\n ice_sts = random.randint(min_ice_sts, max_ice_sts)\n return ice_sts\n\n#chance de rolar dano de fogo ou gelo na arma.\nfire_chance = random.randint(1,20)\nice_chance = random.randint(1,20)\nif fire_chance >=18:\n fire_sts = fire_atr()\nif ice_chance >=18:\n ice_sts = ice_atr()\n\nt_dmg = round((avg_damage * spd_dmg) + fire_sts + ice_sts,1)\nprint(\"Your dagger's status:\\n\")\n\nif t_dmg > 50 and t_dmg < 100:\n print(\"Rare dagger\")\nelif t_dmg >= 100 and t_dmg < 175:\n print(\"Epic dagger\")\nelif t_dmg >= 175:\n print(\"Legendary dagger\")\nelse:\n print(\"Common dagger\")\nprint(f\"\\n{min_dmg} - {max_dmg}\\n\")\nprint(f\"Avg Damage: {avg_damage}\\nAttack speed: {spd_dmg}\\nFire damage: {fire_sts}\\nIce damage: {ice_sts}\\nDPS: {t_dmg}\")","repo_name":"Danill0-o/aula01-udemy","sub_path":"dagger_generator.py","file_name":"dagger_generator.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34099081422","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom builtins import str, bytes, dict, int\nfrom builtins import map, zip, filter\nfrom builtins import object, range\n\nimport os\nimport sys\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), \"..\"))\nimport unittest\nimport subprocess\n\nfrom pattern import it\n\nfrom io import open\n\ntry:\n PATH = os.path.dirname(os.path.realpath(__file__))\nexcept:\n PATH = \"\"\n\n#---------------------------------------------------------------------------------------------------\n\n\nclass TestInflection(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_article(self):\n # Assert definite and indefinite article inflection.\n for a, n, g in (\n (\"il\" , \"giorno\" , it.M),\n (\"l'\" , \"altro giorno\", it.M),\n (\"lo\" , \"zio\" , it.M),\n (\"l'\" , \"amica\" , it.F),\n (\"la\" , \"nouva amica\" , it.F),\n (\"i\" , \"giapponesi\" , it.M + it.PL),\n (\"gli\", \"italiani\" , it.M + it.PL),\n (\"gli\", \"zii\" , it.M + it.PL),\n (\"le\" , \"zie\" , it.F + it.PL)):\n v = it.article(n, \"definite\", gender=g)\n self.assertEqual(a, v)\n for a, n, g in (\n (\"uno\", \"zio\" , it.M),\n (\"una\", \"zia\" , it.F),\n (\"un\" , \"amico\", it.M),\n (\"un'\", \"amica\", it.F)):\n v = it.article(n, \"indefinite\", gender=g)\n self.assertEqual(a, v)\n v = it.referenced(\"amica\", gender=\"f\")\n self.assertEqual(v, \"un'amica\")\n print(\"pattern.it.article()\")\n print(\"pattern.it.referenced()\")\n\n def test_gender(self):\n # Assert the accuracy of the gender disambiguation algorithm.\n from pattern.db import Datasheet\n i, n = 0, 0\n for pos, sg, pl, mf in Datasheet.load(os.path.join(PATH, \"corpora\", \"wordforms-it-wiktionary.csv\")):\n g = it.gender(sg)\n if mf in g and it.PLURAL not in g:\n i += 1\n g = it.gender(pl)\n if mf in g and it.PLURAL in g:\n i += 1\n n += 2\n self.assertTrue(float(i) / n > 0.92)\n print(\"pattern.it.gender()\")\n\n def test_pluralize(self):\n # Assert the accuracy of the pluralization algorithm.\n from pattern.db import Datasheet\n i, n = 0, 0\n for pos, sg, pl, mf in Datasheet.load(os.path.join(PATH, \"corpora\", \"wordforms-it-wiktionary.csv\")):\n if it.pluralize(sg) == pl:\n i += 1\n n += 1\n self.assertTrue(float(i) / n > 0.93)\n print(\"pattern.it.pluralize()\")\n\n def test_singularize(self):\n # Assert the accuracy of the singularization algorithm.\n from pattern.db import Datasheet\n i, n = 0, 0\n for pos, sg, pl, mf in Datasheet.load(os.path.join(PATH, \"corpora\", \"wordforms-it-wiktionary.csv\")):\n if it.singularize(pl) == sg:\n i += 1\n n += 1\n self.assertTrue(float(i) / n > 0.84)\n print(\"pattern.it.singularize()\")\n\n def test_predicative(self):\n # Assert the accuracy of the predicative algorithm (\"cruciali\" => \"cruciale\").\n\n from pattern.db import Datasheet\n i, n = 0, 0\n for pos, sg, pl, mf in Datasheet.load(os.path.join(PATH, \"corpora\", \"wordforms-it-wiktionary.csv\")):\n if pos != \"j\":\n continue\n if it.predicative(pl) == sg:\n i += 1\n n += 1\n self.assertTrue(float(i) / n > 0.87)\n print(\"pattern.it.predicative()\")\n\n def test_find_lemma(self):\n # Assert the accuracy of the verb lemmatization algorithm.\n i, n = 0, 0\n r = 0\n for v1, v2 in it.inflect.verbs.inflections.items():\n if it.inflect.verbs.find_lemma(v1) == v2:\n i += 1\n n += 1\n self.assertTrue(float(i) / n > 0.81)\n print(\"pattern.it.inflect.verbs.find_lemma()\")\n\n def test_find_lexeme(self):\n # Assert the accuracy of the verb conjugation algorithm.\n i, n = 0, 0\n for v, lexeme1 in it.inflect.verbs.infinitives.items():\n lexeme2 = it.inflect.verbs.find_lexeme(v)\n for j in range(len(lexeme2)):\n if lexeme1[j] == lexeme2[j]:\n i += 1\n n += 1\n self.assertTrue(float(i) / n > 0.89)\n print(\"pattern.it.inflect.verbs.find_lexeme()\")\n\n def test_conjugate(self):\n # Assert different tenses with different conjugations.\n for (v1, v2, tense) in (\n (\"essere\", \"essere\", it.INFINITIVE),\n (\"essere\", \"sono\", (it.PRESENT, 1, it.SINGULAR)),\n (\"essere\", \"sei\", (it.PRESENT, 2, it.SINGULAR)),\n (\"essere\", \"è\", (it.PRESENT, 3, it.SINGULAR)),\n (\"essere\", \"siamo\", (it.PRESENT, 1, it.PLURAL)),\n (\"essere\", \"siete\", (it.PRESENT, 2, it.PLURAL)),\n (\"essere\", \"sono\", (it.PRESENT, 3, it.PLURAL)),\n (\"essere\", \"essendo\", (it.PRESENT + it.PARTICIPLE)),\n (\"essere\", \"stato\", (it.PAST + it.PARTICIPLE)),\n (\"essere\", \"ero\", (it.IMPERFECT, 1, it.SINGULAR)),\n (\"essere\", \"eri\", (it.IMPERFECT, 2, it.SINGULAR)),\n (\"essere\", \"era\", (it.IMPERFECT, 3, it.SINGULAR)),\n (\"essere\", \"eravamo\", (it.IMPERFECT, 1, it.PLURAL)),\n (\"essere\", \"eravate\", (it.IMPERFECT, 2, it.PLURAL)),\n (\"essere\", \"erano\", (it.IMPERFECT, 3, it.PLURAL)),\n (\"essere\", \"fui\", (it.PRETERITE, 1, it.SINGULAR)),\n (\"essere\", \"fosti\", (it.PRETERITE, 2, it.SINGULAR)),\n (\"essere\", \"fu\", (it.PRETERITE, 3, it.SINGULAR)),\n (\"essere\", \"fummo\", (it.PRETERITE, 1, it.PLURAL)),\n (\"essere\", \"foste\", (it.PRETERITE, 2, it.PLURAL)),\n (\"essere\", \"furono\", (it.PRETERITE, 3, it.PLURAL)),\n (\"essere\", \"sarei\", (it.CONDITIONAL, 1, it.SINGULAR)),\n (\"essere\", \"saresti\", (it.CONDITIONAL, 2, it.SINGULAR)),\n (\"essere\", \"sarebbe\", (it.CONDITIONAL, 3, it.SINGULAR)),\n (\"essere\", \"saremmo\", (it.CONDITIONAL, 1, it.PLURAL)),\n (\"essere\", \"sareste\", (it.CONDITIONAL, 2, it.PLURAL)),\n (\"essere\", \"sarebbero\", (it.CONDITIONAL, 3, it.PLURAL)),\n (\"essere\", \"sarò\", (it.FUTURE, 1, it.SINGULAR)),\n (\"essere\", \"sarai\", (it.FUTURE, 2, it.SINGULAR)),\n (\"essere\", \"sarà\", (it.FUTURE, 3, it.SINGULAR)),\n (\"essere\", \"saremo\", (it.FUTURE, 1, it.PLURAL)),\n (\"essere\", \"sarete\", (it.FUTURE, 2, it.PLURAL)),\n (\"essere\", \"saranno\", (it.FUTURE, 3, it.PLURAL)),\n (\"essere\", \"sii\", (it.PRESENT, 2, it.SINGULAR, it.IMPERATIVE)),\n (\"essere\", \"sia\", (it.PRESENT, 3, it.SINGULAR, it.IMPERATIVE)),\n (\"essere\", \"siamo\", (it.PRESENT, 1, it.PLURAL, it.IMPERATIVE)),\n (\"essere\", \"siate\", (it.PRESENT, 2, it.PLURAL, it.IMPERATIVE)),\n (\"essere\", \"siano\", (it.PRESENT, 3, it.PLURAL, it.IMPERATIVE)),\n (\"essere\", \"sia\", (it.PRESENT, 1, it.SINGULAR, it.SUBJUNCTIVE)),\n (\"essere\", \"sia\", (it.PRESENT, 2, it.SINGULAR, it.SUBJUNCTIVE)),\n (\"essere\", \"sia\", (it.PRESENT, 3, it.SINGULAR, it.SUBJUNCTIVE)),\n (\"essere\", \"siamo\", (it.PRESENT, 1, it.PLURAL, it.SUBJUNCTIVE)),\n (\"essere\", \"siate\", (it.PRESENT, 2, it.PLURAL, it.SUBJUNCTIVE)),\n (\"essere\", \"siano\", (it.PRESENT, 3, it.PLURAL, it.SUBJUNCTIVE)),\n (\"essere\", \"fossi\", (it.PAST, 1, it.SINGULAR, it.SUBJUNCTIVE)),\n (\"essere\", \"fossi\", (it.PAST, 2, it.SINGULAR, it.SUBJUNCTIVE)),\n (\"essere\", \"fosse\", (it.PAST, 3, it.SINGULAR, it.SUBJUNCTIVE)),\n (\"essere\", \"fossimo\", (it.PAST, 1, it.PLURAL, it.SUBJUNCTIVE)),\n (\"essere\", \"foste\", (it.PAST, 2, it.PLURAL, it.SUBJUNCTIVE)),\n (\"essere\", \"fossero\", (it.PAST, 3, it.PLURAL, it.SUBJUNCTIVE))):\n self.assertEqual(it.conjugate(v1, tense), v2)\n print(\"pattern.it.conjugate()\")\n\n def test_lexeme(self):\n # Assert all inflections of \"essere\".\n v = it.lexeme(\"essere\")\n self.assertEqual(v, [\n 'essere', 'sono', 'sei', 'è', 'siamo', 'siete', 'essendo',\n 'fui', 'fosti', 'fu', 'fummo', 'foste', 'furono', 'stato',\n 'ero', 'eri', 'era', 'eravamo', 'eravate', 'erano',\n 'sarò', 'sarai', 'sarà', 'saremo', 'sarete', 'saranno',\n 'sarei', 'saresti', 'sarebbe', 'saremmo', 'sareste', 'sarebbero',\n 'sii', 'sia', 'siate', 'siano',\n 'fossi', 'fosse', 'fossimo', 'fossero'\n ])\n print(\"pattern.it.inflect.lexeme()\")\n\n def test_tenses(self):\n # Assert tense recognition.\n self.assertTrue((it.PRESENT, 3, it.SG) in it.tenses(\"è\"))\n self.assertTrue(\"2sg\" in it.tenses(\"sei\"))\n print(\"pattern.it.tenses()\")\n\n#---------------------------------------------------------------------------------------------------\n\n\nclass TestParser(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_find_lemmata(self):\n # Assert lemmata for nouns, adjectives, verbs and determiners.\n v = it.parser.find_lemmata([\n [\"I\", \"DT\"], [\"gatti\", \"NNS\"], [\"neri\", \"JJ\"],\n [\"seduti\", \"VB\"], [\"sul\", \"IN\"], [\"tatami\", \"NN\"]])\n self.assertEqual(v, [\n [\"I\", \"DT\", \"il\"],\n [\"gatti\", \"NNS\", \"gatto\"],\n [\"neri\", \"JJ\", \"nero\"],\n [\"seduti\", \"VB\", \"sedutare\"],\n [\"sul\", \"IN\", \"sul\"],\n [\"tatami\", \"NN\", \"tatami\"]])\n print(\"pattern.it.parser.find_lemmata()\")\n\n def test_parse(self):\n # Assert parsed output with Penn Treebank II tags (slash-formatted).\n # \"il gatto nero\" is a noun phrase, \"sulla stuoia\" is a prepositional noun phrase.\n v = it.parser.parse(\"Il gatto nero seduto sulla stuoia.\")\n self.assertEqual(v,\n \"Il/DT/B-NP/O gatto/NN/I-NP/O nero/JJ/I-NP/O \" +\n \"seduto/VB/B-VP/O \" + \\\n \"sulla/IN/B-PP/B-PNP stuoia/NN/B-NP/I-PNP ././O/O\"\n )\n # Assert the accuracy of the Italian tagger.\n i, n = 0, 0\n for sentence in open(os.path.join(PATH, \"corpora\", \"tagged-it-wacky.txt\")).readlines():\n sentence = sentence.strip()\n s1 = [w.split(\"/\") for w in sentence.split(\" \")]\n s2 = [[w for w, pos in s1]]\n s2 = it.parse(s2, tokenize=False)\n s2 = [w.split(\"/\") for w in s2.split(\" \")]\n for j in range(len(s1)):\n t1 = s1[j][1]\n t2 = s2[j][1]\n # WaCKy test set tags plural nouns as \"NN\", pattern.it as \"NNS\".\n # Some punctuation marks are also tagged differently,\n # but these are not necessarily errors.\n if t1 == t2 or (t1 == \"NN\" and t2.startswith(\"NN\")) or s1[j][0] in \"\\\":;)-\":\n i += 1\n n += 1\n #print(float(i) / n)\n self.assertTrue(float(i) / n > 0.92)\n print(\"pattern.it.parser.parse()\")\n\n def test_tag(self):\n # Assert [(\"il\", \"DT\"), (\"gatto\", \"NN\"), (\"nero\", \"JJ\")].\n v = it.tag(\"il gatto nero\")\n self.assertEqual(v, [(\"il\", \"DT\"), (\"gatto\", \"NN\"), (\"nero\", \"JJ\")])\n print(\"pattern.it.tag()\")\n\n def test_command_line(self):\n # Assert parsed output from the command-line (example from the documentation).\n p = [\"python\", \"-m\", \"pattern.it\", \"-s\", \"Il gatto nero.\", \"-OTCRL\"]\n p = subprocess.Popen(p, stdout=subprocess.PIPE)\n p.wait()\n v = p.stdout.read().decode('utf-8')\n v = v.strip()\n self.assertEqual(v, \"Il/DT/B-NP/O/O/il gatto/NN/I-NP/O/O/gatto nero/JJ/I-NP/O/O/nero ././O/O/O/.\")\n print(\"python -m pattern.it\")\n\n#---------------------------------------------------------------------------------------------------\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestInflection))\n suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestParser))\n return suite\n\nif __name__ == \"__main__\":\n\n result = unittest.TextTestRunner(verbosity=1).run(suite())\n sys.exit(not result.wasSuccessful())\n","repo_name":"clips/pattern","sub_path":"test/test_it.py","file_name":"test_it.py","file_ext":"py","file_size_in_byte":12428,"program_lang":"python","lang":"en","doc_type":"code","stars":8585,"dataset":"github-code","pt":"52"} +{"seq_id":"43442099707","text":"\nimport re\n\n\ndef validate_html(html):\n '''\n This function performs a limited version of html validation by\n checking whether every opening tag has a corresponding closing tag.\n >>> validate_html('example')\n True\n >>> validate_html('example')\n False\n '''\n if len(html) == 0:\n return True\n tag = _extract_tags(html)\n if not tag:\n return False\n s = []\n index = 0\n balanced = True\n while index < len(tag) and balanced:\n a = tag[index]\n b = a[1:-1]\n if \"/\" not in a:\n s.append(b)\n else:\n if not s:\n balanced = False\n else:\n top = s.pop()\n if not top == b[1:]:\n balanced = False\n index = index + 1\n if balanced and not s:\n return True\n else:\n return False\n\n\ndef _extract_tags(html):\n '''\n This is a helper function for `validate_html`.\n By convention in Python, helper functions that are not meant to be\n used directly by the user are prefixed with an underscore.\n\n This function returns a list of all the html tags contained in the\n input string,stripping out all text not contained within angle\n brackets.\n\n >>> _extract_tags('Python rocks!')\n ['', '']\n '''\n tags = re.findall(r'<[^>]+>', html)\n return tags\n","repo_name":"tylerting/html_validator","sub_path":"HTML_Validator.py","file_name":"HTML_Validator.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"18133490346","text":"import copy\nfrom math import inf\nfrom tracemalloc import stop\nimport grid, tour, random, mutate\nfrom main import NUM_CITIES, POPULATION_SIZE, ELITE_SIZE, NUM_PARENTS\n\n################################################################\n#util.py\n#This module hosts methods that will handle repetetive heavy lifting for the search algorithms\n#the algorithms should be able to get all the outside data and functionality that they need \n#from util.py\n#\n#getTourCost():\n#gets the total cost for a tour of the cities, the search algorithms use this value\n#to determine an effective move and to find local maxima\n#\n###############################################################\n\n\n#calculate the cost for this tour, return cost as an integer\n#Change TourCost to receive a tour as a list (example lsit of [0-4] is [0,1,2,3,4])\n#return cost as an integer\n\ndef initialize (city_tour, current_population, cost_map, worst_tours, best_tours, list_of_tours, WORST_SIZE):\n #city_tour is the grid object to pass to the genetic algorithms\n #setGrid is required to establish cost to travel from city to city\n #getRandomTour can be used to seed the initial generation \n city_tour.setGrid()\n #populate initial generation\n seedFirstGeneration(POPULATION_SIZE, city_tour, current_population, cost_map, list_of_tours)\n\n #map tour cost to the tour object and sort by tour cost\n #util.mapTourList(current_population)\n \n #get best and worst tours for easy reference\n #best tours will reproduce, worst tours will be replaced\n getBestTours(ELITE_SIZE, best_tours, cost_map)\n getWorstTours(WORST_SIZE, worst_tours,cost_map)\n\n#returns cost of a tour, tour cost is our fitness\ndef getTourCost(tour, cost_graph):\n cost = 0\n copy_of_tour = []\n for i in tour:\n copy_of_tour.append(i)\n #create list of coordinates for flight costs\n #add home city to end of tour list\n copy_of_tour.append(copy_of_tour[0])\n\n #build list of cost grid coordinate sets (represents the tour)\n tour_coordinates = []\n for i in range(len(copy_of_tour)):\n if i == len(copy_of_tour)-1:\n break\n tour_coordinates.append((copy_of_tour[i], copy_of_tour[i+1])) \n\n for flight in tour_coordinates:\n this_flight_cost = cost_graph[flight[0]][flight[1]]\n cost += this_flight_cost\n\n copy_of_tour.clear()\n return cost\n\n#reset the variables after a run\ndef reset (current_population, cost_map, best_tours, worst_tours, list_of_tours, city_tour, worst_size, best_size):\n current_population.clear(), list_of_tours.clear(), cost_map.clear()\n worst_tours.clear(), best_tours.clear()\n seedFirstGeneration(POPULATION_SIZE, city_tour, current_population, cost_map, list_of_tours)\n getWorstTours(worst_size, worst_tours, cost_map)\n getBestTours(best_size, best_tours, cost_map)\n\n\n#seeds initial generation with a randomly generated population\n#this should give us a wide range of initial memebers to choose from\ndef seedFirstGeneration(population_size, city_tour, current_population, cost_map, list_of_tours):\n \n while len(current_population) < population_size:\n x = tour.Tour()\n x.setGeneration(1)\n x.setTour(city_tour.getRandomTour())\n x.setCost(getTourCost(x.getTour(), city_tour.getGrid()))\n #ensure that we don't seed our first generation with replicas\n if x.getCost() not in cost_map.keys():\n current_population.append(x)\n list_of_tours.append(x.getTour())\n cost_map[x.getCost()] = x\n\n#maps tour cost to tour object for later assessment\n#tour cost is esseentially our fitness\ndef mapTourList(cost_map, current_population, list_of_tours):\n cost_map.clear()\n for tour in current_population:\n cost_map[tour.getCost()] = tour\n #get rid of duplicates in population\n current_population.clear()\n list_of_tours.clear()\n for i, (j,k) in enumerate(cost_map.items()):\n current_population.append(k)\n list_of_tours.append(k.getTour())\n\n#returns a map of the best tours (cost mapped to tour object)\ndef getBestTours(num_tours, best_tours ,cost_map):\n for i, (j,k) in enumerate(sorted(cost_map.items())):\n if i >= num_tours: break\n best_tours.append(k)\n \n#returns a map of worst tours\ndef getWorstTours(num_tours, worst_tours, cost_map):\n cost_values = sorted(cost_map.keys())\n for i in range (len(cost_values)-num_tours, len(cost_values)):\n worst_tours.append(cost_map[cost_values[i]])\n \n\n#used for crossing over genes in gene crossover operator\ndef getCrossoverIndex(index, length):\n if index >= length-1:\n return 1\n return index+1\n\n#calls breeding operators and selects the next generation\ndef getTournamentParents (curr_gen, how_many): \n #select parents for tournament\n parents = [] \n for i in range(how_many): \n #get 4 parents for each round of tournament\n candidate_parents = []\n for j in range(2):\n candidate_parent = curr_gen[random.randrange(0, POPULATION_SIZE)]\n while candidate_parent in candidate_parents:\n candidate_parent = curr_gen[random.randrange(0, POPULATION_SIZE)]\n candidate_parents.append(candidate_parent)\n lowest_cost = inf\n parent = None\n for candidate in candidate_parents:\n if candidate.getCost() < lowest_cost: parent, lowest_cost = candidate, candidate.getCost()\n while parent in parents:\n parent = curr_gen[random.randrange(0, POPULATION_SIZE)]\n parents.append(parent)\n return parents\n\n#performs the crossover operator\ndef breedCrossover (parents):\n #first, perform crossover\n children = []\n for i in range(0, len(parents), 2): \n child1, child2 = mutate.orderCrossover(parents[i], parents[i+1], NUM_CITIES)\n children.append(child1)\n children.append(child2)\n return children\n\n#remove worst individuals from population, don't let population drop below 50 individua;ls\ndef getSacrifice(cost_map, current_population, list_of_tours, worst_tours):\n if len(cost_map) >= 50:\n for item in worst_tours: \n list_of_tours.remove(item.getTour())\n current_population.remove(item)\n mapTourList(cost_map, current_population, list_of_tours)\n \n worst_tours.clear()\n\n\n#make tour objects out of our children\ndef setChildren(children, current_population, cost_map, city_tour, list_of_tours, generation):\n for child in children:\n x = tour.Tour()\n x.setGeneration(generation)\n x.setTour(child)\n x.setCost(getTourCost(x.getTour(), city_tour.getGrid()))\n current_population.append(x)\n list_of_tours.append(x.getTour())\n cost_map[x.getCost()] = x\n if x in current_population:\n if x.getCost() in cost_map.keys():\n pass\n else: print(\"stop\")\n\n#handles the insert Mutation\ndef insertMutation(temp):\n #TODO: write and handle insert mutation\n print (\"insert called, :\", temp, \" passed in...\")\n return \"Insert Mutation\"\n\n#handles the swap Mutation\ndef swapMutation(temp):\n #TODO: write and handle swap mutation\n print (\"swap called, :\", temp, \" passed in...\")\n return \"Swap Mutation\"\n\n#handles the inversion Mutation\ndef inversionMutation(temp):\n #TODO: write and handle inversion mutation\n print (\"inversion called, :\", temp, \" passed in...\")\n return \"Inversion Mutation\"\n\n#handles the insert Mutation\ndef scrambleMutation(temp):\n #TODO: write and handle scramble mutation\n print (\"scramble called, :\", temp, \" passed in...\")\n return \"Scramble Mutation\"","repo_name":"marshallpratt1/CSCEA412-PA1","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3239874952","text":"# 옹알이 (1)\n# 문제 설명\n# 머쓱이는 태어난 지 6개월 된 조카를 돌보고 있습니다.\n# 조카는 아직 \"aya\", \"ye\", \"woo\", \"ma\" 네 가지 발음을 최대 한 번씩 사용해\n# 조합한(이어 붙인) 발음밖에 하지 못합니다. 문자열 배열 babbling이 매개변수로 주어질 때,\n# 머쓱이의 조카가 발음할 수 있는 단어의 개수를 return하도록 solution 함수를 완성해주세요.\n\ndef solution(babbling):\n c = 0\n for b in babbling:\n for w in [\"aya\", \"ye\", \"woo\", \"ma\"]:\n if w * 2 not in b:\n b = b.replace(w, ' ')\n if len(b.strip()) == 0:\n c += 1\n return c\n","repo_name":"juwon5272/Programmers_Python","sub_path":"Basic/3week/옹알이(1).py","file_name":"옹알이(1).py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9099211521","text":"\nfrom queue import Queue\nimport RPi.GPIO as GPIO\nfrom pwmPCA9685 import pwm as pwm\nimport time\nimport threading\n\nfrom queueRunner import QueueRunner\n\nclass lightOneChannel(QueueRunner, threading.Thread, ):\n def __init__(self, config = {}, name=\"WhiteThread\"):\n threading.Thread.__init__(self, name=name)\n\n self.queue = Queue()\n\n self.inputPin = -1\n if 'dimInput' in config:\n self.inputPin = config['dimInput']\n GPIO.setup(self.inputPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.add_event_detect(self.inputPin, GPIO.RISING, callback=self.dim)\n\n\n self.out = pwm(config['output'],255)\n\n self.currVal = 0 # 0-255\n\n self.dimThreshold = 0.5\n self.startThreshold = 0.05\n\n self.on = False\n self.rise = True\n\n def dim(self,c):\n # global storeValue, strip, on, rise, channel, start, number, dimThreshold, startThreshold\n print(\"dim\")\n starttime = time.time()\n while GPIO.input(self.inputPin):\n time.sleep(0.02)\n if time.time() - starttime >= 0.5:\n break\n endtime = time.time()\n timediff = endtime-starttime\n if timediff < self.startThreshold:\n return 0\n if timediff < self.dimThreshold:\n if not self.on:\n for i in range(0,101):\n value = (self.currVal*i/100)\n # print value\n self.out.set(value)\n time.sleep(0.005)\n self.on = not self.on\n else:\n for i in range(0,101):\n value = (self.currVal*(100-i)/100)\n # print value\n self.out.set(value)\n time.sleep(0.005)\n self.on = not self.on\n else:\n if not self.on:\n self.currVal = 0\n while GPIO.input(self.inputPin):\n if self.rise:\n if self.currVal < 255:\n self.currVal += 1\n else:\n if self.currVal > 0:\n self.currVal -= 1\n value = (self.currVal)\n # print value\n self.out.set(value)\n if self.currVal == 0:\n self.on = False\n self.currVal = 50\n break\n else:\n self.on = True\n time.sleep(0.015)\n self.rise = not self.rise\n\n def morphto(self,value):\n print(\"morphing to\",value)\n if (value == 0):\n if not self.on:\n return\n else:\n for i in range(0,101):\n value = self.currVal*(100-i)/100\n # print value\n self.out.set(value)\n time.sleep(0.005)\n self.on = False\n self.rise = True\n return\n else:\n if not self.on:\n self.currVal = value\n for i in range(0,101):\n value = self.currVal*i/100\n # print value\n self.out.set(value)\n time.sleep(0.005)\n self.on = True\n return\n if (value > 127):\n self.rise = False\n else:\n self.rise = True\n\n start = self.currVal\n d1 = int(value) - start\n\n n = 100\n speed = 1\n for counter in range(0, n + 1):\n self.currVal = start + (counter * d1 / 100)\n self.out.set(self.currVal)\n time.sleep(float(speed)/n)\n\n def set(self, value):\n if (value == 0):\n if not self.on:\n return\n else:\n self.out.set(value)\n self.on = False\n self.rise = True\n return\n else:\n if not self.on:\n self.currVal = value\n self.out.set(value)\n self.on = True\n if (value > 127):\n self.rise = False\n else:\n self.rise = True\n return\n\n def setMQTT(self,value):\n self.queue.put({'f':self.morphto, 'a': [int(value)]})\n\n def setToggle(self,value):\n if self.on:\n self.morphto(0)\n else:\n self.morphto(255)\n\n\n def setJarvis(self,value):\n value = value.decode(\"utf-8\")\n print(\"setJarvis: \",value)\n if (value == \"on\"):\n self.morphto(100)\n elif (value == \"off\"):\n self.morphto(0)\n","repo_name":"julianullrich99/homebox","sub_path":"lightOneChannel.py","file_name":"lightOneChannel.py","file_ext":"py","file_size_in_byte":4586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"807945565","text":"from pymongo import MongoClient\nimport json\nimport datetime\nimport matplotlib.pyplot as plt\n\nclient = MongoClient('localhost', 27017)\ndb = client.ChemiCo_db\ncollection = db.listen_collection\n\nsession_id = 1002\nmax_iteration = 32\niteration = 4\nfft_x = 48\nfft_y = 20\n\nwhile iteration < max_iteration:\n ear_right = collection.find_one({'session_id':session_id , 'iteration': iteration})\n while ear_right['which_ear'] != 'right':\n iteration = iteration +1\n ear_right = collection.find_one({'session_id':session_id , 'iteration': iteration})\n iteration = iteration +1\n ear_left = collection.find_one({'session_id':session_id , 'iteration': iteration})\n while ear_left['which_ear'] != 'left':\n iteration = iteration +1\n ear_left = collection.find_one({'session_id':session_id , 'iteration': iteration})\n fft_right = ear_right['fft_data']\n fft_left = ear_left['fft_data']\n xy_list =[]\n for y in range(fft_y):\n xy_list.append(fft_right[y*fft_x:fft_x+y*fft_x])\n for y in range(fft_y):\n xy_list.append(fft_left[y*fft_x:fft_x+y*fft_x])\n plt.imshow(xy_list, origin='lower', cmap='nipy_spectral')\n print(iteration)\n plt.pause(0.01)","repo_name":"eeAI-works/ChemiCo-SAN","sub_path":"SimpleMonitor/show_map__listen.py","file_name":"show_map__listen.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70718113764","text":"# Предположим, что есть функция c определенным поведением. Эту функцию\n# очень любят давать на собеседованиях в качестве самой первой задачи.\n# Я не опишу ее поведение, а лишь предоставлю тесты, которые она должна\n# проходить. Вы должны на основе тестов написать исходную функцию.\n\nimport unittest\n\nimport main\n\ndef fizzbuzz(n):\n for i in range(n):\n if i % 15 == 0:\n print('FizzBizz')\n elif i % 3 == 0:\n print('Fizz')\n elif i % 5 == 0:\n print('Bizz')\n else:\n print(i)\n\n\nclass TestFizzBuzz(unittest.TestCase):\n\n def test_with_range(self):\n self.assertEqual(main.fizzbuzz(range(1, 21)),\n [1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8,\n 'Fizz', 'Buzz', 11, 'Fizz', 13, 14,\n 'FizzBuzz', 16, 17, 'Fizz', 19, 'Buzz'])\n\n def test_normal(self):\n self.assertEquals(main.fizzbuzz([1, 27, 45, 4, 7, 8, 9, 0]),\n [1, 'Fizz', 'FizzBuzz', 4, 7, 8, 'Fizz', 'FizzBuzz'])\n\n def test_empty(self):\n self.assertListEqual(main.fizzbuzz([]), [])\n#t = fizzbuzz(21)\n#print(t)","repo_name":"Qooller/Python","sub_path":"Python1/Задание 7-2.py","file_name":"Задание 7-2.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9263621628","text":"#Required\nimport requests\nfrom pprint import pprint\nfrom secret import GITHUB_TOKEN\nimport argparse\nimport os\nimport time\nimport sys\nPYTHONIOENCODING=\"UTF-8\"\nimport json\n\n###Notes\n### https://github.community/t/create-branch-protection-rules-at-an-organization-level/12368/5 \n## https://github.community/t/create-branch-protection-rules-at-an-organization-level/12368/20\n\n#GitHub Org Creds\nUSERNAME = 'MalwareHomie'\nAPI_URL= \"https://api.github.com\"\nAPI_PAYLOAD = '{\"name\":\"xxxRepoNamexxx\"}'\nORG_NAME = 'GithubSiliconValley'\n# REPO_NAME = 'demo-ghas-verademo'\n#TOKEN = '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'\n# The repository to add this issue to\n#REPO_OWNER = 'GithubSiliconValley'\n# REPO_NAME = 'demo-ghas-verademo'\nAPI_BP_ENDPOINT = \"https://api.github.com/orgs/GithubSiliconValley\"\n\n#Branch Protection Properties\nBRANCH_PROTECT = '{\"required_status_checks\":{\"strict\":true,\"contexts\":[\"contexts\"]},\"enforce_admins\":true,\"required_pull_request_reviews\":{\"dismissal_restrictions\":{\"users\":[\"users\"],\"teams\":[\"teams\"]},\"dismiss_stale_reviews\":true,\"require_code_owner_reviews\":true,\"required_approving_review_count\":2},\"restrictions\":{\"users\":[\"users\"],\"teams\":[\"teams\"],\"apps\":[\"apps\"]}}'\n\n#Debugging help thanks to @Jonmagic (https://gist.github.com/jonmagic/5282384165e0f86ef105)\n# Authentication for user creating repo \nheaders = {\n \"Authorization\": \"token \" + GITHUB_TOKEN,\n \"Accept\":\"application/vnd.github.v3+json\"\n}\n\nputheaders ={\n \"Authorization\": \"token \" + GITHUB_TOKEN,\n \"Accept\":\"application/vnd.github.luke-cage-preview+json\"\n}\n\n#Parsing input from \"webhook\"...\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--name\",\"-n\",type=str,dest=\"name\",required=True)\nparser.add_argument(\"--private\",\"-p\",dest=\"is_private\",action=\"store_true\")\nparser.add_argument(\"--auto_init\",\"-a\",dest='auto_init',action=\"store_true\")\n\nargs = parser.parse_args()\nprint(args)\nrepo_name = args.name\nis_private = args.is_private\nauto_init = args.auto_init\n\nif is_private & auto_init:\n payload = '{\"name\": \"' + repo_name + '\", \"private\": true, \"auto_init\": \"true\"}'\nelse:\n payload = '{\"name\": \"' + repo_name + '\", \"private\": false, \"auto_init\": \"true\"}'\nprint(payload)\n\ntry:\n print(API_URL+\"/orgs/\"+ORG_NAME+\"/\"+\"repos\")\n print(\"Repo Created - Issue Generation and Protection Rule in Process...\")\n reponse = requests.post(API_URL+\"/orgs/\"+ORG_NAME+\"/\"+\"repos\",data=payload,headers = headers)\n if(reponse.status_code==201):\n putresponse = requests.put(API_BP_ENDPOINT+\"/\"+repo_name+\"/branches/main/protection\",data=BRANCH_PROTECT,headers=putheaders)\n\n else:\n reponse.raise_for_status()\n\nexcept requests.exceptions.RequestException as err:\n raise SystemExit(err)\n#This script was inspired by @DerBla (https://gist.github.com/JeffPaine/3145490?permalink_comment_id=4008650#gistcomment-4008650)\n# Authentication for user filing issue (must have read/write access to\n# repository to add issue to)\ndef make_github_issue(title, body=None, milestone=None, labels=None):\n # Create an issue on github.com using the given parameters\n # Url to create issues via POST\n url = 'https://api.github.com/repos/%s/%s/issues' % (ORG_NAME, repo_name)\n \n # Headers are different for issues generation\n headers = {\n \"Authorization\": \"token %s\" % GITHUB_TOKEN,\n \"Accept\": \"application/vnd.github.v3+json\"\n }\n \n # Create our issue\n data = { 'title': title,\n 'body': body,\n 'milestone': milestone,\n 'labels': labels}\n\n # Add the issue to our repository\n response = requests.request(\"POST\", url, data=json.dumps(data), headers=headers)\n if response.status_code == 201:\n print ('Successfully created Issue \"%s\"' % title)\n else:\n print ('Could not create Issue \"%s\"' % title)\n print ('Response:', response.content)\n\n#Args to pass thru\ntitle = 'Protection Rule Applied'\nbody = '@MalwareHomie
The following Protections have been placed on the master branch:
requiresApprovingReviews=true
requiresCodeOwnerReviews=true
requiredApprovingReviewCount=1
requiresStatusChecks=true
requiresStrictStatusChecks=false
requiresLinearHistory=true'\nmilestone = None\nlabels = [\"ProtectionRule\"]\n\nmake_github_issue(title, body, milestone, labels)\n\n### Triggering borrowed sh script to apply protection rules by @cgpu (https://github.com/cgpu/add-branch-protection-rules) using GH CLI. \n#Can be too fast.\ntime.sleep(3)\n#Required args for the sh script\ncmd = './createBranchProtectionRule.sh \\\ngithub.com \\\nGithubSiliconValley \\\n%s \\\nmaster \\\nrequiresApprovingReviews=true \\\nrequiresCodeOwnerReviews=true \\\nrequiredApprovingReviewCount=1 \\\nrequiresStatusChecks=true \\\nrequiresStrictStatusChecks=false \\\nrequiresLinearHistory=true' % (repo_name)\n\n#Not best practice, but will need to research further. \nos.popen(cmd)","repo_name":"MalwareHomie/GitHub-Benny","sub_path":"RepoBranchProtectionAutomation/NEW_REPO_ADD_ISSUE_AND_SEC.py","file_name":"NEW_REPO_ADD_ISSUE_AND_SEC.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30302695358","text":"from datetime import date, datetime\nimport iso8601\n\nfrom faunadb.objects import FaunaTime, Ref, SetRef, Native\nfrom faunadb import query\nfrom tests.helpers import FaunaTestCase\n\nclass ObjectsTest(FaunaTestCase):\n @classmethod\n def setUpClass(cls):\n super(ObjectsTest, cls).setUpClass()\n cls.ref = Ref(\"123\", Ref(\"frogs\", Native.COLLECTIONS))\n cls.json_ref = ('{\"@ref\":{'\n '\"collection\":{\"@ref\":{\"collection\":{\"@ref\":{\"id\":\"collections\"}},\"id\":\"frogs\"}},'\n '\"id\":\"123\"'\n '}}')\n\n def test_obj(self):\n self.assertParseJson({\"a\": 1, \"b\": 2}, '{\"@obj\": {\"a\": 1, \"b\": 2}}')\n\n def test_ref(self):\n self.assertJson(self.ref, self.json_ref)\n\n self.assertRaises(ValueError, lambda: Ref(None))\n\n ref = Ref(\"123\", Native.KEYS)\n self.assertEqual(ref.id(), \"123\")\n self.assertEqual(ref.collection(), Native.KEYS)\n self.assertEqual(ref.database(), None)\n\n self.assertRegexCompat(\n repr(ref),\n r\"Ref\\(id=123, collection=Ref\\(id=keys\\)\\)\"\n )\n\n def test_set(self):\n index = Ref(\"frogs_by_size\", Native.INDEXES)\n json_index = '{\"@ref\":{\"collection\":{\"@ref\":{\"id\":\"indexes\"}},\"id\":\"frogs_by_size\"}}'\n match = SetRef(query.match(index, self.ref))\n json_match = '{\"@set\":{\"match\":%s,\"terms\":%s}}' % (json_index, self.json_ref)\n self.assertJson(match, json_match)\n\n self.assertNotEqual(\n match,\n SetRef(query.match(index, query.ref(query.collection(\"frogs\"), \"456\")))\n )\n\n def test_time_conversion(self):\n dt = datetime.now(iso8601.UTC)\n self.assertEqual(FaunaTime(dt).to_datetime(), dt)\n\n # Must be time zone aware.\n self.assertRaises(ValueError, lambda: FaunaTime(datetime.utcnow()))\n\n dt = datetime.fromtimestamp(0, iso8601.UTC)\n ft = FaunaTime(dt)\n self.assertEqual(ft, FaunaTime(\"1970-01-01T00:00:00Z\"))\n self.assertEqual(ft.to_datetime(), dt)\n\n def test_time(self):\n test_ts = FaunaTime(\"1970-01-01T00:00:00.123456789Z\")\n test_ts_json = '{\"@ts\":\"1970-01-01T00:00:00.123456789Z\"}'\n self.assertJson(test_ts, test_ts_json)\n\n self.assertToJson(datetime.fromtimestamp(0, iso8601.UTC), '{\"@ts\":\"1970-01-01T00:00:00Z\"}')\n\n self.assertEqual(repr(test_ts), \"FaunaTime('1970-01-01T00:00:00.123456789Z')\")\n\n self.assertNotEqual(test_ts, FaunaTime(\"some_other_time\"))\n\n def test_date(self):\n test_date = date(1970, 1, 1)\n test_date_json = '{\"@date\":\"1970-01-01\"}'\n self.assertJson(test_date, test_date_json)\n","repo_name":"fauna/faunadb-python","sub_path":"tests/test_objects.py","file_name":"test_objects.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"52"} +{"seq_id":"16982740629","text":"from . import arvore_sintatica as sinTree\n\n\nclass Parser():\n \"\"\"\n Classe responsável por todo o parser da linguagem.\n\n Implementado utilizando GLCs.\n \"\"\"\n\n def __init__(self, token_list):\n \"\"\"\n Construtor padrão da classe.\n\n token_list = lista de tokens recebida pelo lexer\n \"\"\"\n self.token_list = token_list\n self.index = 0\n\n if len(self.token_list) > 0:\n self.current_token = self.token_list[self.index]\n self.do_loop = True\n else:\n self.current_token = None\n self.do_loop = False\n\n self.treeList = []\n\n def error(self, message=False):\n \"\"\"\n Invoca uma exceção.\n\n Caso não receba parâmetro, imprime um erro genérico.\n \"\"\"\n raise Exception(message if message else \"deu merda\") # arrumar depois\n\n def eat(self):\n \"\"\"Avança para o próximo token.\"\"\"\n self.index += 1\n if self.index >= len(self.token_list):\n self.do_loop = False\n else:\n self.current_token = self.token_list[self.index]\n\n def vomit(self):\n \"\"\"Retrocede para o token anterior.\"\"\"\n if self.index == 0:\n pass\n else:\n self.index += 1\n self.current_token = self.token_list[self.index]\n\n def rollback_to(self, time):\n \"\"\"Seta o token para um index especificado.\"\"\"\n self.index = time\n self.current_token = self.token_list[self.index]\n\n def parse(self):\n \"\"\"Faz a inicialização do parsing.\"\"\"\n while self.do_loop:\n self.treeList.append(self.s())\n\n def solve(self):\n \"\"\"Chama iterativamente as funções solve.\"\"\"\n for i in self.treeList:\n i.solve()\n\n def s(self):\n \"\"\"\n Representa os não terminais possíveis em uma linha.\n\n Itera entre todas as possibilidades e devolve o encontrado.\n \"\"\"\n func_list = [self.decvar, self.matlab, self.flux, self.rpt,\n self.control]\n\n for i in enumerate(func_list):\n a = i[1]()\n if a is not None:\n return a\n\n self.error(f\"Erro no parser: sentença não reconhecida com {self.current_token[1]}\")\n\n def decvar(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n type var '=' LITERAL eos\n \"\"\"\n pace = 0\n index_backup = self.index\n node_list = []\n is_decvar = False\n\n while pace < 5:\n if self.current_token[0] == \"type\" and pace == 0:\n node_list.append(self.current_token[1])\n self.eat()\n pace += 1\n is_decvar = True\n elif self.current_token[0] == \"var\" and pace == 1:\n node_list.append(self.current_token[1])\n self.eat()\n pace += 1\n elif self.current_token[1] == \"=\" and pace == 2:\n self.eat()\n pace += 1\n elif pace == 3:\n node = self.literal()\n node_list.append(node)\n pace += 1\n elif self.current_token[0] == \"eos\" and pace == 4:\n self.eat()\n pace += 1\n elif is_decvar:\n self.error(\"Erro no parser: decvar incompleto\")\n else:\n return None\n\n if len(node_list) < 3:\n self.rollback_to(index_backup)\n self.error(\"erro no decvar\")\n\n for node in node_list:\n if node is None:\n self.rollback_to(index_backup)\n self.error(\"erro no decvar\")\n\n return sinTree.Decvar(sinTree.Type(node_list[0]),\n sinTree.Var(node_list[1]),\n node_list[2])\n\n def literal(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n str | MATLAB | BOOL | emp\n \"\"\"\n if self.current_token[0] == \"str\":\n tree_node = sinTree.Str(self.current_token[1])\n self.eat()\n return tree_node\n\n if self.current_token[0] == \"emp\":\n tree_node = sinTree.Emp(self.current_token[1])\n self.eat()\n return tree_node\n\n a = self.matlab(consume_eos=False)\n if a is not None:\n return a\n\n a = self.bool_ean()\n if a is not None:\n return a\n\n return None\n\n def bool_ean(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n tru | fls\n \"\"\"\n if self.current_token[0] in (\"tru\", \"fls\"):\n a = sinTree.Bool(self.current_token[1])\n self.eat()\n return a\n else:\n return None\n\n def matlab(self, consume_eos=True):\n \"\"\"\n Implementa a seguinte GLC.\n\n MATLAB' (+ | -) MATLAB [eos] | MATLAB' [eos]\n\n O parâmetro consume_eos serve como uma análise semântica imbutida.\n \"\"\"\n node1 = self.matlab1(consume_eos)\n\n if not node1:\n return None\n\n if self.current_token and self.current_token[1] in ('+', '-'):\n token = self.current_token\n self.eat()\n elif consume_eos and self.current_token and self.current_token[0] == \"eos\":\n self.eat()\n return node1\n else:\n return node1\n\n node2 = self.matlab(consume_eos)\n if not node2:\n self.error(\"Erro no parser: operação matlab incompleta\")\n\n if consume_eos and self.current_token and self.current_token[0] == \"eos\":\n self.eat()\n\n return sinTree.BinOp(node1, token[1], node2)\n\n def matlab1(self, consume_eos=True):\n \"\"\"\n Implementa a seguinte GLC.\n\n MATLAB'' (* | / | ^) MATLAB'' [eos] | MATLAB''.\n\n O parâmetro consume_eos serve como uma análise semântica imbutida.\n É referido como MATLAB'\n \"\"\"\n node1 = self.matlab2(consume_eos)\n\n if not node1:\n return None\n\n if self.current_token[1] in ('*', '/', '^'):\n token = self.current_token\n self.eat()\n else:\n return node1\n\n node2 = self.matlab1(consume_eos)\n\n if not node2:\n node2 = self.matlab(consume_eos)\n if not node2:\n self.error(\"Erro no parser: operação matlab incompleta\")\n\n if consume_eos and self.current_token and self.current_token[0] == \"eos\":\n self.eat()\n\n return sinTree.BinOp(node1, token[1], node2)\n\n def matlab2(self, consume_eos=True):\n \"\"\"\n Implementa a seguinte GLC.\n\n num | var | '(' MATLAB ')'.\n\n O parâmetro consume_eos serve como uma análise semântica imbutida.\n É referido como MATLAB''\n \"\"\"\n token = self.current_token\n\n if token[0] == \"num\":\n self.eat()\n return sinTree.Num(token[1])\n elif token[0] == \"var\":\n self.eat()\n return sinTree.Var(token[1])\n elif token[0] == \"(\":\n self.eat()\n node = self.matlab(consume_eos)\n if self.current_token[0] == ')':\n self.eat()\n return node\n else:\n self.error(\"Erro no parser: faltando )\")\n\n def flux(self):\n \"\"\"\n Implementa as seguintes GLC.\n\n IFI = ifi (EXPR) scope_init S scope_end\n ELS = els scope_init S scope_end\n \"\"\"\n ifi = self.flux_ifi()\n if ifi is None:\n return None\n\n if not self.do_loop:\n return ifi\n\n els = self.flux_els()\n if els is None:\n return ifi\n else:\n ifi.els = els\n return ifi\n\n def flux_ifi(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n ifi (EXPR) scope_init S scope_end\n \"\"\"\n checkpoint = self.index\n is_ifi = False\n\n sequence = (\"ifi\", \"(\", \"EXPR\", \")\", \"scope_init\", \"S\", \"scope_end\")\n for i in enumerate(sequence):\n if not self.do_loop:\n break\n if i[0] == 0 and self.current_token[0] == i[1]:\n self.eat()\n is_ifi = True\n elif i[0] == 2:\n expr = self.expr()\n if expr is None:\n break\n elif i[0] == 5:\n s = []\n while self.do_loop and self.current_token[0] != \"scope_end\":\n s.append(self.s())\n if len(s) == 0:\n break\n elif self.current_token[0] == i[1]:\n self.eat()\n else:\n break\n else:\n return sinTree.Ifi(expr, s, None)\n\n if is_ifi:\n self.error(\"Erro no parser: ifi incompleto\")\n else:\n self.rollback_to(checkpoint)\n return None\n\n def flux_els(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n els scope_init S scope_end\n \"\"\"\n checkpoint = self.index\n is_els = False\n\n sequence = (\"els\", \"scope_init\", \"S\", \"scope_end\")\n for i in enumerate(sequence):\n if not self.do_loop:\n break\n if i[0] == 0 and self.current_token[0] == \"els\":\n self.eat()\n is_els = True\n elif i[0] == 2:\n s = []\n while self.do_loop and self.current_token[0] != \"scope_end\":\n s.append(self.s())\n if len(s) == 0:\n break\n elif self.current_token[0] == i[1]:\n self.eat()\n else:\n break\n else:\n return sinTree.Els(s)\n\n if is_els:\n self.error(\"Erro no parser: els incompleto\")\n else:\n self.rollback_to(checkpoint)\n return None\n\n def expr(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n EXPR' OPBOOL EXPR' [(and|orr) EXPR] | EXPR'\n \"\"\"\n # EXPR'\n expr1 = self.expr2()\n if expr1 is None:\n return None\n\n checkpoint = self.index\n\n # OPBOOL\n op = self.opbool()\n if op is None:\n return expr1\n\n # EXPR'\n expr2 = self.expr2()\n if expr2 is None:\n self.rollback_to(checkpoint)\n return expr1\n else:\n op.left = expr1\n op.right = expr2\n\n checkpoint = self.index\n\n # (and|orr)\n if self.current_token and self.current_token[1] in (\"and\", \"orr\"):\n op2 = sinTree.BinOp(None, self.current_token[1], None)\n self.eat()\n else:\n return op\n\n # EXPR\n expr3 = self.expr()\n if expr3 is None:\n self.rollback_to(checkpoint)\n return op\n else:\n op2.left = op\n op2.right = expr3\n return op2\n\n def expr2(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n LITERAL | (EXPR) | ! EXPR\n É referido como EXPR'\n \"\"\"\n # LITERAL\n a = self.literal()\n if a is not None:\n return a\n\n # (EXPR)\n if self.current_token[0] == \"(\":\n checkpoint = self.index\n self.eat()\n a = self.expr()\n if a is None:\n self.vomit()\n return None\n elif self.current_token[0] == \")\":\n self.eat()\n return a\n else:\n self.rollback_to(checkpoint)\n\n # ! EXPR\n if self.current_token[1] == \"!\":\n checkpoint = self.index\n self.eat()\n if self.current_token[0] == \"(\":\n self.eat()\n else:\n self.error(\n \"Erro no parser: operação ! não seguido de parênteses\"\n )\n a = self.expr()\n if a is None:\n self.rollback_to(checkpoint)\n else:\n if self.current_token[0] == \")\":\n self.eat()\n return sinTree.UnOP(\"!\", a)\n\n return None\n\n def opbool(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n == | > | >= | < | <=\n \"\"\"\n tokens_aceitos = (\"==\", \"!=\", \">\", \">=\", \"<\", \"<=\")\n if self.current_token[1] in tokens_aceitos:\n a = sinTree.BinOp(None, self.current_token[1], None)\n self.eat()\n return a\n else:\n return None\n\n def rpt(self):\n \"\"\"\n Implementa as seguintes GLCs.\n\n WHL = whl (EXPR) scope_init S scope_end\n FOR = for [type] var '=' RANGE scope_init S scope_end\n \"\"\"\n # whl (EXPR) scope_init S scope_end\n a = self.rpt_whl()\n if a is not None:\n return a\n\n # for [type] var '=' RANGE scope_init S scope_end\n a = self.rpt_for()\n if a is not None:\n return a\n return None\n\n def rpt_whl(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n whl (EXPR) scope_init S scope_end\n \"\"\"\n # whl (EXPR) scope_init S scope_end\n checkpoint = self.index\n is_whl = False\n\n sequence = (\"whl\", \"(\", \"EXPR\", \")\", \"scope_init\", \"S\", \"scope_end\")\n for i in enumerate(sequence):\n if not self.do_loop:\n break\n if i[0] == 0 and self.current_token[0] == i[1]:\n self.eat()\n is_whl = True\n elif i[0] == 2:\n expr = self.expr()\n if expr is None:\n break\n elif i[0] == 5:\n s = []\n while self.do_loop and self.current_token[0] != \"scope_end\":\n s.append(self.s())\n if len(s) == 0:\n break\n elif self.current_token[0] == i[1]:\n self.eat()\n else:\n break\n else:\n return sinTree.Whl(expr, s)\n\n if is_whl:\n self.error(\"Erro no parser: whl incompleto\")\n else:\n self.rollback_to(checkpoint)\n return None\n\n def rpt_for(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n for [type] var '=' RANGE scope_init S scope_end\n \"\"\"\n # for [type] var '=' RANGE scope_init S scope_end\n checkpoint = self.index\n is_for = False\n\n sequence = (\"for\", \"type\", \"var\", \"=\", \"RANGE\", \"scope_init\", \"S\",\n \"scope_end\")\n for i in enumerate(sequence):\n if not self.do_loop:\n break\n if i[0] == 0 and self.current_token[0] == i[1]:\n self.eat()\n is_for = True\n elif i[0] == 1:\n if self.current_token[0] == \"type\":\n typo = self.current_token[1]\n self.eat()\n else:\n typo = None\n elif i[0] == 2:\n if self.current_token[0] == \"var\":\n var = sinTree.Var(self.current_token[1])\n self.eat()\n else:\n break\n elif i[0] == 3:\n if self.current_token[1] == \"=\":\n self.eat()\n elif i[0] == 4:\n rang = self.ranger()\n if not rang:\n break\n elif i[0] == 6:\n s = []\n while self.do_loop and self.current_token[0] != \"scope_end\":\n s.append(self.s())\n if len(s) == 0:\n break\n elif self.current_token[0] == i[1]:\n self.eat()\n else:\n break\n else:\n return sinTree.For(typo, var, rang, s)\n\n if is_for:\n self.error(\"Erro no parser: for incompleto\")\n else:\n self.rollback_to(checkpoint)\n return None\n\n def ranger(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n num : num\n \"\"\"\n # num\n if self.current_token[0] == \"num\":\n num1 = sinTree.Num(self.current_token[1])\n self.eat()\n else:\n return None\n\n # :\n if self.current_token[1] == \":\":\n self.eat()\n else:\n self.vomit()\n return None\n\n # num\n if self.current_token[0] == \"num\":\n num2 = sinTree.Num(self.current_token[1])\n self.eat()\n return sinTree.BinOp(num1, \":\", num2)\n else:\n self.vomit()\n self.vomit()\n return None\n\n def control(self):\n \"\"\"\n Implementa a seguinte GLC.\n\n brk | jmp | emp\n \"\"\"\n if self.current_token[0] == \"brk\":\n token = \"brk\"\n self.eat()\n elif self.current_token[0] == \"jmp\":\n token = \"jmp\"\n self.eat()\n elif self.current_token[0] == \"emp\":\n token = \"emp\"\n self.eat()\n else:\n return None\n\n # ;\n if self.current_token[0] == \"eos\":\n self.eat()\n return sinTree.Control(token)\n else:\n self.vomit()\n return None\n","repo_name":"sociedade-do-pastel/simple3","sub_path":"simple_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":17228,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"16590110834","text":"#문자열 연산하기\n\n#1.문자열 더해서 연결하기\nhead = \"Python\"\ntail = \" is fun!\"\nhead + tail\n\na = \"python\"\na*2\n\nprint(\"=\" * 50)\nprint(\"My Program\")\nprint(\"=\" * 50)\n\n#문자열 길이 구하기\na = \"Life is too short\"\nlen(a)\n\nb = \"You need python\"\nlen(b)\n\n#문자열 인덱싱\nc = \"Life is too short, You need Python\"\nc[5]\nc[-1] #뒤에서부터 세어 첫 번째가 되는 문자\nc[0]\nc[-0]\n\n","repo_name":"yeyae/Python5","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31577327469","text":"from .source_details import SourceDetails\nfrom oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401\nfrom oci.decorators import init_model_state_from_kwargs\n\n\n@init_model_state_from_kwargs\nclass OccSourceDetails(SourceDetails):\n \"\"\"\n Details about the Oracle Cloud@Customer account, the source environment from which you want to migrate the application.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new OccSourceDetails object with values from keyword arguments. The default value of the :py:attr:`~oci.application_migration.models.OccSourceDetails.type` attribute\n of this class is ``OCC`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param type:\n The value to assign to the type property of this OccSourceDetails.\n Allowed values for this property are: \"OCIC\", \"INTERNAL_COMPUTE\", \"OCC\", \"OCIC_IDCS\", \"IMPORT\"\n :type type: str\n\n :param compute_account:\n The value to assign to the compute_account property of this OccSourceDetails.\n :type compute_account: str\n\n \"\"\"\n self.swagger_types = {\n 'type': 'str',\n 'compute_account': 'str'\n }\n\n self.attribute_map = {\n 'type': 'type',\n 'compute_account': 'computeAccount'\n }\n\n self._type = None\n self._compute_account = None\n self._type = 'OCC'\n\n @property\n def compute_account(self):\n \"\"\"\n **[Required]** Gets the compute_account of this OccSourceDetails.\n If you are using an Oracle Cloud@Customer account with Identity Cloud Service (IDCS), enter the service instance ID.\n For example, if Compute-567890123 is the account name of your Oracle Cloud@Customer Compute service entitlement,\n then enter 567890123.\n\n\n :return: The compute_account of this OccSourceDetails.\n :rtype: str\n \"\"\"\n return self._compute_account\n\n @compute_account.setter\n def compute_account(self, compute_account):\n \"\"\"\n Sets the compute_account of this OccSourceDetails.\n If you are using an Oracle Cloud@Customer account with Identity Cloud Service (IDCS), enter the service instance ID.\n For example, if Compute-567890123 is the account name of your Oracle Cloud@Customer Compute service entitlement,\n then enter 567890123.\n\n\n :param compute_account: The compute_account of this OccSourceDetails.\n :type: str\n \"\"\"\n self._compute_account = compute_account\n\n def __repr__(self):\n return formatted_flat_dict(self)\n\n def __eq__(self, other):\n if other is None:\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/application_migration/models/occ_source_details.py","file_name":"occ_source_details.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"73452116006","text":"\"\"\"Integration tests conftest.\"\"\"\n\nfrom collections import namedtuple\nimport os\nimport time\n\nimport pytest\n\nimport boto3\nfrom humilis.environment import Environment\nfrom s3keyring.s3 import S3Keyring\n\nkeyring = S3Keyring(config_file=\".s3keyring.ini\")\n\n\n@pytest.fixture(scope=\"session\")\ndef settings():\n \"\"\"Global test settings.\"\"\"\n Settings = namedtuple('Settings',\n 'stage environment_path streams_layer_name '\n 'output_path')\n envfile = \"tests/integration/humilis-kinesis-processor\"\n stage = os.environ.get(\"STAGE\", \"DEV\")\n return Settings(\n stage=stage,\n environment_path=\"{}.yaml.j2\".format(envfile),\n output_path=\"{}-{}.outputs.yaml\".format(envfile, stage),\n streams_layer_name=\"streams\")\n\n\n@pytest.yield_fixture(scope=\"session\")\ndef environment(settings):\n \"\"\"The test environment: this fixtures creates it and takes care of\n removing it after tests have run.\"\"\"\n env = Environment(settings.environment_path, stage=settings.stage)\n if os.environ.get(\"UPDATE\", \"yes\") == \"yes\":\n env.create(update=True, output_file=settings.output_path)\n else:\n env.create(output_file=settings.output_path)\n\n val = keyring.get_password(\n \"humilis-kinesis-processor/{}\".format(settings.stage), \"sentry/dsn\")\n env.set_secret(\"sentry.dsn\", val)\n yield env\n if os.environ.get(\"DESTROY\", \"yes\") == \"yes\":\n # Empty the S3 bucket\n bucket = env.outputs[\"storage\"][\"BucketName\"]\n os.system(\"aws s3 rm s3://{} --recursive\".format(bucket))\n env.delete()\n\n\n@pytest.fixture(scope=\"session\")\ndef output_stream_name(settings, environment):\n \"\"\"The name of the output Kinesis stream.\"\"\"\n layer = [l for l in environment.layers\n if l.name == settings.streams_layer_name][0]\n return [(layer.outputs.get(\"OutputStream1\"), 2),\n (layer.outputs.get(\"OutputStream2\"), 1)]\n\n\n@pytest.fixture(scope=\"session\")\ndef error_stream_name(settings, environment):\n \"\"\"The name of the error Kinesis stream.\"\"\"\n layer = [l for l in environment.layers\n if l.name == settings.streams_layer_name][0]\n return [(layer.outputs.get(\"ErrorStream\"), 1)]\n\n\n@pytest.fixture(scope=\"session\")\ndef input_stream_name(settings, environment):\n \"\"\"The name of the output Kinesis stream.\"\"\"\n layer = [l for l in environment.layers\n if l.name == settings.streams_layer_name][0]\n return layer.outputs.get(\"InputStream\")\n\n\n@pytest.fixture(scope=\"session\")\ndef kinesis():\n \"\"\"Boto3 kinesis client.\"\"\"\n region = os.environ.get(\"AWS_DEFAULT_REGION\") or \"eu-west-1\"\n return boto3.client(\"kinesis\", region_name=region)\n\n\n","repo_name":"humilis/humilis-kinesis-processor","sub_path":"tests/integration/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"24197479429","text":"\nfrom 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\nfrom pyvirtualdisplay import Display\n\ntry:\n display = Display(visible=0, size=(800,600))\n display.start()\n\n options = webdriver.ChromeOptions()\n#All the arguments added for chromium to work on selenium\n options.add_argument(\"--no-sandbox\") #This make Chromium reachable\n options.add_argument(\"--no-default-browser-check\") #Overrides default choices\n options.add_argument(\"--no-first-run\")\n options.add_argument(\"--disable-default-apps\")\n\n print(\"open chrome\")\n driver = webdriver.Chrome('./chromedriver',chrome_options=options)\n print(\"connecting to soribada..\")\n driver.get('http://www.soribada.com/music/chart')\n\n print(\"connected to soribada\")\n\n wait_time = 20\n\n WebDriverWait(driver, wait_time).until(EC.presence_of_element_located((By.XPATH, \"//div[@class='list-area2']\")))\n\n l = driver.find_elements_by_xpath(\"//div[@class='list-area2']\")\n\n i=1\n print(\"crawling start\")\n with open(\"soribada.txt\", \"w\") as f:\n for elem in l:\n print(str(i)+\" 's crawling\")\n try:\n f.write(str(i)+\"st --------\")\n f.write(\"title: \" + elem.find_element_by_xpath(\".//span[@class='song-title']\").text)\n f.write(\"artist: \" + elem.find_element_by_xpath(\".//span[@class='link-type2-name artist']\").text)\n f.write(\"album title: \" + elem.find_element_by_xpath(\".//span[@class='link-type2 album-title']\").text)\n except Exception as e:\n print(e)\n f.write(\"artist: \" + elem.find_element_by_xpath(\".//span[@class='link-type2-name artist detail_artist']\").text)\n i += 1\nexcept Exception as e:\n print(e)\n\ndriver.quit()\ndisplay.stop()\n","repo_name":"JoosJuliet/duckmate-server","sub_path":"crawling/soribada.py","file_name":"soribada.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74858128483","text":"# https://www.acmicpc.net/problem/2798\n\nimport sys\n\nN, M = map(int, sys.stdin.readline().split())\ncard = list(map(int, sys.stdin.readline().split()))\n\nblackjack = 0\nsum = 0\n\nfor i in range(N):\n for j in range(i+1, N):\n for k in range(j+1, N):\n sum = card[i] + card[j] + card[k]\n if sum > blackjack and sum <=M:\n blackjack = sum\nprint(blackjack)\n","repo_name":"leeryeongsong/baekjoon-step-by-step-python3","sub_path":"step11/level1-2798-블랙잭.py","file_name":"level1-2798-블랙잭.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23811192556","text":"import wx\nimport time\nimport os\nimport numpy as np\nfrom ui.panels import TrainingVisualizer, ActionLog, ParameterControl, Logs\nfrom algorithms.ppo import PPO_Train\nfrom multiprocessing import Process, Queue\nfrom _test_.subprocess_test import subprocess_test\n\n\nclass MainFrame(wx.Frame):\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=title)\n self.selectedEnvId = 0\n self.debugQueue = None\n self.InitUI()\n self.Show(True)\n\n\n def InitUI(self):\n self.panel = wx.Panel(self, wx.ID_ANY)\n topSizer = wx.GridSizer(2, 2, 2, 2)\n\n self.logQueue = Queue()\n self.ppo = PPO_Train(self.logQueue)\n self.logs = Logs(self, self.logQueue)\n self.logTimer = wx.Timer(self)\n self.Bind(wx.EVT_TIMER, self.OnLogTimer, self.logTimer)\n\n self.visual = TrainingVisualizer(self, 8)\n self.actionLog = ActionLog(self)\n self.control = ParameterControl(self, self.ppo.settings, self.StartTraining)\n\n topSizer.Add(self.visual, 0, wx.EXPAND)\n topSizer.Add(self.actionLog, 0, wx.EXPAND)\n topSizer.Add(self.control, 0, wx.EXPAND)\n topSizer.Add(self.logs, 0, wx.EXPAND)\n\n self.panel.SetSizerAndFit(topSizer)\n topSizer.Fit(self)\n\n self.logTimer.Start(1000)\n\n def InitTrainingProcess(self, f_path=''):\n self.logs.Clear()\n self.actionLog.Clear()\n\n self.debugQueue = Queue()\n self.pauseQueue = Queue()\n self.trainingProcess = Process(target=self.ppo.Start, args=(self.debugQueue, self.pauseQueue, f_path, ))\n\n self.debugInfoRefreshTimer = wx.Timer(self)\n self.Bind(wx.EVT_TIMER, self.OnDebugData, self.debugInfoRefreshTimer)\n\n self.trainingProcess.start()\n self.debugInfoRefreshTimer.Start(1000 / 60)\n\n\n def OnLogTimer(self, e):\n self.logs.WriteLogsInQueue()\n\n def OnDebugData(self, e):\n data = ()\n while not self.debugQueue.empty():\n data = self.debugQueue.get()\n if len(data) > 0:\n index = len(data[0][0]) - 3\n self.visual.SetVisualData(data[0][self.selectedEnvId][:index])\n self.actionLog.PushActionsIn(data[0][self.selectedEnvId][index:])\n self.actionLog.PushActionsOut(data[3][self.selectedEnvId], data[1][self.selectedEnvId], data[2][self.selectedEnvId])\n if data[2][self.selectedEnvId]:\n self.actionLog.Clear()\n\n def PauseTraining(self):\n self.pauseQueue.put(1)\n self.logs.Log('Training Paused...')\n\n def ResumeTraining(self):\n self.pauseQueue.put(1)\n self.logs.Log('Training Resumed...')\n\n def StartTrainingFromFile(self, f_path):\n self.control.StartEnv()\n self.logQueue.put('Starting Environment, sleeping for 1 second...')\n time.sleep(1)\n self.InitTrainingProcess(f_path)\n\n def StartTraining(self, e):\n self.control.StartEnv()\n self.logQueue.put('Starting Environment, sleeping for 1 second...')\n time.sleep(1)\n self.InitTrainingProcess()\n\n def StopTraining(self):\n if self.debugQueue is not None:\n self.debugQueue.close()\n self.logQueue.close()\n self.trainingProcess.terminate()\n\n def Play(self, f_path):\n self.logs.Clear()\n self.control.StartEnv()\n self.logQueue.put('Starting Environment, sleeping for 1 second...')\n time.sleep(1)\n self.playProcess = Process(target=self.ppo.Play, args=(f_path, False, ))\n self.playProcess.start()\n\n\nex = wx.App(False)\nmain = MainFrame(None, \"Training Control\")\nex.MainLoop()\nmain.StopTraining()\n","repo_name":"Sunbvert/Chuang","sub_path":"AI_Core/ppo/training_control.py","file_name":"training_control.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74587648165","text":"from collections import deque\n\nt = int(input())\n\nfor _ in range(1, t+1):\n n = int(input())\n\n fr = [-1]*(n+1) # y 를 만들기 전의 숫자 fr[y] = x\n how = [-1]*(n+1) # x 에서 y를 만들때 1을 썻는지 0을 썻는지\n dist = [-1]*(n+1) # y 숫자의 길이\n\n q = deque()\n q.append(1%n)\n dist[1%n] = 0\n how[1%n] = 1\n\n while q:\n p = q.popleft()\n \n for i in range(2):\n nxt = (p*10+i)%n\n if dist[nxt] == -1:\n dist[nxt] = dist[p] + 1\n fr[nxt] = p\n how[nxt] = i\n q.append(nxt)\n\n if dist[0] == -1:\n print('BRAK')\n else:\n ans = ''\n i = 0\n while i != -1:\n ans = str(how[i]) + ans\n i = fr[i]\n \n print(ans)","repo_name":"jngcii/TIL","sub_path":"Algorithm/Advanced/Graph/BFS/8111.0과1.py","file_name":"8111.0과1.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"3270409227","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 17 20:41:42 2020\r\n\r\n@author: Norbert Toth\r\n\"\"\"\r\n\r\n\r\n\r\nimport numpy as np; # importing numerical computing package\r\nfrom urllib.request import urlopen; # importing url handling\r\nfrom sklearn import model_selection as ms; # importing model selection tools\r\nfrom sklearn import linear_model as lm; # importing linear models\r\nfrom sklearn import naive_bayes as nb; # importing naive Bayes classifiers\r\nfrom sklearn import metrics; # importing performance metrics\r\nfrom matplotlib import pyplot as plt; # importing MATLAB-like plotting framework\r\nimport itertools;\r\nimport sklearn.preprocessing as pre;\r\n\r\ndef plot_confusion_matrix(cm, classes,\r\n normalize=False,\r\n title='Confusion matrix',\r\n cmap=plt.cm.Greens):\r\n \"\"\"\r\n This function prints and plots the confusion matrix.\r\n Normalization can be applied by setting `normalize=True`.\r\n \"\"\"\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n print(\"Normalized confusion matrix\")\r\n else:\r\n print('Confusion matrix, without normalization')\r\n\r\n print(cm)\r\n\r\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n plt.title(title)\r\n plt.colorbar()\r\n tick_marks = np.arange(len(classes))\r\n plt.xticks(tick_marks, classes, rotation=45)\r\n plt.yticks(tick_marks, classes)\r\n\r\n fmt = '.2f' if normalize else 'd'\r\n thresh = cm.max() / 2.\r\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n plt.text(j, i, format(cm[i, j], fmt),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label')\r\n plt.tight_layout()\r\n \r\n# Reading the dataset\r\n\r\nurl = 'https://raw.githubusercontent.com/notusedusername/machine_learning/master/winequality-red.csv';\r\nlabel_row_number = 1;\r\nattribute_cols = 10;\r\noutput_variable_col = 11;\r\n\r\n\r\n\r\nraw_data = urlopen(url);\r\ndata = np.loadtxt(raw_data, delimiter=\";\", dtype = float, skiprows=label_row_number)\r\nraw_data = urlopen(url);\r\nattribute_names = np.loadtxt(raw_data, delimiter=\";\", dtype=str, max_rows=1)\r\ndel raw_data;\r\n\r\n\r\n\r\n# Defining input and target variables\r\nX = data[:,0:attribute_cols]; \r\ny = data[:,output_variable_col];\r\ndel data;\r\ninput_names = attribute_names[0:attribute_cols];\r\ntarget_names = list(range(1,11)); #rating between 1 and 10\r\n\r\n# Partitioning into training and test sets\r\nX_train, X_test, y_train, y_test = ms.train_test_split(X,y, test_size=0.3, \r\n shuffle = True, random_state=2020);\r\n\r\n\r\n\r\n# Fitting logistic regression\r\nlogreg_classifier = lm.LogisticRegression();\r\nlogreg_classifier.fit(X_train,y_train);\r\nypred_logreg = logreg_classifier.predict(X_train);\r\ncm_logreg_train = metrics.confusion_matrix(y_train, ypred_logreg, labels=target_names); # train confusion matrix\r\nypred_logreg = logreg_classifier.predict(X_test);\r\ncm_logreg_test = metrics.confusion_matrix(y_test, ypred_logreg, labels=target_names); # test confusion matrix\r\nyprobab_logreg = logreg_classifier.predict_proba(X_test); # prediction probabilities\r\n\r\n\r\n\r\n# Fitting naive Bayes classifier\r\nnaive_bayes_classifier = nb.GaussianNB();\r\nnaive_bayes_classifier.fit(X_train,y_train);\r\nypred_naive_bayes = naive_bayes_classifier.predict(X_train); # prediction for train\r\ncm_naive_bayes_train = metrics.confusion_matrix(y_train, ypred_naive_bayes, labels=target_names); # train confusion matrix\r\nypred_naive_bayes = naive_bayes_classifier.predict(X_test); #prediction\r\ncm_naive_bayes_test = metrics.confusion_matrix(y_test, ypred_naive_bayes,labels=target_names); # test confusion matrix \r\nyprobab_naive_bayes = naive_bayes_classifier.predict_proba(X_test); # prediction probabilities\r\n\r\n# Plot non-normalized confusion matrix\r\nplt.figure(1);\r\nplot_confusion_matrix(cm_logreg_test, classes=target_names,\r\n title='Confusion matrix for test dataset (LogReg)');\r\nplt.show();\r\n\r\nplt.figure(2);\r\nplot_confusion_matrix(cm_naive_bayes_test, classes=target_names,\r\n title='Confusion matrix for test dataset (naive Bayes)');\r\nplt.show();\r\n\r\ny_test_binarized = pre.label_binarize(y_test, target_names)\r\n\r\nfpr_logreg, tpr_logreg, _ = metrics.roc_curve(y_test_binarized[:,6], yprobab_logreg[:,4]);\r\nroc_auc_logreg = metrics.auc(fpr_logreg, tpr_logreg);\r\n\r\nfpr_naive_bayes, tpr_naive_bayes, _ = metrics.roc_curve(y_test_binarized[:,6], yprobab_naive_bayes[:,4]);\r\nroc_auc_naive_bayes = metrics.auc(fpr_naive_bayes, tpr_naive_bayes);\r\n\r\nplt.figure(3);\r\nlw = 1;\r\nplt.plot(fpr_logreg, tpr_logreg, color='red',\r\n lw=lw, label='Logistic regression (area = %0.2f)' % roc_auc_logreg);\r\nplt.plot(fpr_naive_bayes, tpr_naive_bayes, color='blue',\r\n lw=lw, label='Naive Bayes (area = %0.2f)' % roc_auc_naive_bayes);\r\nplt.plot([0, 1], [0, 1], color='black', lw=lw, linestyle='--');\r\nplt.xlim([0.0, 1.0]);\r\nplt.ylim([0.0, 1.05]);\r\nplt.xlabel('False Positive Rate');\r\nplt.ylabel('True Positive Rate');\r\nplt.title('Receiver operating characteristic curve');\r\nplt.legend(loc=\"lower right\");\r\nplt.show();","repo_name":"notusedusername/machine_learning","sub_path":"2nd/Tanit.py","file_name":"Tanit.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21829830111","text":"import base64\n\nfrom libcloud.utils.py3 import urlencode\nfrom libcloud.utils.py3 import b\n\nfrom libcloud.common.base import XmlResponse, ConnectionUserAndKey\nfrom libcloud.common.types import InvalidCredsError\nfrom libcloud.compute.types import NodeState, Provider\nfrom libcloud.compute.base import NodeDriver, Node, NodeImage, NodeSize, NodeLocation, NodeAuthSSHKey\n\nHOST = 'www-147.ibm.com'\nREST_BASE = '/computecloud/enterprise/api/rest/20100331'\n\nclass IBMResponse(XmlResponse):\n def success(self):\n return int(self.status) == 200\n\n def parse_error(self):\n if int(self.status) == 401:\n if not self.body:\n raise InvalidCredsError(str(self.status) + ': ' + self.error)\n else:\n raise InvalidCredsError(self.body)\n return self.body\n\nclass IBMConnection(ConnectionUserAndKey):\n \"\"\"\n Connection class for the IBM Developer Cloud driver\n \"\"\"\n\n host = HOST\n responseCls = IBMResponse\n\n def add_default_headers(self, headers):\n headers['Accept'] = 'text/xml'\n headers['Authorization'] = ('Basic %s' % (base64.b64encode(b('%s:%s' %\n (self.user_id, self.key)))))\n if not 'Content-Type' in headers:\n headers['Content-Type'] = 'text/xml'\n return headers\n\n def encode_data(self, data):\n return urlencode(data)\n\nclass IBMNodeDriver(NodeDriver):\n \"\"\"\n IBM Developer Cloud node driver.\n \"\"\"\n connectionCls = IBMConnection\n type = Provider.IBM\n name = \"IBM Developer Cloud\"\n\n NODE_STATE_MAP = { 0: NodeState.PENDING, # New\n 1: NodeState.PENDING, # Provisioning\n 2: NodeState.TERMINATED, # Failed\n 3: NodeState.TERMINATED, # Removed\n 4: NodeState.TERMINATED, # Rejected\n 5: NodeState.RUNNING, # Active\n 6: NodeState.UNKNOWN, # Unknown\n 7: NodeState.PENDING, # Deprovisioning\n 8: NodeState.REBOOTING, # Restarting\n 9: NodeState.PENDING, # Starting\n 10: NodeState.PENDING, # Stopping\n 11: NodeState.TERMINATED, # Stopped\n 12: NodeState.PENDING, # Deprovision Pending\n 13: NodeState.PENDING, # Restart Pending\n 14: NodeState.PENDING, # Attaching\n 15: NodeState.PENDING } # Detaching\n\n def create_node(self, **kwargs):\n \"\"\"\n Creates a node in the IBM Developer Cloud.\n\n See L{NodeDriver.create_node} for more keyword args.\n\n @keyword auth Name of the pubkey to use. When constructing\n C{NodeAuthSSHKey} instance, 'pubkey' argument must be\n the name of the public key to use.\n You chose this name when creating a new public key on\n the IBM server.\n @type auth C{NodeAuthSSHKey}\n\n @keyword ex_configurationData: Image-specific configuration parameters.\n Configuration parameters are defined in\n the parameters.xml file. The URL to\n this file is defined in the NodeImage\n at extra[parametersURL].\n\n Note: This argument must be specified\n when launching a Windows instance. It\n must contain 'UserName' and 'Password'\n keys.\n @type ex_configurationData: C{dict}\n \"\"\"\n\n # Compose headers for message body\n data = {}\n data.update({'name': kwargs['name']})\n data.update({'imageID': kwargs['image'].id})\n data.update({'instanceType': kwargs['size'].id})\n if 'location' in kwargs:\n data.update({'location': kwargs['location'].id})\n else:\n data.update({'location': '1'})\n if 'auth' in kwargs and isinstance(kwargs['auth'], NodeAuthSSHKey):\n data.update({'publicKey': kwargs['auth'].pubkey})\n if 'ex_configurationData' in kwargs:\n configurationData = kwargs['ex_configurationData']\n for key in configurationData.keys():\n data.update({key: configurationData.get(key)})\n\n # Send request!\n resp = self.connection.request(action = REST_BASE + '/instances',\n headers = {'Content-Type': 'application/x-www-form-urlencoded'},\n method = 'POST',\n data = data).object\n return self._to_nodes(resp)[0]\n\n def destroy_node(self, node):\n url = REST_BASE + '/instances/%s' % (node.id)\n status = int(self.connection.request(action = url, method='DELETE').status)\n return status == 200\n\n def reboot_node(self, node):\n url = REST_BASE + '/instances/%s' % (node.id)\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n data = {'state': 'restart'}\n\n resp = self.connection.request(action = url,\n method = 'PUT',\n headers = headers,\n data = data)\n return int(resp.status) == 200\n\n def list_nodes(self):\n return self._to_nodes(self.connection.request(REST_BASE + '/instances').object)\n\n def list_images(self, location = None):\n return self._to_images(self.connection.request(REST_BASE + '/offerings/image').object)\n\n def list_sizes(self, location = None):\n return [ NodeSize('BRZ32.1/2048/60*175', 'Bronze 32 bit', None, None, None, None, self.connection.driver),\n NodeSize('BRZ64.2/4096/60*500*350', 'Bronze 64 bit', None, None, None, None, self.connection.driver),\n NodeSize('COP32.1/2048/60', 'Copper 32 bit', None, None, None, None, self.connection.driver),\n NodeSize('COP64.2/4096/60', 'Copper 64 bit', None, None, None, None, self.connection.driver),\n NodeSize('SLV32.2/4096/60*350', 'Silver 32 bit', None, None, None, None, self.connection.driver),\n NodeSize('SLV64.4/8192/60*500*500', 'Silver 64 bit', None, None, None, None, self.connection.driver),\n NodeSize('GLD32.4/4096/60*350', 'Gold 32 bit', None, None, None, None, self.connection.driver),\n NodeSize('GLD64.8/16384/60*500*500', 'Gold 64 bit', None, None, None, None, self.connection.driver),\n NodeSize('PLT64.16/16384/60*500*500*500*500', 'Platinum 64 bit', None, None, None, None, self.connection.driver) ]\n\n def list_locations(self):\n return self._to_locations(self.connection.request(REST_BASE + '/locations').object)\n\n def _to_nodes(self, object):\n return [ self._to_node(instance) for instance in object.findall('Instance') ]\n\n def _to_node(self, instance):\n public_ips = []\n\n ip = instance.findtext('IP')\n if ip:\n public_ips.append(ip)\n\n return Node(id = instance.findtext('ID'),\n name = instance.findtext('Name'),\n state = self.NODE_STATE_MAP[int(instance.findtext('Status'))],\n public_ips = public_ips,\n private_ips = [],\n driver = self.connection.driver)\n\n def _to_images(self, object):\n return [ self._to_image(image) for image in object.findall('Image') ]\n\n def _to_image(self, image):\n return NodeImage(id = image.findtext('ID'),\n name = image.findtext('Name'),\n driver = self.connection.driver,\n extra = {'parametersURL': image.findtext('Manifest')})\n\n def _to_locations(self, object):\n return [ self._to_location(location) for location in object.findall('Location') ]\n\n def _to_location(self, location):\n # NOTE: country currently hardcoded\n return NodeLocation(id = location.findtext('ID'),\n name = location.findtext('Name'),\n country = 'US',\n driver = self.connection.driver)\n","repo_name":"ConPaaS-team/conpaas","sub_path":"conpaas-director/cpsdirector/iaas/libcloud/compute/drivers/ibm_sbc.py","file_name":"ibm_sbc.py","file_ext":"py","file_size_in_byte":8457,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"} +{"seq_id":"36084936433","text":"num = 9\nstart = 0\nend = 8.0\n\n\n\nwhile start <= end:\n print(start, end)\n mid = (start+end)/2\n mid_square = mid**2\n print(mid_square)\n\n if abs(mid**2-num) <= 0.001:\n print(\"hello\")\n break \n elif mid_square < num:\n print(\"small\")\n start = mid+ 0.001\n else:\n print(\"big\")\n end = mid-0.001\n print(start, end)\n\n\n\n# def square_root(n, epsilon=1e-10):\n# x = n / 2 # start with an initial guess for the square root\n# while abs(x**2 - n) > epsilon:\n# x = (x + n/x) / 2\n# return x\n# print(square_root(0.25))\n","repo_name":"ajaygc95/DS-ALGO","sub_path":"Algorithms/Searching and Sorting/find_sqrt.py","file_name":"find_sqrt.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30822360232","text":"import numpy as np\nfrom ML_Lib.models.model import DifferentiableProbabilityModel\nimport autograd\nimport autograd.numpy as agnp\nimport autograd.scipy as agsp\n\nclass TargetDistribution(DifferentiableProbabilityModel):\n\n def __init__(self, n_dims, log_prob, init = None):\n self.n_dims = n_dims\n if init is None:\n self.params = np.zeros((1,self.n_dims))\n else:\n self.params = init\n self.full_log_prob = lambda params, x : log_prob\n self.full_grad_log_prob = lambda params, X: autograd.elementwise_grad(self.full_log_prob)\n self.log_prob = log_prob\n self.grad_log_prob = autograd.elementwise_grad(self.log_prob)\n\n def get_params(self):\n return self.params\n \n def set_params(self, params):\n self.params = params\n \nif __name__ == '__main__':\n\n import plotly.offline as pyo\n import plotly.graph_objs as go\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n from ML_Lib.inference.sampling import HMC, MetropolisHastings\n from ML_Lib.inference.variational_inference import BlackBoxKLQPScore, BlackBoxKLQPReparam, FullRank, MeanField, ImplicitVI\n from ML_Lib.inference.optimization import MAP\n import os\n\n class BananaDistribution(DifferentiableProbabilityModel):\n\n def __init__(self, a, b, cov):\n self.a = a\n self.b = b\n self.cov = cov\n self.grad_log_prob = autograd.elementwise_grad(self.log_prob)\n self.params = np.ones((1,2))\n\n def sample(self,N = 1000):\n t = np.random.multivariate_normal(np.zeros(2), self.cov, size = (N))\n z1 = self.a*t[:,0]\n z2 = t[:,1]/self.a - self.b * (z1**2 + self.a)\n return np.array([z1,z2]).T\n\n def log_prob(self,z):\n t1 = z[:,0]/self.a\n t2 = (z[:,1] + self.b * (z[:,0]**2 + self.a))*self.a\n L = agnp.array([t1,t2]).T\n lpd = agsp.stats.multivariate_normal.logpdf(L, np.zeros(2), self.cov)\n return lpd\n\n def get_params(self):\n return self.params\n\n def set_params(self, params):\n self.params = params\n\n class MixtureDistribution(DifferentiableProbabilityModel):\n\n def __init__(self, means, covs = None):\n self.means = means\n self.dims = self.means.shape[1]\n self.n_mixes = self.means.shape[0]\n self.grad_log_prob = autograd.elementwise_grad(self.log_prob)\n self.params = np.zeros((1,2))\n if covs is None:\n self.covs = [np.eye(self.dims)] * self.n_mixes\n else:\n self.covs = covs\n\n def sample(self, N = 100):\n s = []\n for i in range(N):\n z = np.random.choice(list(range(self.n_mixes)))\n s.append(np.random.multivariate_normal(self.means[z,:], self.covs[z]))\n return np.array(s)\n\n def log_prob(self,z):\n lp = []\n for i in range(self.n_mixes):\n lp.append(agnp.exp(agsp.stats.multivariate_normal.logpdf(z, self.means[i,:], self.covs[i])))\n return agnp.log(agnp.array(sum(lp)))\n\n def get_params(self):\n return self.params\n\n def set_params(self, params):\n self.params = params\n\n class DonutDistribution(DifferentiableProbabilityModel):\n\n def __init__(self, radius = 2.6, sigma2 = 0.033):\n self.radius = radius\n self.sigma2 = sigma2\n self.params = np.ones((1,2))\n self.grad_log_prob = autograd.elementwise_grad(self.log_prob)\n\n def log_prob(self, z):\n r = agnp.linalg.norm(z)\n return -agnp.power(r - self.radius, 2) / self.sigma2\n\n def get_params(self):\n return self.params\n \n def set_params(self, params):\n self.params = params\n\n class MixtureDonutDistribution(DifferentiableProbabilityModel):\n\n def __init__(self, radii = [5, 2.6], sigma2 = [0.033,0.033]):\n self.radii = radii\n self.sigma2 = sigma2\n self.params = np.ones((1,2))\n self.grad_log_prob = autograd.elementwise_grad(self.log_prob)\n\n def log_prob(self, z):\n r = agnp.linalg.norm(z)\n lp = []\n for i in range(len(self.radii)):\n lp.append(agnp.exp(-agnp.power(r - self.radii[i], 2) / self.sigma2[i]))\n return agnp.log(agnp.array(sum(lp)))\n\n def get_params(self):\n return self.params\n \n def set_params(self, params):\n self.params = params\n\n class SquiggleDistribution(DifferentiableProbabilityModel):\n\n def __init__(self, mean, cov):\n self.mean = mean\n self.cov = cov\n self.params = np.zeros((1,2))\n self.grad_log_prob = autograd.elementwise_grad(self.log_prob)\n\n def log_prob(self, z):\n y = agnp.array([z[:,0],z[:,1] + agnp.sin(5 * z[:,0])])\n t = agsp.stats.multivariate_normal.logpdf(y.T, self.mean, self.cov)\n return t\n\n def get_params(self):\n return self.params\n\n def set_params(self, params):\n self.params = params\n\n mx = MixtureDistribution(np.array([[-3,-3],[3,3]]),covs = [np.array([[1,0.3],[0.3,1]]), np.array([[1,0.7],[0.7,1]])])\n #mx = BananaDistribution(1,1,np.array([[1,0.7],[0.7,1]]))\n #mx = DonutDistribution()\n #mx = SquiggleDistribution(np.array([0,0]), np.array([[2,0.25],[0.25,0.5]]))\n #mx = MixtureDonutDistribution()\n \n x = np.linspace(-20,20,100)\n y = np.linspace(-20,20,100)\n Z = np.zeros((100,100))\n for i in range(100):\n for j in range(100):\n Z[i,j] = mx.log_prob(np.array([x[i],y[j]]))\n \n #hmc = HMC(mx)\n #hmc_samples = hmc.train(num_samples = 8000, num_cores = 4, num_chains = 1, step_size = 0.8, integration_steps = 40)\n #ma = MAP(mx)\n #mx_max = ma.train()\n \n #td = TargetDistribution(2, mx.log_prob, init = mx.get_params())\n #vi_mean_field = BlackBoxKLQPScore(mx,variational_distribution = MeanField)\n #vi_full_rank = BlackBoxKLQPScore(mx,variational_distribution = FullRank)\n vi_implicit = ImplicitVI(mx)\n \n # Set up figure.\n fig = plt.figure(figsize=(12,8), facecolor='white')\n ax = fig.add_subplot(111, frameon=False)\n plt.show(block=False)\n \n def get_callback(vi_method):\n def callback(params, i, grad):\n if i % 100 == 0:\n plt.cla()\n #vi_method.v_dist.set_params(params)\n vi_method.generator.set_params(params)\n vi_samples = vi_method.sample(1000)\n \n # Show posterior marginals.\n ax.set_xlim([-20,20])\n ax.set_ylim([-20,20])\n\n #ax.plot(s[:,0], s[:,1], 'b.', label = 'target')\n ax.contourf(x, y, Z)\n vf = ax.plot(vi_samples[:,0], vi_samples[:,1], 'r.', label = 'variational samples')\n ax.legend()\n plt.draw()\n plt.pause(1.0/90.0)\n return callback\n\n #vi_mean_field.train(n_mc_samples = 10, step_size = 0.1, num_iters = 1000, callback = get_callback(vi_mean_field))\n #vi_full_rank.train(n_mc_samples = 10, step_size = 0.1, num_iters = 1000, callback = get_callback(vi_full_rank))\n vi_implicit.train(n_iters = 100, callback = get_callback(vi_implicit))\n plt.pause(3.0)\n \n \"\"\"\n # Final Plt\n # Set up figure.\n fig = plt.figure(figsize=(20,8), facecolor='white')\n ax1 = fig.add_subplot(131)\n ax2 = fig.add_subplot(132)\n ax3 = fig.add_subplot(133)\n\n plt.cla()\n vi_mf_samples = vi_mean_field.sample(1000)\n vi_fr_samples = vi_full_rank.sample(1000)\n\n ax1.set_xlim([-20,20])\n ax1.set_ylim([-20,20])\n ax1.contourf(x,y,Z)\n ax2.set_xlim([-20,20])\n ax2.set_ylim([-20,20])\n ax2.contourf(x,y,Z)\n ax3.set_xlim([-20,20])\n ax3.set_ylim([-20,20])\n ax3.contourf(x,y,Z)\n\n vfmf = ax1.plot(vi_mf_samples[:,0], vi_mf_samples[:,1], 'r.', label = 'meanfield')\n vffr = ax2.plot(vi_fr_samples[:,0], vi_fr_samples[:,1], 'b.', label = 'fullrank')\n vfhmc = ax3.plot(hmc_samples[:,0], hmc_samples[:,1], 'g.', label = 'HMC')\n ax1.legend()\n ax2.legend()\n ax3.legend()\n plt.draw()\n plt.savefig('/Users/richardjiang/Documents/figs/mixture.png')\n \"\"\"\n","repo_name":"rmjiang7/ML_Lib","sub_path":"ML_Lib/models/target_dist.py","file_name":"target_dist.py","file_ext":"py","file_size_in_byte":8407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33975115461","text":"import os\nos.environ['PYOPENGL_PLATFORM'] = 'osmesa'\nimport glob\nimport numpy as np\nimport torch\nimport yaml\nimport trimesh\nimport numbers\n\nimport pickle as pkl\n\nfrom torch.utils import data\n\nfrom scipy.spatial import cKDTree as KDTree\nfrom scipy.spatial.transform import Rotation as R\n# from human_body_prior.mesh import MeshViewer\nfrom im2mesh.utils.libmesh import check_mesh_contains\n\nSMPL2IPNET_IDX = np.array([11, 12, 13, 11, 3, 8, 11, 1, 6, 11, 1, 6, 0, 11, 11, 0, 5, 10, 4, 9, 2, 7, 2, 7])\nIPNET2SMPL_IDX = np.array([12, 7, 20, 4, 18, 16, 8, 21, 5, 19, 17, 0, 1, 2])\nSMPL_parents = np.array([-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14,\n 16, 17, 18, 19, 20, 21], dtype=np.int32)\nIPNet_parents = np.array([11, 3, 4, 12, 5, 11, 8, 9, 13, 10, 11, -1, 11, 11], dtype=np.int32)\nIPNet_parents_in_SMPL = np.array([9, 4, 18, 1, 16, 13, 5, 19, 2, 17, 14, -1, 0, 0], dtype=np.int32)\n\n''' Copied from IPNet'''\ndef get_3DSV(mesh):\n from opendr.camera import ProjectPoints\n from opendr.renderer import DepthRenderer\n WIDTH, HEIGHT = 250, 250\n\n rt = R.from_euler('xyz', [np.pi, 0, 0]).as_rotvec()\n rt_mat = R.from_euler('xyz', [np.pi, 0, 0]).as_matrix()\n camera = ProjectPoints(v=mesh.vertices, f=np.array([WIDTH, WIDTH]), c=np.array([WIDTH, HEIGHT]) / 2.,\n t=np.array([0, 0, 3.0]), rt=rt, k=np.zeros(5))\n frustum = {'near': 1., 'far': 10., 'width': WIDTH, 'height': HEIGHT}\n rn = DepthRenderer(camera=camera, frustum=frustum, f=mesh.faces, overdraw=False)\n\n # import cv2\n depth_image = rn.depth_image.copy()\n mask = depth_image < depth_image.max() - 0.01\n depth_image[~mask] = 0\n depth_image[mask] = 255 - (depth_image[mask] - depth_image[mask].min()) / (depth_image[mask].max() - depth_image[mask].min()) * 255\n\n points3d = camera.unproject_depth_image(rn.r)\n mask = points3d[:, :, 2] > np.min(points3d[:, :, 2]) + 0.01\n\n points3d = points3d[mask]\n\n return points3d, depth_image\n\nclass CAPESingleViewDataset(data.Dataset):\n ''' CAPE dataset class.\n '''\n\n def __init__(self, dataset_folder,\n subjects=['00032', '00096', '00122', '00127', '00134', '00145', '00159', '00215', '02474', '03223', '03284', '03331', '03375', '03383', '03394'],\n mode='train',\n input_type='pointcloud',\n voxel_res=128,\n double_layer=False,\n use_aug=False,\n use_v_template=False,\n use_abs_bone_transforms=False,\n num_joints=24,\n input_pointcloud_n=5000,\n input_pointcloud_noise=0.001,\n points_size=2048,\n points_uniform_ratio=0.5,\n use_global_trans=False,\n normalized_scale=False,\n query_on_clothed=False,\n points_sigma=0.05,\n sequence_idx=None,\n subject_idx=None):\n ''' Initialization of the the 3D shape dataset.\n\n Args:\n dataset_folder (str): dataset folder\n '''\n # Attributes\n self.cape_path = '/cluster/home/shawang/Datasets/CAPE'\n self.dataset_folder = dataset_folder\n self.subjects = subjects\n self.use_global_trans = use_global_trans\n self.use_aug = use_aug\n self.mode = mode\n self.normalized_scale = normalized_scale\n self.input_type = input_type\n self.voxel_res = voxel_res\n self.double_layer = double_layer\n self.num_joints = num_joints\n self.query_on_clothed = query_on_clothed\n self.use_abs_bone_transforms = use_abs_bone_transforms\n\n # if normalized_scale:\n # assert ( not use_global_trans )\n\n self.points_size = points_size if self.mode in ['train', 'test'] else 100000\n # self.points_padding = 0.1\n self.points_padding = 1 / 3 # For IPNet, mesh is normalized to [-0.75, 0.75] while sampling space is [-1, 1]\n self.points_uniform_ratio = points_uniform_ratio if self.mode in ['train', 'test'] else 0.5\n self.points_sigma = points_sigma # 5cm standard deviation for surface points\n\n if input_type == 'pointcloud':\n self.input_pointcloud_n = input_pointcloud_n\n self.input_pointcloud_noise = input_pointcloud_noise\n else:\n self.input_pointcloud_n = self.input_pointcloud_noise = 0\n\n self.faces = np.load('body_models/misc/faces.npz')['faces']\n self.skinning_weights = dict(np.load('body_models/misc/skinning_weights_all.npz'))\n self.posedirs = dict(np.load('body_models/misc/posedirs_all.npz'))\n if self.use_abs_bone_transforms:\n self.J_regressors = dict(np.load('body_models/misc/J_regressors.npz'))\n\n with open('body_models/misc/smpl_parts_dense.pkl', 'rb') as f:\n part_labels = pkl.load(f)\n\n labels = np.zeros(6890, dtype=np.int32)\n for idx, k in enumerate(part_labels):\n labels[part_labels[k]] = idx\n\n self.part_labels = labels\n\n self.use_v_template = use_v_template\n if use_v_template:\n self.v_templates = dict(np.load('body_models/misc/v_templates.npz'))\n\n # Get all data\n self.data = []\n if subject_idx is not None:\n subjects = [subjects[subject_idx]]\n\n with open(os.path.join(self.cape_path, 'cape_release/misc/subj_genders.pkl'), 'rb') as f:\n genders = pkl.load(f)\n\n for subject in subjects:\n subject_dir = os.path.join(dataset_folder, subject)\n sequence_dirs = glob.glob(os.path.join(subject_dir, '*'))\n sequences = set()\n for sequence_dir in sequence_dirs:\n sequences.add(os.path.basename(sequence_dir).split('.')[0])\n\n sequences = sorted(list(sequences))\n\n if sequence_idx is not None:\n sequences = [sequences[sequence_idx]]\n\n for sequence in sequences:\n points_dir = os.path.join(subject_dir, sequence)\n\n points_files = sorted(glob.glob(os.path.join(points_dir, '*.npz')))\n\n self.data += [\n {'subset': 'cape',\n 'subject': subject,\n 'gender': genders[subject],\n 'sequence': sequence,\n 'data_path': points_file}\n for points_file in points_files\n ]\n # self.data = [self.data[200]]\n\n def augm_params(self):\n \"\"\"Get augmentation parameters.\"\"\"\n if self.mode == 'train' and self.use_aug:\n # The rotation is a number in the area [-2*rotFactor, 2*rotFactor]\n # Roll\n rot_x = min(2*90,\n max(-2*90, np.random.randn()*90))\n\n sn, cs = np.sin(np.pi / 180 * rot_x), np.cos(np.pi / 180 * rot_x)\n rot_x = np.eye(4)\n rot_x[1, 1] = cs\n rot_x[1, 2] = -sn\n rot_x[2, 1] = sn\n rot_x[2, 2] = cs\n\n rot_y = min(2*90,\n max(-2*90, np.random.randn()*90))\n\n # Pitch\n sn, cs = np.sin(np.pi / 180 * rot_y), np.cos(np.pi / 180 * rot_y)\n rot_y = np.eye(4)\n rot_y[0, 0] = cs\n rot_y[0, 2] = sn\n rot_y[2, 0] = -sn\n rot_y[2, 2] = cs\n\n rot_z = min(2*90,\n max(-2*90, np.random.randn()*90))\n\n # Yaw\n sn, cs = np.sin(np.pi / 180 * rot_z), np.cos(np.pi / 180 * rot_z)\n rot_z = np.eye(4)\n rot_z[0, 0] = cs\n rot_z[0, 1] = -sn\n rot_z[1, 0] = sn\n rot_z[1, 1] = cs\n\n rot_mat = np.dot(rot_x, np.dot(rot_y, rot_z))\n\n # but it is identity with probability 3/5\n if np.random.uniform() <= 0.6:\n rot_mat = np.eye(4)\n\n else:\n rot_mat = np.eye(4)\n\n\n return rot_mat\n\n def __len__(self):\n ''' Returns the length of the dataset.\n '''\n return len(self.data)\n\n def __getitem__(self, idx):\n ''' Returns an item of the dataset.\n\n Args:\n idx (int): ID of data point\n '''\n data_path = self.data[idx]['data_path']\n subject = self.data[idx]['subject']\n gender = self.data[idx]['gender']\n data = {}\n\n aug_rot = self.augm_params().astype(np.float32)\n\n points_dict = np.load(data_path)\n\n # 3D models and points\n loc = points_dict['loc'].astype(np.float32)\n trans = points_dict['trans'].astype(np.float32)\n root_loc = points_dict['Jtr'][0].astype(np.float32)\n scale = points_dict['scale'].astype(np.float32)\n\n # Also get GT SMPL poses\n pose_body = points_dict['pose_body']\n pose_hand = points_dict['pose_hand']\n pose = np.concatenate([pose_body, pose_hand], axis=-1)\n pose = R.from_rotvec(pose.reshape([-1, 3]))\n\n body_mesh_a_pose = points_dict['a_pose_mesh_points']\n # Break symmetry if given in float16:\n if body_mesh_a_pose.dtype == np.float16:\n body_mesh_a_pose = body_mesh_a_pose.astype(np.float32)\n body_mesh_a_pose += 1e-4 * np.random.randn(*body_mesh_a_pose.shape)\n else:\n body_mesh_a_pose = body_mesh_a_pose.astype(np.float32)\n\n n_smpl_points = body_mesh_a_pose.shape[0]\n\n bone_transforms = points_dict['bone_transforms'].astype(np.float32)\n # Apply rotation augmentation to bone transformations\n bone_transforms_aug = np.matmul(np.expand_dims(aug_rot, axis=0), bone_transforms)\n bone_transforms_aug[:, :3, -1] += root_loc - trans - np.dot(aug_rot[:3, :3], root_loc - trans)\n bone_transforms = bone_transforms_aug\n # Get augmented posed-mesh\n skinning_weights = self.skinning_weights[gender]\n if self.use_abs_bone_transforms:\n J_regressor = self.J_regressors[gender]\n\n T = np.dot(skinning_weights, bone_transforms.reshape([-1, 16])).reshape([-1, 4, 4])\n\n homogen_coord = np.ones([n_smpl_points, 1], dtype=np.float32)\n a_pose_homo = np.concatenate([body_mesh_a_pose - trans, homogen_coord], axis=-1).reshape([n_smpl_points, 4, 1])\n body_mesh = np.matmul(T, a_pose_homo)[:, :3, 0].astype(np.float32) + trans\n\n posed_trimesh = trimesh.Trimesh(vertices=body_mesh, faces=self.faces)\n input_pointcloud, _ = get_3DSV(posed_trimesh)\n noise = self.input_pointcloud_noise * np.random.randn(*input_pointcloud.shape)\n input_pointcloud = (input_pointcloud + noise).astype(np.float32)\n\n # Get extents of model.\n bb_min = np.min(input_pointcloud, axis=0)\n bb_max = np.max(input_pointcloud, axis=0)\n # total_size = np.sqrt(np.square(bb_max - bb_min).sum())\n total_size = (bb_max - bb_min).max()\n # Scales all dimensions equally.\n scale = max(1.6, total_size) # 1.6 is the magic number from IPNet\n loc = np.array(\n [(bb_min[0] + bb_max[0]) / 2,\n (bb_min[1] + bb_max[1]) / 2,\n (bb_min[2] + bb_max[2]) / 2],\n dtype=np.float32\n )\n\n if self.input_pointcloud_n <= input_pointcloud.shape[0]:\n rand_inds = np.random.choice(input_pointcloud.shape[0], size=self.input_pointcloud_n, replace=False)\n else:\n rand_inds = np.random.choice(input_pointcloud.shape[0], size=self.input_pointcloud_n, replace=True)\n\n input_pointcloud = input_pointcloud[rand_inds, :]\n\n n_points_uniform = int(self.points_size * self.points_uniform_ratio)\n n_points_surface = self.points_size - n_points_uniform\n\n boxsize = 1 + self.points_padding\n points_uniform = np.random.rand(n_points_uniform, 3)\n points_uniform = boxsize * (points_uniform - 0.5)\n # Scale points in (padded) unit box back to the original space\n points_uniform *= scale\n points_uniform += loc\n # Sample points around posed-mesh surface\n n_points_surface_cloth = n_points_surface // 2 if self.double_layer else n_points_surface\n points_surface = posed_trimesh.sample(n_points_surface_cloth)\n\n points_surface += np.random.normal(scale=self.points_sigma, size=points_surface.shape)\n\n if self.double_layer:\n n_points_surface_minimal = n_points_surface // 2\n\n posedir = self.posedirs[gender]\n minimal_shape_path = os.path.join(self.cape_path, 'cape_release', 'minimal_body_shape', subject, subject + '_minimal.npy')\n minimal_shape = np.load(minimal_shape_path)\n pose_mat = pose.as_matrix()\n ident = np.eye(3)\n pose_feature = (pose_mat - ident).reshape([207, 1])\n pose_offsets = np.dot(posedir.reshape([-1, 207]), pose_feature).reshape([6890, 3])\n minimal_shape += pose_offsets\n\n if self.use_abs_bone_transforms:\n Jtr_cano = np.dot(J_regressor, minimal_shape)\n Jtr_cano = Jtr_cano[IPNET2SMPL_IDX, :]\n\n a_pose_homo = np.concatenate([minimal_shape, homogen_coord], axis=-1).reshape([n_smpl_points, 4, 1])\n minimal_body_mesh = np.matmul(T, a_pose_homo)[:, :3, 0].astype(np.float32) + trans\n minimal_posed_trimesh = trimesh.Trimesh(vertices=minimal_body_mesh, faces=self.faces)\n\n # Sample points around minimally clothed posed-mesh surface\n points_surface_minimal = minimal_posed_trimesh.sample(n_points_surface_minimal)\n points_surface_minimal += np.random.normal(scale=self.points_sigma, size=points_surface_minimal.shape)\n\n points_surface = np.vstack([points_surface, points_surface_minimal])\n\n # Check occupancy values for sampled ponits\n query_points = np.vstack([points_uniform, points_surface]).astype(np.float32)\n if self.double_layer:\n # Double-layer occupancies, as was done in IPNet\n # 0: outside, 1: between body and cloth, 2: inside body mesh\n occupancies_cloth = check_mesh_contains(posed_trimesh, query_points)\n occupancies_minimal = check_mesh_contains(minimal_posed_trimesh, query_points)\n occupancies = occupancies_cloth.astype(np.int64)\n occupancies[occupancies_minimal] = 2\n else:\n occupancies = check_mesh_contains(posed_trimesh, query_points).astype(np.float32)\n\n # Skinning inds by querying nearest SMPL vertex on the clohted mesh\n kdtree = KDTree(body_mesh if self.query_on_clothed else minimal_body_mesh)\n _, p_idx = kdtree.query(query_points)\n pts_W = skinning_weights[p_idx, :]\n skinning_inds_ipnet = self.part_labels[p_idx] # skinning inds (14 parts)\n skinning_inds_smpl = pts_W.argmax(1) # full skinning inds (24 parts)\n if self.num_joints == 14:\n skinning_inds = skinning_inds_ipnet\n else:\n skinning_inds = skinning_inds_smpl\n\n # Invert LBS to get query points in A-pose space\n T = np.dot(pts_W, bone_transforms.reshape([-1, 16])).reshape([-1, 4, 4])\n T = np.linalg.inv(T)\n\n homogen_coord = np.ones([self.points_size, 1], dtype=np.float32)\n posed_homo = np.concatenate([query_points - trans, homogen_coord], axis=-1).reshape([self.points_size, 4, 1])\n query_points_a_pose = np.matmul(T, posed_homo)[:, :3, 0].astype(np.float32) + trans\n\n if self.use_abs_bone_transforms:\n assert (not self.use_v_template and self.num_joints == 24)\n query_points_a_pose -= Jtr_cano[SMPL2IPNET_IDX[skinning_inds], :]\n\n if self.use_v_template:\n v_template = self.v_templates[gender]\n pose_shape_offsets = v_template - minimal_shape\n query_points_template = query_points_a_pose + pose_shape_offsets[p_idx, :]\n\n sc_factor = 1.0 / scale * 1.5 if self.normalized_scale else 1.0 # 1.5 is the magic number from IPNet\n offset = loc\n\n bone_transforms_inv = bone_transforms.copy()\n bone_transforms_inv[:, :3, -1] += trans - loc\n bone_transforms_inv = np.linalg.inv(bone_transforms_inv)\n bone_transforms_inv[:, :3, -1] *= sc_factor\n\n data = {\n None: (query_points - offset) * sc_factor,\n 'occ': occupancies,\n 'trans': trans,\n 'root_loc': root_loc,\n 'pts_a_pose': (query_points_a_pose - (trans if self.use_global_trans else offset)) * sc_factor,\n 'skinning_inds': skinning_inds,\n 'skinning_inds_ipnet': skinning_inds_ipnet,\n 'skinning_inds_smpl': skinning_inds_smpl,\n 'loc': loc,\n 'scale': scale,\n 'bone_transforms': bone_transforms,\n 'bone_transforms_inv': bone_transforms_inv,\n }\n\n if self.use_v_template:\n data.update({'pts_template': (query_points_template - (trans if self.use_global_trans else offset)) * sc_factor})\n\n if self.mode in ['test']:\n data.update({'smpl_vertices': body_mesh, 'smpl_a_pose_vertices': body_mesh_a_pose})\n if self.double_layer:\n data.update({'minimal_smpl_vertices': minimal_body_mesh})\n\n data_out = {}\n field_name = 'points' if self.mode in ['train', 'test'] else 'points_iou'\n for k, v in data.items():\n if k is None:\n data_out[field_name] = v\n else:\n data_out['%s.%s' % (field_name, k)] = v\n\n if self.input_type == 'pointcloud':\n data_out.update(\n {'inputs': (input_pointcloud - offset) * sc_factor,\n 'idx': idx,\n }\n )\n elif self.input_type == 'voxel':\n voxels = np.unpackbits(points_dict['voxels_occ']).astype(np.float32)\n voxels = np.reshape(voxels, [self.voxel_res] * 3)\n data_out.update(\n {'inputs': voxels,\n 'idx': idx,\n }\n )\n else:\n raise ValueError('Unsupported input type: {}'.format(self.input_type))\n\n return data_out\n\n def get_model_dict(self, idx):\n return self.data[idx]\n","repo_name":"taconite/PTF","sub_path":"im2mesh/data/cape_sv.py","file_name":"cape_sv.py","file_ext":"py","file_size_in_byte":18195,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"52"} +{"seq_id":"9204422704","text":"from datetime import datetime\nimport uuid\nfrom .. import schemas, models\nfrom sqlalchemy.orm import Session\nfrom fastapi import Depends, HTTPException, status, APIRouter, Response\nfrom ..models.database import get_db\nfrom sqlalchemy import text\n\nfrom ..schemas import schemas\n\nrouter = APIRouter()\n\n@router.get('/', response_model=schemas.ListCarModelResponse)\ndef get_carmodels(db: Session = Depends(get_db), limit: int = 10, page: int = 1, search: str = ''):\n skip = (page - 1) * limit\n\n carmodels = db.query(models.CarModel).group_by(models.CarModel.id).filter(\n models.CarModel.name.contains(search)).limit(limit).offset(skip).all()\n return {'status': 'success', 'results': len(carmodels), 'carmodels': carmodels}\n\n@router.get('/{id}', response_model=schemas.CarModelResponse)\ndef get_carmodel(id: str, db: Session = Depends(get_db)):\n carmodel = db.query(models.CarModel).filter(models.CarModel.id == id).first()\n if not carmodel:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"No carmodel with this id: {id} found\")\n return carmodel\n\n@router.get('/carbrands/{carbrand_id}', response_model=schemas.ListCarModelResponse)\ndef get_carmodel_by_carbrand(carbrand_id: str, db: Session = Depends(get_db), limit: int = 10, page: int = 1):\n skip = (page - 1) * limit\n\n carbrand = db.query(models.CarBrand).filter(models.CarBrand.id == carbrand_id).first()\n if not carbrand:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"No carbrand with this id: {carbrand_id} found\")\n\n carmodels = db.query(models.CarModel).filter(\n models.CarModel.carbrand_id == carbrand_id).limit(limit).offset(skip).all()\n return {'status': 'success', 'results': len(carmodels), 'carmodels': carmodels}\n\n@router.post('/', status_code=status.HTTP_201_CREATED, response_model=schemas.CarModelResponse)\ndef create_carmodel(carmodel: schemas.CarModelBaseSchema, db: Session = Depends(get_db)):\n carbrand = db.query(models.CarBrand).filter(models.CarBrand.id == carmodel.carbrand_id).first()\n if not carbrand:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"No carbrand with this id: {carmodel.carbrand_id} found\")\n\n new_carmodel = models.CarModel(**carmodel.dict())\n db.add(new_carmodel)\n db.commit()\n db.refresh(new_carmodel)\n return new_carmodel\n\n@router.put('/{id}', response_model=schemas.CarModelResponse)\ndef update_carmodel(id: str, carmodel: schemas.UpdateCarModelSchema, db: Session = Depends(get_db)):\n if carmodel.carbrand_id:\n carbrand = db.query(models.CarBrand).filter(models.CarBrand.id == carmodel.carbrand_id).first()\n if not carbrand:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"No carbrand with this id: {carmodel.carbrand_id} found\")\n\n carmodel_query = db.query(models.CarModel).filter(models.CarModel.id == id)\n updated_carmodel = carmodel_query.first()\n\n if not updated_carmodel:\n raise HTTPException(status_code=status.HTTP_200_OK,\n detail=f'No carmodel with this id: {id} found')\n\n carmodel_query.update(carmodel.dict(exclude_unset=True), synchronize_session=False)\n db.commit()\n return updated_carmodel\n\n@router.delete('/{id}')\ndef delete_carmodel(id: str, db: Session = Depends(get_db)):\n carmodel_query = db.query(models.CarModel).filter(models.CarModel.id == id)\n carmodel = carmodel_query.first()\n if not carmodel:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f'No carmodel with this id: {id} found')\n\n carmodel_query.delete(synchronize_session=False)\n db.commit()\n return Response(status_code=status.HTTP_204_NO_CONTENT)","repo_name":"ntdu/uCar_be","sub_path":"core/routers/carmodels_routers.py","file_name":"carmodels_routers.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36662121667","text":"# ex90 dicionarios\r\n\"\"\"Exercício Python 090: Faça um programa que leia nome e média de um aluno, \r\nguardando também a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela.\"\"\"\r\nfrom statistics import mean\r\n\r\n\r\ndef RecNot(i):\r\n while True:\r\n try:\r\n n = float(input(f\"Digite a {i}ª nota do aluno: \"))\r\n except:\r\n print(\"Ocorreu um erro, tente novamente\")\r\n continue\r\n if n < 0 or n > 10:\r\n print(\"Digite uma nota válida\")\r\n continue\r\n break\r\n return n\r\n\r\n\r\ndef deciCont():\r\n while True:\r\n deci = input(\"Quer continuar?(N pra sair): \")\r\n if deci not in (\"SsnN\"):\r\n print(\"Ocorreu um erro, digite N pra sair\")\r\n continue\r\n break\r\n return deci\r\n\r\n\r\naluno = {}\r\naluno[\"Nome\"] = input(\"Nome do aluno: \")\r\naluno[\"Nota\"] = [RecNot(1), RecNot(2)]\r\nif mean(aluno[\"Nota\"]) > 6:\r\n sit = \"aprovado\"\r\nelif mean(aluno[\"Nota\"]) >= 5:\r\n sit = \"recuperação\"\r\nelse:\r\n sit = \"reprovado\"\r\nprint(f'Nome: {aluno[\"Nome\"]} notas: {aluno[\"Nota\"][0]}, {aluno[\"Nota\"][1]} situação:{sit}')\r\n","repo_name":"PauloHIG/PythonCEV","sub_path":"pythonCEV/Exercicios/ex90Dicionario.py","file_name":"ex90Dicionario.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38131337624","text":"homeDir = \"/home/tristan/\"\n\nprefixSourceDir = homeDir + \"source/\"\nblenderSourceDir = prefixSourceDir + \"blender/\"\n\ntraceMainScript = homeDir + \"scripts/mainloop/TraceMain.py\"\ntraceDir = homeDir + \"trace/\"\nimageDir = homeDir + \"image/\"\n\ndocDir = prefixSourceDir + \"doc/\"\n\nconfigDir = homeDir + \"config/\"\n\ndoxygenDir = docDir + \"doc/doxygen/\"\ndoxygenBuildDir = doxygenDir + \"html/\"\ndoxygenConfigFile = configDir + \"doxygen/Doxyfile\"\n\nsphinxDir = docDir + \"doc/python_api/\"\nsphinxScript = sphinxDir + \"sphinx_doc_gen.py\"\nsphinxInputDir = sphinxDir + \"sphinx-in/\"\nsphinxOutputDir = sphinxDir + \"sphinx-out/\"\n\nlogDir = homeDir + \"logs/\"\nbuildLogDir = logDir + \"build/\"\ntestLogDir = logDir + \"test/\"\nvalgrindLogDir = testLogDir + \"valgrind/\"\npythonTestLogDir = testLogDir + \"python/\"\n\nvalgrindSuppressionsFile = configDir + \"valgrind-suppressions.supp\"\n\ntestFiles = homeDir + \"files/\"\npythonMainScript = homeDir + \"scripts/mainloop/\"\n\nprefixBuildBranchDir = homeDir + \"build_normal/\"\nprefixBuildBranchDebugDir = homeDir + \"build_debug/\"\nprefixBuildReleaseDir = homeDir + \"build_release/\"\nprefixBuildDebugDir = homeDir + \"build_debug/\"\n\nreleaseConfigFile = configDir + \"release_make_config.cmake\"\nliteConfigFile = configDir + \"branch_make_config.cmake\"\ndebugConfigFile = configDir + \"debug_make_config.cmake\"\n\nlibsListFile = configDir + \"libs.txt\"\n\nhashDir = homeDir + \"build_hash/\"\nbranchHashDir = hashDir + \"branch/\"\nreleaseHashDir = hashDir + \"release/\"\nreleaseHashDir = hashDir + \"debug/\"\nbranchMaskFile = configDir + \"branch.mask\"\n\nreleaseDir = homeDir + \"releases/\"\nlinuxReleaseDir = homeDir + \"download/release/linux64/\"\nlinuxBranchDir = homeDir + \"download/buildbot/branch/\"\n\nprintVersionFile = homeDir + \"version.txt\"\nprintVersionBlendFile = homeDir + \"print_version.blend\"\n\ncompileProcess = 4\n","repo_name":"UPBGE/buildbot","sub_path":"scripts/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37896554506","text":"#!/usr/bin/python3\n# Contact: ivanm@security-net.biz\n# Interesting analysis done with similar scripts:\n# 1. https://security-net.biz/shared/bots/Analiza_neocekivanog_Twitter_statusa_IM_2022.pdf\n# 2. https://security-net.biz/shared/bots/Analiza_neocekivanog_Twitter_statusa_IM_2022_v2.pdf\n\n# Imports\nimport argparse\nimport re, os, time, shutil\nimport sys\nfrom datetime import datetime\nimport simplejson as simplejson\nimport tweepy\n\n# Go to https://apps.twitter.com/ and create an app.\n# The consumer key and secret will be generated for you after\napi_key = \"-CHANGE-ME-\" # UPDATE THIS PART WITH NEW VALUES !!!\napi_secrets = \"-CHANGE-ME-\" # UPDATE THIS PART WITH NEW VALUES !!!\n\n# After the step above, you will be redirected to your app's page.\n# Create an access token under the the \"Create New App\" section\naccess_token = \"-CHANGE-ME-\" # UPDATE THIS PART WITH NEW VALUES !!!\naccess_secret = \"-CHANGE-ME-\" # UPDATE THIS PART WITH NEW VALUES !!!\n\nparser = argparse.ArgumentParser(\"\")\nparser.add_argument(\"-c\", help=\"Delete all files and start from beginning.\", action='store_true')\nparser.add_argument(\"-i\", help=\"Ignore processed file and download data again.\", action='store_true')\nparser.add_argument(\"-b\", help=\"Backup all files.\", action='store_true')\nparser.add_argument(\"-s\", help=\"Sleep between requests, default 1 second.\", default=1)\nparser.add_argument(\"-r\", help=\"Save raw JSON too.\", action='store_true')\nargs = parser.parse_args()\n\ndef make_csv(acc_name, acc_data):\n\n x_date = \"\"\n x_verified = 0\n x_locked = 0\n x_posts = 0\n x_followers = 0\n x_following = 0\n x_likes = 0\n x_last_rt = 0\n\n csv_data = acc_name\n # Full name\n output = re.search('name\\': \\'(.*?)\\', \\'screen_name', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",\" + '\"' + output.group(1) + '\"'\n else:\n csv_data += \",\" + \"ERROR\"\n # Registration Date\n output = re.search('created_at\\': (.*?), \\'favourites_count', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",\" + output.group(1)\n x_date = output.group(1).split(\" \")[-1].replace(\"'\",\"\")\n else:\n csv_data += \",\" + \"ERROR\"\n # Is verified\n output = re.search('verified\\': (.*?), \\'statuses_count', acc_data, flags=re.IGNORECASE)\n if output is not None:\n if output.group(1) == 'True':\n csv_data += \",\" + \"True\"\n x_verified = 1\n else:\n csv_data += \",\" + \"False\"\n else:\n csv_data += \",\" + \"False\"\n # Is protected\n output = re.search('protected\\': (.*?), \\'followers_count', acc_data, flags=re.IGNORECASE)\n if output is not None:\n if output.group(1) == 'True':\n csv_data += \",\" + \"True\"\n x_locked = 1\n else:\n csv_data += \",\" + \"False\"\n else:\n csv_data += \",\" + \"False\"\n # Followers\n output = re.search('followers_count\\': (.*?), \\'friends_count', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",\" + output.group(1)\n x_followers = output.group(1)\n else:\n csv_data += \",0\"\n # Following\n output = re.search('friends_count\\': (.*?), \\'listed_count', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",\" + output.group(1)\n x_following = output.group(1)\n else:\n csv_data += \",0\"\n # Posts\n output = re.search('statuses_count\\': (.*?), \\'lang', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",\" + output.group(1)\n x_posts = output.group(1)\n else:\n csv_data += \",0\"\n # Likes\n output = re.search('favourites_count\\': (.*?), \\'utc_offset', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",\" + output.group(1)\n x_likes = output.group(1)\n else:\n csv_data += \",0\"\n # Latest\n if \"retweeted_status\" in acc_data: # If Retweet\n x_last_rt = 1\n output = re.search('text\\': \\'RT (.*?)\\', \\'truncated', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",True,\" + '\"' + output.group(1).replace('\"', \"'\") + '\"'\n else:\n csv_data += \",True,EMPTY\"\n else: # If Status\n output = re.search('text\\': \\'(.*?)\\', \\'truncated', acc_data, flags=re.IGNORECASE)\n if output is not None:\n csv_data += \",False,\" + '\"' + output.group(1).replace('\"', \"'\") + '\"'\n else:\n csv_data += \",False,EMPTY\"\n\n # Year,Accounts,Verified,Locked,NoPost,NoFollowers,NoFollowing,L5Posts,L100Posts,L5Following,L100Following,L5Followers,L100Followers,L50Likes,LastRT\\\n # Account | Date, Verified, Locked, NoPosts, NoFollowers, NoFollowing, NoLikes, LastRT\n return [csv_data, x_date, x_verified, x_locked, x_posts, x_followers, x_following, x_likes, x_last_rt]\n\n# Create Backup\nif(args.b):\n dateTimeObj = datetime.now()\n timestampStr = dateTimeObj.strftime(\"%d-%b-%Y-%H-%M-%S\")\n os.mkdir(\"backup/\" + timestampStr)\n\n shutil.copy2(\"./acc_list.txt\", \"./backup/\" + timestampStr + \"/\" + \"acc_list.txt\")\n shutil.copy2(\"./not_found.txt\", \"./backup/\" + timestampStr + \"/\" + \"not_found.txt\")\n shutil.copy2(\"./processed.txt\", \"./backup/\" + timestampStr + \"/\" + \"processed.txt\")\n shutil.copy2(\"./suspended.txt\", \"./backup/\" + timestampStr + \"/\" + \"suspended.txt\")\n shutil.copy2(\"./summary_data.csv\", \"./backup/\" + timestampStr + \"/\" + \"summary_data.csv\")\n shutil.copy2(\"./summary_data_per_year.csv\", \"./backup/\" + timestampStr + \"/\" + \"summary_data_per_year.csv\")\n shutil.copytree(\"./data\", \"./backup/\" + timestampStr + \"/\" + \"data\")\n\n print(\"Backup is created: ./backup/\" + timestampStr)\n exit()\n\nif(args.c):\n print(\"\\nAre you sure you want to delete all files and start from the beginning?\")\n answer = input(\"Enter yes or no: \")\n if answer == \"yes\":\n try:\n os.remove(\"./acc_list.txt\")\n except:\n pass\n try:\n os.remove(\"./suspended.txt\")\n except:\n pass\n try:\n os.remove(\"./processed.txt\")\n except:\n pass\n try:\n os.remove(\"./not_found.txt\")\n except:\n pass\n try:\n os.remove(\"./summary_data.csv\")\n except:\n pass\n try:\n os.remove(\"./summary_data_per_year.csv\")\n except:\n pass\n try:\n for i in os.listdir(\"./data\"):\n os.remove(\"./data/\" + i)\n os.rmdir(\"./data\")\n except Exception as e:\n print(str(e))\n pass\n print(\"All files are deleted. You will have fresh start :)\")\n exit()\n\n# Check files\nif not os.path.exists(\"./acc_list.txt\") or os.stat(\"./acc_list.txt\").st_size == 0:\n with open(\"./acc_list.txt\", mode='a'): pass\n print(\"\\n> Please enter Twitter account names into acc_list.txt file, separated by new line.\\n\")\n exit()\n\nif not os.path.exists(\"./suspended.txt\"):\n with open(\"./suspended.txt\", mode='a'): pass\n\nif not os.path.exists(\"processed.txt\"):\n with open(\"processed.txt\", mode='a'): pass\n\nif not os.path.exists(\"not_found.txt\"):\n with open(\"not_found.txt\", mode='a'): pass\n\nif not os.path.exists(\"./data\"):\n os.mkdir(\"./data\")\n\nif not os.path.exists(\"./backup\"):\n os.mkdir(\"./backup\")\n\nif not os.path.exists(\"summary_data.csv\"):\n with open(\"summary_data.csv\", \"a\") as myfile:\n myfile.write(\"Account,FullName,RegDate,Verified,Locked,Followers,Following,Posts,Likes,IsRT,LatestPost\\n\")\n myfile.close()\n\nif not os.path.exists(\"summary_data_per_year.csv\"):\n with open(\"summary_data_per_year.csv\", \"a\") as myfile:\n myfile.write(\"Year,Accounts,Verified,Locked,NoPost,NoFollowers,NoFollowing,L5Posts,L100Posts,L5Following,L100Following,L5Followers,L100Followers,L50Likes,LastRT\\n\")\n myfile.close()\n\nprint(\"\"\"\n> You are running getTwitterAccountDetailsTxt.py script.\n> This script will try to download Twitter account data, from the account list file: ./acc_list.txt. \n> And it will create summary in files: summary_data*.csv, which you can open with Office applications.\n\"\"\")\n\n# Load accounts list\ntxt_file = open(\"./acc_list.txt\", \"r\")\nscreen_name_list = txt_file.readlines()\n\nif (args.i):\n screen_name_list_p = []\nelse:\n txt_file_p = open(\"./processed.txt\", \"r\")\n screen_name_list_p = txt_file_p.readlines()\n\n# Authenticate to Twitter\nauth = tweepy.OAuthHandler(api_key, api_secrets)\nauth.set_access_token(access_token, access_secret)\napi = tweepy.API(auth)\n\ntry:\n api.verify_credentials()\n print('\\n> Successful Authentication to Twitter API.')\nexcept:\n print('\\n> Failed authentication to Twitter API. Check your settings.')\n exit()\n\nprint(\"\"\"\n================================================.\n .-. .-. .--. |\n | 00| | 00| / _.-' .-. .-. .-. .-. |\n | --| | --| \\ '-. '-' '-' '-' '-' |\n '^^^' '^^^' '--' |\n===============. .================. .-. |\n | | | '-' |\n\n> START WITH DATA COLLECTION:\n\"\"\")\n\ncsv_data = \"\"\ncvs_data_per_year = {}\nfor acc in screen_name_list:\n acc = acc.strip()\n\n if (None != acc and acc != \"\" and acc + \"\\n\" not in screen_name_list_p):\n try:\n user = api.get_user(screen_name=acc)\n # print(user._json)\n\n #TODO: Bug, Case\n with open(\"data/\"+acc+\".txt\", \"w\") as myfile:\n myfile.write(simplejson.dumps(user._json, indent=4, sort_keys=True))\n myfile.close()\n\n # TODO: Bug, Case\n if(args.r):\n with open(\"data/\" + acc + \"_raw.txt\", \"w\") as myfile:\n myfile.write(str(user._json))\n myfile.close()\n\n # Prepare CSV 1\n csv_data_temp = make_csv(acc, str(user._json))\n csv_data += csv_data_temp[0] + \"\\n\"\n\n # Prepare CSV 2\n if csv_data_temp[1] not in cvs_data_per_year:\n cvs_data_per_year.update({csv_data_temp[1]: {\"accounts\": 0, \"verified\": 0, \"locked\": 0, \"nopost\": 0,\n \"nofollowers\": 0, \"nofollowing\": 0, \"l5posts\": 0,\n \"l100posts\": 0, \"l5following\": 0, \"l100following\": 0,\n \"l5followers\": 0, \"l100followers\": 0, \"l50likes\": 0,\n \"lastrt\": 0}})\n\n # Year,Accounts,Verified,Locked,NoPost,NoFollowers,NoFollowing,L5Posts,L100Posts,L5Following,L100Following,L5Followers,L100Followers,L50Likes,LastRT\n # return [csv_data, x_date, x_verified, x_locked, x_posts, x_followers, x_following, x_likes, x_last_rt]\n x_date = csv_data_temp[1]\n x_verified = int(csv_data_temp[2])\n x_locked = int(csv_data_temp[3])\n x_posts = int(csv_data_temp[4])\n x_followers = int(csv_data_temp[5])\n x_following = int(csv_data_temp[6])\n x_likes = int(csv_data_temp[7])\n x_last_rt = int(csv_data_temp[8])\n\n cvs_data_per_year[x_date][\"accounts\"] += 1\n if x_verified == 1:\n cvs_data_per_year[x_date][\"verified\"] += 1\n if x_locked == 1:\n cvs_data_per_year[x_date][\"locked\"] += 1\n if x_posts == 0:\n cvs_data_per_year[x_date][\"nopost\"] += 1\n if x_posts < 5:\n cvs_data_per_year[x_date][\"l5posts\"] += 1\n if x_posts < 100:\n cvs_data_per_year[x_date][\"l100posts\"] += 1\n if x_followers == 0:\n cvs_data_per_year[x_date][\"nofollowers\"] += 1\n if x_followers < 5:\n cvs_data_per_year[x_date][\"l5followers\"] += 1\n if x_followers < 100:\n cvs_data_per_year[x_date][\"l100followers\"] += 1\n if x_following == 0:\n cvs_data_per_year[x_date][\"nofollowing\"] += 1\n if x_following < 5:\n cvs_data_per_year[x_date][\"l5following\"] += 1\n if x_following < 100:\n cvs_data_per_year[x_date][\"l100following\"] += 1\n if x_likes < 50:\n cvs_data_per_year[x_date][\"l50likes\"] += 1\n if x_last_rt == 1:\n cvs_data_per_year[x_date][\"lastrt\"] += 1\n\n with open(\"processed.txt\", \"a\") as myfile:\n myfile.write(str(acc) + \"\\n\")\n myfile.close()\n\n print(\"New record inserted: \", acc)\n except Exception as e:\n print(\"---\")\n print(acc, str(e))\n if (\"user not found\" in str(e).lower()):\n # If we detect not found / deleted account it will be recorded in this file\n # TODO: Remove duplicates.\n with open(\"not_found.txt\", \"a\") as myfile:\n myfile.write(acc + \"\\n\")\n pass\n elif (\"suspended\" in str(e).lower()):\n # If we detect suspended account it will be recorded in this file\n # TODO: Remove duplicates.\n with open(\"suspended.txt\", \"a\") as myfile:\n myfile.write(acc + \"\\n\")\n pass\n else:\n print(\"> Unhandled exception, please take screenshot (mask sensitive data), and contact the author: ivanm@security-net.biz.\")\n exception_type, exception_object, exception_traceback = sys.exc_info()\n filename = exception_traceback.tb_frame.f_code.co_filename\n line_number = exception_traceback.tb_lineno\n print(\"> Exception type: \", exception_type)\n print(\"> File name: \", filename)\n print(\"> Line number: \", line_number)\n print(\"---\")\n exit()\n print(\"---\")\n\n # This value is sleep time between each request, you can put smaller value but watch about API limitations\n time.sleep(float(args.s))\n else:\n print(\"Skip: \", acc)\n\n# Create summary_data.csv\n# TODO: Save on every 100\nwith open(\"summary_data.csv\", \"a\") as myfile:\n myfile.write(csv_data)\nmyfile.close()\n\n# Create summary_data_per_year.csv\n# print(simplejson.dumps(cvs_data_per_year, indent=4, sort_keys=True))\n# Year,Accounts,Verified,Locked,NoPost,NoFollowers,NoFollowing,L5Posts,L100Posts,L5Following,L100Following,L5Followers,L100Followers,L50Likes,LastRT\n# TODO: Save on every 100\nt_accounts = 0\nt_verified = 0\nt_locked = 0\nt_nopost = 0\nt_nofollowers = 0\nt_nofollowing = 0\nt_l5posts = 0\nt_l100posts = 0\nt_l5following = 0\nt_l100following = 0\nt_l5followers = 0\nt_l100followers = 0\nt_l50likes = 0\nt_lastrt = 0\nwith open(\"summary_data_per_year.csv\", \"a\") as myfile2:\n for x in sorted(cvs_data_per_year):\n # TODO: Automatic Loop Concat\n t_accounts += cvs_data_per_year[x][\"accounts\"]\n t_verified += cvs_data_per_year[x][\"verified\"]\n t_locked += cvs_data_per_year[x][\"locked\"]\n t_nopost += cvs_data_per_year[x][\"nopost\"]\n t_nofollowers += cvs_data_per_year[x][\"nofollowers\"]\n t_nofollowing += cvs_data_per_year[x][\"nofollowing\"]\n t_l5posts += cvs_data_per_year[x][\"l5posts\"]\n t_l100posts += cvs_data_per_year[x][\"l100posts\"]\n t_l5following += cvs_data_per_year[x][\"l5following\"]\n t_l100following += cvs_data_per_year[x][\"l100following\"]\n t_l5followers += cvs_data_per_year[x][\"l5followers\"]\n t_l100followers += cvs_data_per_year[x][\"l100followers\"]\n t_l50likes += cvs_data_per_year[x][\"l50likes\"]\n t_lastrt += cvs_data_per_year[x][\"lastrt\"]\n\n myfile2.write(str(x)+\",\"+str(cvs_data_per_year[x][\"accounts\"])+\",\"+str(cvs_data_per_year[x][\"verified\"])+\",\"+str(\n cvs_data_per_year[x][\"locked\"])+\",\"+str(cvs_data_per_year[x][\"nopost\"])+\",\"+str(\n cvs_data_per_year[x][\"nofollowers\"])+\",\"+str(cvs_data_per_year[x][\"nofollowing\"])+\",\"+str(\n cvs_data_per_year[x][\"l5posts\"])+\",\"+str(cvs_data_per_year[x][\"l100posts\"])+\",\"+str(\n cvs_data_per_year[x][\"l5following\"])+\",\"+str(cvs_data_per_year[x][\"l100following\"])+\",\"+str(\n cvs_data_per_year[x][\"l5followers\"])+\",\"+str(cvs_data_per_year[x][\"l100followers\"])+\",\"+str(\n cvs_data_per_year[x][\"l50likes\"])+\",\"+str(cvs_data_per_year[x][\"lastrt\"])+\"\\n\")\n\n myfile2.write(\"Total,\" + str(t_accounts) + \",\" + str(t_verified) + \",\" + str(t_locked) + \",\" + str(t_nopost) + \",\" + str(t_nofollowers) + \",\" + str(t_nofollowing) + \",\" + str(t_l5posts) + \",\" + str(t_l100posts) + \",\" + str(t_l5following) + \",\" + str(t_l100following) + \",\" + str(t_l5followers) + \",\" + str(t_l100followers) + \",\" + str(t_l50likes) + \",\" + str(t_lastrt) + \"\\n\")\nmyfile2.close()\n\n\nprint(\"\\nThat's all folks!\")\n\nprint(\"\"\"\n> In file ./suspended.txt you can find suspended accounts.\n> In file ./not_found.txt you can find deleted accounts.\n> You can open ./summary_data*.csv file with Office applications. \n> All other accounts data is in ./data/ folder as JSON.\n\"\"\")\n\n","repo_name":"Ivan-Markovic/TwitterFun","sub_path":"getTwitterAccountDetailsTxt.py","file_name":"getTwitterAccountDetailsTxt.py","file_ext":"py","file_size_in_byte":17094,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"9670578280","text":"import requests\nimport threading\nimport queue\n\nq = queue.Queue()\n\nwith open(\"/root/lair-v2/p.txt\", \"r\") as f:\n proxies = f.read().split(\"\\n\")\n for p in proxies:\n q.put(p)\n\n\ndef check():\n global q\n while not q.empty():\n proxy = q.get()\n try:\n res = requests.get(\"http://ipinfo.io/json\", proxies={\"http\": proxy, \"https\": proxy})\n\n except:\n continue\n\n if res.status_code == 200:\n with open(\"/root/lair-v2/proxies.txt\", \"a\") as f:\n f.write(proxy + \"\\n\")\n\n\nfor _ in range(10):\n threading.Thread(target=check).start()","repo_name":"hifthot/skidcity","sub_path":"lair/utilities/proxycheck.py","file_name":"proxycheck.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"12560926615","text":"'''\r\nAUTHOR: DIONISIO RIBEIRO\r\n13/04/2019\r\nRISK ANALYSIS WITH COLORMAP\r\n'''\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport funcoes as f\r\n\r\npaced = 0.01\r\npacep = 0.01\r\nvd = list(np.arange(0,1.01,paced)) #vetor dinheiro\r\nvp = list(np.arange(0,1.01,pacep)) #vetor pessoa\r\nvet = []\r\nvr = [] #vetor risco\r\n'''\r\n#inicializacao dos vetores\r\nfor d in vd:\r\n for p in vp:\r\n vet.append((d,p))\r\n vr.append(vet)\r\n vet = []\r\n''' \r\nfor d in vd:\r\n for p in vp:\r\n area = 0\r\n alt = 0 \r\n for k in np.arange(0,1.01,0.01):\r\n area += k*100*f.altura(k,d,p)\r\n alt +=f.altura(k,d,p)\r\n vet.append(area/alt)\r\n vr.append(vet)\r\n vet = [] \r\n#plt.imshow(vr)\r\nplt.matshow(vr,cmap='jet')\r\nplt.xlabel('PESSOAS')\r\nplt.ylabel('DINHEIRO')\r\n#plt.title('HEAT_MAP_FUZZY') \r\nplt.colorbar(label='RISCO')\r\nplt.show()\r\n","repo_name":"DioRao89/FUZZY","sub_path":"defuzzyficacao_heat_map.py","file_name":"defuzzyficacao_heat_map.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19654709645","text":"import time\nfrom tempfile import TemporaryDirectory\nfrom secrets import token_urlsafe\nimport os\nimport threading\nfrom queue import Queue\n\n\nCONTENT_SIZE = 1\nHUNDRED_THOUSAND = 10 ** 5\n\n\ndef write_file(path):\n p = os.path.join(path, f\"{token_urlsafe(64)}.txt\")\n c = token_urlsafe(CONTENT_SIZE)\n with open(p, \"w+\") as f:\n time.sleep(1)\n f.write(c)\n print(p)\n\n\ndef do_job(jobs):\n while not jobs.empty():\n job = jobs.get()\n write_file(job)\n jobs.task_done()\n\n\ndef write_threaded(size):\n p = \"/tmp/thr\"\n os.makedirs(p, exist_ok=True)\n jobs = Queue()\n\n for i in range(size):\n jobs.put(p)\n\n for i in range(1000):\n worker = threading.Thread(target=do_job, args=(jobs,))\n worker.start()\n return jobs\n\n\nif __name__ == \"__main__\":\n start = time.time()\n n = HUNDRED_THOUSAND // 100\n write_threaded(n).join()\n end = time.time()\n print(f\"Threaded: {n} files in {end - start:.2f} seconds\")\n","repo_name":"almazkun/asyncio_way","sub_path":"thr.py","file_name":"thr.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39505997643","text":"class GenderExtractor:\n\tdef _extract_gender(self, name):\n\t\ttry:\n\t\t\tif \" \" in name:\n\t\t\t\tnameis = str(name).strip().replace(\" \",\"/\")\n\t\t\telse:\n\t\t\t\tnameis = str(name) + \"/a\"\n\t\t\turl = \"http://api.namsor.com/onomastics/api/json/gendre/\" + nameis\n\t\t\tresponse = requests.post(url)\n\t\t\tgender = response.json()[\"gender\"]\n\t\texcept Exception as e:\n\t\t\tgender = \"Unknown\"\n\t\treturn gender","repo_name":"shivam5992/headline-feats","sub_path":"GenderExtractor.py","file_name":"GenderExtractor.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8717425016","text":"from django.shortcuts import render\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom .forms import SignupForm\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.template.loader import render_to_string\nfrom django.contrib.auth.decorators import login_required\nfrom .tokens import account_activation_token\nfrom django.utils.translation import ugettext_lazy as gettext\nfrom django.core.mail import send_mail\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse, JsonResponse, HttpResponseRedirect\nfrom taggit.models import Tag\nfrom .models import Conspect\nfrom .forms import ConspectForm\n\n\nHOST_EMAIL = 'Riwerz2@yandex.ru'\n\n\ndef load_conspect(request):\n return render(request, 'conspect/conspect_create.html')\n\n\ndef load_mainpage(request):\n return render(request, 'mainpage.html', {\n 'conspects_latest': Conspect.objects.all().order_by('-published_date')[:10],\n 'conspects_best': Conspect.objects.all().filter(ratings__isnull=False).order_by('-ratings__average')[:10],\n 'tags_all': Tag.objects.all()\n })\n\n\ndef conspect_browse(request):\n return render(request, 'conspect/conspect_browse.html', {'conspect': Conspect.objects.get(pk=request.GET['pk'])})\n\n\n@login_required(login_url='/login')\ndef load_profile(request):\n return render(request, 'profile.html', {'conspects': Conspect.objects.filter(author=request.user)})\n\n\ndef load_login(request):\n if request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return load_mainpage(request)\n else:\n form = AuthenticationForm()\n return render(request, 'login/login.html', {'form': form})\n\n\ndef load_signup(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.first_name = request.POST['name']\n user.last_name = request.POST['surname']\n user.is_active = False\n user.save()\n current_site = get_current_site(request)\n mail_subject = 'Activate your blog account.'\n message = render_to_string('login/acc_active_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),\n 'token': account_activation_token.make_token(user),\n })\n to_email = form.cleaned_data.get('email')\n send_mail(mail_subject, message, HOST_EMAIL, [to_email], fail_silently=False)\n return render(request, 'login/email_confirm.html')\n else:\n form = SignupForm()\n return render(request, 'login/signup.html', {'form': form})\n\n\ndef publish_conspect(request):\n if request.method == 'POST':\n form = ConspectForm(request.POST)\n if form.is_valid():\n conspect = form.save(commit=False)\n conspect.author = request.user\n conspect.publish()\n conspect.save()\n form.save_m2m()\n return HttpResponseRedirect('/' + request.LANGUAGE_CODE + '/profile')\n else:\n form = ConspectForm()\n return render(request, 'conspect/conspect_create.html', {'form': form})\n\n\ndef conspect_entries(request):\n return render(request, 'conspect/conspect_table.html', {'conspects': Conspect.objects.filter(author=request.user)})\n\n\ndef conspect_delete(request):\n id = request.POST['id']\n Conspect.objects.filter(pk=id).delete()\n return JsonResponse({'id': id})\n\n\ndef conspect_edit(request, id):\n post = Conspect.objects.get(pk=id)\n if request.method == 'POST':\n form = ConspectForm(request.POST, instance=post)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/' + request.LANGUAGE_CODE + '/profile')\n else:\n form = ConspectForm(instance=post)\n return render(request, 'conspect/conspect_create.html', {'form': form})\n\n\ndef activate(request, uidb64, token):\n try:\n uid = urlsafe_base64_decode(uidb64)\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user, backend='django.contrib.auth.backends.ModelBackend')\n message = gettext('Адрес электронной почти подтверждён')\n else:\n message = gettext('Недействительная ссылка')\n return HttpResponse(message)\n\n\ndef log_out(request):\n logout(request)\n return load_mainpage(request)\n\n\ndef load_conspects_by_tag(request, tag):\n conspects = Conspect.objects.filter(tags__name=tag)\n return render(request, 'tag_search.html', {'conspects': conspects, 'tag': tag})\n","repo_name":"Riwerz/course","sub_path":"rootApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25130430432","text":"# -*- coding: utf-8 -*-\n# @Department: 测试\n# @Author: 杨凤娇\n# @Description: 医院 =》活动管理\nfrom test.common.page import Page\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nfrom time import sleep\n\n\nclass ActionManage(Page):\n # 定位元素\n menu1 = (By.XPATH, '//*[@id=\"menuGov\"]/li[9]/a') # 院内活动管理\n menu2 = (By.XPATH, '//*[@id=\"menu4\"]/ul/li[1]/a') # 活动管理\n btnAdd = (By.ID, 'btnAdd') # 添加\n txtProName = (By.ID, 'txtProjName') # 院内活动名称\n txtProNo = (By.ID, 'txtProjNo') # 院内活动编号\n ddlKnowledgeType = (By.ID, 'ddlknowledgeType') # 所在学科\n ddlParentCourse = (By.ID, 'ddlParentCourse')\n ddlChildCourse = (By.ID, 'ddlChildCourse')\n ddlHoldType = (By.ID, 'ddlHoldType') # 举办方式\n txtStartDate = (By.ID, 'txtStartDate') # 举办时间\n txtEndDate = (By.ID, 'txtEndDate')\n ddlCheckType = (By.ID, 'ddlCheckType') # 考核方式\n txtPeriod = (By.ID, 'txtPeriod') # 学时\n txtScores = (By.ID, 'txtScores') # 拟授学分\n txtRemark = (By.ID, 'txtRemark') # 备注\n btnCourse = (By.XPATH, '//*[@id=\"form1\"]/div[3]/table/tbody/tr[9]/td/span[1]/a') # 添加教师和课程\n teacher1 = (By.XPATH, '//*[@id=\"subjectList\"]/table[1]/tbody/tr[1]/td[3]/input[2]') # 教师姓名1\n title1 = (By.XPATH, '//*[@id=\"subjectList\"]/table[1]/tbody/tr[1]/td[5]/input') # 讲授题目1\n date1 = (By.XPATH, '//*[@id=\"subjectList\"]/table[1]/tbody/tr[2]/td[2]/input') # 学时1\n type1 = (By.XPATH, '//*[@id=\"subjectList\"]/table[1]/tbody/tr[2]/td[4]/select') # 教学方法1\n teacher2 = (By.XPATH, '//*[@id=\"subjectList\"]/table[2]/tbody/tr[1]/td[3]/input[2]') # 教师姓名2\n title2 = (By.XPATH, '//*[@id=\"subjectList\"]/table[2]/tbody/tr[1]/td[5]/input') # 讲授题目2\n date2 = (By.XPATH, '//*[@id=\"subjectList\"]/table[2]/tbody/tr[2]/td[2]/input') # 学时2\n type2 = (By.XPATH, '//*[@id=\"subjectList\"]/table[2]/tbody/tr[2]/td[4]/select') # 教学方法2\n delete = (By.XPATH, '//*[@id=\"subjectList\"]/table[1]/tbody/tr[1]/td[1]') # 删除\n next = (By.ID, 'next') # 提交\n ddlYear = (By.ID, 'ddlYear') # 年度\n select1 = (By.ID, 'KnowledgeSelect_ddlknowledge1') # 所属学科\n select2 = (By.ID, 'KnowledgeSelect_ddlknowledge2')\n select3 = (By.ID, 'KnowledgeSelect_ddlknowledge3')\n btnSearch = (By.ID, 'btnSearch') # 查询\n listSelect = (By.ID, 'listSelect') # 选择\n\n def menu1_loc(self):\n self.find_element(*self.menu1).click()\n\n def menu2_loc(self):\n self.find_element(*self.menu2).click()\n\n def btnAdd_loc(self):\n self.find_element(*self.btnAdd).click()\n\n def txtProName_loc(self, txtProName):\n self.find_element(*self.txtProName).clear()\n self.find_element(*self.txtProName).send_keys(txtProName)\n\n def txtProNo_loc(self, txtProNo):\n self.find_element(*self.txtProNo).clear()\n self.find_element(*self.txtProNo).send_keys(txtProNo)\n\n def ddlKnowledgeType_loc(self, ddlKnowledgeType):\n Select(self.find_element(*self.ddlKnowledgeType)).select_by_visible_text(ddlKnowledgeType)\n\n def ddlParentCourse_loc(self, ddlParentCourse):\n Select(self.find_element(*self.ddlParentCourse)).select_by_visible_text(ddlParentCourse)\n\n def ddlChildCourse_loc(self, ddlChildCourse):\n Select(self.find_element(*self.ddlChildCourse)).select_by_visible_text(ddlChildCourse)\n\n def ddlHoldType_loc(self, ddlHoldType):\n Select(self.find_element(*self.ddlHoldType)).select_by_visible_text(ddlHoldType)\n\n def txtStartDate_loc(self, txtStartDate):\n self.find_element(*self.txtStartDate).clear()\n self.find_element(*self.txtStartDate).send_keys(txtStartDate)\n\n def txtEndDate_loc(self, txtEndDate):\n self.find_element(*self.txtEndDate).clear()\n self.find_element(*self.txtEndDate).send_keys(txtEndDate)\n\n def ddlCheckType_loc(self, ddlCheckType):\n Select(self.find_element(*self.ddlCheckType)).select_by_visible_text(ddlCheckType)\n\n def txtPeriod_loc(self, txtPeriod):\n self.find_element(*self.txtPeriod).clear()\n self.find_element(*self.txtPeriod).send_keys(txtPeriod)\n\n def txtScores_loc(self, txtScores):\n self.find_element(*self.txtScores).clear()\n self.find_element(*self.txtScores).send_keys(txtScores)\n\n def txtRemark_loc(self, txtRemark):\n self.find_element(*self.txtRemark).clear()\n self.find_element(*self.txtRemark).send_keys(txtRemark)\n\n def btnCourse_loc(self):\n self.find_element(*self.btnCourse).click()\n\n def teacher1_loc(self, teacher1):\n self.find_element(*self.teacher1).clear()\n self.find_element(*self.teacher1).send_keys(teacher1)\n\n def title1_loc(self, title1):\n self.find_element(*self.title1).clear()\n self.find_element(*self.title1).send_keys(title1)\n\n def date1_loc(self, date1):\n self.find_element(*self.date1).clear()\n self.find_element(*self.date1).send_keys(date1)\n\n def type1_loc(self, type1):\n Select(self.find_element(*self.type1)).select_by_visible_text(type1)\n\n def teacher2_loc(self, teacher2):\n self.find_element(*self.teacher2).clear()\n self.find_element(*self.teacher2).send_keys(teacher2)\n\n def title2_loc(self, title2):\n self.find_element(*self.title2).clear()\n self.find_element(*self.title2).send_keys(title2)\n\n def date2_loc(self, date2):\n self.find_element(*self.date2).clear()\n self.find_element(*self.date2).send_keys(date2)\n\n def type2_loc(self, type2):\n Select(self.find_element(*self.type2)).select_by_visible_text(type2)\n\n def delete_loc(self):\n self.find_element(*self.delete).click()\n\n def next_loc(self):\n self.find_element(*self.next).click()\n\n def ddlYear_loc(self, ddlYear):\n Select(self.find_element(*self.ddlYear)).select_by_visible_text(ddlYear)\n\n def select1_loc(self, select1):\n Select(self.find_element(*self.select1)).select_by_visible_text(select1)\n\n def select2_loc(self, select2):\n Select(self.find_element(*self.select2)).select_by_visible_text(select2)\n\n def select3_loc(self, select3):\n Select(self.find_element(*self.select3)).select_by_visible_text(select3)\n\n def btnSearch_loc(self):\n self.find_element(*self.btnSearch).click()\n\n # 添加活动\n def action_add(self, txtProName, txtProNo, ddlKnowledgeType, ddlParentCourse, ddlChildCourse, ddlHoldType, txtStartDate\n , txtEndDate, ddlCheckType, txtPeriod, txtScores, txtRemark, teacher1, title1, date1, type1, teacher2\n , title2, date2, type2):\n self.menu1_loc() # 院内活动管理\n sleep(1)\n self.menu2_loc() # 活动管理\n self.frame(\"centerIframeUnitManageAction\")\n sleep(1)\n self.btnAdd_loc() # 添加\n self.back()\n sleep(1)\n self.txtProName_loc(txtProName) # 院内活动名称\n self.txtProNo_loc(txtProNo) # 院内活动编号\n self.ddlKnowledgeType_loc(ddlKnowledgeType) # 所在学科\n sleep(1)\n self.ddlParentCourse_loc(ddlParentCourse)\n sleep(1)\n self.ddlChildCourse_loc(ddlChildCourse)\n self.ddlHoldType_loc(ddlHoldType) # 举办方式\n self.txtStartDate_loc(txtStartDate) # 举办日期\n self.txtEndDate_loc(txtEndDate)\n self.ddlCheckType_loc(ddlCheckType) # 考核方式\n self.txtPeriod_loc(txtPeriod) # 学时\n self.txtScores_loc(txtScores) # 拟授学分\n self.txtRemark_loc(txtRemark) # 拟备注\n self.btnCourse_loc() # 添加教师和课程\n sleep(1)\n self.teacher1_loc(teacher1) # 教师姓名1\n self.title1_loc(title1) # 讲授题目1\n self.date1_loc(date1) # 学时1\n self.type1_loc(type1) # 教学方法1\n self.teacher2_loc(teacher2) # 教师姓名2\n self.title2_loc(title2) # 讲授题目2\n self.date2_loc(date2) # 学时2\n self.type2_loc(type2) # 教学方法2\n self.delete_loc() # 删除教师1\n sleep(1)\n self.next_loc() # 提交按钮\n sleep(1)\n self.accept()\n sleep(1)\n self.driver.switch_to.default_content()\n self.frame(\"centerIframeUnitManageAction\")\n sleep(1)\n\n # 活动验证\n def verify_action(self, txtProName, txtProNo, ddlYear, select1, select2, select3, txtStartDate, txtEndDate):\n self.txtProName_loc(txtProName) # 院内活动名称\n self.txtProNo_loc(txtProNo) # 院内活动编号\n if ddlYear != \"\":\n self.ddlYear_loc(ddlYear) # 年度\n if select1 != \"\":\n self.select1_loc(select1) # 所属学科\n sleep(1)\n if select2 != \"\":\n self.select2_loc(select2)\n sleep(1)\n if select3 != \"\":\n self.select3_loc(select3)\n if txtStartDate != \"\":\n self.txtStartDate_loc(txtStartDate) # 举办日期\n if txtEndDate != \"\":\n self.txtEndDate_loc(txtEndDate)\n self.btnSearch_loc() # 查询\n sleep(1)\n if self.vb_find(*self.listSelect) > 0:\n return True\n else:\n return False\n","repo_name":"test-yfj/UItest","sub_path":"test/pages/action_manage.py","file_name":"action_manage.py","file_ext":"py","file_size_in_byte":9261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24490775329","text":"from flask import Blueprint, current_app as app, redirect, flash, url_for, render_template\nfrom flask_discord import requires_authorization\n\nimport banappeals.blueprints.discord as discord\nfrom banappeals import database as db\nfrom banappeals.blueprints.auth import staff_only\n\n\nbp = Blueprint(\"views\", __name__)\n\n\n@bp.route(\"/\")\ndef index():\n user = banned = None\n if app.discord.authorized:\n user = app.discord.fetch_user()\n banned = discord.get_ban(user_id=user.id)\n return render_template(template_name_or_list=\"index.htm\", user=user, banned=banned)\n\n\n@bp.route(\"/review\", defaults={\"id\": None})\n@bp.route(\"/review/\")\n@requires_authorization\n@staff_only\ndef review(id):\n if not id:\n return redirect(url_for(\"views.overview\"))\n\n appeal = db.get_appeal(id=id)\n return render_template(\n template_name_or_list=\"review.htm\",\n stats=db.get_stats(),\n reviewer=app.discord.fetch_user(),\n appellant=discord.get_user(appeal[\"discord_id\"]),\n appeal=appeal,\n )\n\n\n@bp.route(\"/status\")\n@requires_authorization\ndef status():\n user = app.discord.fetch_user()\n\n id = db.get_appeal(discord_id=user.id)\n if not id:\n flash(\"You have not submitted an appeal.\", \"danger\")\n return redirect(url_for(\"views.index\"))\n\n return render_template(template_name_or_list=\"status.htm\", appeal=db.get_application(id))\n\n\n@bp.route(\"/overview\")\n@requires_authorization\n@staff_only\ndef overview():\n return render_template(\n template_name_or_list=\"overview.htm\",\n stats=db.get_stats(),\n reviewer=app.discord.fetch_user(),\n appeals=db.get_appeals(),\n )\n","repo_name":"Snaacky/banappeals","sub_path":"banappeals/blueprints/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30324166939","text":"'''\n 프로그래머스: 이진 변환 반복하기\n \n'''\n\ndef solution(s):\n cnt = 0\n cnt_zero = 0\n \n while s != '1':\n cnt_zero += s.count('0') # 0의 수를 카운트 \n s = s.replace('0', '') # '0'을 지운다\n s = bin(len(s))[2:] # bin 함수는 십진수를 이진수로 나타낸다\n cnt += 1 # [2:]를 한 이유는 bin함수는 앞에 0b를 앞에 붙이기 때문에 제거하기 위해서이다\n \n answer = [cnt, cnt_zero]\n return answer\n\ns = \"110010101001\"\nprint(solution(s))","repo_name":"kimkihyun1/TIL","sub_path":"CodingTest/2305/230511.py","file_name":"230511.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9678885000","text":"import discord, json, humanfriendly, asyncio, datetime, random \nfrom discord.ext import commands, tasks \nfrom tools.checks import Perms\n\nasync def gwend_task(bot: commands.AutoShardedBot, result, date: datetime.datetime): \n members = json.loads(result['members'])\n winners = result['winners']\n channel_id = result['channel_id']\n message_id = result['message_id']\n channel = bot.get_channel(channel_id)\n if channel: \n message = await channel.fetch_message(message_id)\n if message: \n wins = []\n if len(members) <= winners: \n embed = discord.Embed(color=bot.color, title=message.embeds[0].title, description=f\"Hosted by: <@!{result['host']}>\\n\\nNot enough entries to determine the winners!\")\n await message.edit(embed=embed, view=None)\n else: \n for _ in range(winners): wins.append(random.choice(members))\n embed = discord.Embed(color=bot.color, title=message.embeds[0].title, description=f\"Ended \\nHosted by: <@!{result['host']}>\").add_field(name=\"winners\", value='\\n'.join([f\"**{bot.get_user(w)}** ({w})\" for w in wins]))\n await message.edit(embed=embed, view=None)\n await message.reply(f\"**{result['title']}** winners:\\n\" + '\\n'.join([f\"<@{w}> ({w})\" for w in wins])) \n await bot.db.execute(\"INSERT INTO gw_ended VALUES ($1,$2,$3)\", channel_id, message_id, json.dumps(members))\n await bot.db.execute(\"DELETE FROM giveaway WHERE channel_id = $1 AND message_id = $2\", channel_id, message_id)\n\n@tasks.loop(seconds=5)\nasync def gw_loop(bot: commands.AutoShardedBot):\n results = await bot.db.fetch(\"SELECT * FROM giveaway\")\n date = datetime.datetime.now()\n for result in results: \n if date.timestamp() > result['finish'].timestamp(): await gwend_task(bot, result, date)\n\nclass GiveawayView(discord.ui.View): \n def __init__(self): \n super().__init__(timeout=None) \n\n @discord.ui.button(emoji=\"🎉\", style=discord.ButtonStyle.green, custom_id=\"persistent:join_gw\")\n async def join_gw(self, interaction: discord.Interaction, button: discord.ui.Button):\n check = await interaction.client.db.fetchrow(\"SELECT * FROM giveaway WHERE guild_id = $1 AND message_id = $2\", interaction.guild.id, interaction.message.id)\n lis = json.loads(check['members'])\n if interaction.user.id in lis: \n button1 = discord.ui.Button(label=\"Leave the Giveaway\", style=discord.ButtonStyle.danger)\n\n async def button1_callback(inter: discord.Interaction): \n lis.remove(interaction.user.id)\n await interaction.client.db.execute(\"UPDATE giveaway SET members = $1 WHERE guild_id = $2 AND message_id = $3\", json.dumps(lis), inter.guild.id, interaction.message.id) \n interaction.message.embeds[0].set_field_at(0, name=\"entries\", value=f\"{len(lis)}\")\n await interaction.message.edit(embed=interaction.message.embeds[0])\n return await inter.response.edit_message(content=\"You left the giveaway\", view=None)\n button1.callback = button1_callback\n vi = discord.ui.View()\n vi.add_item(button1)\n return await interaction.response.send_message(content=\"You are already in this giveaway\", view=vi, ephemeral=True)\n else: \n lis.append(interaction.user.id)\n await interaction.client.db.execute(\"UPDATE giveaway SET members = $1 WHERE guild_id = $2 AND message_id = $3\", json.dumps(lis), interaction.guild.id, interaction.message.id) \n interaction.message.embeds[0].set_field_at(0, name=\"entries\", value=f\"{len(lis)}\")\n return await interaction.response.edit_message(embed=interaction.message.embeds[0])\n \nclass Giveaway(commands.Cog): \n def __init__(self, bot: commands.AutoShardedBot): \n self.bot = bot \n \n @commands.Cog.listener()\n async def on_connect(self): \n gw_loop.start(self.bot)\n\n @commands.command(name=\"gcreate\", brief=\"manage server\", description=\"create a giveaway in this server\", help=\"config\", usage=\"\")\n @Perms.get_perms(\"manage_guild\")\n async def gcreate(self, ctx: commands.Context, *, channel: discord.TextChannel=None): \n return await ctx.invoke(self.bot.get_command('giveaway create'), channel=channel or ctx.channel) \n \n @commands.command(description=\"returns a list of active giveaways in the server\", help=\"config\")\n async def glist(self, ctx: commands.Context): \n return await ctx.invoke(self.bot.get_command('giveaway list')) \n \n @commands.command(brief=\"manage_server\", description=\"end a giveaway\", help=\"config\", usage=\"[message id] \")\n @Perms.get_perms(\"manage_guild\") \n async def gend(self, ctx: commands.Context, message_id: int, *, channel: discord.TextChannel=None): \n await ctx.invoke(self.bot.get_command('giveaway end'), message_id=message_id, channel=channel or ctx.channel) \n \n @commands.command(help=\"config\", description=\"reroll a giveaway\", brief=\"manage server\", usage=\"[message id] \")\n @Perms.get_perms(\"manage_guild\") \n async def greroll(self, ctx: commands.Context, message_id: int, *, channel: discord.TextChannel=None): \n await ctx.invoke(self.bot.get_command('giveaway reroll'), message_id=message_id, channel=channel or ctx.channel) \n\n @commands.group(invoke_without_command=True, aliases=['gw'])\n async def giveaway(self, ctx): \n return await ctx.create_pages()\n \n @giveaway.command(name=\"end\", brief=\"manage_server\", description=\"end a giveaway\", help=\"config\", usage=\"[message id] \")\n @Perms.get_perms(\"manage_guild\")\n async def gw_end(self, ctx: commands.Context, message_id: int, *, channel: discord.TextChannel=None): \n if not channel: channel = ctx.channel\n check = await self.bot.db.fetchrow(\"SELECT * FROM giveaway WHERE guild_id = $1 AND channel_id = $2 AND message_id = $3\", ctx.guild.id, channel.id, message_id) \n if not check: return await ctx.send_warning(\"This message is not a giveaway or it ended if it was one\")\n await gwend_task(self.bot, check, datetime.datetime.now())\n return await ctx.send_success(f\"Ended giveaway in {channel.mention}\")\n\n @giveaway.command(name=\"reroll\", help=\"config\", description=\"reroll a giveaway\", brief=\"manage server\", usage=\"[message id] \")\n @Perms.get_perms(\"manage_guild\")\n async def gw_reroll(self, ctx: commands.Context, message_id: int, *, channel: discord.TextChannel=None): \n if not channel: channel = ctx.channel\n check = await self.bot.db.fetchrow(\"SELECT * FROM gw_ended WHERE channel_id = $1 AND message_id = $2\", channel.id, message_id) \n if not check: return await ctx.send_warning(f\"This message is not a giveaway or it didn't end if it is one. Use `{ctx.clean_prefix}gend` to end the giveaway\")\n members = json.loads(check['members'])\n await ctx.reply(f\"**New winner:** <@!{random.choice(members)}>\")\n\n @giveaway.command(name=\"list\", description=\"returns a list of active giveaways in the server\", help=\"config\")\n async def gw_list(self, ctx: commands.Context): \n i=0\n k=1\n l=0\n mes = \"\"\n number = []\n messages = []\n results = await self.bot.db.fetch(\"SELECT * FROM giveaway WHERE guild_id = $1\", ctx.guild.id)\n if len(results) == 0: return await ctx.send_error(\"There are no giveaways\")\n for result in results:\n mes = f\"{mes}`{k}` [**{result['title']}**](https://discord.com/channels/{ctx.guild.id}/{result['channel_id']}/{result['message_id']}) ends \\n\"\n k+=1\n l+=1\n if l == 10:\n messages.append(mes)\n number.append(discord.Embed(color=self.bot.color, title=f\"giveaways ({len(results)})\", description=messages[i]))\n i+=1\n mes = \"\"\n l=0\n \n messages.append(mes)\n number.append(discord.Embed(color=self.bot.color, title=f\"giveaways ({len(results)})\", description=messages[i]))\n await ctx.paginator(number) \n\n @giveaway.command(name=\"create\", brief=\"manage server\", description=\"create a giveaway in this server\", help=\"config\", usage=\"\")\n @Perms.get_perms(\"manage_guild\")\n async def gw_create(self, ctx: commands.Context, *, channel: discord.TextChannel=None):\n if not channel: channel = ctx.channel \n await ctx.reply(f\"Starting giveaway in {channel.mention}...\")\n responses = [] \n for me in [\"What is the prize for this giveaway?\", \"How long should the Giveaway last?\", \"How many winners should this Giveaway have?\"]:\n await ctx.send(me)\n try: \n def is_author(m): return m.author.id == ctx.author.id and m.channel.id == ctx.channel.id \n message = await self.bot.wait_for('message', check=is_author, timeout=10.0)\n responses.append(message.content)\n await message.add_reaction(\"<:catthumbsup:974982144021626890>\")\n except asyncio.TimeoutError: return await ctx.send(content=\"You didn't reply in time\") \n description = responses[0]\n try: seconds = humanfriendly.parse_timespan(responses[1])\n except humanfriendly.InvalidTimespan: return await ctx.send(content=\"Invalid time parsed\")\n try: winners = int(responses[2])\n except ValueError: return await ctx.send(content=\"Invalid number of winners\") \n embed = discord.Embed(color=self.bot.color, title=description, description=f\"Ends: ()\\nHosted by: {ctx.author.mention}\\nWinners: **{winners}**\")\n embed.add_field(name=\"Entries\", value=\"0\")\n view=GiveawayView()\n await ctx.send(content=f\"Giveaway setup completed! Check {channel.mention}\")\n mes = await channel.send(embed=embed, view=view)\n await self.bot.db.execute(\"INSERT INTO giveaway VALUES ($1,$2,$3,$4,$5,$6,$7,$8)\", ctx.guild.id, channel.id, mes.id, winners, json.dumps([]), (datetime.datetime.now() + datetime.timedelta(seconds=seconds)), ctx.author.id, description)\n\nasync def setup(bot: commands.AutoShardedBot) -> None:\n await bot.add_cog(Giveaway(bot)) ","repo_name":"hifthot/skidcity","sub_path":"pretend/cogs/giveaway.py","file_name":"giveaway.py","file_ext":"py","file_size_in_byte":9822,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"30965201915","text":"from sklearn.decomposition import FactorAnalysis\nfrom sklearn.decomposition import FastICA\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import NMF\nfrom sklearn.manifold import Isomap\nfrom sklearn.manifold import MDS\nfrom sklearn.manifold import LocallyLinearEmbedding\nfrom sklearn.manifold import SpectralEmbedding\nfrom sklearn.manifold import TSNE\nfrom umap import UMAP\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom ._pca import PCAReducer\nimport numpy as np\nimport pandas as pd\n\ntry:\n from ._autoenconder import Autoencoder\n\n AUTOENCONDER_AVAILABLE = True\nexcept (ModuleNotFoundError, ImportError):\n AUTOENCONDER_AVAILABLE = False\n import warnings\n\n warnings.warn(\n \"Warning: optional dependency keras is not available. Autoencoder its not available\"\n )\n\n\nclass DimensionalityReducer:\n def __init__(self, reducer, **kwargs):\n \"\"\"\n Constructor\n\n Parameters\n ----------\n selector : str\n name of algorithm to be applied\n **kwargs :\n optional and positional arguments of the choosen algorithm (selector)\n Returns\n -------\n FeatureSelector\n Examples\n ---------\n variance thresholding: f = FeatureSelector('variance', threshold=0.3) #Instantiating\n f.fit(X[,y]) #fitting (y is optional for variance thresholding)\n X = f.transform(X) #transforming\n\n filter-based, k best (MAD): f = FeatureSelector('univariate_kbest', score_func=FeatureSelector.mean_abs_diff, k=2) #Instantiating\n #score_func can be any function f: R^n -> R^n (n = number of columns)\n f.fit(X,y) #fitting\n X = f.transform(X) #transforming\n\n wrapper, recursive: f = FeatureSelector('recursive', estimator = LinearSVC(), n_features_to_select=2) #Instantiating\n #estimator should be an instance of a classification or regression model class from scikit-learn\n #one can use a custom class but it must be compatible with scikit-learn arquitecture\n f.fit(X,y) #fitting\n X = f.transform(X) #transforming\n\n wrapper, sequential: f = FeatureSelector('sequential', estimator = LinearSVC(), direction='forward') #Instantiating\n #estimator should be an instance of a classification or regression model class from scikit-learn\n #one can use a custom class but it must be compatible with scikit-learn arquitecture\n f.fit(X,y) #fitting\n X = f.transform(X) #transforming\n\n to better understand the optional arguments of each algorithm see: https://scikit-learn.org/stable/modules/feature_selection.html\n \"\"\"\n self.reducer = reducer\n self.reducers = {\n \"factor_analysis\": FactorAnalysis,\n \"pca\": PCAReducer,\n \"ica\": FastICA,\n \"isomap\": Isomap,\n \"locally_linear_embedding\": LocallyLinearEmbedding,\n \"spectral_embedding\": SpectralEmbedding,\n \"tsne\": TSNE,\n \"mds\": MDS,\n \"umap\": UMAP,\n \"latent_dirichlet\": LatentDirichletAllocation,\n \"truncated_svd\": TruncatedSVD,\n \"nmf\": NMF,\n \"linear_discriminant\": LinearDiscriminantAnalysis,\n }\n if AUTOENCONDER_AVAILABLE:\n self.reducers[\"autoencoder\"] = Autoencoder\n self.kwargs = kwargs\n self.fitted = False\n self.reduction = self.reducers[self.reducer](**self.kwargs)\n\n def fit(self, X: pd.DataFrame, y=None):\n \"\"\"\n Identify the features to be selected.\n\n Parameters\n ----------\n X : pd.DataFrame\n features to be selected\n\n y : pd.DataFrame\n target values\n\n Returns\n -------\n None\n \"\"\"\n self.columns = X.columns\n self.reduction.fit(X, y)\n self.fitted = True\n\n def transform(self, df: pd.DataFrame, y=None):\n \"\"\"\n Select features based on fit\n\n Parameters\n ----------\n pd.DataFrame\n dataframe with features to be selected\n\n Returns\n -------\n df : pd.DataFrame\n dataframe with selected features only\n \"\"\"\n if not self.fitted:\n raise Exception(\"Not yet trained.\")\n\n return self.reduction.transform(df)\n\n def fit_transform(self, df: pd.DataFrame, y=None):\n \"\"\"\n Select features based on fit\n\n Parameters\n ----------\n pd.DataFrame\n dataframe with features to be selected\n\n Returns\n -------\n df : pd.DataFrame\n dataframe with selected features only\n \"\"\"\n return self.reduction.fit_transform(df, y)\n\n def inverse_transform(self, df: pd.DataFrame):\n \"\"\"\n Apply the invese_transform of vectorizer to each column\n Options: index, bag_of_words and tf_idf\n\n Parameters\n ----------\n df : pd.DataFrame\n dataframe with columns to be unvectorizer\n\n Returns\n -------\n pd.DataFrame\n \"\"\"\n if not self.fitted:\n raise Exception(\"Not yet trained.\")\n\n return self.reduction.inverse_transform(df)\n","repo_name":"A3Data/hermione","sub_path":"hermione/core/analysis/_dimensionality_reduction.py","file_name":"_dimensionality_reduction.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","stars":200,"dataset":"github-code","pt":"52"} +{"seq_id":"73258980646","text":"# SPDX-License-Identifier: GPL-3.0-or-later\n\nimport os\nimport math\n\nfrom .material import Material\nfrom .object import Object\nfrom .texture import loadTexture\n\n\ndef mtl_getopt(args, arg_spec):\n results = {}\n\n i = 0\n while i < len(args):\n matched = False\n if args[i].startswith('-'):\n for name, count in arg_spec.items(): \n if args[i][1:] == name:\n results[name] = tuple(args[i+1:i+count+1])\n i += count\n matched = True\n if not matched:\n break\n i += 1\n\n return (results, tuple(args[i:]))\n\n\ndef parse_mtl(path):\n f = open(path)\n\n materials = {}\n cur_material = None\n\n for l in f:\n l = l.split()\n if not l or l[0].startswith('#'):\n continue\n\n if l[0] == 'newmtl':\n m = Material()\n materials[l[1]] = m\n cur_material = m\n # Ambient\n elif l[0] == 'Ka':\n cur_material.Ka = tuple(float(i) for i in l[1:4])\n # Diffuse\n elif l[0] == 'Kd':\n cur_material.Kd = tuple(float(i) for i in l[1:4])\n # Specular\n elif l[0] == 'Ks':\n cur_material.Ks = tuple(float(i) for i in l[1:4])\n elif l[0] == 'Ns':\n cur_material.Ns = float(l[1])\n elif l[0] == 'Ni':\n cur_material.Ni = float(l[1])\n elif l[0] == 'd':\n cur_material.d = float(l[1])\n elif l[0] == 'map_Kd':\n # XXX handle s\n opts, rest = mtl_getopt(l[1:], {'s': 3})\n map_Kd = ' '.join(rest)\n cur_material.map_Kd = loadTexture(os.path.dirname(path) + '/' + map_Kd)\n elif l[0] == 'map_Bump':\n # XXX handle s\n opts, rest = mtl_getopt(l[1:], {'s': 3, 'bm': 1})\n if 'bm' in opts:\n cur_material.bm = float(opts['bm'][0])\n else:\n cur_material.bm = 1.0\n map_Bump = ' '.join(rest)\n cur_material.map_Bump = loadTexture(os.path.dirname(path) + '/' + map_Bump)\n # Illumination mode\n elif l[0] == 'illum':\n pass\n else:\n print(f\"Ignoring {l[0]}\")\n\n return materials\n\n\ndef parse_obj(path):\n f = open(path)\n\n objects = {}\n cur_object = None\n mtls = None\n\n v_list = []\n vt_list = []\n vn_list = []\n\n for l in f:\n l = l.split()\n if not l or l[0].startswith('#'):\n continue\n\n # Load materials from file\n if l[0] == 'mtllib':\n mtls = parse_mtl(os.path.dirname(path) + '/' + l[1])\n # Use material\n elif l[0] == 'usemtl':\n cur_object.mtl_list.append([mtls[l[1]], len(cur_object.vertices) // 8, 0])\n # Smoothing\n elif l[0] == 's':\n pass\n # Face\n elif l[0] == 'f':\n for i in l[1:4]:\n v, vt, vn = (int(j or 0) for j in i.split('/'))\n cur_object.vertices.extend(v_list[v - 1])\n if (vt == 0):\n cur_object.vertices.extend((0, 0))\n else:\n cur_object.vertices.extend(vt_list[vt - 1])\n cur_object.vertices.extend(vn_list[vn - 1])\n cur_object.mtl_list[-1][2] += 3\n # Vertex\n elif l[0] == 'v':\n v_list.append(tuple(float(i) for i in l[1:4]))\n # Texture vertex\n elif l[0] == 'vt':\n vt_list.append(tuple(float(i) for i in l[1:3]))\n # Vertex normal\n elif l[0] == 'vn':\n vn_list.append(tuple(float(i) for i in l[1:4]))\n # Object\n elif l[0] == 'o':\n cur_object = Object()\n objects[l[1]] = cur_object\n # Ignore lines\n elif l[0] == 'l':\n pass\n else:\n print(f\"Ignoring {l[0]}\")\n\n radius = max(math.sqrt(a**2+b**2+c**2) for a, b, c in v_list)\n\n for v in objects.values():\n v.radius = radius\n\n return objects\n","repo_name":"ids1024/naev-model-view","sub_path":"obj_view/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29758548704","text":"import serial, csv, os\nfrom time import sleep\nif os.path.isfile('output.csv'): os.remove('output.csv')\narduino = serial.Serial(port='COM8', baudrate=115200, timeout=.1)\nwriting = False\nf = open('output.csv', \"x\")\nwith open('output.csv','w') as csvfile:\n w = csv.writer(csvfile, delimiter=',')\n try:\n while True:\n try:\n line = arduino.readline().decode().rstrip().split()\n print(line)\n except UnicodeDecodeError: continue\n except KeyboardInterrupt: break\n\n if 'VALIDATED!' in line:\n writing = True\n continue\n \n if writing:\n line = list(map(float, line))\n line[4] += line[1]\n line[5] += line[2]\n line[6] += line[3]\n w.writerow(line)\n \n finally:\n csvfile.close()\n print(\"File closed!\")","repo_name":"gcfc/6808","sub_path":"pose/get_serial.py","file_name":"get_serial.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37468734309","text":"import _pyisaac\n\n\n__all__ = ('rand',)\n\n\ndef rand(*dimensions):\n \"\"\"\n rand(d0, d1, ..., dn)\n\n Random values in a given shape.\n\n Create a numpy array of the given shape and propagate it with\n random samples from a uniform distribution over ``[0, 1)``.\n\n Parameters\n ----------\n d0, d1, ..., dn : int, optional\n The dimensions of the returned array, should all be positive.\n If no argument is given a single Python float is returned.\n\n Returns\n -------\n out : ndarray, shape ``(d0, d1, ..., dn)``\n Random values.\n\n Examples\n --------\n >>> pyisaac.np.rand(3, 2)\n array([[ 0.14022471, 0.96360618],\n [ 0.37601032, 0.25528411],\n [ 0.49313049, 0.94909878]])\n \"\"\"\n if len(dimensions) == 0:\n return _pyisaac.random()\n else:\n if any(dim < 0 for dim in dimensions):\n raise ValueError('negative dimensions are not allowed')\n\n return _pyisaac.np_rand(dimensions)\n","repo_name":"guilload/pyisaac","sub_path":"pyisaac/np.py","file_name":"np.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"1640048469","text":"#!/usr/bin/env python3\n# vim: ai ts=4 sts=4 et sw=4 nu\n\nimport argparse\nimport logging\nimport sys\n\nfrom youtube2zim.constants import CHANNEL, NAME, PLAYLIST, SCRAPER, USER, logger\nfrom youtube2zim.utils import has_argument\n\n\ndef main():\n parser = argparse.ArgumentParser(\n prog=f\"{NAME}-playlists\",\n description=\"Scraper to create ZIM file(s) from a Youtube Channel or Playlists\",\n epilog=\"Playlists titles, descriptions and names \"\n \"can use the following variables: \"\n \"{title}, {description}, {playlist_id}, {slug} (from title), \"\n \"{creator_id}, {creator_name}.\",\n )\n\n parser.add_argument(\n \"--type\",\n help=\"Type of collection\",\n choices=[CHANNEL, PLAYLIST, USER],\n required=True,\n dest=\"collection_type\",\n )\n parser.add_argument(\n \"--id\", help=\"Youtube ID of the collection\", required=True, dest=\"youtube_id\"\n )\n\n parser.add_argument(\"--api-key\", help=\"Youtube API Token\", required=True)\n\n parser.add_argument(\n \"--indiv-playlists\",\n help=\"Playlists mode: build one ZIM per playlist of the channel\",\n action=\"store_true\",\n dest=\"playlists_mode\",\n )\n\n parser.add_argument(\n \"--playlists-name\",\n help=\"Format for building individual --name argument. \"\n \"Required in playlist mode.\",\n )\n parser.add_argument(\n \"--playlists-zim-file\",\n help=\"Format for building individual --zim-file argument. \"\n \"Uses --playlists-name otherwise\",\n )\n parser.add_argument(\n \"--playlists-title\",\n help=\"Custom title format for individual playlist ZIM\",\n )\n parser.add_argument(\n \"--playlists-description\",\n help=\"Custom description format for individual playlist ZIM\",\n )\n parser.add_argument(\n \"--metadata-from\",\n help=\"File path or URL to a JSON file holding custom metadata \"\n \"for individual playlists. Format in README\",\n )\n parser.add_argument(\n \"--debug\", help=\"Enable verbose output\", action=\"store_true\", default=False\n )\n parser.add_argument(\n \"--version\",\n help=\"Display scraper version and exit\",\n action=\"version\",\n version=SCRAPER,\n )\n\n args, extra_args = parser.parse_known_args()\n\n # prevent setting --title and --description\n for arg in (\"name\", \"title\", \"description\", \"zim-file\"):\n if args.playlists_mode and has_argument(arg, extra_args):\n parser.error(\n f\"Can't use --{arg} in playlists mode. \"\n f\"Use --playlists-{arg} to set format.\"\n )\n\n # playlists-name mandatory in playlist-mode\n if args.playlists_mode and not args.playlists_name:\n parser.error(\"--playlists-name is mandatory in playlists mode\")\n\n logger.setLevel(logging.DEBUG if args.debug else logging.INFO)\n\n from youtube2zim.playlists.scraper import YoutubeHandler\n\n try:\n handler = YoutubeHandler(dict(args._get_kwargs()), extra_args=extra_args)\n return handler.run()\n except Exception as exc:\n logger.error(f\"FAILED. An error occurred: {exc}\")\n if args.debug:\n logger.exception(exc)\n return 1\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"openzim/youtube","sub_path":"src/youtube2zim/playlists/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"52"} +{"seq_id":"5277256651","text":"\"\"\"\nThis script configures all of the test cases. Is called on the CMakeLists.txt file configure step.\n\"\"\"\n\nimport json\nimport sys\nimport pathlib\nimport shutil\nimport glob\n\nif __name__ == '__main__':\n nf_test_version = sys.argv[1]\n ntries = sys.argv[2]\n cmake_build_dir = sys.argv[3]\n test_dir = '/'.join(sys.argv[4:])\n test_name = sys.argv[5]\n\ndef file_replace(func, in_dir, out_dir, variant=None):\n with open(out_dir, 'w') as input_file:\n with open(in_dir, 'r') as template_file:\n input_file.write(func(template_file.read(), variant))\n\ndef replace_single(input_data, variant):\n input_data = input_data.replace('@nf_test_version_input@', nf_test_version)\n input_data = input_data.replace('@nf_test_current_ntries@', ntries)\n return input_data\n\ndef replace_modes(input_data, variant):\n input_data = input_data.replace('@nf_test_version_input@', nf_test_version)\n input_data = input_data.replace('@nf_test_current_ntries@', ntries)\n for entry_k, entry_v in variant.items():\n if isinstance(entry_v, list):\n for i, v in enumerate(entry_v):\n input_data = input_data.replace(f'@{entry_k}_{i}@', f'{v}')\n else:\n input_data = input_data.replace(f'@{entry_k}@', f'{entry_v}')\n return input_data\n\ndef main():\n modes = {}\n\n try:\n with open(f'{test_dir}/modes.json', 'r') as in_file:\n modes = json.load(in_file)\n except FileNotFoundError:\n pass\n\n # Generate the output folder(s)\n if not modes:\n print(f'-- Configuring Test -> {test_name} (Single Variant)')\n test_build_dir = f'{cmake_build_dir}/tests/{test_name}'\n pathlib.Path(f'{test_build_dir}/').mkdir(exist_ok=True, parents=True)\n file_replace(replace_single,\n f'{test_dir}/nf_input.dat.in',\n f'{test_build_dir}/nf_input.dat',\n variant=None)\n for f in glob.glob(f'{test_dir}/*.dat'): shutil.copy2(f, f'{test_build_dir}/')\n shutil.copy2(f'{test_dir}/nf_expect.py', f'{test_build_dir}/nf_expect.py')\n else:\n for i, variant in enumerate(modes['variants']):\n print(f'-- Configuring Test -> {test_name} (Variant {i})')\n test_build_dir = f'{cmake_build_dir}/tests/{test_name}_{i}'\n pathlib.Path(f'{test_build_dir}/').mkdir(exist_ok=True, parents=True)\n file_replace(replace_modes,\n f'{test_dir}/nf_input.dat.in',\n f'{test_build_dir}/nf_input.dat',\n variant=variant)\n for f in glob.glob(f'{test_dir}/*.dat'): shutil.copy2(f, f'{test_build_dir}/')\n shutil.copy2(f'{test_dir}/nf_expect.py', f'{test_build_dir}/nf_expect.py')\n\nif __name__ == '__main__':\n main()\n","repo_name":"martinit18/nested_fit","sub_path":"tests/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"8379211320","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^main$', views.main_page_index_template),\n url(r'^success$', views.register_success_test),\n url(r'^dashboard$', views.dashboard_index_template),\n url(r'^clear$', views.logout),\n url(r'^login_success$', views.login_success_test),\n url(r'^wish_items/create', views.wish_items_index_template),\n url(r'^created_success$', views.item_create_success_test),\n url(r'^item_delete_success/(?P\\d+)$', views.item_delete_success_test),\n url(r'^item_show_success/(?P\\d+)$', views.item_show_index_template),\n url(r'^item_add_success/(?P\\d+)$', views.item_add_success),\n]","repo_name":"Tandd2015/python_stack","sub_path":"django/django_full_stack/wish_list_proj/apps/wish_list_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24799323713","text":"#! /usr/bin/env python\nimport argparse\nimport logging\n\nimport bonobo\nimport yaml\nfrom bonobo.constants import BEGIN\n\nimport nodes\nimport util\n\nif __name__ == '__main__':\n # Parse command line arguments\n parser = argparse.ArgumentParser(description='Analyse sentiment from a live tweetstream.')\n parser.add_argument('-c', '--config_file', default='config.yml', help='the application configuration')\n args = parser.parse_args()\n\n # Load the app configuration\n yaml.add_implicit_resolver('!env', util.env_var_resolver, Loader=yaml.SafeLoader)\n yaml.add_constructor('!env', util.env_var_constructor, Loader=yaml.SafeLoader)\n with open(args.config_file) as f:\n config = yaml.safe_load(f)\n\n # Configure logging\n logging.basicConfig(**config.get('logging', {}))\n\n # Configure the bonobo graph\n graph = bonobo.Graph()\n for name, props in config['graph'].items():\n node = nodes.configure_node(props['class'], **props.get('config', {}))\n graph.add_chain(node, _name=name, _input=props.get('input', BEGIN), _output=props.get('output', None))\n\n # Run the graph\n try:\n bonobo.run(graph)\n except KeyboardInterrupt:\n pass # Don't print the trace when the stream is stopped\n","repo_name":"donaghhorgan/twitter-sentiment-analysis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18749626867","text":"from unittest.mock import DEFAULT\n\n\n\nACCOUNT_OK = 0\nACCOUNT_DELETE = -1\n\nGEOMETRIC_POLICY = 0\nINFINITE_POLICY = 1\n\n\nROBOT_OK = 0\nROBOT_CREATING = 2\nROBOT_PAUSE = 1\nROBOT_DESTORYING = 3\nROBOT_DELETE = -1\n\nORDER_FINISH = 0\nORDER_WAIT = 1\nORDER_CANCEL = 2\nORDER_Fail = 3\n\nORDER_BUY = 0\nORDER_SELL = 1\n\nORDER_NONE_REF = -1\n\nORDER_NONE_FLAG = -1\n# ORDER_CANCEL_FLAG = 1\n\n\nROBOT_MODIFY_PAUSE_RESUME = 0\nROBOT_MODIFY_DELETE = 1\n\nSTATUS_ERROR = -1\nSTATUS_OK = 0\n\nMAX_ORDER_NUM = 50\nBASE_ORDER_NUM = 1\nDISTANCE_RATIO = 0.1\nDISTANCE_MAX = 1e-4\nORDER_DISTANCE = 1e-3\n\nMAX_REPOST_NUM = 2\nMAX_DAYS = 4\n\nDEFAULT_API = \"空\"\nINVALID_ACCOUNT = -1\n\n\n# HUOBI_CONSTANT = 0\n# BIAN_CONSTANT = 1\nDEFAULT_PLANTFORM = \"空\"\nHUOBI_STR = '火币'\nBIAN_STR = '币安'\nOK_STR = 'OK'\nMAGIC_NUMBER = 13\nOK_DELAY_TIME = 0\n\ncheck_frequency = {HUOBI_STR: 200, OK_STR: 100}\nplantform_array = ['火币', 'OK']\ncurrency_arry = [\"btcusdt\", \"ethusdt\", \"ltcusdt\"]","repo_name":"wispytrace/bituniverse-wispy","sub_path":"django/bitApp/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74818068643","text":"'''\n5. 练习:统计不同气温的分组柱状图\n* 题目描述:绘制1-3月的每月零上气温和零下气温天数���分组柱状图 \n\n* 题目要求: \n* 使用Matplotlib进行分组柱状图的绘制 \n\n* 数据文件: \n* 数据源下载地址:https://video.mugglecode.com/temp2.csv(数据源与第二节练习相同) \n* temp2.csv,包含了2018年1-3月北京的气温(每日的最低温度)。每行记录为1天的数据。 \n* 共2列数据,第1列month为月份,第2列temperature为摄氏温度 \n'''\n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\n\n# mac系统获取中文字体\ndef get_chinese_font():\n return FontProperties(fname='/System/Library/Fonts/PingFang.ttc')\n\n\nfilename = './data/data_temp/temp2.csv'\noutput_path = './output'\n\nif not os.path.exists(output_path):\n os.makedirs(output_path)\n\n\ndef collect_process_data():\n data = np.loadtxt(filename, delimiter=',', skiprows=1, dtype=float)\n positive_data = []\n nagetive_data = []\n for i in range(3):\n month_data = data[data[:, 0] == i + 1]\n positive_data.append(month_data[month_data[:, 1] >= 0].shape[0])\n nagetive_data.append(month_data[month_data[:, 1] < 0].shape[0])\n return (positive_data, nagetive_data)\n\n\ndef show_data(data):\n bar_locs = np.arange(3)\n bar_width = 0.35 # 柱子宽度\n xtick_labels = ['{}月份'.format(i + 1) for i in range(3)]\n positve_data = data[0]\n nagetive_data = data[1]\n plt.figure()\n plt.bar(bar_locs, positve_data, width=bar_width, color='r', alpha=0.7, label='零上')\n plt.bar(bar_locs + bar_width, nagetive_data, width=bar_width, color='g', alpha=0.7, label='零下')\n plt.xticks(bar_locs + bar_width / 2, xtick_labels, rotation=45, fontproperties=get_chinese_font())\n plt.ylabel('单位:天', fontproperties=get_chinese_font())\n plt.title('零上零下气温天数', fontproperties=get_chinese_font())\n plt.legend(loc='best', prop=get_chinese_font())\n\n plt.tight_layout()\n plt.savefig(os.path.join(output_path, 'temp_count.png'))\n plt.show()\n\n\nif __name__ == '__main__':\n data = collect_process_data()\n show_data(data)\n","repo_name":"xppppd/dataAnalyze_muggle","sub_path":"统计不同月份气温的分组柱状图.py","file_name":"统计不同月份气温的分组柱状图.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27135760958","text":"import architecture\nimport tensorflow as tf\n\ndef leaky_relu(x, alpha=0.2):\n return tf.nn.relu(x) - alpha * tf.nn.relu(-x)\n\nclass Unet(architecture.Architecture):\n \n\n def __init__(self):\n parameters_list = ['input_size', 'summary_writing_period',\n \"validation_period\", \"model_saving_period\"]\n\n self.config_dict = self.open_config(parameters_list)\n self.input_size = self.config_dict[\"input_size\"][0:2]\n\n def prediction(self, sample, training=False):\n \n normalizer_params = {'is_training':training, 'center':True,\n 'updates_collections':None, 'scale':True}\n ngf = 64\n paddings = tf.constant([[0,0], [1, 1,], [1, 1], [0, 0]])\n # input is (nc) x 256 x 256\n \n sample = tf.image.resize_images(sample, size=[256, 256]) \n \n sample_pad = tf.pad(sample, paddings)\n print(sample)\n print(sample_pad)\n encode1 = tf.contrib.layers.conv2d(inputs=sample_pad, num_outputs=ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=None,\n activation_fn=None)\n print(encode1)\n # input is (ngf) x 128 x 128\n conv1 = leaky_relu(encode1)\n conv1_pad = tf.pad(conv1, paddings)\n encode2 = tf.contrib.layers.conv2d(inputs=conv1_pad, num_outputs=2*ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None) \n print(encode2)\n # input is (ngf * 2) x 64 x 64\n conv2 = leaky_relu(encode2)\n conv2_pad = tf.pad(conv2, paddings)\n encode3 = tf.contrib.layers.conv2d(inputs=conv2_pad, num_outputs=4*ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n print(encode3)\n # input is (ngf * 4) x 32 x 32\n conv3 = leaky_relu(encode3)\n conv3_pad = tf.pad(conv3, paddings)\n encode4 = tf.contrib.layers.conv2d(inputs=conv3_pad, num_outputs=8*ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n print(encode4)\n # input is (ngf * 8) x 16 x 16\n conv4 = leaky_relu(encode4)\n conv4_pad = tf.pad(conv4, paddings)\n encode5 = tf.contrib.layers.conv2d(inputs=conv4_pad, num_outputs=8*ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n print(encode5)\n # input is (ngf * 8) x 8 x 8\n conv5 = leaky_relu(encode5)\n conv5_pad = tf.pad(conv5, paddings)\n encode6 = tf.contrib.layers.conv2d(inputs=conv5_pad, num_outputs=8*ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n print(encode6)\n # input is (ngf * 8) x 4 x 4\n conv6 = leaky_relu(encode6)\n conv6_pad = tf.pad(conv6, paddings)\n encode7 = tf.contrib.layers.conv2d(inputs=conv6_pad, num_outputs=8*ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n print(encode7)\n # input is (ngf * 8) x 2 x 2\n conv7 = leaky_relu(encode7)\n conv7_pad = tf.pad(conv7, paddings)\n encode8 = tf.contrib.layers.conv2d(inputs=conv7_pad, num_outputs=8*ngf, kernel_size=[4, 4],\n stride=[2, 2], padding='VALID',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=tf.nn.relu)\n print(encode8)\n # input is (ngf * 8) x 1 x 1\n decode1 = tf.contrib.layers.conv2d_transpose(encode8, num_outputs=8*ngf,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n\n# decode1 = tf.image.crop_to_bounding_box(decode1,\n# offset_height = 1,\n# offset_width = 1,\n# target_height = decode1.get_shape()[1]-2,\n# target_width = decode1.get_shape()[2]-2)\n\n decode1_drop = tf.nn.dropout(decode1, keep_prob=0.5)\n print(decode1_drop)\n decode1 = tf.nn.relu(tf.concat([decode1_drop, encode7],3))\n\n # input is (ngf * 8) x 2 x 2\n # decode1_pad = tf.pad(decode1, paddings)\n decode2 = tf.contrib.layers.conv2d_transpose(decode1, num_outputs=8*ngf,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n\n # decode2 = tf.image.crop_to_bounding_box(decode2,\n # offset_height = 1,\n # offset_width = 1,\n # target_height = decode2.get_shape()[1]-2,\n # target_width = decode2.get_shape()[2]-2)\n\n decode2_drop = tf.nn.dropout(decode2, keep_prob=0.5)\n decode2 = tf.nn.relu(tf.concat([decode2_drop, encode6],3))\n\n # input is (ngf * 8) x 4 x 4\n # decode2_pad = tf.pad(decode2, paddings)\n decode3 = tf.contrib.layers.conv2d_transpose(decode2, num_outputs=8*ngf,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n\n# decode3 = tf.image.crop_to_bounding_box(decode3,\n# offset_height = 1,\n# offset_width = 1,\n# target_height = decode3.get_shape()[1]-2,\n# target_width = decode3.get_shape()[2]-2)\n\n decode3_drop = tf.nn.dropout(decode3, keep_prob=0.5)\n decode3 = tf.nn.relu(tf.concat([decode3_drop, encode5],3))\n\n\n # input is (ngf * 8) x 8 x 8\n # decode3_pad = tf.pad(decode3, paddings)\n decode4 = tf.contrib.layers.conv2d_transpose(decode3, num_outputs=8*ngf,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n\n# decode4 = tf.image.crop_to_bounding_box(decode4,\n# offset_height = 1,\n# offset_width = 1,\n# target_height = decode4.get_shape()[1]-2,\n# target_width = decode4.get_shape()[2]-2)\n decode4 = tf.nn.relu(tf.concat([decode4, encode4],3))\n\n # input is (ngf * 8) x 16 x 16\n # decode4_pad = tf.pad(decode4, paddings)\n decode5 = tf.contrib.layers.conv2d_transpose(decode4, num_outputs=4*ngf,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n\n# decode5 = tf.image.crop_to_bounding_box(decode5,\n# offset_height = 1,\n# offset_width = 1,\n# target_height = decode5.get_shape()[1]-2,\n# target_width = decode5.get_shape()[2]-2)\n\n decode5 = tf.nn.relu(tf.concat([decode5, encode3],3))\n\n # input is (ngf * 4) x 32 x 32\n # decode5_pad = tf.pad(decode5, paddings)\n decode6 = tf.contrib.layers.conv2d_transpose(decode5, num_outputs=2*ngf,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n# decode6 = tf.image.crop_to_bounding_box(decode6,\n# offset_height = 1,\n# offset_width = 1,\n# target_height = decode6.get_shape()[1]-2,\n# target_width = decode6.get_shape()[2]-2)\n decode6 = tf.nn.relu(tf.concat([decode6, encode2],3))\n\n # input is (ngf * 2) x 64 x 64\n # decode6_pad = tf.pad(decode6, paddings)\n decode7 = tf.contrib.layers.conv2d_transpose(decode6, num_outputs=ngf,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=None)\n\n# decode7 = tf.image.crop_to_bounding_box(decode7,\n# offset_height = 1,\n# offset_width = 1,\n# target_height = decode7.get_shape()[1]-2,\n# target_width = decode7.get_shape()[2]-2)\n\n decode7 = tf.nn.relu(tf.concat([decode7, encode1],3))\n\n # input is (ngf) x 128 x 128\n # decode7_pad = tf.pad(decode7, paddings)\n decode8 = tf.contrib.layers.conv2d_transpose(decode7, num_outputs=3,\n kernel_size=[4,4],stride=[2, 2],\n padding='SAME',\n normalizer_fn=tf.contrib.layers.batch_norm,\n normalizer_params=normalizer_params,\n activation_fn=tf.nn.tanh)\n\n# decode8 = tf.image.crop_to_bounding_box(decode8,\n# offset_height = 1,\n# offset_width = 1,\n# target_height = decode8.get_shape()[1]-2,\n# target_width = decode8.get_shape()[2]-2)\n\n decode8 = tf.image.resize_images(decode8, size=self.input_size) \n\n tf.summary.image('architecture output', decode8)\n\n return decode8\n\n\n\n def get_validation_period(self):\n return self.config_dict[\"validation_period\"]\n\n def get_model_saving_period(self):\n return self.config_dict[\"model_saving_period\"]\n\n def get_summary_writing_period(self):\n return self.config_dict[\"summary_writing_period\"]\n","repo_name":"nautecfurg/modelo_netuno","sub_path":"Architectures/ProjectDeepdive/unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":13747,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"71656309924","text":"def miis():\n return map(int,input().split())\ndef ii():\n return int(input()) \ndef judge(a):\n if a:\n print(\"Yes\")\n else:\n print(\"No\")\ndef cheak(mid):\n buy_ok = 0\n uru_ok = 0\n for i in range(N):\n if A[i] <= mid:\n uru_ok += 1\n for i in range(M):\n if B[i] >= mid:\n buy_ok += 1\n if uru_ok >= buy_ok:\n return True\n else:\n return False\n# 決め打ち二分探索?\nN, M = miis()\nA = list(miis())\nB = list(miis())\nok = 10**9+1\nng = 0\nwhile abs(ng - ok) != 1:\n mid = (ok + ng) // 2\n if cheak(mid):\n ok = mid\n else:\n ng = mid\nprint(max(ok,ng))","repo_name":"mitu24472/Atcoder","sub_path":"ABC/Atcoder Beginner Contest 312/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10951184969","text":"import torch\nfrom torch import nn\nfrom tqdm import tqdm\n\nfrom dataset import *\nfrom spdnet.spd import SPDTransform, SPDTangentSpace, SPDRectified\nfrom spdnet.optimizer import StiefelMetaOptimizer\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.trans1 = SPDTransform(400, 200)\n self.trans2 = SPDTransform(200, 100)\n self.trans3 = SPDTransform(100, 50)\n self.rect1 = SPDRectified()\n self.rect2 = SPDRectified()\n self.rect3 = SPDRectified()\n self.tangent = SPDTangentSpace(50)\n self.linear = nn.Linear(1275, 7, bias=True)\n # self.dropout = nn.Dropout(p=0.5)\n\n def forward(self, x):\n x = self.trans1(x)\n x = self.rect1(x)\n x = self.trans2(x)\n x = self.rect2(x)\n x = self.trans3(x)\n x = self.rect3(x)\n x = self.tangent(x)\n # x = self.dropout(x)\n x = self.linear(x)\n return x\n\ntransformed_dataset = AfewDataset(train=True)\ndataloader = DataLoader(transformed_dataset, batch_size=30,\n shuffle=True, num_workers=4)\n\ntransformed_dataset_val = AfewDataset(train=False)\ndataloader_val = DataLoader(transformed_dataset_val, batch_size=30,\n shuffle=False, num_workers=4)\n\nuse_cuda = True\nmodel = Net()\nif use_cuda:\n model = model.cuda()\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)\n# optimizer = torch.optim.Adadelta(model.parameters())\n# optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)\noptimizer = StiefelMetaOptimizer(optimizer)\n\n# Training\ndef train(epoch):\n print('\\nEpoch: %d' % epoch)\n model.train()\n train_loss = 0\n correct = 0.0\n total = 0.0\n bar = tqdm(enumerate(dataloader))\n for batch_idx, sample_batched in bar:\n inputs = sample_batched['data']\n targets = sample_batched['label'].squeeze()\n\n if use_cuda:\n inputs = inputs.cuda()\n targets = targets.cuda()\n\n optimizer.zero_grad()\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.data.item()\n _, predicted = torch.max(outputs.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum().data.item()\n\n bar.set_description('Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1.0), 100.*correct/total, correct, total))\n\n return (train_loss/(batch_idx+1), 100.*correct/total)\n\nbest_acc = 0\ndef test(epoch):\n global best_acc\n model.eval()\n test_loss = 0\n correct = 0.0\n total = 0.0\n bar = tqdm(enumerate(dataloader_val))\n for batch_idx, sample_batched in bar:\n inputs = sample_batched['data']\n targets = sample_batched['label'].squeeze()\n\n if use_cuda:\n inputs = inputs.cuda()\n targets = targets.cuda()\n\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.data.item()\n _, predicted = torch.max(outputs.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum().data.item()\n\n bar.set_description('Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n # Save checkpoint.\n acc = 100.*correct/total\n if acc > best_acc:\n print('Saving..')\n state = {\n 'net': model,\n 'acc': acc,\n 'epoch': epoch,\n }\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n torch.save(state, './checkpoint/ckpt.t7')\n best_acc = acc\n\n return (test_loss/(batch_idx+1), 100.*correct/total)\n\nlog_file = open('log.txt', 'a')\n\nstart_epoch = 1\nfor epoch in range(start_epoch, start_epoch+500):\n train_loss, train_acc = train(epoch)\n test_loss, test_acc = test(epoch)\n\n log_file.write('%d,%f,%f,%f,%f\\n' % (epoch, train_loss, train_acc, test_loss, test_acc))\n log_file.flush()\n\nlog_file.close()","repo_name":"adavoudi/spdnet","sub_path":"examples/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"52"} +{"seq_id":"34962829840","text":"import math\n\nimport numpy as np\n\n\ndef compute(image):\n img = np.array(image)\n mag = []\n theta = []\n for i in range(image.height):\n magnitudeArray = []\n angleArray = []\n for j in range(image.width):\n # Condition for axis 0\n if j - 1 <= 0 or j + 1 >= image.width:\n \"\"\"\n Ignoring the egdes\n \"\"\"\n Gx=0\n \"\"\"\n Previously for edges i was subtracting with 0\n \"\"\"\n # if j - 1 <= 0:\n # # Condition if first element\n # Gx = img[i][j + 1] - 0\n # elif j + 1 >= len(img[0]):\n # Gx = 0 - img[i][j - 1]\n # Condition for first element\n else:\n # Applying mask <-1, 0, 1>\n Gx = int(img[i][j + 1]) - int(img[i][j - 1])\n\n # Condition for axis 1\n if i - 1 <= 0 or i + 1 >= image.height:\n \"\"\"\n Ignoring the egdes\n \"\"\"\n Gy=0\n \"\"\"\n Previously for edges i was subtracting with 0\n \"\"\"\n # if i - 1 <= 0:\n # Gy = 0 - img[i + 1][j]\n # elif i + 1 >= 128:\n # Gy = img[i - 1][j] - 0\n else:\n # Applying mask <-1, 0, 1> transpose\n Gy = int(img[i - 1][j]) - int(img[i + 1][j])\n\n # Calculating magnitude\n magnitude = math.sqrt(pow(Gx, 2) + pow(Gy, 2))\n mag.append(round(magnitude, 9))\n\n # Calculating angle\n if Gx == 0:\n angle = np.degrees(0.0)\n else:\n angle = np.degrees(360 + np.arctan2(Gy, Gx)) % 360\n theta.append(round(angle, 9))\n # mag.append(magnitudeArray)\n # theta.append(angleArray)\n\n \"\"\"\n The above calculation will give the magnitude and angle for each of the pixels in 300*100 grid\n Now we will save them in 9 bins\n \"\"\"\n bin_size = 40\n hog_bins = [0] * (360 // bin_size) # Create an array of 9 bin size\n for index in range(0, len(mag)):\n angle = theta[index]\n magnitude = mag[index]\n lower_bin = math.floor(angle/bin_size)\n upper_bin = lower_bin+1\n\n mag_lower_bin = (upper_bin-angle/bin_size)*magnitude\n mag_upper_bin = magnitude - mag_lower_bin\n\n hog_bins[lower_bin] += mag_lower_bin\n hog_bins[upper_bin % len(hog_bins)] += mag_upper_bin #the upper index should be cycled back to 0 ig the index is more than 9\n\n return hog_bins\n\n\ndef calculate_hog(image):\n if image.mode != 'RGB':\n return \"Image not an RGB!! Cannot Process\"\n\n newsize = (300, 100)\n image = image.resize(newsize)\n\n # Convert the image to grayscale\n gray_img = image.convert('L')\n\n # Partition the image into a 10x10 grid\n num_rows, num_cols = 10, 10\n image_height = gray_img.height\n image_width = gray_img.width\n\n tile_width = image_width // 10\n tile_height = image_height // 10\n tiles = [gray_img.crop(box=(w, h, w + tile_width, h + tile_height))\n for h in range(0, image_height, tile_height)\n for w in range(0, image_width, tile_width)]\n\n results = []\n for tile in tiles:\n results.append(compute(tile.getchannel(0)))\n\n # Return as a unified flattened vector\n return np.array(results).flatten()\n","repo_name":"shubhodeepMitra/MultiMediaRetrieval_phase1","sub_path":"Code/hog.py","file_name":"hog.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37285518228","text":"#\n# @lc app=leetcode id=467 lang=python3\n#\n# [467] Unique Substrings in Wraparound String\n#\n# https://leetcode.com/problems/unique-substrings-in-wraparound-string/description/\n#\n# algorithms\n# Medium (35.56%)\n# Likes: 612\n# Dislikes: 86\n# Total Accepted: 25.5K\n# Total Submissions: 71.6K\n# Testcase Example: '\"a\"'\n#\n# Consider the string s to be the infinite wraparound string of\n# \"abcdefghijklmnopqrstuvwxyz\", so s will look like this:\n# \"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\".\n# \n# Now we have another string p. Your job is to find out how many unique\n# non-empty substrings of p are present in s. In particular, your input is the\n# string p and you need to output the number of different non-empty substrings\n# of p in the string s.\n# \n# Note: p consists of only lowercase English letters and the size of p might be\n# over 10000.\n# \n# Example 1:\n# \n# Input: \"a\"\n# Output: 1\n# \n# Explanation: Only the substring \"a\" of string \"a\" is in the string \u0010s.\n# \n# \n# \n# Example 2:\n# \n# Input: \"cac\"\n# Output: 2\n# Explanation: There are two substrings \"a\", \"c\" of string \"cac\" in the string\n# s.\n# \n# \n# \n# Example 3:\n# \n# Input: \"zab\"\n# Output: 6\n# Explanation: There are six substrings \"z\", \"a\", \"b\", \"za\", \"ab\", \"zab\" of\n# string \"zab\" in the string s.\n# \n# \n#\n\n# @lc code=start\nfrom collections import defaultdict\n\nclass Solution:\n def findSubstringInWraproundString(self, p: str) -> int:\n # p, d, lo = '0' + p, defaultdict(int), 0\n # for hi in range(1, len(p)):\n # if p[hi-1:hi+1] not in \"abcdefghijklmnopqrstuvwxyza\":\n # lo = hi\n # d[p[hi]] = max(d[p[hi]], hi - lo + 1)\n # return sum(d.values())\n\n\n res = {i: 1 for i in p}\n l = 1\n for i, j in zip(p, p[1:]):\n l = l + 1 if (ord(j) - ord(i)) % 26 == 1 else 1\n res[j] = max(res[j], l)\n return sum(res.values())\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"467.unique-substrings-in-wraparound-string.py","file_name":"467.unique-substrings-in-wraparound-string.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"36686955654","text":"import asyncio\n\nimport nextcord\nfrom nextcord import SlashOption\nfrom nextcord.ext import commands\n\nfrom time import sleep\nfrom chatgpt_wrapper import ChatGPT\nfrom threading import Thread\nimport configparser\nfrom speechkit import Session, SpeechSynthesis\n\n# It's important to pass guild_ids explicitly while developing your bot because\n# commands can take up to an hour to roll out when guild_ids is not passed. Once\n# you deploy your bot to production, you can remove guild_ids to add your\n# commands globally.\n#\n# You can find your guild ID by right clicking on the name of your server inside\n# Discord and clicking \"Copy ID\".\n\nDEV_GUILD_ID = 856999207583612938 # Replace with your guild ID\nguild_ids = [DEV_GUILD_ID]\n\nApi_key = '' #api ключ яндекса\ncatalog_id = \"\"\n\nbot = commands.Bot()\nconfig = configparser.ConfigParser()\nsession = Session.from_api_key(Api_key, catalog_id)\nsynthesizeAudio = SpeechSynthesis(session)\n\nguild_to_voice_client = dict()\n\ndef _context_to_voice_channel(ctx):\n return ctx.user.voice.channel if ctx.user.voice else None\n\n\nasync def _get_or_create_voice_client(ctx):\n if ctx.guild.id in guild_to_voice_client:\n voice_client = guild_to_voice_client[ctx.guild.id]\n else:\n print(ctx.guild.id)\n voice_channel = _context_to_voice_channel(ctx)\n if voice_channel is None:\n voice_client = None\n else:\n voice_client = await voice_channel.connect()\n guild_to_voice_client[ctx.guild.id] = voice_client\n return (voice_client)\n\n@bot.slash_command(\n name=\"join\",\n guild_ids=guild_ids,\n)\nasync def join_vc(ctx: nextcord.Interaction): #для присоединения к каналу\n voice_client = await _get_or_create_voice_client(ctx)\n if voice_client is None:\n await ctx.response.send_message(\n \"You're not in a voice channel. Join a voice channel to invite the bot!\",\n ephemeral=True,\n )\n elif ctx.user.voice and voice_client.channel.id != ctx.user.voice.channel.id:\n old_channel_name = voice_client.channel.name\n await voice_client.disconnect()\n voice_client = await ctx.user.voice.channel.connect()\n new_channel_name = voice_client.channel.name\n guild_to_voice_client[ctx.guild.id] = voice_client\n await ctx.response.send_message(\n f\"Switched from #{old_channel_name} to #{new_channel_name}!\"\n )\n else:\n await ctx.response.send_message(\"Connected to voice channel!\")\n guild_to_voice_client[ctx.guild.id] = voice_client\n\n\n@bot.slash_command(name=\"kick\", guild_ids=guild_ids)\nasync def kick_vc(ctx: nextcord.Interaction): #для отключения от канала\n if ctx.guild.id in guild_to_voice_client:\n voice_client = guild_to_voice_client.pop(ctx.guild.id)\n await voice_client.disconnect()\n await ctx.response.send_message(\"Disconnected from voice channel\")\n else:\n await ctx.response.send_message(\n \"Bot is not connected to a voice channel. Nothing to kick.\", ephemeral=True\n )\n\n@bot.slash_command(\n name=\"ask\",\n guild_ids=guild_ids,\n)\nasync def speak_vc( #получения зпроса, отправка в ChatGPT, и озвучивание\n ctx: nextcord.Interaction,\n msg: str = SlashOption(\n name=\"msg\", description=\"Рrompt for voiceGPT\", required=True\n ),\n):\n voice_client = await _get_or_create_voice_client(ctx)\n if voice_client:\n config.read('gptTemp.ini')\n await asyncio.sleep(0.5)\n config['chatGPT']['allow'] = 'yes' #разрешить ChatGPT обработать запрос\n config['chatGPT']['ask'] = msg #сообщение для ChatGPT\n with open('gptTemp.ini', 'w') as configfile: # save\n config.write(configfile)\n\n botMsg = await ctx.response.send_message(\"Processing...\",)\n\n config.read('gptTemp.ini')\n while config[\"chatGPT\"][\"allow\"] == 'yes': #проигрывать звук пока идёт обработка\n if not voice_client.is_playing():\n source = await nextcord.FFmpegOpusAudio.from_probe(\"loading.mp3\", method=\"fallback\")\n voice_client.play(source, after=None)\n await asyncio.sleep(0.5)\n config.read('gptTemp.ini') #обновление конфига\n\n voice_client.stop()\n response = config.get(\"chatGPT\", \"response\") #ответ ChatGpt\n\n await botMsg.edit(content=\"\", embed=nextcord.Embed(title=f'{ctx.user}: {msg}', description= f\"**VoiceGPT**: {response}\")) #изменить сообщение в дс\n\n synthesizeAudio.synthesize( #сгенерировать голос\n 'out.mp3', text=response,\n voice=config[\"chatGPT\"][\"voice\"], format='oggopus', sampleRateHertz='16000' #голос меняется в конфиге (https://cloud.yandex.ru/docs/speechkit/tts/voices)\n )\n \n source = await nextcord.FFmpegOpusAudio.from_probe(\"out.mp3\", method=\"fallback\")\n voice_client.play(source, after=None) #воспроизвести голос\n while voice_client.is_playing():\n await asyncio.sleep(0.5)\n \n else: # проверка находится ли user в гс канале\n await ctx.response.send_message(\n \"You're not in a voice channel. Join a voice channel to invite the bot!\",\n ephemeral=True,\n )\n\n@bot.slash_command(\n name=\"retry\",\n guild_ids=guild_ids,\n)\nasync def retry(ctx: nextcord.Interaction): #повтор ответа от ChatGpt\n voice_client = await _get_or_create_voice_client(ctx)\n if voice_client:\n config.read('gptTemp.ini')\n response = config.get(\"chatGPT\", \"response\")\n await ctx.response.send_message(f\"last response: \",embed=nextcord.Embed(description=response))\n source = await nextcord.FFmpegOpusAudio.from_probe(\"out.mp3\", method=\"fallback\") #проигрывание прошлого запроса\n voice_client.play(source, after=None)\n while voice_client.is_playing():\n await asyncio.sleep(0.5)\n\n\n# Do the same thing for /vc-kick and the rest of the commands...\n\n# Run the bot\nDISCORD_TOKEN = \"\" #токен бота (https://discord.com/developers/applications/)\n\ndef gptMain(): #получение данных от ChatGPT в отдельном потоке\n gpt = ChatGPT()\n while True:\n try:\n config.read('gptTemp.ini') #загрузка конфига\n sleep(0.15)\n if config[\"chatGPT\"][\"allow\"] == 'yes':\n config[\"chatGPT\"][\"response\"] = gpt.ask(config.get(\"chatGPT\", \"ask\")) # запрос к ChatGPT\n config['chatGPT']['allow'] = 'no'\n with open('gptTemp.ini', 'w') as configfile: # save\n config.write(configfile)\n except:\n print('tread1 error')\n \nif __name__ == \"__main__\":\n \n loop = asyncio.get_event_loop()\n try:\n tread1 = Thread(target=gptMain) # запуск потока\n tread1.start()\n print('started tread')\n loop.run_until_complete(bot.start(DISCORD_TOKEN)) # запуск бота\n except KeyboardInterrupt:\n loop.run_until_complete(bot.close())\n finally:\n loop.close()\n","repo_name":"Zizazar/VoiceGPT-DiscordBot","sub_path":"bot_speechkit.py","file_name":"bot_speechkit.py","file_ext":"py","file_size_in_byte":7386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1533570376","text":"\"\"\"\nProject: FACE MASK RECOGNITION, DISTANCE AND CROWD DENSITY\nMember: DA0 DUY NGU, LE VAN THIEN\nInstructor: PhD. TRAN THI MINH HANH\n*************** CONTACT INFORMATION ***********************************\nTHE UNIVERSITY OF DA NANG\nTHE UNIVERSITY OF SCIENCE AND TECHNOLOGY\nTHE FACULTY OF ELECTRONIC AND TELECOMMUNICATION\nMajor: Computer engineering\nAddress: 54 Nguyen Luong Bang Street, Lien Chieu District, Da Nang city\n***********************************************************************\n\"\"\"\n\nfrom glob import glob\nimport cv2\nfrom retinaface.detector import FaceDetection\nimport argparse\nimport os\nfrom classification.utils.load_model import Model\nfrom pathlib import Path\n\n\n# ******************************** ROOT PATH *****************************\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[0]\nWEIGHTS = ROOT / 'weight'\n\n\ndef draw_bbox(image, bboxs):\n for label, bbox in bboxs:\n x1, y1, x2, y2, score = bbox\n cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), thickness=2, lineType=cv2.LINE_AA)\n cv2.putText(image, str(round(score, 2)), (x1, y1+10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2, cv2.LINE_AA)\n cv2.putText(image, label, (x1, y2 - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n (255, 0, 255), 2, cv2.LINE_AA)\n return image\n\n\ndef detect_image(path_image):\n \"\"\"\n function: detect face mask of folder image\n :param path_image: path of folder contain image\n :return: None\n \"\"\"\n if not os.path.exists(path_image):\n raise ValueError(\"Input folder (\", path_image, \") does not exist.\")\n list_images = glob(path_image + '/*.jpg') + glob(path_image + '/*.jpeg') + glob(path_image + '/*.png')\n list_images.sort()\n print(\"Number image: \", len(list_images))\n # load model face mask classification\n model = Model(WEIGHTS / 'result_mobilenetv2')\n # Load model face detect\n detector = FaceDetection(net='mobilenet').detect_faces\n # Set thresh\n thresh = 0\n for path in list_images:\n image = cv2.imread(path)\n h, w, _ = image.shape\n bboxs, landmark = detector(image)\n list_predict = []\n for bbox in bboxs:\n x1, y1, x2, y2 = [round(i) for i in bbox[0:4]]\n x1, y1, x2, y2 = max(x1 - thresh, 0), max(y1 - thresh, 0), min(x2 + thresh, w - 1), min(y2 + thresh, h - 1)\n pred = model.predict(image[y1:y2, x1:x2])\n list_predict.append((pred[0] + ': %d%%' % (round(max(pred[1]))), (x1, y1, x2, y2, bbox[4])))\n # save data file yolo\n image = draw_bbox(image, list_predict)\n cv2.imshow('image', image)\n cv2.waitKey(0)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Detect Face Image')\n parser.add_argument(\"-f\", \"--file_folder\", help=\"folder file image\", default='', type=str)\n args = parser.parse_args()\n path_image = args.file_folder\n detect_image(path_image)\n\n\n\n\n","repo_name":"DuyNguDao/Project-Covid19","sub_path":"detect_dir_image.py","file_name":"detect_dir_image.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40497246417","text":"from ast import literal_eval\nfrom odoo import models\nfrom odoo.http import request\n\n\nclass Website(models.Model):\n \"\"\"\n Extends the 'website' model to filter product search.\n \"\"\"\n _inherit = \"website\"\n _description = \"Website\"\n\n def _search_with_fuzzy(self, search_type, search, limit, order, options):\n \"\"\"\n This method extends the base search functionality to include additional\n filtering\n \"\"\"\n res = super()._search_with_fuzzy(\n search_type, search, limit, order, options)\n response = list(res)\n available_products = False\n user = request.env['res.users'].sudo().search(\n [('id', '=', request.env.user.id)])\n if response[1][0] and (response[1][0].get(\n 'model', '') == 'product.template' or response[1][0].get(\n 'model', '') == 'product.public.category'):\n if not user:\n mode = request.env['ir.config_parameter'].sudo().get_param(\n 'filter_mode')\n products = literal_eval(\n request.env['ir.config_parameter'].sudo().get_param(\n 'website_product_visibility.'\n 'available_products_for_guest_ids', 'False'))\n if mode == 'product_only':\n available_products = request.env['product.template'].search(\n [('id', 'in', products)])\n cat = literal_eval(\n request.env['ir.config_parameter'].sudo().get_param(\n 'website_product_visibility.available_cat_for_guest_ids',\n 'False'))\n available_categ = request.env['product.public.category'].search(\n [('id', 'in', cat)])\n else:\n partner = request.env['res.partner'].sudo().search(\n [('id', '=', user.partner_id.id)])\n mode = partner.filter_mode\n if mode == 'product_only':\n available_products = self.available_products()\n available_categ = partner.website_available_cat_ids\n Category_avail = []\n Category = request.env['product.public.category']\n for ids in available_categ:\n if not ids.parent_id.id in available_categ.ids:\n Category_avail.append(ids.id)\n categ = request.env['product.public.category'].search(\n [('id', 'in', Category_avail)])\n if mode == 'product_only':\n categ = Category.search([('parent_id', '=', False), (\n 'product_tmpl_ids', 'in', available_products.ids)])\n # supering shop***\n if not available_categ and not available_products and \\\n request.env.user.has_group(\n 'base.group_portal'):\n mode = request.env['ir.config_parameter'].sudo().get_param(\n 'filter_mode_portal')\n products = literal_eval(\n request.env['ir.config_parameter'].sudo().get_param(\n 'website_product_visibility.'\n 'available_products_for_portal_ids', 'False'))\n if mode == 'product_only':\n available_products = request.env['product.template'].search(\n [('id', 'in', products)])\n cat = literal_eval(\n request.env['ir.config_parameter'].sudo().get_param(\n 'website_product_visibility.available_cat_for_portal_ids',\n 'False'))\n available_categ = request.env['product.public.category'].search(\n [('id', 'in', cat)])\n if available_products:\n product_category = available_products.mapped('public_categ_ids')\n category = set(response[1][0]['results'].ids).intersection(set(\n product_category.ids))\n products = set(response[1][-1]['results'].ids).intersection(set(\n available_products.ids))\n response[1][-1]['results'] = request.env[\n 'product.template'].browse(products)\n response[1][0]['results'] = request.env[\n 'product.public.category'].browse(category)\n if available_categ:\n categ_products = available_categ.mapped('product_tmpl_ids')\n products = set(response[1][-1]['results'].ids).intersection(set(\n categ_products.ids))\n category = set(response[1][0]['results'].ids).intersection(set(\n available_categ.ids))\n response[1][0]['results'] = request.env[\n 'product.public.category'].browse(category)\n response[1][-1]['results'] = request.env[\n 'product.template'].browse(products)\n return tuple(response)\n\n def available_products(self):\n \"\"\"Returns the available product (product.template) ids\"\"\"\n user = request.env['res.users'].sudo().search(\n [('id', '=', request.env.user.id)])\n partner = request.env['res.partner'].sudo().search(\n [('id', '=', user.partner_id.id)])\n return partner.website_available_product_ids\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"product_visibility_website/models/website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"36798012311","text":"import heapq\nimport string\nfrom huffman_tree import create_node, add_node\n\ndef huffman(text):\n frequencies = get_frequencies(text)\n nodes = make_nodes_heap(frequencies)\n tree = make_tree(nodes)\n codes = calculate_codes(tree)\n binary_for_huffman = make_huffman(codes, text)\n return get_everything_in_bin(binary_for_huffman, tree)\n\ndef get_frequencies(text):\n frequencies = {}\n letters = string.printable\n for letter in letters:\n frequencies[letter] = 0\n for letter in text:\n frequencies[letter] += 1\n return frequencies\n\ndef make_nodes_heap(frequencies):\n nodes = []\n for symbol, value in frequencies.items():\n if value != 0:\n node = create_node(value, symbol)\n nodes.append(node)\n heapq.heapify(nodes)\n return nodes\n\ndef make_tree(nodes):\n while len(nodes) > 1:\n node1 = heapq.heappop(nodes)\n node2 = heapq.heappop(nodes)\n new_node = add_node(node1, node2)\n heapq.heappush(nodes, new_node)\n return heapq.heappop(nodes)\n\ndef calculate_codes(point, codes={}, code=\"\"):\n if point.left_child:\n code0 = code + \"0\"\n codes = calculate_codes(point.left_child, codes, code0)\n if point.right_child:\n code1 = code + \"1\"\n codes = calculate_codes(point.right_child, codes, code1)\n if point.symbol:\n codes[point.symbol] = code\n return codes\n\ndef make_huffman(codes, text):\n binary_for_huffman = \"\"\n for symbol in text:\n binary_for_huffman += codes[symbol]\n return binary_for_huffman\n\ndef get_everything_in_bin(binary_form, tree):\n tree_in_binary = tree_to_binary(tree)\n tree_lenght_bin = format(len(tree_in_binary), \"032b\")\n data_lenght_bin = format(len(binary_form), \"032b\")\n #lenght of tree in bin, lenght of the data in bin, tree in bin, data in bin, couple extra bits\n over_from_bytes = (64 + len(tree_in_binary) + len(binary_form)) % 8\n if over_from_bytes == 0:\n extra_bits = \"\"\n else:\n extra_bits_needed = 8 - over_from_bytes\n extra_bits = \"0\" * extra_bits_needed\n to_save = tree_lenght_bin + data_lenght_bin + tree_in_binary + binary_form + extra_bits\n return to_save\n\ndef tree_to_binary(tree, tree_in_binary=\"\"):\n # 0 for leaf, 1 has children, left 1st right 2nd\n if tree.symbol:\n tree_in_binary += \"1\"\n symbol_in_ascii = ord(tree.symbol)\n symbol_in_binary = format(symbol_in_ascii, '07b')\n tree_in_binary += symbol_in_binary\n else:\n tree_in_binary += \"0\"\n tree_in_binary = tree_to_binary(tree.left_child, tree_in_binary)\n tree_in_binary = tree_to_binary(tree.right_child, tree_in_binary)\n return tree_in_binary\n\ndef dehuffing(binary):\n tree_lenght = int(binary[0:32], 2)\n data_lenght = int(binary[32:64], 2)\n tree_in_binary = binary[64:64+tree_lenght]\n data_in_binary = binary[64+tree_lenght:64+tree_lenght+data_lenght+1]\n tree = get_tree(tree_in_binary)\n text = get_text(data_in_binary, tree)\n return text\n\ndef get_tree(tree_in_binary):\n def read_bits(spot):\n if spot >= len(tree_in_binary):\n return None, spot\n bit = tree_in_binary[spot]\n if bit == \"1\":\n symbol_range_left = spot+1\n symbol_range_right = symbol_range_left + 7\n symbol_bits = tree_in_binary[symbol_range_left:symbol_range_right]\n symbol_encoded = int(symbol_bits, 2)\n symbol = chr(symbol_encoded)\n return create_node(None, symbol), symbol_range_right\n left_node, pos = read_bits(spot + 1)\n right_node, pos = read_bits(pos)\n return add_node(left_node, right_node), pos\n node, pos = read_bits(0)\n return node\n\ndef get_text(data_in_binary, tree):\n text = \"\"\n node = tree\n for number in data_in_binary:\n if number == \"0\":\n node = node.left_child\n elif number == \"1\":\n node = node.right_child\n if node.symbol:\n text += node.symbol\n node = tree\n return text\n","repo_name":"eevahanka/compressing","sub_path":"src/huffman.py","file_name":"huffman.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21082884357","text":"\nimport argparse\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\"--positive_dist_threshold\", type=int, default=25,\n help=\"distance (in meters) for a prediction to be considered a positive\")\n parser.add_argument(\"--method\", type=str, default=\"cosplace\",\n choices=[\"netvlad\", \"sfrs\", \"cosplace\", \"convap\", \"mixvpr\", \"eigenplaces\"],\n help=\"_\")\n parser.add_argument(\"--backbone\", type=str, default=None,\n choices=[None, \"VGG16\", \"ResNet18\", \"ResNet50\", \"ResNet101\", \"ResNet152\"],\n help=\"_\")\n parser.add_argument(\"--descriptors_dimension\", type=int, default=None,\n help=\"_\")\n parser.add_argument(\"--database_folder\", type=str, required=True,\n help=\"path/to/database\")\n parser.add_argument(\"--queries_folder\", type=str, required=True,\n help=\"path/to/queries\")\n parser.add_argument(\"--num_workers\", type=int, default=4,\n help=\"_\")\n parser.add_argument(\"--batch_size\", type=int, default=4,\n help=\"set to 1 if database images may have different resolution\")\n parser.add_argument(\"--exp_name\", type=str, default=\"default\",\n help=\"experiment name, output logs will be saved under logs/exp_name\")\n parser.add_argument(\"--device\", type=str, default=\"cuda\", choices=[\"cuda\", \"cpu\"],\n help=\"_\")\n parser.add_argument(\"--recall_values\", type=int, nargs=\"+\", default=[1, 5, 10, 20],\n help=\"values for recall (e.g. recall@1, recall@5)\")\n parser.add_argument(\"--num_preds_to_save\", type=int, default=0,\n help=\"set != 0 if you want to save predictions for each query\")\n parser.add_argument(\"--save_only_wrong_preds\", action=\"store_true\",\n help=\"set to true if you want to save predictions only for \"\n \"wrongly predicted queries\")\n \n args = parser.parse_args()\n \n if args.method == \"netvlad\":\n if args.backbone not in [None, \"VGG16\"]:\n raise ValueError(\"When using NetVLAD the backbone must be None or VGG16\")\n if args.descriptors_dimension not in [None, 4096, 32768]:\n raise ValueError(\"When using NetVLAD the descriptors_dimension must be one of [None, 4096, 32768]\")\n if args.descriptors_dimension is None:\n args.descriptors_dimension = 4096\n \n elif args.method == \"sfrs\":\n if args.backbone not in [None, \"VGG16\"]:\n raise ValueError(\"When using SFRS the backbone must be None or VGG16\")\n if args.descriptors_dimension not in [None, 4096]:\n raise ValueError(\"When using SFRS the descriptors_dimension must be one of [None, 4096]\")\n if args.descriptors_dimension is None:\n args.descriptors_dimension = 4096\n \n elif args.method == \"cosplace\":\n if args.backbone is None:\n args.backbone = \"ResNet50\"\n if args.descriptors_dimension is None:\n args.descriptors_dimension = 512\n if args.backbone == \"VGG16\" and args.descriptors_dimension not in [64, 128, 256, 512]:\n raise ValueError(\"When using CosPlace with VGG16 the descriptors_dimension must be in [64, 128, 256, 512]\")\n if args.backbone == \"ResNet18\" and args.descriptors_dimension not in [32, 64, 128, 256, 512]:\n raise ValueError(\"When using CosPlace with ResNet18 the descriptors_dimension must be in [32, 64, 128, 256, 512]\")\n if args.backbone in [\"ResNet50\", \"ResNet101\", \"ResNet152\"] and args.descriptors_dimension not in [32, 64, 128, 256, 512, 1024, 2048]:\n raise ValueError(f\"When using CosPlace with {args.backbone} the descriptors_dimension must be in [32, 64, 128, 256, 512, 1024, 2048]\")\n \n elif args.method == \"convap\":\n if args.backbone is None:\n args.backbone = \"ResNet50\"\n if args.descriptors_dimension is None:\n args.descriptors_dimension = 512\n if args.backbone not in [None, \"ResNet50\"]:\n raise ValueError(\"When using Conv-AP the backbone must be None or ResNet50\")\n if args.descriptors_dimension not in [None, 512, 2048, 4096, 8192]:\n raise ValueError(\"When using Conv-AP the descriptors_dimension must be one of [None, 512, 2048, 4096, 8192]\")\n \n elif args.method == \"mixvpr\":\n if args.backbone is None:\n args.backbone = \"ResNet50\"\n if args.descriptors_dimension is None:\n args.descriptors_dimension = 512\n if args.backbone not in [None, \"ResNet50\"]:\n raise ValueError(\"When using Conv-AP the backbone must be None or ResNet50\")\n if args.descriptors_dimension not in [None, 128, 512, 4096]:\n raise ValueError(\"When using Conv-AP the descriptors_dimension must be one of [None, 128, 512, 4096]\")\n \n elif args.method == \"eigenplaces\":\n if args.backbone is None:\n args.backbone = \"ResNet50\"\n if args.descriptors_dimension is None:\n args.descriptors_dimension = 512\n if args.backbone == \"VGG16\" and args.descriptors_dimension not in [512]:\n raise ValueError(\"When using EigenPlaces with VGG16 the descriptors_dimension must be in [512]\")\n if args.backbone == \"ResNet18\" and args.descriptors_dimension not in [256, 512]:\n raise ValueError(\"When using EigenPlaces with ResNet18 the descriptors_dimension must be in [256, 512]\")\n if args.backbone in [\"ResNet50\", \"ResNet101\", \"ResNet152\"] and args.descriptors_dimension not in [128, 256, 512, 2048]:\n raise ValueError(f\"When using EigenPlaces with {args.backbone} the descriptors_dimension must be in [128, 256, 512, 2048]\")\n \n return args\n\n","repo_name":"gmberton/VPR-methods-evaluation","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5918,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"32189294488","text":"\"\"\"\nFaça um programa que peça ao usuário para digitar um número inteiro,\ninforme se este número é par ou ímpar. Caso o usuário não digite um número\ninteiro, informe que não é um número inteiro.\n\"\"\"\n\n\nnum = input('Entre com um número inteiro: ')\n\n'''\nif num.isdigit():\n num_int = int(num)\n if(num_int % 2 == 0):\n print(f'O número {num_int} é par.')\n else:\n print(f'O número {num_int} é impar.')\nelse:\n print('A entrada não é um número inteiro.')\n'''\ntry:\n num_int = int(num)\n if(num_int % 2 == 0):\n print(f'O número {num_int} é par.')\n else:\n print(f'O número {num_int} é impar.')\nexcept:\n print('A entrada não é um número inteiro.')\n\n\n\"\"\"\nFaça um programa que pergunte a hora ao usuário e, baseando-se no horário \ndescrito, exiba a saudação apropriada. Ex. \nBom dia 0-11, Boa tarde 12-17 e Boa noite 18-23.\n\"\"\"\n\nhora = input('Digite a hora em números inteiros: ')\n\ntry:\n hora_int = int(hora)\n\n if(hora_int >= 18 and hora_int <= 23):\n print('Bom dia!')\n elif (hora_int > 11 and hora_int <= 17):\n print('Boa tarde!')\n else:\n print('Bom dia!')\nexcept:\n print('O valor de entrada não é um número inteiro.')\n\n\"\"\"\nFaça um programa que peça o primeiro nome do usuário. Se o nome tiver 4 letras ou \nmenos escreva \"Seu nome é curto\"; se tiver entre 5 e 6 letras, escreva \n\"Seu nome é normal\"; maior que 6 escreva \"Seu nome é muito grande\". \n\"\"\"\n\nnome = input('Entre com o seu nome: ')\n\nif(len(nome) <= 4):\n print('Seu nome é curto.')\nelif(len(nome) > 6):\n print('Seu nome é muito grande.')\nelse:\n print('Seu nome é normal.')","repo_name":"Vinicius203/OtavioMiranda_Python","sub_path":"Iniciante/aula32.py","file_name":"aula32.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11708013870","text":"class Hashtable:\n def __init__(self):\n self.max = 10\n self.arr = [None for i in range(self.max)]\n\n \n def getHash(self, key):\n h = 0\n for i in key:\n h += ord(i)\n \n return h % self.max\n\n def __setitem__(self, key, value):\n h = self.getHash(key)\n\n if self.arr[h] is None:\n self.arr[h] = (key, value)\n else:\n new_h = self.findSlot(key, h)\n self.arr[new_h] = (key, value)\n\n def __getitem__(self, key):\n h = self.getHash(key)\n prob_range = self.getProbRange(h)\n for i in prob_range:\n if self.arr[i] is None or self.arr[i][0] != key:\n continue\n if self.arr[i][0] == key:\n return self.arr[i][1]\n raise Exception(\"Item not in the list\")\n\n def __delitem__(self, key):\n h = self.getHash(key)\n prob_range = self.getProbRange(h)\n for i in prob_range:\n if self.arr[i] is None or self.arr[i][0] != key:\n continue\n if self.arr[i][0] == key:\n self.arr[i] = None\n return\n raise Exception(\"Item not in the list\")\n\n\n def findSlot(self, key, h):\n prob_range = self.getProbRange(h)\n for i in prob_range:\n if self.arr[i] is None:\n return i\n elif self.arr[i][0] == key:\n return i\n raise Exception(\"List is Full\")\n\n def getProbRange(self, h):\n return [*range(h, len(self.arr))] + [*range(0, h)]\n\nhashobj = Hashtable()\n\nhashobj['march 6'] = 25\nhashobj['march 6'] = 21\nhashobj['march 17'] = 24\nhashobj['march 7'] = 30\n# print(hashobj['march 6'])\n# print(hashobj['march 17'])\n# print(hashobj['march 8'])\nprint(hashobj.arr)\n# del hashobj['march 6']\n# print(hashobj.arr)\n# del hashobj['march 21']\n# print(hashobj.arr)\n","repo_name":"alamgiruk7/DSA","sub_path":"05-1_linear_probing_practice.py","file_name":"05-1_linear_probing_practice.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43204397862","text":"import os\nimport shutil\n\ndef copy_files_from_list(source_dir, destination_dir, file_list):\n # Create the destination directory if it doesn't exist\n os.makedirs(destination_dir, exist_ok=True)\n\n # Read the file list and copy the files\n with open(file_list, \"r\") as file:\n for line in file:\n filename = line.strip() # Remove any leading/trailing whitespaces or newline characters\n file_path = os.path.join(source_dir, filename)\n\n if os.path.isfile(file_path):\n shutil.copy(file_path, destination_dir)\n else:\n print(f\"File '{filename}' not found in the source directory.\")\n\n print(\"File copying completed.\")\n","repo_name":"linyq017/lidar","sub_path":"2.1 Copy_overlap_to_folder.py","file_name":"2.1 Copy_overlap_to_folder.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28666494614","text":"# Chapter 8 \r\n# Exercise 2\r\n\r\n# Define the main function\r\ndef main():\r\n # Input the numbers \r\n numbers = input('Enter numbers with no spaces: ')\r\n # Define total\r\n total = 0\r\n # Add the numbers together\r\n for i in numbers:\r\n total += int(i)\r\n # Print the total\r\n print(total)\r\n# Run the main function\r\nmain()\r\n","repo_name":"matchadieu/programming-with-python","sub_path":"chapter-8/ch8-ex02.py","file_name":"ch8-ex02.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25062658567","text":"INPUT=\"TTGTGTC\"\n\nATGC_MAP = {\n \"A\":\"T\",\n \"T\":\"A\",\n \"G\":\"C\",\n \"C\":\"G\"\n}\n\ndef create_complement(gene):\n result = [ATGC_MAP[char] for char in INPUT[::-1]]\n return \"\".join(result)\n\ndef main():\n complement = create_complement(INPUT)\n print(complement)\n\nif __name__ == \"__main__\":\n main()","repo_name":"mdsung/bioinformatics_workshop","sub_path":"bioinfomatics1/week1/ReverseComplement.py","file_name":"ReverseComplement.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37843061171","text":"import json\nimport logging\nfrom copy import deepcopy\nfrom urllib3 import Retry\nfrom binascii import unhexlify\ntry:\n from json.decoder import JSONDecodeError\nexcept ImportError:\n JSONDecodeError = ValueError\n\nimport requests\nimport datetime as dt\nfrom dateutil import parser\nfrom future.utils import raise_from\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.exceptions import InsecureRequestWarning\n\nfrom polyswarm_api import settings, exceptions\n\nlogger = logging.getLogger(__name__)\n\n\nclass PolyswarmSession(requests.Session):\n def __init__(self, key, retries, user_agent=settings.DEFAULT_USER_AGENT, verify=True, **kwargs):\n super(PolyswarmSession, self).__init__(**kwargs)\n logger.debug('Creating PolyswarmHTTP instance')\n self.requests_retry_session(retries=retries)\n\n if not verify:\n logger.warn('Disabling TLS verification for this session.')\n requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)\n\n self.verify = verify\n\n if key:\n self.set_auth(key)\n\n if user_agent:\n self.set_user_agent(user_agent)\n\n def requests_retry_session(self, retries=settings.DEFAULT_RETRIES, backoff_factor=settings.DEFAULT_BACKOFF,\n status_forcelist=settings.DEFAULT_RETRY_CODES):\n retry = Retry(\n total=retries,\n read=retries,\n connect=retries,\n backoff_factor=backoff_factor,\n status_forcelist=status_forcelist,\n )\n adapter = HTTPAdapter(max_retries=retry)\n self.mount('http://', adapter)\n self.mount('https://', adapter)\n\n def set_auth(self, key):\n if key:\n self.headers.update({'Authorization': key})\n else:\n self.headers.pop('Authorization', None)\n\n def set_user_agent(self, ua):\n if ua:\n self.headers.update({'User-Agent': ua})\n else:\n self.headers.pop('User-Agent', None)\n\n\nclass RequestParamsEncoder(json.JSONEncoder):\n def default(self, obj):\n try:\n return json.JSONEncoder.default(self, obj)\n except Exception:\n return str(obj)\n\n\nclass PolyswarmRequest(object):\n \"\"\"This class holds a requests-compatible dictionary and extra information we need to parse the response.\"\"\"\n def __init__(self, api_instance, request_parameters, key=None, result_parser=None, **kwargs):\n logger.debug('Creating PolyswarmRequest instance.\\nRequest parameters: %s\\nResult parser: %s',\n request_parameters, result_parser.__name__ if result_parser else 'No result parser')\n self.api_instance = api_instance\n # we should not access the api_instance session directly, but provide as a\n # parameter in the constructor, but this will do for the moment\n self.session = self.api_instance.session or PolyswarmSession(key, retries=settings.DEFAULT_RETRIES)\n self.timeout = self.api_instance.timeout or settings.DEFAULT_HTTP_TIMEOUT\n self.request_parameters = request_parameters\n self.result_parser = result_parser\n self.raw_result = None\n self.status_code = None\n self.status = None\n self.errors = None\n self._result = None\n\n self._paginated = False\n self.total = None\n self.limit = None\n self.offset = None\n self.order_by = None\n self.direction = None\n self.has_more = None\n\n self.parser_kwargs = kwargs\n\n def result(self):\n if self._paginated:\n return self.consume_results()\n else:\n return self._result\n\n def execute(self):\n logger.debug('Executing request.')\n self.request_parameters.setdefault('timeout', self.timeout)\n if self.result_parser and not issubclass(self.result_parser, BaseJsonResource):\n self.request_parameters.setdefault('stream', True)\n self.raw_result = self.session.request(**self.request_parameters)\n logger.debug('Request returned code %s', self.raw_result.status_code)\n self.parse_result(self.raw_result)\n return self\n\n def _bad_status_message(self):\n request_parameters = json.dumps(self.request_parameters, indent=4, sort_keys=True, cls=RequestParamsEncoder)\n message = \"Error when running the request:\\n{}\\n\" \\\n \"Return code: {}\\n\" \\\n \"Message: {}\".format(request_parameters,\n self.status_code,\n self._result)\n if self.errors:\n message = '{}\\nErrors:\\n{}'.format(message, '\\n'.join(str(error) for error in self.errors))\n return message\n\n def _extract_json_body(self, result):\n self.json = result.json()\n self._result = self.json.get('result')\n self.status = self.json.get('status')\n self.errors = self.json.get('errors')\n\n def parse_result(self, result):\n self.status_code = result.status_code\n if self.request_parameters['method'] == 'HEAD':\n logger.debug('HEAD method does not return results, setting it to the status code.')\n self._result = self.status_code\n if not self.result_parser:\n logger.debug('Result parser is not defined, skipping parsing results.')\n return\n logger.debug('Parsing request results.')\n try:\n if self.status_code // 100 != 2:\n self._extract_json_body(result)\n if self.status_code == 429:\n message = '{} This may mean you need to purchase a ' \\\n 'larger package, or that you have exceeded ' \\\n 'rate limits. If you continue to have issues, ' \\\n 'please contact us at info@polyswarm.io.'.format(self._result)\n raise exceptions.UsageLimitsExceededException(self, message)\n elif self.status_code == 404:\n raise exceptions.NotFoundException(self, self._result)\n else:\n raise exceptions.RequestException(self, self._bad_status_message())\n elif self.status_code == 204:\n raise exceptions.NoResultsException(self, 'The request returned no results.')\n elif issubclass(self.result_parser, BaseJsonResource):\n self._extract_json_body(result)\n if self.request_parameters['method'] == 'GET' and 'has_more' in self.json:\n # has_more will always be present, being either False or True\n self._paginated = True\n self.total = self.json.get('total')\n self.limit = self.json.get('limit')\n self.offset = self.json.get('offset')\n self.order_by = self.json.get('order_by')\n self.direction = self.json.get('direction')\n self.has_more = self.json.get('has_more')\n if 'result' in self.json:\n result = self.json['result']\n elif 'results' in self.json:\n result = self.json['results']\n else:\n raise exceptions.RequestException(\n self,\n 'The response standard must contain either the \"result\" or \"results\" key.'\n )\n if isinstance(result, list):\n self._result = self.result_parser.parse_result_list(self.api_instance, result, **self.parser_kwargs)\n else:\n self._result = self.result_parser.parse_result(self.api_instance, result, **self.parser_kwargs)\n else:\n self._result = self.result_parser.parse_result(self.api_instance, result, **self.parser_kwargs)\n except JSONDecodeError as e:\n if self.status_code == 404:\n raise raise_from(exceptions.NotFoundException(self, 'The requested endpoint does not exist.'), e)\n else:\n err_msg = 'Server returned non-JSON response [{}]: {}'.format(self.status_code, result)\n raise raise_from(exceptions.RequestException(self, err_msg), e)\n\n def __iter__(self):\n return self.consume_results()\n\n def consume_results(self):\n # StopIteration is deprecated\n # As per https://www.python.org/dev/peps/pep-0479/\n # We simply return upon termination condition\n request = self\n while True:\n # consume items from list if iterable\n # of yield the single result if not\n try:\n for result in request._result:\n yield result\n except TypeError:\n yield request._result\n # if the result is not a list, there is not next page\n return\n\n # if the server indicates that there are no more results, return\n if not request.has_more:\n return\n # try to get the next page and execute the request\n request = request.next_page()\n\n def next_page(self):\n new_parameters = deepcopy(self.request_parameters)\n params = new_parameters.setdefault('params', {})\n if isinstance(params, dict):\n params['offset'] = self.offset\n params['limit'] = self.limit\n else:\n params = [p for p in params if p[0] != 'offset' and p[0] != 'limit']\n params.extend([('offset', self.offset), ('limit', self.limit)])\n new_parameters['params'] = params\n return PolyswarmRequest(\n self.api_instance,\n new_parameters,\n result_parser=self.result_parser,\n ).execute()\n\n\nclass BaseResource(object):\n def __init__(self, content, *args, **kwargs):\n # hack to behave as in python 3, signature should be\n # __init__(self, content, *args, api=None, **kwargs)\n api = kwargs.pop('api', None)\n super(BaseResource, self).__init__(*args, **kwargs)\n self.api = api\n self._content = content\n\n @classmethod\n def parse_result(cls, api, content, **kwargs):\n logger.debug('Parsing resource %s', cls.__name__)\n return cls(content, api=api, **kwargs)\n\n\nclass BaseJsonResource(BaseResource):\n RESOURCE_ENDPOINT = None\n RESOURCE_ID_KEYS = ['id']\n\n def __init__(self, content, *args, **kwargs):\n super(BaseJsonResource, self).__init__(content, *args, **kwargs)\n self.json = content\n\n def __int__(self):\n id_ = getattr(self, 'id', None)\n if id_ is None:\n raise TypeError('Resource {} does not have an id and can not be cast to int'.format(type(self).__name__))\n return int(id_)\n\n def _get(self, path, default=None, content=None):\n \"\"\"\n Helper for rendering attributes of child objects in the json that might be None.\n Returns the default value if any item in the path is not present.\n \"\"\"\n previous_attribute = 'resource_json'\n obj = content or self.json\n try:\n for attribute in path.split('.'):\n if obj is None:\n raise KeyError('{} is None, can not resolve full path'.format(previous_attribute))\n if attribute.endswith(']'):\n # handling the list case, e.g.: \"root.list_attr[2]\"\n attribute, _, index = attribute.rpartition('[')\n index = int(index.rstrip(']'))\n obj = obj[attribute]\n if obj is None:\n raise KeyError('{} is None, but is it supposed to be a list'.format(attribute))\n elif not isinstance(obj, list):\n raise ValueError('Can not access index for {}, it is not a list.'.format(attribute))\n else:\n obj = obj[index]\n else:\n obj = obj[attribute]\n previous_attribute = attribute\n return obj\n except (KeyError, IndexError) as e:\n logger.debug('Returning default value: %s', e)\n return default\n\n @classmethod\n def parse_result_list(cls, api_instance, json_data, **kwargs):\n return [cls.parse_result(api_instance, entry, **kwargs) for entry in json_data]\n\n @classmethod\n def _endpoint(cls, api, **kwargs):\n if cls.RESOURCE_ENDPOINT is None:\n raise exceptions.InvalidValueException('RESOURCE_ENDPOINT is not configured for this resource.')\n return '{api.uri}{endpoint}'.format(api=api, endpoint=cls.RESOURCE_ENDPOINT, **kwargs)\n\n @classmethod\n def _list_endpoint(cls, api, **kwargs):\n return cls._endpoint(api, **kwargs) + '/list'\n\n @classmethod\n def _create_endpoint(cls, api, **kwargs):\n return cls._endpoint(api, **kwargs)\n\n @classmethod\n def _get_endpoint(cls, api, **kwargs):\n return cls._endpoint(api, **kwargs)\n\n @classmethod\n def _head_endpoint(cls, api, **kwargs):\n return cls._endpoint(api, **kwargs)\n\n @classmethod\n def _update_endpoint(cls, api, **kwargs):\n return cls._endpoint(api, **kwargs)\n\n @classmethod\n def _delete_endpoint(cls, api, **kwargs):\n return cls._endpoint(api, **kwargs)\n\n @classmethod\n def _params(cls, method, *param_keys, **kwargs):\n params = {}\n json_params = {}\n for k, v in kwargs.items():\n if v is not None:\n # try to parse \"*_id\" stuff as integer\n if k == 'id' or k.endswith('_id'):\n try:\n parsed_value = str(int(v))\n except Exception:\n # fallback to string\n parsed_value = str(v)\n elif isinstance(v, bool):\n parsed_value = int(v)\n else:\n parsed_value = v\n if method == 'POST':\n json_params[k] = parsed_value\n elif method == 'GET' or k in param_keys:\n params[k] = parsed_value\n else:\n json_params[k] = parsed_value\n\n params = params if params else None\n json_params = json_params if json_params else None\n return params, json_params\n\n @classmethod\n def _list_params(cls, **kwargs):\n return cls._params('GET', *cls.RESOURCE_ID_KEYS, **kwargs)\n\n @classmethod\n def _create_params(cls, **kwargs):\n return cls._params('POST', *cls.RESOURCE_ID_KEYS, **kwargs)\n\n @classmethod\n def _get_params(cls, **kwargs):\n return cls._params('GET', *cls.RESOURCE_ID_KEYS, **kwargs)\n\n @classmethod\n def _head_params(cls, **kwargs):\n return cls._params('HEAD', *cls.RESOURCE_ID_KEYS, **kwargs)\n\n @classmethod\n def _update_params(cls, **kwargs):\n return cls._params('PUT', *cls.RESOURCE_ID_KEYS, **kwargs)\n\n @classmethod\n def _delete_params(cls, **kwargs):\n return cls._params('DELETE', *cls.RESOURCE_ID_KEYS, **kwargs)\n\n @classmethod\n def _list_headers(cls, api):\n return None\n\n @classmethod\n def _create_headers(cls, api):\n return None\n\n @classmethod\n def _get_headers(cls, api):\n return None\n\n @classmethod\n def _head_headers(cls, api):\n return None\n\n @classmethod\n def _update_headers(cls, api):\n return None\n\n @classmethod\n def _delete_headers(cls, api):\n return None\n\n @classmethod\n def _build_request(cls, api, method, url, headers, params, json_params):\n request_params = {'method': method, 'url': url}\n if params:\n request_params['params'] = params\n if json_params:\n request_params['json'] = json_params\n if headers:\n request_params['headers'] = headers\n return PolyswarmRequest(api, request_params, result_parser=cls)\n\n @classmethod\n def create(cls, api, **kwargs):\n return cls._build_request(api, 'POST', cls._create_endpoint(api, **kwargs),\n cls._create_headers(api), *cls._create_params(**kwargs)).execute()\n\n @classmethod\n def get(cls, api, **kwargs):\n return cls._build_request(api, 'GET', cls._get_endpoint(api, **kwargs),\n cls._get_headers(api), *cls._get_params(**kwargs)).execute()\n\n @classmethod\n def head(cls, api, **kwargs):\n return cls._build_request(api, 'HEAD', cls._head_endpoint(api, **kwargs),\n cls._head_headers(api), *cls._head_params(**kwargs)).execute()\n\n @classmethod\n def update(cls, api, **kwargs):\n return cls._build_request(api, 'PUT', cls._update_endpoint(api, **kwargs),\n cls._update_headers(api), *cls._update_params(**kwargs)).execute()\n\n @classmethod\n def delete(cls, api, **kwargs):\n return cls._build_request(api, 'DELETE', cls._delete_endpoint(api, **kwargs),\n cls._delete_headers(api), *cls._delete_params(**kwargs)).execute()\n\n @classmethod\n def list(cls, api, **kwargs):\n return cls._build_request(api, 'GET', cls._list_endpoint(api, **kwargs),\n cls._list_headers(api), *cls._list_params(**kwargs)).execute()\n\n\ndef is_hex(value):\n try:\n _ = int(value, 16)\n return True\n except ValueError:\n return False\n\n\ndef is_valid_sha1(value):\n if len(value) != 40:\n return False\n return is_hex(value)\n\n\ndef is_valid_md5(value):\n if len(value) != 32:\n return False\n return is_hex(value)\n\n\ndef is_valid_sha256(value):\n if len(value) != 64:\n return False\n return is_hex(value)\n\n\nclass Hashable(object):\n SUPPORTED_HASH_TYPES = {\n 'sha1': is_valid_sha1,\n 'sha256': is_valid_sha256,\n 'md5': is_valid_md5,\n }\n\n def __init__(self, *args, **kwargs):\n # hack to behave as in python 3, signature should be\n # __init__(self, content, *args, hash_value=None, hash_type=None, validate_hash=False, **kwargs)\n hash_value = kwargs.pop('hash_value', None)\n hash_type = kwargs.pop('hash_type', None)\n validate_hash = kwargs.pop('validate_hash', False)\n super(Hashable, self).__init__(*args, **kwargs)\n\n self._hash = hash_value.strip() if hash_value is not None else None\n\n if hash_type:\n if hash_type not in self.SUPPORTED_HASH_TYPES:\n raise exceptions.InvalidValueException('Hash type provided is not supported.')\n self._hash_type = hash_type\n else:\n self._hash_type = self.resolve_hash_type()\n\n if self._hash_type is None:\n raise exceptions.InvalidValueException('Invalid hash provided: {}'.format(self._hash))\n\n if validate_hash:\n self.validate()\n\n @property\n def hash(self):\n return self._hash\n\n @hash.setter\n def hash(self, value):\n self._hash = value.strip() if value is not None else None\n\n @property\n def hash_type(self):\n return self._hash_type\n\n def validate(self):\n hash_type = self.resolve_hash_type()\n if self.hash_type != hash_type:\n raise exceptions.InvalidValueException('Detected hash type {}, got type {} for hash {}'\n .format(hash_type, self.hash_type, self.hash))\n\n def resolve_hash_type(self):\n for hash_type, validator in self.SUPPORTED_HASH_TYPES.items():\n if validator(self._hash):\n return hash_type\n return None\n\n @property\n def raw(self):\n return unhexlify(self.hash)\n\n def __eq__(self, other):\n return self.hash == other\n\n\ndef parse_isoformat(date_string):\n \"\"\"Parses the current date format version \"\"\"\n if isinstance(date_string, (dt.date, dt.datetime)):\n return date_string\n elif date_string:\n return parser.isoparse(date_string)\n else:\n return None\n","repo_name":"polyswarm/polyswarm-api","sub_path":"src/polyswarm_api/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":20066,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"20585325910","text":"'''\n백준 9935번\n문자열 폭발\n'''\n\na = input()\nb = input()\n\n\nres = \"\"\n\ni = 0\nl = \"\"\nst = []\n\ndef check():\n if len(st) >= len(b):\n for i in range(1,len(b)+1):\n if st[-i] != b[-i]:\n return False\n return True\n else:\n return False \n\nwhile True:\n if i >= len(a):\n break\n st.append(a[i])\n if check():\n for _ in range(len(b)):\n st.pop()\n \n i+=1\n\nif len(st)==0:\n print(\"FRULA\")\nfor v in st:\n print(v,end='')\n","repo_name":"tjddls1124/Algorithm","sub_path":"baekjoon/baek9935.py","file_name":"baek9935.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33321910831","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split as split\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import confusion_matrix as confusion\n\n# import\nbc = datasets.load_wine()\nX = bc.data;\nY = bc.target;\n\n# classify\ny1 = Y*0\ny2 = Y*0\ny3 = Y*0\n\ny1[np.argwhere(Y==0)] = 1\ny2[np.argwhere(Y==1)] = 1\ny3[np.argwhere(Y==2)] = 1\n\nY1 = np.asarray([y1,y2,y3]).T\n\n# split\nx_train, x_test, y_train, y_test = split(X, Y1, test_size = 0.1, random_state = 1)\n\n# Layers\nann = tf.keras.models.Sequential()\nann.add(tf.keras.layers.Dense(units=3))\nann.add(tf.keras.layers.Dense(units=3))\n\n# compile\nepoc = 1500\nann.compile(optimizer='adam', loss='mean_squared_error')\nv = ann.fit(x_train, y_train, epochs = epoc, verbose = 0)\nres = ann.predict(x_test)\n\nloss = v.history['loss']\nplt.plot(np.arange(1500), loss)\nprint(\"loss = \", loss[-1])\nprint(\"mse = \", mse(y_test, np.round(res)))\n","repo_name":"eladyesh/Machine_Learning","sub_path":"classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32799106725","text":"import os\nimport argparse\nimport asyncio\nfrom dotenv import load_dotenv\nload_dotenv()\nfrom starkboard.utils import RepeatedTimer, StarkboardDatabase, Requester\nfrom starkboard.events.events import get_events, BlockEventsParser\nfrom starkboard.transactions import transactions_in_block, get_transfer_transactions_in_block#, get_swap_info_in_block\nfrom starkboard.user import count_wallet_deploy_in_block, get_active_wallets_in_block\nfrom starkboard.contracts import count_contract_deployed_in_block, get_declared_class_in_block\nfrom starkboard.constants import EVENT_KEYS_RETAINER\nfrom starkboard.tokens import get_eth_total_supply, get_balance_of\nfrom starkboard.fees import get_fees_in_block\nfrom monitor import monitor_deployed_contracts\nimport signal\nfrom datetime import datetime\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-t\", \"--transfer_catching\", help=\"Boolean to execute transfer count pipeline\", required=False)\nparser.add_argument(\"-b\", \"--block_data\", help=\"Boolean to execute block data pipeline\", required=False)\nparser.add_argument(\"-from\", \"--fromBlock\", help=\"From Block\", required=False)\nparser.add_argument(\"-to\", \"--toBlock\", help=\"To Block\", required=False)\nparser.add_argument(\"-n\", \"--network\", help=\"Network to target\", required=False)\n\ndef fetch_checkpoint(db):\n res = db.get_checkpoint_block()\n return res['block_number']\n\n\n######################################################################\n# Block & Tx Fetcher #\n######################################################################\n\nlast_checked_block = int(os.environ.get(\"STARTING_BLOCK_FETCHER\", 0))\n\ndef block_tx_fetcher(block_id, node, db, loop):\n print(\"---\")\n current_block = transactions_in_block(block_id, starknet_node=node)\n if 'code' in current_block:\n print(\"Still same block...\")\n return None, None, None, None, None, None, block_id - 1\n events = get_events(block_id, starknet_node=node)\n wallet_deployed = count_wallet_deploy_in_block(events)\n contract_deployed = count_contract_deployed_in_block(current_block['transactions'])\n transfer_executed = get_transfer_transactions_in_block(events)\n fees = get_fees_in_block(current_block['transactions'], starknet_node=node)\n active_wallets = get_active_wallets_in_block(current_block['transactions'])\n print(\"Here\")\n print(f'Fetched Block {current_block[\"block_number\"]} at {datetime.fromtimestamp(current_block[\"timestamp\"])}')\n print(f'> {len(current_block[\"transactions\"])} Txs found in block.')\n print(f'> {wallet_deployed[\"deployed_wallets\"]} User Wallet created in block.')\n print(f'> {contract_deployed[\"count_deployed_contracts\"]} Contract deployed in block.')\n print(f'> {transfer_executed[\"count_transfer\"]} Transfer executed in block.')\n print(f'> {fees[\"total_fees\"]} Total fees in block.')\n print(f'> {fees[\"mean_fees\"]} Average fees in block.')\n print(f'> {active_wallets[\"count_active_wallets\"]} Active wallets found in block.')\n get_declared_class_in_block(current_block['transactions'], node, db)\n monitor_deployed_contracts(current_block['transactions'], current_block['timestamp'], node, db, loop)\n filtered_events = list(filter(lambda x: int(x['from_address'], 16) != int(\"0x12fadd18ec1a23a160cc46981400160fbf4a7a5eed156c4669e39807265bcd4\", 16), events))\n block_events_parser = BlockEventsParser(filtered_events, current_block['timestamp'], fees['fee_per_tx'], node, db, loop)\n formatted_events = list(filter(lambda x: x['event_key'] in EVENT_KEYS_RETAINER, block_events_parser.events))\n db.insert_events_bulk(formatted_events)\n# get_transactions_info_in_block # get the different events counts and fees\n# get_swap_info_in_block(current_block[\"timestamp\"], events, node, db, loop)\n return current_block, wallet_deployed, contract_deployed, transfer_executed, fees, active_wallets, current_block[\"block_number\"]\n\n\ndef block_aggreg_fetcher(db, node):\n global last_checked_block\n print(f'Checking next block {last_checked_block + 1}')\n try:\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n current_block, wallet_deployed, contract_deployed, transfer_executed, fees, active_wallets, current_block_number = block_tx_fetcher(last_checked_block + 1, node, db, loop)\n loop.close()\n if not current_block:\n print(\"Connection timed out, retrying...\")\n return True\n except Exception as e:\n print(e)\n print(\"Connection timed out, retrying...\")\n return True\n block_data = {\n \"block_number\": current_block[\"block_number\"],\n \"timestamp\": datetime.fromtimestamp(current_block[\"timestamp\"]).strftime('%Y-%m-%d %H:%M:%S'),\n \"full_day\": datetime.fromtimestamp(current_block[\"timestamp\"]).strftime('%Y-%m-%d'),\n \"count_txs\": len(current_block[\"transactions\"]),\n \"count_new_wallets\": wallet_deployed[\"deployed_wallets\"],\n \"count_new_contracts\": contract_deployed[\"count_deployed_contracts\"],\n \"count_transfers\": transfer_executed[\"count_transfer\"],\n \"total_fees\": fees[\"total_fees\"],\n \"mean_fees\": fees[\"mean_fees\"],\n \"wallets_active\": active_wallets['wallets_active']\n }\n insert_res = db.insert_block_data(block_data)\n if insert_res:\n print(\"Block Inserted !\")\n last_checked_block = current_block_number\n else:\n print(\"Error Inserting Block. Retrying\")\n return True\n\n######################################################################\n# TVL, ERC20 & ETH data #\n######################################################################\n\nasync def ethereum_stats():\n \"\"\"\n Getting Ethereum Statistics on Starknet\n \"\"\"\n await get_eth_total_supply()\n\n\n######################################################################\n# User Data #\n######################################################################\n\nasync def get_wallets_balance():\n with open(\"testnet_wallets.txt\") as file:\n for address in file:\n bal = await get_balance_of(address, \"ETH\")\n print(f'Wallet {address} has {bal} ETH')\n\n\ndef handler(signum, frame):\n rt.stop()\n res = input(\"Ctrl-c was pressed. Do you really want to exit? y/n \")\n if res == 'y':\n exit(1)\n else:\n rt.start()\n \nsignal.signal(signal.SIGINT, handler)\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n if args.network == \"mainnet\":\n delay = 30\n starknet_node = Requester(os.environ.get(\"STARKNET_NODE_URL_MAINNET\"), headers={\"Content-Type\": \"application/json\"})\n starknet_sequencer = Requester(os.environ.get(\"STARKNET_FEEDER_GATEWAY_URL_MAINNET\"), headers={\"Content-Type\": \"application/json\"})\n else:\n starknet_node = Requester(os.environ.get(\"STARKNET_NODE_URL\"), headers={\"Content-Type\": \"application/json\"})\n starknet_sequencer = Requester(os.environ.get(\"STARKNET_FEEDER_GATEWAY_URL\"), headers={\"Content-Type\": \"application/json\"})\n delay = 5\n starkboard_db = StarkboardDatabase(args.network)\n if args.block_data:\n last_checked_block = fetch_checkpoint(starkboard_db)\n rt = RepeatedTimer(delay, block_aggreg_fetcher, starkboard_db, starknet_node)\n","repo_name":"StarkBoard/starkboard-back","sub_path":"fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":7352,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"2545480949","text":"import abc\nimport uuid\nimport base64\nimport datetime\nfrom dataclasses import dataclass\nfrom typing import Tuple, Any, List\nfrom server_protocol import SignupRequest\n\n\nclass StorageLayerException(Exception):\n ...\n\n\nclass StorageLayer(abc.ABC):\n @abc.abstractmethod\n def get_user_by_id(\n self, identifier: str\n ) -> Tuple[uuid.UUID, str, str, datetime.datetime]:\n \"\"\"\n :param identifier: user_id\n :return: user_id, name, public_key and last_seen_time\n \"\"\"\n ...\n\n @abc.abstractmethod\n def check_if_user_exists(self, identifier: str) -> bool:\n ...\n\n @abc.abstractmethod\n def create_new_user(self, name: str, public_key: str) -> str:\n ...\n\n @abc.abstractmethod\n def get_message_list_for_user(\n self, identifier: str\n ) -> List[Tuple[str, str, str, int, bytes]]:\n ...\n\n @abc.abstractmethod\n def get_user_id_list(self, id_to_ignore: str) -> List[str]:\n ...\n\n @abc.abstractmethod\n def send_message(self, sender, receiver, message_type, content) -> str:\n ...\n\n @abc.abstractmethod\n def update_user_last_seen(self, user_id) -> None:\n ...\n\n @abc.abstractmethod\n def close_connection(self) -> None:\n ...\n\n\n@dataclass\nclass Message:\n message_id: str\n source: uuid.UUID\n destination: uuid.UUID\n message_type: int\n content: bytes\n\n\nclass User:\n def __init__(\n self,\n identifier: uuid.UUID,\n name: str,\n public_key: str,\n last_seen: datetime.datetime,\n ) -> None:\n self._id = identifier\n self._name = name\n self._public_key = base64.b64decode(public_key)\n self._last_seen = last_seen\n\n @staticmethod\n def get_user_by_id(storage_layer: StorageLayer, user_id: str) -> Any:\n if not storage_layer.check_if_user_exists(user_id):\n raise StorageLayerException(f\"User {user_id} does not exist!\")\n return User(*storage_layer.get_user_by_id(user_id))\n\n @staticmethod\n def create_new_user(storage_layer: StorageLayer, request: SignupRequest) -> Any:\n new_id = storage_layer.create_new_user(\n name=request.name.decode(),\n public_key=base64.b64encode(request.pub_key).decode(),\n )\n return User.get_user_by_id(storage_layer, new_id)\n\n def get_all_messages(self, storage_layer: StorageLayer) -> List[Message]:\n messages: List[Message] = []\n for (\n message_id,\n source,\n destination,\n message_type,\n content,\n ) in storage_layer.get_message_list_for_user(self.id):\n messages.append(\n Message(\n message_id,\n uuid.UUID(hex=str(source)),\n uuid.UUID(hex=str(destination)),\n message_type,\n content,\n )\n )\n return messages\n\n def send_message(\n self,\n storage_layer: StorageLayer,\n sender: str,\n message_type: int,\n content: bytes,\n ) -> str:\n message_id = storage_layer.send_message(sender, self.id, message_type, content)\n return message_id\n\n @property\n def id(self) -> str:\n return str(self._id).replace(\"-\", \"\")\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def public_key(self) -> str:\n return self._public_key\n\n @property\n def last_seen(self) -> str:\n return self._last_seen\n\n\nclass UserList:\n @staticmethod\n def get_user_list(storage_layer: StorageLayer, user_to_ignore: str) -> List[User]:\n users: List[User] = []\n for user_id in storage_layer.get_user_id_list(user_to_ignore):\n users.append(User.get_user_by_id(storage_layer, user_id))\n return users\n","repo_name":"nikosokolik/defensive_programing_project","sub_path":"server/storage/storage_layer.py","file_name":"storage_layer.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9699415079","text":"import sys\r\n\r\n\r\ndef eingabe_wichtige_daten():\r\n # Eingabe aller wichtigen Daten\r\n daten_temp = [input(\"Vorname?: \"), input(\"Nachname?: \"), \"\", \"\"]\r\n\r\n while type(daten_temp[2]) != int:\r\n try:\r\n daten_temp[2] = (int(input(\"Alter?: \")))\r\n break\r\n except ValueError:\r\n print(\"Die Eingabe ist kein Integer\")\r\n\r\n daten_temp[3] = (input(\"Wohnort?: \"))\r\n\r\n return daten_temp\r\n\r\n\r\ndef abfragePersönlicheDaten():\r\n firmaCodingStar = \"\"\r\n AGB = \"\"\r\n\r\n AlleDaten = eingabe_wichtige_daten()\r\n\r\n # Ist egal ob groß oder klein\r\n if AlleDaten[3].lower() == \"löhne\":\r\n # Fragen nur stellen, wenn man in Löhne wohnt\r\n firmaCodingStar = input(\"Kennen Sie die Firma Coding Star?: \")\r\n if firmaCodingStar.lower() == \"ja\":\r\n firmaCodingStar = True\r\n elif firmaCodingStar.lower() == \"nein\":\r\n firmaCodingStar = False\r\n else:\r\n print(\"Keine gültige Eingabe\")\r\n sys.exit(0)\r\n\r\n AGB = input(\"Waren Sie auf dem August-Griese-Berufskolleg?: \")\r\n if AGB.lower() == \"ja\":\r\n AGB = True\r\n elif AGB.lower() == \"nein\":\r\n AGB = False\r\n else:\r\n print(\"Keine gültige Eingabe\")\r\n sys.exit(0)\r\n\r\n # Ausgabe abhängig von der Antwort oben\r\n print(f\"\\n{AlleDaten[0]} {AlleDaten[1]} wohnt in {AlleDaten[3]} und ist {AlleDaten[2]} Jahre alt\")\r\n if AlleDaten[3].lower() == \"löhne\":\r\n if firmaCodingStar:\r\n firmaCodingStar = \"Ja\"\r\n elif not firmaCodingStar:\r\n firmaCodingStar = \"Nein\"\r\n if AGB:\r\n AGB = \"Ja\"\r\n elif not AGB:\r\n AGB = \"Nein\"\r\n\r\n print(f\"Kennt Coding Star?: {firmaCodingStar}\")\r\n print(f\"War auf dem AGB?: {AGB}\")\r\n","repo_name":"Sevynidd/GrundlagenDerProgrammierung","sub_path":"Aufgabe1PersoenlicheDaten.py","file_name":"Aufgabe1PersoenlicheDaten.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7262619313","text":"from PIL import Image\nimport numpy as np\nimport scipy.stats as stats\n\n\n\n\ndef dilation(image):\n width, height = image.size\n aperture_size = 3\n new_image = Image.new('P', (width, height)) \n s2 = aperture_size // 2\n matrix_image = np.array(image, dtype = 'uint32')\n for i in range(height):\n for j in range(width):\n x1 = j - s2\n x2 = j + s2\n y1 = i - s2\n y2 = i + s2\n \n if (x1 < 0):\n x1 = 0\n \n if (x2 >= width):\n x2 = width - 1\n \n if (y1 < 0):\n y1 = 0\n \n if (y2 >= height):\n y2 = height - 1\n \n aperture = matrix_image[y1:y2+1,x1:x2+1]\n value = max(aperture.flatten())\n new_image.putpixel((j, i), int(value))\n return new_image\n\n\n\ndef erosion(image):\n width, height = image.size\n aperture_size = 3\n new_image = Image.new('P', (width, height)) \n s2 = aperture_size // 2\n matrix_image = np.array(image, dtype = 'uint32')\n for i in range(height):\n for j in range(width):\n x1 = j - s2\n x2 = j + s2\n y1 = i - s2\n y2 = i + s2\n \n if (x1 < 0):\n x1 = 0\n \n if (x2 >= width):\n x2 = width - 1\n \n if (y1 < 0):\n y1 = 0\n \n if (y2 >= height):\n y2 = height - 1\n \n aperture = matrix_image[y1:y2+1,x1:x2+1]\n value = min(aperture.flatten())\n new_image.putpixel((j, i), int(value))\n return new_image\n\n\n\ndef closing(image):\n new_image = dilation(image)\n return erosion(new_image)\n\n\n\ndef different(image, new_image):\n width, height = image.size\n dif_image = Image.new('P', (width, height))\n for x in range(width):\n for y in range(height):\n dif_image.putpixel((x, y), abs(image.getpixel((x,y)) - new_image.getpixel((x,y))))\n return dif_image\n \n\n\ndef main():\n text_image = Image.open(\"pictures/new_text.bmp\")\n new_image = closing(text_image)\n new_image.save(\"pictures/closing_text.bmp\")\n new_image.show()\n text_differ = different(text_image, new_image)\n text_differ.save(\"pictures/text_differ.bmp\")\n text_differ.show()\n Disgusting_Men = Image.open(\"pictures/newDisgustingMen.bmp\")\n new_Disgusting_Men = closing(Disgusting_Men)\n new_Disgusting_Men.save(\"pictures/closingDisgustingMen.bmp\")\n new_Disgusting_Men.show()\n Disgusting_Men_differ = different(Disgusting_Men, new_Disgusting_Men)\n Disgusting_Men_differ.save(\"pictures/DisgustingMenDiffer.bmp\")\n Disgusting_Men_differ.show()\n woman_picture = Image.open(\"pictures/woman_picture.bmp\")\n new_woman_picture = closing(woman_picture)\n new_woman_picture.save(\"pictures/closingwoman_picture.bmp\")\n new_woman_picture.show()\n woman_picture_differ = different(woman_picture, new_woman_picture)\n woman_picture_differ.save(\"pictures/woman_picture_differ.bmp\")\n woman_picture_differ.show()\n\nif __name__ == \"__main__\":\n main()","repo_name":"Kron610/ProcessVisAudioInf","sub_path":"Laba2/Laba2.py","file_name":"Laba2.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8590588833","text":"#\n# Algorithm implementing the wave equation\n# with external potential\n#\n#\n\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\n''' potentials '''\n\ndef tort2schw_root(rst, M=1, acc=1e-14, maxit=100):\n \"\"\"\n Return r(r*) using a root finder\n :rst: a point of the grid.\n \"\"\"\n\n tm = 2. * M\n ootm = 1. / tm\n rmin = (2. + acc) * M\n # initial guess for the solution\n if rst < 0.:\n ro = rmin + 0.001\n elif rst < 4. * M:\n ro = 4.1 * M\n elif rst > 4. * M:\n ro = rst * M\n else:\n # rst == 4.*M\n return rst\n #\n\n\n for i in np.arange(maxit):\n # recursive algorithm\n # r* = r + 2 * G * M ln(-1. + r/2GM)\n rn = ro - ((tm - ro) * (rst - ro - tm * np.log(-1. + ro * ootm))) / ro\n rn = max(rn, rmin)\n delta = np.fabs(rn - ro)\n if np.fabs(delta) < acc:\n return rn\n ro = rn\n return -1\ndef tort2schw(rs, M=1., acc=1e-14, maxit=100):\n \"\"\"\n :rs: array. Radial grid.\n Return r(r*) using a root finder\n \"\"\"\n if M <= 0.:\n # if the space-time is flat, the schw radius = tort radius\n return rs\n r = np.zeros_like(rs)\n for i in np.arange(len(rs)):\n r[i] = tort2schw_root(rs[i], M, acc, maxit)\n return r\ndef rwz_potential(xarr, ell = 2, l=2, M=1.):\n \"\"\"\n Potential is defined for Swarchild coordinates.\n It exist as an 'odd' and 'eve' potential, Vo, Ve\n First the coorinate transformation is required\n :ell: ellepticity\n :param xarr: tortous coordinates\n :param l: multipole\n :param M: mass of a BH\n :return: v\n \"\"\"\n\n r = tort2schw(xarr, M=M) # swarchild coordinates\n\n if M == 0.:\n # flat space-time\n return np.zeros(len(xarr))#, np.zeros_like(xarr)\n\n lam = l * (l + 1.)\n lamm2 = lam - 2.\n lamm2sq = lamm2 ** 2\n r2 = r ** 2\n r3 = r2 * r\n oor = 1. / r\n oor2 = oor ** 2\n oor3 = oor ** 3\n A = (1. - 2. * M * oor)\n Ve = - A * (lam * lamm2sq * r3 + 6.0 * lamm2sq * M * r2 + 36. * lamm2 * M ** 2 * r + 72. * M ** 3) / (\n r3 * (lamm2 * r + 6. * M) ** 2)\n #\n Vo = - A * (lam * oor2 - 6. * M * oor3)\n\n if ell % 2 == 0:\n V = Ve\n else:\n V = Vo\n\n return V\n\ndef pw_potential(xarr, m=1.):\n\n beta = 0#1j * 1 * np.pi / 2\n kappa = 0.1#0.1\n v0 = 0.15#0.15\n V = v0 * ((np.exp(kappa * xarr + beta) - np.exp(-kappa * xarr - beta)) /\n (np.exp(kappa * xarr + beta) + np.exp(-kappa * xarr - beta))) ** 2 - v0\n\n return V\n\n''' initial data '''\n\ndef gaussian_packet(x, Rps, dsigma, timesym=0.):\n \"\"\"\n Gaussian packet initial data\n \"\"\"\n d2sigma = dsigma * dsigma\n norm = dsigma / np.sqrt(2.0 * np.pi)\n gauss = norm * np.exp(-0.5 * d2sigma * (x - Rps) ** 2)\n dgauss = -(x - Rps) * d2sigma * gauss * timesym\n return gauss, dgauss\n\n''' other '''\n\ndef retime(t, rs, M=1.):\n \"\"\"\n Retarded time\n \"\"\"\n if M == 0.:\n # for flat space-time\n return t\n return 0.5 * (t - rs) / M\n\ndef output_detector(fname, time, z):\n \"\"\"\n Output wave at detector,\n append if file exists\n use index instead of radius for convergence studies)\n \"\"\"\n with open(fname, 'a') as f:\n np.savetxt(f, np.c_[time, z], fmt='%.9e')\n return\n\ndef output_solution(fname, time, rs, z, di, ng=2):\n \"\"\"\n Output solution at given time,\n append if file exists\n \"\"\"\n with open(fname, 'a') as f:\n # resample excluding ghosts, assume ng\n np.savetxt(f, np.c_[rs[ng:-ng:di], z[ng:-ng:di]], fmt='%.9e', header=\"time = %.6e\" % time, comments='\"')\n # f.write(b'\\n\\n')\n return\n\n''' solver '''\n\nclass WaveEqSolver:\n\n def __init__(self, xmin=-300., xmax=300., nr=401, cfl=0.5, tend=600., mass=0.,\n indexdet=(0,200,400), itout=(1,10), isout=2,\n stencilorder=4, potential=\"RWZ\", initdata=\"Gauss\", outdir=\"./wave/\"):\n #\n # xmin = -300. # coord min\n # xmax = 300. # coord max\n # nr = 401 # phyiscal points\n # cfl = 0.5 # dt/dr\n # tend = 600. # end of the evolution time\n # outdir = \"./ex6/\"\n # indexdet = [0,200,400]\n # itout = 1, 10 # save every nth iteration (for_detector, for xy graph)\n # isout = 2 # save every nth grid point\n # stencilorder=4\n # potential = \"PT\" # None or RWZ or PW\n # # M = 1. # mass of the black hole\n # initdata = \"Gauss\"\n\n #\n if not os.path.isdir(outdir):\n os.mkdir(outdir)\n\n #\n if stencilorder == 2:\n rhs = self.rhs_stencil2\n ng = 1\n elif stencilorder == 4:\n rhs = self.rhs_stencil4\n ng = 2\n else:\n raise NameError(\"stencilorder={} is not recognized\".format(stencilorder))\n indexdet = np.array(indexdet, dtype=int) + ng # shifting the detector with respect to ng\n #\n alln = nr + 2 * ng # all points of a grid\n dxs = (xmax - xmin) / float(nr-1) # grid spacing\n xs = -2. * dxs + xmin + dxs * np.arange(alln) # all spatial grid (+ghosts)\n dt = cfl * dxs # time step\n u = np.zeros(2 * alln) # solution vector. u[:N] = solution, u[N:2N] = its derivative\n #\n\n if potential == None:\n v = np.zeros(alln) # no potential. Flat space-time\n elif potential == \"RWZ\":\n v = rwz_potential(xs, ell=2, l=2, M=mass) # defauled RWZ potential\n elif potential == \"PT\":\n v = pw_potential(xs, mass) # defauled pochi-teller potential\n else:\n raise NameError(\"potential:{} is not implemented\".format(potential))\n\n #\n if initdata == \"Gauss\":\n # filling the state vector with initial data\n u[0:alln], u[alln:2*alln] = gaussian_packet(xs, Rps=150., dsigma=0.25, timesym=0.)\n else:\n raise NameError(\"initdata:{} is not recognized\".format(initdata))\n #\n\n t = 0\n i = 0\n _i = 0\n\n while t < tend:\n print(\"t:{:07d} t:{:.4e} / {:.4e}\".format(i, t, tend))\n if i % itout[0] == 0:\n for idet in np.array([indexdet], dtype=int).flatten():\n z = u[0:alln]\n s = u[alln:2 * alln]\n output_detector(outdir + \"psi_%06d\" % idet + \".txt\",\n retime(t, xs[idet], mass),\n z[idet])\n output_detector(outdir + \"dpsi_%06d\" % idet + \".txt\",\n retime(t, xs[idet], mass),\n s[idet])\n # print(_i)\n _i = _i + 1\n\n if i % itout[1] == 0:\n z = u[0:alln]\n output_solution(outdir + \"rwz.yg\", t, xs, z, isout, ng = ng)\n i = i + 1\n t = i * dt\n u = self.timestep(i, dt, u, rhs, (xs, v, nr, ng))\n\n\n def timestep(self, i, dt, u, rhs, pars):\n \"\"\"\n Runge-Kutta 4\n \"\"\"\n # storage\n utmp = np.zeros_like(u)\n # shorthand\n halfdt = 0.5 * dt\n dt6 = dt / 6.\n # time = n*dt\n # steps\n k1 = rhs(u, *pars)\n utmp[:] = u[:] + halfdt * k1[:]\n k2 = rhs(utmp, *pars)\n utmp[:] = u[:] + halfdt * k2[:]\n k3 = rhs(utmp, *pars)\n utmp[:] = u[:] + dt * k3[:]\n k4 = rhs(utmp, *pars)\n u[:] = u[:] + dt6 * (k1[:] + 2. * (k2[:] + k3[:]) + k4[:])\n return u\n\n def rhs_stencil2(self, u, xs, v, nr, ng):\n N = nr + 2 * ng # grid size including ghosts\n dotu = np.zeros_like(u) # rhs\n\n z = u[0:N] # reference\n s = u[N:2 * N]\n dotz = dotu[0:N] # reference\n dots = dotu[N:2 * N]\n d2z = np.zeros_like(z) # mem for drvt\n\n drs = xs[1] - xs[0]\n idx = 1. / drs\n\n i = 0\n z[i] = z[i + 2] - 2 * drs * s[i + 1]\n s[i] = 2 * s[i + 1] - s[i + 2]\n\n i = N - 1\n z[i] = z[i - 2] - 2 * drs * s[i - 1]\n s[i] = 2 * s[i - 1] - s[i - 2]\n\n i = np.arange(1, nr + 1)\n # Wiki: -1/12 * z[i-2] + 4/3 * z[i-1] -5/2 * z[i] + 4/3 * z[i+1] - 1/12 * z[i+2]\n d2z[i] = idx * idx * (z[i+1] + z[i-1] - 2 * z[i])\n dotz[i] = s[i]\n dots[i] = d2z[i] + z[i] * v[i]\n # print(dotu); exit(1)\n return dotu\n\n def rhs_stencil4(self, u, xs, v, nr, ng):\n \"\"\"\n :param u: state vector u[0:N] - function, u[N:2N] - its derivative\n :return:\n \"\"\"\n N = nr + 2 * ng # grid size including ghosts\n dotu = np.zeros_like(u) # rhs\n\n z = u[0:N] # reference\n s = u[N:2 * N]\n dotz = dotu[0:N] # reference\n dots = dotu[N:2 * N]\n d2z = np.zeros_like(z) # mem for drvt\n\n drs = xs[1] - xs[0]\n factdrs2 = 1. / (12. * drs * drs)\n othree = 1. / 3.\n\n i = 1\n z[i] = - 4. * drs * s[i + 1] - 10. * othree * z[i + 1] + 6. * z[i + 2] - 2. * z[i + 3] + othree * z[i + 4]\n\n i = N - 2\n z[i] = - 4. * drs * s[i - 1] - 10. * othree * z[i - 1] + 6. * z[i - 2] - 2. * z[i - 3] + othree * z[i - 4]\n\n i = 0\n # z[i] = - 20.*drs*s[i+2] - 80.*othree*z[i+2] + 40.*z[i+3] - 15.*z[i+4] + 8.*othree*z[i+5] -- 32\n z[i] = + 5. * z[i + 1] - 10. * z[i + 2] + 10. * z[i + 3] - 5. * z[i + 4] + z[i + 5]\n # z[i] = - 20 * s[i + 2] - (80/3.) * z[i + 3] + 40 * z[i + 4] - 15. * z[i + 5] + (8/3.) * z[i+6]\n\n i = N - 1\n # z[i] = - 20.*drs*s[i-2] - 80.*othree*z[i-2] + 40.*z[i-3] - 15.*z[i-4] + 8.*othree*z[i-5] -- 32\n z[i] = + 5 * z[i - 1] - 10. * z[i - 2] + 10. * z[i - 3] - 5. * z[i - 4] + z[i - 5]\n # z[i] = 20 * s[i - 2] - (80 / 3.) * z[i - 3] + 40 * z[i - 4] - 15. * z[i -5] + (8 / 3.) * z[i - 6]\n\n # u = (z,s)\n # z,t = s\n # s,t = z,xx + V z\n i = np.arange(2, nr + 2)\n # Wiki: -1/12 * z[i-2] + 4/3 * z[i-1] -5/2 * z[i] + 4/3 * z[i+1] - 1/12 * z[i+2]\n d2z[i] = (16. * (z[i + 1] + z[i - 1]) - 30. * z[i] - (z[i + 2] + z[i - 2])) * factdrs2\n dotz[i] = s[i]\n dots[i] = d2z[i] + z[i] * v[i]\n\n # print(dotu); exit(1)\n return dotu\n\ndef compare_potentials(xmin=-50., xmax=50., nr=401, mass=1.):\n\n # xs = np.arange(start=xmin, stop=xmax, step=nr)\n xs = np.mgrid[xmin:xmax:nr*1j]\n\n v_rwz = rwz_potential(xs, ell=2, l=2, M=mass)\n v_pt = pw_potential(xs, mass)\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(xs, v_rwz, color='red', ls='-', label=\"PWZ\")\n ax.plot(xs, v_pt, color='blue', ls='-', label='PT')\n ax.set_xlabel(r'$xs$', fontsize='large')\n ax.set_ylabel(r'$V$', fontsize='large')\n ax.tick_params(\n axis='both', which='both', labelleft=True,\n labelright=False, tick1On=True, tick2On=True,\n labelsize=int(12),\n direction='in',\n bottom=True, top=True, left=True, right=True\n )\n ax.minorticks_on()\n ax.legend()\n fig.tight_layout()\n plt.savefig(\"./potential_comparison.png\")\n plt.show()\n\ndef self_convergence():\n\n mass = 0\n WaveEqSolver(-300., 300, 101, 0.5, 600., mass, (50), (2, 20), 1,\n stencilorder=4, potential=\"RWZ\", initdata=\"Gauss\", outdir=\"./flat_101/\")\n WaveEqSolver(-300., 300, 201, 0.5, 600., mass, (100), (4, 40), 2,\n stencilorder=4, potential=\"RWZ\", initdata=\"Gauss\", outdir=\"./flat_201/\")\n WaveEqSolver(-300., 300, 401, 0.5, 600., mass, (200), (8, 80), 4,\n stencilorder=4, potential=\"RWZ\", initdata=\"Gauss\", outdir=\"./flat_401/\")\n\n # pick solution at detectors x=0.\n tl, low = np.loadtxt(\"flat_101/psi_000052.txt\", unpack=True)\n tm, med = np.loadtxt(\"flat_201/psi_000102.txt\", unpack=True)\n th, hig = np.loadtxt(\"flat_401/psi_000202.txt\", unpack=True)\n print(\"low:{} med:{} high:{}\".format(len(low), len(med), len(hig)))\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.plot(tl, low - med, 'o-', label=\"(low-med)\")\n ax.plot(tm, med - hig, 'x-', label=\"(med-hig)\")\n ax.plot(th, (low - med) / 16., '--', label=\"(low-med) scaled 4th order\")\n ax.set_xlabel('time')\n ax.tick_params(\n axis='both', which='both', labelleft=True,\n labelright=False, tick1On=True, tick2On=True,\n labelsize=int(12),\n direction='in',\n bottom=True, top=True, left=True, right=True\n )\n # ax.set_yscale(\"log\")\n ax.minorticks_on()\n ax.legend()\n plt.show()\n exit(1)\n\ndef find_nearest_index(array, value):\n ''' Finds index of the value in the array that is the closest to the provided one '''\n idx = (np.abs(array - value)).argmin()\n return idx\n\ndef load_solution(fname):\n\n if not os.path.isfile(fname):\n raise IOError(\"file:{} not found\".format(fname))\n\n times = []\n # data = np.zeros(2)\n data = []\n with open(fname) as infile:\n for line in infile:\n if line.__contains__(\"\\\"time = \"):\n t = float(line.split(\"\\\"time = \")[-1])\n times.append(t)\n print(\"read t: {}\".format(t))\n elif len(line.split()) == 0:\n pass\n else:\n _row = np.array(line.split(), dtype=float)\n # print(_row)\n data.append(_row)#np.vstack((data, _row))\n # data = np.delete(data, 0, 0)\n data = np.array(data)\n times = np.array(times, dtype=float)\n\n # print(data.shape)\n # print(len(times))\n # print(len(data[:,0]) / len(times))\n data = np.reshape(data, ( len(times), int(len(data[:,0])/(len(times))), 2 ))\n print(\"Read times: {}\".format(len(times)))\n print(\"Data: {} [timesteps, data_coordiantes, data_values]\".format(data.shape))\n # print(data[1, :, :])\n\n #\n\n #\n\n return times, data\n\ndef plot_solution_at_times():\n\n # list_times = [75, 100., 125., 150.]\n list_times = [150, 175., 200., 225.]\n # list_times = [75, 100., 125., 150.]\n list_fnames = [\"./wave_rwz/rwz.yg\"]\n colors = [\"blue\"]\n lss = [\"-\"]\n #\n res = {}\n #\n print(\"Collecting data\")\n for fname in list_fnames:\n res[fname] = {}\n times, data = load_solution(fname)\n for t in list_times:\n res[fname][t] = {}\n idx = find_nearest_index(times, t)\n x_arr = data[idx, :, 0]\n y_arr = data[idx, :, 1]\n res[fname][t][\"x_arr\"] = x_arr\n res[fname][t][\"y_arr\"] = y_arr\n print(\"Data collected\")\n #\n fig = plt.figure(figsize=(len(list_times)*3.6, 3.6))\n #\n axes = []\n for i in range(1, len(list_times)+1):\n if i == 1:axes.append(fig.add_subplot(1,len(list_times), i))\n else: axes.append(fig.add_subplot(1,len(list_times), i, sharey=axes[0]))\n #\n for ax, t in zip(axes, list_times):\n for fname, color in zip(list_fnames, colors):\n x_arr = res[fname][t][\"x_arr\"]\n y_arr = res[fname][t][\"y_arr\"]\n ax.plot(x_arr, y_arr, color=color, ls='-', label='{}'.format(fname))\n #\n for ax, time in zip(axes, list_times):\n ax.set_title(\"$time:{}$\".format(time))\n ax.set_xlabel(\"$x$\", fontsize='large')\n ax.set_ylabel(\"$\\phi$\", fontsize='large')\n ax.tick_params(\n axis='both', which='both', labelleft=True,\n labelright=False, tick1On=True, tick2On=True,\n labelsize=int(12),\n direction='in',\n bottom=True, top=True, left=True, right=True\n )\n ax.set_xlim(0, x_arr.max())\n ax.minorticks_on()\n ax.legend(loc=\"lower left\", ncol=1)\n # ax.set_ylim(-2.,2.)\n plt.tight_layout()\n plt.subplots_adjust(hspace=0.2)\n plt.subplots_adjust(wspace=0.0)\n plt.savefig(\"./profiles.png\", dpi=128)\n plt.show()\n\ndef plot_solution_3d():\n\n list_fnames = [\"./wave_rwz/rwz.yg\", \"./wave_pt/rwz.yg\"]\n colors = [\"blue\", \"red\"]\n lss = [\"-\"]\n plot_every = 10 # plot every timestep\n\n res = {}\n _times = []\n print(\"Collecting data\")\n for fname in list_fnames:\n res[fname] = {}\n times, data = load_solution(fname)\n # print(times[:]); exit()\n for t in times[::plot_every]:\n res[fname][t] = {}\n print(\"t:{}\".format(t))\n idx = find_nearest_index(times, t)\n x_arr = data[idx, :, 0]\n y_arr = data[idx, :, 1]\n res[fname][t][\"x_arr\"] = x_arr\n res[fname][t][\"y_arr\"] = y_arr\n print(\"Data collected\")\n # print(res[list_fnames[0]].keys())\n\n\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n\n for fname, color in zip(list_fnames, colors):\n for i, time in enumerate(res[list_fnames[0]].keys()):\n #\n x_arr = res[fname][time][\"x_arr\"]\n y_arr = res[fname][time][\"y_arr\"]\n\n z = np.zeros(x_arr.shape)\n z.fill(time)\n print(\"plotting t:{}\".format(time))\n ax.plot(x_arr, y_arr, z, color=color, ls='-', lw=0.8)\n\n\n\n ax.legend(loc='lower left', shadow=False, fontsize='large', frameon=False)\n # ax.set_yscale(\"log\")\n ax.set_xlabel(\"$x$\", fontsize='large')\n ax.set_ylabel(\"$\\phi$\", fontsize='large')\n ax.set_zlabel(\"$time$\", fontsize='large')\n # ax.set_ylabel()\n ax.tick_params(\n axis='both', which='both', labelleft=True,\n labelright=False, tick1On=True, tick2On=True,\n labelsize=int(12),\n direction='in',\n bottom=True, top=True, left=True, right=True\n )\n ax.minorticks_on()\n ax.set_title(\"Wave propagation\")\n plt.subplots_adjust(hspace=0.2)\n plt.subplots_adjust(wspace=0.2)\n plt.savefig(\"./wave_3d.png\", dpi=128)\n plt.tight_layout()\n plt.show()\n exit(1)\n\nif __name__ == '__main__':\n\n arr = np.array([1,2,3,4,5,6,7,8,9], dtype=int)\n print(arr)\n arr = arr[3:]\n print(arr)\n # exit(1)\n\n # compare_potentials()\n #\n # self_convergence()\n #\n # plot_solution_at_times()\n #\n plot_solution_3d()\n # exit(1)\n # load_solution(\"./wave_rwz/rwz.yg\")\n #\n # WaveEqSolver(-300., 300., 401, 0.5, 600., 1., (0, 200, 400), (1, 10), 2,\n # stencilorder=4, potential=\"RWZ\", initdata=\"Gauss\", outdir=\"./wave_rwz/\")\n #\n WaveEqSolver(-300., 300., 401, 0.5, 600., 1., (0, 200, 400), (1, 10), 2,\n stencilorder=4, potential=\"PT\", initdata=\"Gauss\", outdir=\"./wave_pt/\")\n\n t1, psi_rwz = np.loadtxt(\"./wave_rwz/psi_000402.txt\", unpack=True)\n t2, psi_pt = np.loadtxt(\"./wave_pt/psi_000402.txt\", unpack=True)\n fig, ax1 = plt.subplots()\n ax1.plot(t1, psi_rwz, '-', color='red', label='RWZ')\n ax1.plot(t2, psi_pt, '-', color='blue', label='PT')\n ax1.set_xlabel(r'$u$', fontsize='large')\n ax1.set_ylabel(r'$\\Psi_{20}$', fontsize='large')\n ax1.legend()\n ax1.tick_params(\n axis='both', which='both', labelleft=True,\n labelright=False, tick1On=True, tick2On=False,\n labelsize=int(12),\n direction='in',\n bottom=True, top=True, left=True, right=True\n )\n ax1.minorticks_on()\n\n ax2 = ax1.twinx()\n ax2.semilogy(t1, np.fabs(psi_rwz), '--', color='red')\n ax2.semilogy(t2, np.fabs(psi_pt), '--', color='blue')\n ax2.set_ylabel(r'|$\\Psi_{20}|$', fontsize='large')\n # ax1.set_ylim([-0.04,0.05])\n ax2.set_ylim([1e-7, 1e-1])\n ax2.tick_params(\n axis='both', which='both', labelleft=False,\n labelright=True, tick1On=False, tick2On=True,\n labelsize=int(12),\n direction='in',\n bottom=True, top=True, left=True, right=True\n )\n ax2.minorticks_on()\n\n plt.xlim([0, 150])\n fig.tight_layout()\n plt.savefig(\"./psi.png\")\n plt.show()","repo_name":"vsevolodnedora/WaveEqutionPrj","sub_path":"other/old_stuff/ex7.py","file_name":"ex7.py","file_ext":"py","file_size_in_byte":19632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5731552099","text":"import sys\ninput = sys.stdin.readline\n\nnumbers = [True] * (123456 * 2 + 1)\n\nnumbers[0] = numbers[1] = False\n\nsize = int(len(numbers) ** 0.5)\nfor i in range(2, size+1):\n if numbers[i]:\n for j in range(i+i, len(numbers), i):\n numbers[j] = False\n\nwhile True:\n n = int(input())\n\n if n == 0:\n break\n\n count = 0\n for i in range(n+1, 2*n+1):\n if numbers[i]:\n count += 1\n print(count)","repo_name":"BangDori/python-algorithm","sub_path":"baekjoon/4948.py","file_name":"4948.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19726597033","text":"# From https://github.com/vladmandic/automatic/blob/master/cli/lcm-convert.py\n\nimport os\nimport argparse\nimport torch\nfrom diffusers import (\n StableDiffusionPipeline,\n StableDiffusionXLPipeline,\n AutoPipelineForText2Image,\n LCMScheduler,\n)\n\nparser = argparse.ArgumentParser(\"lcm_convert\")\nparser.add_argument(\"--name\", help=\"Name of the new LCM model\", type=str)\nparser.add_argument(\"--model\", help=\"A model to convert\", type=str)\nparser.add_argument(\"--lora-scale\", default=1.0, help=\"Strenght of the LCM\", type=float)\nparser.add_argument(\n \"--huggingface\",\n action=\"store_true\",\n help=\"Use Hugging Face models instead of safetensors models\",\n)\nparser.add_argument(\n \"--upload\", action=\"store_true\", help=\"Upload the new LCM model to Hugging Face\"\n)\nparser.add_argument(\n \"--no-half\", action=\"store_true\", help=\"Convert the new LCM model to FP32\"\n)\nparser.add_argument(\n \"--no-save\", action=\"store_true\", help=\"Don't save the new LCM model to local disk\"\n)\nparser.add_argument(\"--sdxl\", action=\"store_true\", help=\"Use SDXL models\")\nparser.add_argument(\"--ssd-1b\", action=\"store_true\", help=\"Use SSD-1B models\")\n\nargs = parser.parse_args()\n\nif args.huggingface:\n pipeline = AutoPipelineForText2Image.from_pretrained(\n args.model, torch_dtype=torch.float16, variant=\"fp16\"\n )\nelse:\n if args.sdxl or args.ssd_1b:\n pipeline = StableDiffusionXLPipeline.from_single_file(args.model)\n else:\n pipeline = StableDiffusionPipeline.from_single_file(args.model)\n\npipeline.scheduler = LCMScheduler.from_config(pipeline.scheduler.config)\nif args.sdxl:\n pipeline.load_lora_weights(\"latent-consistency/lcm-lora-sdxl\")\nelif args.ssd_1b:\n pipeline.load_lora_weights(\"latent-consistency/lcm-lora-ssd-1b\")\nelse:\n pipeline.load_lora_weights(\"latent-consistency/lcm-lora-sdv1-5\")\npipeline.fuse_lora(lora_scale=args.lora_scale)\n\n# components = pipeline.components\n# pipeline = LatentConsistencyModelPipeline(**components)\n\nif args.no_half:\n pipeline = pipeline.to(dtype=torch.float32)\nelse:\n pipeline = pipeline.to(dtype=torch.float16)\nprint(pipeline)\n\nif not args.no_save:\n os.makedirs(f\"models--local--{args.name}/snapshots\")\n if args.no_half:\n pipeline.save_pretrained(f\"models--local--{args.name}/snapshots/{args.name}\")\n else:\n pipeline.save_pretrained(\n f\"models--local--{args.name}/snapshots/{args.name}\", variant=\"fp16\"\n )\nif args.upload:\n if args.no_half:\n pipeline.push_to_hub(args.name)\n else:\n pipeline.push_to_hub(args.name, variant=\"fp16\")\n","repo_name":"rupeshs/lcm-openvino-converter","sub_path":"lcm-convert.py","file_name":"lcm-convert.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"33402371507","text":"#!/usr/bin/env python3\n\nimport requests\nimport argparse\nimport json\n\nGRAY = '\\033[90m'\nENDC = '\\033[0m'\n\n# Load API key from secret file\nwith open(\"secret\", \"r\") as f:\n api_key = f.read().strip()\n\n# Set API endpoint and parameters\napi_url = \"https://api.openai.com/v1/images/generations\"\nsize = \"1024x1024\"\n\n# Parse command line arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"prompt\", help=\"The prompt to generate an image from\")\n\nargs = parser.parse_args()\nprompt = args.prompt\n#prompt = \"A red panda drinking coffee in a park\"\n\nprint(GRAY + f\"Size: {size}\" + ENDC)\nprint(\" \")\n\nheaders = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {api_key}\"\n}\n\n# Set request data\ndata = {\n \"prompt\": prompt,\n \"size\": size,\n \"n\": 1\n}\n\n# Send request to API\nresponse = requests.post(api_url, headers=headers, data=json.dumps(data))\n\n# Get image URL from response\nimage_url = response.json()[\"data\"][0][\"url\"]\n\n# Download image from URL and save to file\nimage_data = requests.get(image_url).content\nwith open(\"output.png\", \"wb\") as outputFile:\n outputFile.write(image_data)\n\nprint(f\"URL: {image_url}\")\nprint(\" \")\nprint(\"Saved locally as output.png!\")","repo_name":"mattinordstrom/gptcli","sub_path":"dallecli.py","file_name":"dallecli.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7376589230","text":"from django.contrib import admin\nfrom .models import Tutorial, TutorialCategory, TutorialSeries\nfrom tinymce.widgets import TinyMCE\nfrom django.db import models\n\n# Register your models here.\n\n# To overide the order of fields\n\n\nclass TutorialAdmin(admin.ModelAdmin):\n # fields = [\"tutorial_title\",\n # \"tutorial_published\",\n # \"tutorial_content\"]\n\n # Use fieldsets if you would like organise headers\n fieldsets = [\n # Tuple of (Name of header, K,V of fields for list of fields)\n (\"Title and date\", {\"fields\": [\n \"tutorial_title\", \"tutorial_published\"]}),\n (\"URL\", {\"fields\": [\"tutorial_slug\"]}),\n (\"Content\", {\"fields\": [\"tutorial_content\"]}),\n (\"Series\", {\"fields\": [\"tutorial_series\"]})\n ]\n\n formfield_overrides = {\n models.TextField: {'widget': TinyMCE()}\n }\n\n\nadmin.site.register(TutorialSeries)\nadmin.site.register(TutorialCategory)\n\nadmin.site.register(Tutorial, TutorialAdmin)\n","repo_name":"tzihiang/django_webdev","sub_path":"mysite/main/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73185526884","text":"\"\"\"\nThis module implements a spider to use\nfor scraping countries articles of mixed (static and/or PDF/Images html content).\n\ne.g:\nhttps://www.permanentrepresentations.nl/documents/publications/2022/02/01/possibility-to-implement-more-ambitious-national-blending-mandates\n\"\"\"\nfrom datetime import datetime\nimport random\nfrom scrapy import signals\nimport scrapy\nfrom scrapy.exceptions import CloseSpider\nfrom scrapy.utils.project import get_project_settings\nfrom diplomaticpulse.db_elasticsearch.db_es import DpElasticsearch\nfrom diplomaticpulse.misc import cookies_utils\nfrom diplomaticpulse.parsers import html_parser\nfrom diplomaticpulse.dp_loader import item_loader, statementitem_loader\n\nclass StaticPdfSpider(scrapy.spiders.CrawlSpider):\n \"\"\"\n This spider is a subclass of scrapy.spiders.Spider, which indirects its handling of\n the start_urls and subsequently extracted and followed URLs. It is designed to handle combined PDF/Static contents.\n\n \"\"\"\n\n #spider name\n name = \"static_pdf\"\n\n def __init__(self, url, *args, **kwargs):\n \"\"\"\n Create a new instance of HtmlDocSpider\n\n Args\n url (string) :\n country's overview article page,e.g: https://www.foreignminister.gov.au/.\n *args (list) :\n arguments passed to the __init__() method\n **kwargs (dict) :\n keyword arguments passed to the __init__() method:\n\n \"\"\"\n self.start_urls = [url]\n self.settings = get_project_settings()\n self.content_type = \"doc\"\n self.elasticsearch = None\n self.xpaths = None\n self.cookies = None\n self.headers = None\n self.elasticsearch_cl = None\n self.cookies_ = None\n\n @classmethod\n def from_crawler(cls, crawler, *args, **kwargs):\n \"\"\"\n This method creates running spider instance.\n\n Args\n crawler (Crawler instance) :\n crawler to which the spider will be found.\n args (list) :\n arguments passed to the __init__() method.\n kwargs (dict) :\n keyword arguments passed to the __init__() method:\n\n Returns:\n spider :\n instance of spider being running\n\n \"\"\"\n spider = super().from_crawler(crawler, *args, **kwargs)\n crawler.signals.connect(spider.spider_opened, signal=signals.spider_opened)\n return spider\n\n def spider_opened(self, spider):\n \"\"\"\n This is the class method used by Scrapy Framework to open running spider.\n\n Args\n spider(spider (Spider object):\n the spider for which this request is intended\n\n Raises\n CloseSpider( raised from a spider callback):\n when no URL configuration found\n\n \"\"\"\n self.elasticsearch_cl = DpElasticsearch(self.settings[\"ELASTIC_HOST\"])\n self.xpaths = self.elasticsearch_cl.get_url_config(self.start_urls[0], self.settings)\n if not self.xpaths:\n raise CloseSpider(\"No xpaths indexed for the url\")\n self.xpaths[\"index_name\"] = self.settings[\"ELASTIC_INDEX\"]\n self.xpaths[\"content_type\"] = self.content_type\n self.headers = {\"User-Agent\": random.choice(self.settings[\"USER_AGENT_LIST\"])}\n self.cookies_ = cookies_utils.get_cookies(self.xpaths)\n\n\n def start_requests(self):\n \"\"\"\n This method returns an iterable with the first Requests to crawl for this spider. It is called by\n Scrapy when the spider is opened for scraping.\n \"\"\"\n for url in self.start_urls:\n self.logger.debug(\"starting url %s \", url)\n yield scrapy.Request(\n url,\n dont_filter=True,\n headers=self.headers,\n callback=self.parse,\n cookies=self.cookies_,\n )\n\n def parse(self, response):\n \"\"\"\n This is the default callback used by Scrapy Framework to process downloaded responses.\n It extracts links from all start_urls and follow each URL by sending a request.\n\n Args:\n response (response (Response object) – the response being processed):\n html content to parse\n\n Returns:\n request :\n Iterable of Requests\n\n \"\"\"\n self.logger.debug(\"a response arrived from %s \", response.url)\n url_html_blocks = html_parser.get_html_block_links(response, self.xpaths)\n self.logger.debug(\n \"scraped html blocks %s from starting page\", (url_html_blocks)\n )\n first_time_seen_links = self.elasticsearch_cl.search_urls_by_country_type(\n url_html_blocks, self.xpaths\n )\n self.logger.debug(\"first time seen urls %s \", len(first_time_seen_links))\n for url in first_time_seen_links:\n article_info = next(\n (data for data in url_html_blocks if data[\"url\"] == url), None\n )\n self.logger.debug(\"send request for url %s\", response.urljoin(url))\n yield scrapy.Request(\n response.urljoin(url),\n callback=self.parse_static,\n headers=self.headers,\n cookies=self.cookies_,\n cb_kwargs=dict(data=article_info),\n )\n\n def parse_static(self, response, data):\n \"\"\"\n This is the specified callback used by Scrapy to process downloaded responses.\n\n Args:\n response (response (Response object) – the response being processed)\n content to parse\n\n data : dict(String)\n Python dict in the following format:\n data{\n 'title' : \n 'posted_date' : <published date of article >\n }\n\n Returns:\n Dict : (Iterable of items)\n Python dict in the following format:\n {\n 'link' : <link URL>\n 'title' : <title of the article>\n 'statement' : <statement content of the article >\n 'posted_date' :< published date of the article>\n 'indexed_date' :<indexed date of the article >\n 'country' : <country name>\n 'parent_url' : <parent url (country overview page URL)>\n 'content_type' : response content type>\n }\n\n \"\"\"\n self.logger.debug(\"start parsing middle page from %s !\", response.url)\n if data[\"posted_date\"] is None:\n data[\"posted_date\"] = response.xpath(self.xpaths[\"posted_date\"]).get()\n data[\"url\"] = response.url\n url = response.xpath(self.xpaths[\"link_follow\"]).get()\n if url:\n yield scrapy.Request(\n response.urljoin(url),\n callback=self.parse_doc,\n headers=self.headers,\n cb_kwargs=dict(data=data),\n )\n else:\n self.logger.debug(\"start parsing item from %s !\", response.url)\n Item_loader = item_loader.loader(response, data, self.xpaths,None)\n Item_loader.add_value(\"country\", self.xpaths[\"name\"])\n Item_loader.add_value(\"parent_url\", self.start_urls[0])\n Item_loader.add_value(\n \"indexed_date\", (datetime.now()).strftime(\"%Y-%m-%d %H:%M:%S\")\n )\n Item_loader.add_value(\"content_type\", self.content_type)\n yield Item_loader.load_item()\n\n def parse_doc(self, response, data):\n \"\"\"This is the specified callback used by Scrapy to process downloaded pdf.\n\n Args:\n response : response (Response object) – the response being processed\n content to parse\n\n data : dict(String)\n Python dict in the following format:\n data{\n 'title' : <title of the article>\n 'posted_date' : <article published date>\n }\n\n Returns:\n Dict : { Iterable of items}\n Python dict in the following format:\n {\n 'link' : <article URL>\n 'title' : <title of the article>\n 'statement' : <article statement content>\n 'posted_date' :<article published date>\n 'indexed_date' :<article indexed date>\n 'country' : <country name>\n 'parent_url' : <parent url (country overview page URL)>\n 'content_type' : response content type>\n }\n\n \"\"\"\n self.logger.debug(\"start parsing file %s \", response.url)\n item = statementitem_loader.loader(response, data, self.xpaths)\n item[\"content_type\"] = self.content_type\n item[\"indexed_date\"] = (datetime.now()).strftime(\"%Y-%m-%d %H:%M:%S\")\n item[\"country\"] = self.xpaths[\"name\"]\n item[\"parent_url\"] = self.start_urls[0]\n item[\"url\"] = response.url\n yield item\n","repo_name":"qcri/DiplomaticPulse","sub_path":"diplomaticpulse/spiders/static_pdf_spider.py","file_name":"static_pdf_spider.py","file_ext":"py","file_size_in_byte":9033,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"16583832460","text":"import streamlit as st\nimport pandas as pd\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nfrom IPython.display import Image\nimport matplotlib.gridspec as gridspec\nimport seaborn as sns\nimport warnings\n#%matplotlib inline \n#%config InlineBackend.figure_format = 'retina' \npd.set_option('display.max_columns', None) \nwarnings.filterwarnings('ignore')\n\ndf = pd.read_csv(\"attrition_data.csv\")\nst.dataframe(df.head())\n\ndef predict_ready(dframe):\n dframe = dframe.drop(columns=['Over18', 'EmployeeCount', 'StandardHours', 'EmployeeNumber'])\n for cate_features in dframe.select_dtypes(include='object').columns:\n le = preprocessing.LabelEncoder()\n dframe[cate_features] = le.fit_transform(dframe[cate_features])\n #st.write(\"Origin Classes:\", list(le.classes_))\n\n dummies = ['Department', 'EducationField', 'JobRole', 'MaritalStatus']\n dframe = pd.get_dummies(data=dframe, columns=dummies)\n #st.dataframe(df.head())\n numerical_list = ['Age', 'DailyRate', 'DistanceFromHome', 'HourlyRate', 'MonthlyIncome', 'MonthlyRate',\n 'NumCompaniesWorked', 'PercentSalaryHike', 'TotalWorkingYears', 'TrainingTimesLastYear',\n 'YearsAtCompany', 'YearsInCurrentRole', 'YearsSinceLastPromotion', 'YearsWithCurrManager']\n\n std = preprocessing.StandardScaler()\n scaled = std.fit_transform(dframe[numerical_list])\n scaled = pd.DataFrame(scaled, columns=numerical_list)\n for i in numerical_list:\n dframe[i] = scaled[i]\n std = preprocessing.StandardScaler()\n scaled = std.fit_transform(dframe[numerical_list])\n scaled = pd.DataFrame(scaled, columns=numerical_list)\n for i in numerical_list:\n dframe[i] = scaled[i]\n #st.dataframe(df.head())\n dframe = dframe.drop(columns=['Attrition'])\n return dframe\n\n\n\npreprocessedData = predict_ready(df)\nst.dataframe(preprocessedData.head())\n\nfile = open('decisiontree1.pkl', \"rb\")\ndt = pickle.load(file)\n\nresults = dt.predict(preprocessedData)\n#my_confusion_matrix(y_test, y_test_pred_tree1) # Defined before\n#tree1_auc = roc_auc_score(y_test, y_test_pred_tree1)\n#st.write(\"AUC:\", tree1_auc)\n\nres = list(results)\nexit = res.count(1)\nstay = res.count(0)\nst.write('Number of employees predicted to be leaving the company:',exit)\nst.write('Number of employees predicted to stay in the company:',stay)\nst.write('Attrition rate = ', (exit / stay) * 100)\n","repo_name":"amrithasp02/Attrition-Analysis-SE-Project","sub_path":"dt1_testing.py","file_name":"dt1_testing.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37281762988","text":"#\n# @lc app=leetcode id=1156 lang=python3\n#\n# [1156] Swap For Longest Repeated Character Substring\n#\n# https://leetcode.com/problems/swap-for-longest-repeated-character-substring/description/\n#\n# algorithms\n# Medium (48.81%)\n# Likes: 369\n# Dislikes: 27\n# Total Accepted: 12.7K\n# Total Submissions: 26.5K\n# Testcase Example: '\"ababa\"'\n#\n# Given a string text, we are allowed to swap two of the characters in the\n# string. Find the length of the longest substring with repeated characters.\n# \n# \n# Example 1:\n# \n# \n# Input: text = \"ababa\"\n# Output: 3\n# Explanation: We can swap the first 'b' with the last 'a', or the last 'b'\n# with the first 'a'. Then, the longest repeated character substring is \"aaa\",\n# which its length is 3.\n# \n# \n# Example 2:\n# \n# \n# Input: text = \"aaabaaa\"\n# Output: 6\n# Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get\n# longest repeated character substring \"aaaaaa\", which its length is 6.\n# \n# \n# Example 3:\n# \n# \n# Input: text = \"aaabbaaa\"\n# Output: 4\n# \n# \n# Example 4:\n# \n# \n# Input: text = \"aaaaa\"\n# Output: 5\n# Explanation: No need to swap, longest repeated character substring is\n# \"aaaaa\", length is 5.\n# \n# \n# Example 5:\n# \n# \n# Input: text = \"abcdef\"\n# Output: 1\n# \n# \n# \n# Constraints:\n# \n# \n# 1 <= text.length <= 20000\n# text consist of lowercase English characters only.\n# \n# \n#\n\n# @lc code=start\nfrom collections import Counter\nimport itertools\n\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n A = [[c, len(list(g))] for c, g in itertools.groupby(text)]\n count = Counter(text)\n\n res = max(min(k + 1, count[c]) for c, k in A)\n\n for i in range(1, len(A) - 1):\n if A[i - 1][0] == A[i + 1][0] and A[i][1] == 1:\n res = max(res, min(A[i - 1][1] + A[i + 1][1] + 1, count[A[i + 1][0]]))\n\n return res\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"1156.swap-for-longest-repeated-character-substring.py","file_name":"1156.swap-for-longest-repeated-character-substring.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"43387290961","text":"import json\nimport os\n\nimport boto3\n\n\ndef upload_to_aws(local_file, bucket, s3_file, aws_access_key, aws_secret_key):\n \"\"\"Uploads the given file to AWS S3 using the given credentials and config.\"\"\"\n\n s3 = boto3.client(\n \"s3\", aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key\n )\n s3.upload_file(local_file, bucket, s3_file, ExtraArgs={\"ACL\": \"public-read\"})\n print(\"File Upload Successful\")\n\n\ndef generate_sitemap():\n \"\"\"\n This function uses the third party library `https://github.com/c4software/python-sitemap`\n to generate the sitemap in the project root. This uses the configuration from `config.json`.\n Visit the link to find more docs about the config file.\n \"\"\"\n\n os.system(\"python libraries/python-sitemap/main.py --config config.json\")\n print(\"Sitemap generated\")\n\n\ndef get_configurations():\n \"\"\"This function returns the defined configuration in the project root in `config.json`.\"\"\"\n\n config_data = open(\"config.json\", \"r\")\n config = json.load(config_data)\n config_data.close()\n return config\n\n\ndef lambda_handler(event, context):\n \"\"\"\n This is the main function called in AWS lambda. This calls the other\n child functions to get the job done. The event and context are given by lambda.\n \"\"\"\n\n config = get_configurations() # all defined configurations\n generate_sitemap() # generates the temp sitemap\n upload_to_aws(\n local_file=config[\"output\"],\n bucket=config[\"s3_bucket_name\"],\n s3_file=config[\"output\"],\n aws_access_key=config[\"aws_access_key\"],\n aws_secret_key=config[\"aws_secret_key\"],\n ) # uploads the sitemap\n os.remove(config[\"output\"]) # removes the temp sitemap\n\n\nif __name__ == \"__main__\":\n lambda_handler(None, {})\n","repo_name":"ajaidanial/dynamic-sitemap-generator-lambda-s3","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"41900458109","text":"import os\nimport asyncio\n\nfrom httpx import Response\n\nfrom aiocppm.client import CPPMClient as _Client\nfrom aiocppm.mixins.network_device import CPPMNetworkDeviceMixin\nimport csv\n\n\nclass CPPMClient(_Client, CPPMNetworkDeviceMixin):\n pass\n\n\n# sample payload\n# payload = dict(\n# name='test-veos1',\n# ip_address='1.1.1.1',\n# tacacs_secret='foobaz',\n# vendor_name='Arista',\n# radius_secret='',\n# attributes={\n# 'Location': 'nyc1',\n# 'OS Version': 'eos'\n# }\n# )\n\n\ng_tacacs_secret = os.environ[\"TACACS_SECRET\"]\n\n\ndef csv_to_payload(rec: dict):\n return dict(\n name=rec[\"hostname\"],\n ip_address=rec[\"ipaddr\"],\n tacacs_secret=g_tacacs_secret,\n vendor_name=rec[\"vendor\"],\n radius_secret=\"\",\n attributes={\"Location\": rec[\"site\"], \"OS Version\": rec[\"os_name\"]},\n )\n\n\ndef load_csv(filepath):\n with open(filepath) as infile:\n csv.DictReader(infile)\n return list(csv.DictReader(infile))\n\n\nasync def run(records):\n\n cppm = CPPMClient(timeout=30)\n await cppm.login()\n\n existing_devices = await cppm.fetch_devices()\n existing_names = (rec[\"name\"] for rec in existing_devices)\n\n payloads = [\n csv_to_payload(rec) for rec in records if rec[\"hostname\"] not in existing_names\n ]\n\n print(f\"Creating {len(payloads)} device records.\")\n\n tasks = [asyncio.create_task(cppm.create_device(payload)) for payload in payloads]\n\n for next_done in asyncio.as_completed(tasks, timeout=5 * 60):\n res: Response = await next_done\n body = res.json()\n if res.is_error:\n if \"already exists\" in body[\"detail\"]:\n print(f\"OK: {body['detail']}\")\n continue\n print(f\"ERROR: {res.text}\")\n continue\n print(f\"OK: {res.text}\")\n\n\nasync def patch_iosxe(cppm: CPPMClient, records):\n tasks = [\n asyncio.create_task(\n cppm.api.patch(url=f'/api/network-device/{rec[\"id\"]}', json=rec)\n )\n for rec in records\n ]\n\n for next_done in asyncio.as_completed(tasks, timeout=5 * 60):\n res: Response = await next_done\n if res.is_error:\n print(f\"ERROR: {res.text}\")\n continue\n print(f\"OK: {res.text}\")\n\n\ndef main(filepath):\n records = load_csv(filepath)\n asyncio.run(run(records))\n","repo_name":"jeremyschulman/aio-cppm","sub_path":"examples/ex_devices.py","file_name":"ex_devices.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16054437860","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('signup/', views.SignUp.as_view(), name=\"signup\"),\n path('show/', views.show, name=\"show\"),\n path('add_new/', views.add_new, name=\"add_new\"),\n path('insert/', views.insert, name=\"insert\"),\n path('delete/', views.delete, name=\"delete\"),\n path('filter_comment/<str:model>/<str:author>', views.filter_comment, name=\"filter_comment\"),\n path('filter_submission/<str:model>/<str:submission>', views.filter_submission, name=\"filter_submission\")\n] ","repo_name":"Lim-Guowei/web_crawler","sub_path":"webcrawlerapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19379385461","text":"from src import utils,db\nfrom src.fpgaBoard import FpgaBoard\nfrom src import vsguerra\nfrom multiprocessing import Lock\nfrom pymongo import MongoClient,ReplaceOne,ASCENDING,DESCENDING\nfrom collections import defaultdict\nfrom random import shuffle,random\nimport json,os\nfrom tqdm import tqdm\nfrom copy import deepcopy\n\ntcc_db = db.get_database(MongoClient)\nrequest_info = tcc_db['requests_info']\n\n\ndef child_region_allocation(fpga,partitions_parent1, partitions_parent2):\n allocation_possible = True\n\n loop_partitions_parent1 = partitions_parent1[:]\n loop_partitions_parent2 = partitions_parent2[:]\n shuffle(partitions_parent1)\n shuffle(partitions_parent2)\n\n while (allocation_possible):\n allocated_p1 = False\n allocated_p2 = False\n\n\n #varredura nas partições da topologia do pai 1 até achar uma partição que possa ser alocada\n for partition in loop_partitions_parent1:\n start_coords, end_coords = partition['coords']\n allocation_result_p1 = fpga.allocate_region(start_coords,end_coords,partition['resources'])\n loop_partitions_parent1.remove(partition)\n if(allocation_result_p1 is not None):\n allocated_p1 = True\n partitions_parent1.remove(partition)\n break\n\n #varredura nas partições da topologia do pai 2 até achar uma partição que possa ser alocada\n for partition in loop_partitions_parent2:\n start_coords, end_coords = partition['coords']\n allocation_result_p2 = fpga.allocate_region(start_coords,end_coords,partition['resources'])\n\n loop_partitions_parent2.remove(partition)\n if(allocation_result_p2 is not None):\n allocated_p1 = True\n partitions_parent2.remove(partition)\n break\n\n allocation_possible = allocated_p1 or allocated_p2\n\n #print(f'final {len(partitions_parent1)}.{len(partitions_parent2)}')\n return fpga,partitions_parent1,partitions_parent2\n\ndef initialize_child_topology(topology_p1,topology_p2,child_id,fpga_config,logger,req_topology_filename):\n child_topology = defaultdict(lambda: defaultdict(dict))\n partititons_parents = [[],[]]\n\n child_topology['topology_id'] = child_id\n child_topology['topology_score'] = None\n child_topology['filename'] = req_topology_filename\n child_topology['generation'] = topology_p1['generation']+1\n child_topology['node_count'] = topology_p1['node_count']\n child_topology['link_count'] = topology_p1['link_count']\n\n for node_id,node in topology_p1['topology_data'].items():\n child_topology['topology_data'][node_id] = {'FPGA': dict(), 'Links': node['Links']}\n\n for fpga_id,fpga in node['FPGA'].items():\n child_topology['topology_data'][node_id]['FPGA'][fpga_id] = FpgaBoard(fpga_config,logger)\n\n for partition in fpga['partitions'].values():\n partititons_parents[0].append(partition)\n\n for node_id,node in topology_p2['topology_data'].items():\n for fpga_id,fpga in node['FPGA'].items():\n for partition in fpga['partitions'].values():\n partititons_parents[1].append(partition)\n\n return child_topology,partititons_parents\ndef populate_child_topology(topology,partititon_p1,partititon_p2,sizes,allocation_info,full_aloc_rate,resize_rate):\n for node_id,node in topology['topology_data'].items():\n if ('FPGA' in node):\n for fpga_id,fpga in node['FPGA'].items():\n topology['topology_data'][node_id]['FPGA'][fpga_id], partititon_p1, partititon_p2 = child_region_allocation(fpga,partititon_p1,partititon_p2)\n if(random() <= full_aloc_rate):\n topology['topology_data'][node_id]['FPGA'][fpga_id].full_board_allocation(sizes[:],allocation_info)\n if(random() <= resize_rate):\n topology['topology_data'][node_id]['FPGA'][fpga_id].full_board_resize(200,1,10)\n\n else:\n topology[node_id]['FPGA'] = []\n\n return topology\n\ndef save_topology_to_file(topology,path):\n output = {}\n\n for node_id,node in topology['topology_data'].items():\n output[node_id] = {'FPGA':[],'Links': node['Links']}\n for fpga in node['FPGA'].values():\n if(fpga):\n output[node_id]['FPGA'].append(fpga.get_complete_partition_resource_report() )\n\n utils.save_json_file(output,path)\n return\n\ndef save_topology_db(topology,topology_collection):\n db_topology = defaultdict(lambda: defaultdict(dict))\n for node_id,node in topology['topology_data'].items():\n db_topology['topology_data'][node_id]['FPGA'] = dict()\n db_topology['topology_data'][node_id]['Links'] = topology['topology_data'][node_id]['Links']\n\n for fpga_id,fpga in node['FPGA'].items():\n if(fpga):\n db_topology['topology_data'][node_id]['FPGA'][str(fpga_id)] = fpga.get_db_dict()\n\n db_topology['topology_id'] = topology['topology_id']\n\n db_topology['generation'] = topology['generation']\n db_topology['topology_score'] = topology['topology_score']\n topology_collection.replace_one({'topology_id':topology['topology_id'],'generation': db_topology['generation']},db_topology,upsert=True)\n\ndef create_request_list(topology,nodos_G,runs = 30):\n req = int(nodos_G * 1.5 * 4.5)\n req_qtd = 0\n lista_requisicoes = [vsguerra.ler_Requisicoes(vsguerra.gerador_Req(nodos_G, req, topology)) for i in range(runs)]\n return lista_requisicoes\ndef evaluate_topology(topology,topology_filename = None):\n nodos_G = len(topology['topology_data'].keys())\n fpga_count = 0\n for node_id,node in topology['topology_data'].items():\n fpga_count += len(node['FPGA'])\n\n runs = 30\n req_per_run = int(fpga_count * 4.5)\n req_qtd = 0\n\n if(topology_filename is None):\n print(\"no comparison\")\n lista_requisicoes = [ vsguerra.ler_Requisicoes(vsguerra.gerador_Req(nodos_G,req_per_run,topology)) for i in range(runs)]\n\n else:\n #print(f\"não é none: {topology_filename}\")\n request_entry = request_info.find_one({'topology_filename' : topology_filename})\n runs = len(request_entry['requests'])\n req_per_run = len(request_entry['requests'][0])\n #print(f\"{runs=}..{req_per_run=}\")\n\n lista_requisicoes = []\n for req_sublist in request_entry['requests']:\n lista_req_temp = []\n\n for request in req_sublist:\n req = vsguerra.Req(**request)\n functions = request['func']\n req.func = [vsguerra.Function(function['name_func'],function['name_imp'],function['clb'],function['bram'],function['dsp']) for function in functions]\n lista_req_temp.append(req)\n\n lista_requisicoes.append(lista_req_temp)\n\n\n\n for requisao in lista_requisicoes:\n #print(requisao)\n lista_Paths,lista_Nodos= vsguerra.ler_Topologia(topology)\n resultado = vsguerra.greedy(requisao,lista_Paths,lista_Nodos)\n req_qtd += resultado[0]\n #print(resultado)\n\n #topology['topology_score'] = req_qtd/(req*runs)\n\n return req_qtd/(req_per_run*runs)\n\ndef format_topology_db(topology):\n db_topology = defaultdict(lambda: defaultdict(dict))\n\n for node_id,node in topology['topology_data'].items():\n db_topology['topology_data'][node_id]['FPGA'] = dict()\n db_topology['topology_data'][node_id]['Links'] = topology['topology_data'][node_id]['Links']\n\n for fpga_id,fpga in node['FPGA'].items():\n if(fpga):\n db_topology['topology_data'][node_id]['FPGA'][str(fpga_id)] = fpga.get_db_dict()\n\n db_topology['topology_id'] = topology['topology_id']\n db_topology['node_count'] = topology['node_count']\n db_topology['link_count'] = topology['link_count']\n db_topology['generation'] = topology['generation']\n db_topology['topology_score'] = topology['topology_score']\n return db_topology\n\ndef create_child_topology(topology_p1,topology_p2,child_id,fpga_config,logger,sizes,allocation_info,realloc_rate,resize_rate,req_topology_filename):\n child_topology,partititon_topology = initialize_child_topology(topology_p1,topology_p2,child_id,fpga_config,logger,req_topology_filename)\n child_topology = populate_child_topology(child_topology,partititon_topology[0],partititon_topology[1],sizes,allocation_info,realloc_rate,resize_rate)\n child_topology['topology_score'] = evaluate_topology(child_topology,req_topology_filename)\n child_topology['filename'] = req_topology_filename\n\n return child_topology\n\ndef create_child_topology_db_unpacker(args):\n topology_p1, topology_p2, child_id, fpga_config, logger, sizes, allocation_info, realloc_rate, resize_rate,req_topology_filename = args\n return create_child_topology_db(topology_p1,topology_p2,child_id,fpga_config,logger,sizes,allocation_info,realloc_rate,resize_rate,req_topology_filename)\n\n\ndef create_child_topology_db(topology_p1,topology_p2,child_id,fpga_config,logger,sizes,allocation_info,realloc_rate,resize_rate,req_topology_filename):\n #print(\"hello\")\n child_topology = create_child_topology(topology_p1,topology_p2,child_id,fpga_config,logger,sizes,allocation_info,realloc_rate,resize_rate,req_topology_filename)\n child_topology_db = format_topology_db(child_topology)\n child_topology_db['filename'] = req_topology_filename\n #print(\"goodbye\")\n\n return ReplaceOne({'topology_id':child_topology_db['topology_id'],'generation': child_topology_db['generation']},dict(child_topology_db),upsert=True)\n\n\n\ndef create_topology_db_from_json(json_topology,fpga_config,logger,allocation_info,topology_id,return_db_op = True, req_topology_filename = None):\n topologia = {'topology_id': topology_id, 'generation': 0, 'node_count' : len(json_topology),'link_count': None,'topology_data': dict(), 'topology_score': None,'filename': req_topology_filename}\n temp_topologia = {'topology_data': dict()} #para calculo de fitness\n link_count = 0\n for node_id, network_node in json_topology.items():\n topologia['topology_data'][node_id] = None\n topologia['topology_data'][node_id] = {'FPGA': dict(), 'Links': network_node['Links']}\n temp_topologia['topology_data'][node_id] = None\n temp_topologia['topology_data'][node_id] = {'FPGA': dict(), 'Links': network_node['Links']}\n link_count += len(network_node['Links'])\n\n len_fpgas = len(network_node['FPGA'])\n\n if (len_fpgas > 0):\n for pos, fpga in enumerate(network_node['FPGA']):\n # Cria FPGA zerado e faz uma alocação aleatória completa\n fpgaBoard = FpgaBoard(fpga_config, logger)\n fpgaBoard.full_board_allocation(list(fpga_config['partition_size'].keys()), allocation_info)\n\n # Cria entrada para o banco de dados\n fpga_board_description = fpgaBoard.get_db_dict()\n topologia['topology_data'][node_id]['FPGA'][str(pos)] = fpga_board_description\n temp_topologia['topology_data'][node_id]['FPGA'][pos] = fpgaBoard\n\n topologia['topology_score'] = evaluate_topology(temp_topologia,req_topology_filename)\n topologia['link_count'] = int(link_count/2)\n if(return_db_op):\n return ReplaceOne({'topology_id': topology_id, 'generation': 0}, topologia, upsert=True)\n else:\n return topologia\n\ndef create_topology_fpgaboard_from_db(db_topology,fpga_config,logger,allocation_info):\n topologia = {}\n for node_id, network_node in db_topology['topology_data'].items():\n topologia[node_id] = None\n topologia[node_id] = {'FPGA': dict(), 'Links': network_node['Links']}\n\n len_fpgas = len(network_node['FPGA'])\n\n if (len_fpgas > 0):\n for pos, fpga in network_node['FPGA'].items():\n # Cria FPGA zerado e faz uma alocação aleatória completa\n fpgaBoard = FpgaBoard(fpga_config, logger)\n\n for partition in fpga['partitions'].values():\n start_coords, end_coords = partition['coords']\n fpgaBoard.allocate_region(start_coords, end_coords, partition['resources'])\n\n topologia[node_id]['FPGA'][pos] = fpgaBoard\n\n return topologia\n\ndef create_agnostic_topology(topology,agnostic_fpga,fpga_config,logger,allocation_info):\n topologia = {}\n for node_id, network_node in topology.items():\n topologia[node_id] = None\n topologia[node_id] = {'FPGA': dict(), 'Links': network_node['Links']}\n for pos, empty_fpga in enumerate(network_node['FPGA']):\n # Cria FPGA zerado e faz uma alocação aleatória completa\n fpgaBoard = FpgaBoard(fpga_config, logger)\n\n for partition in agnostic_fpga['partitions'].values():\n start_coords, end_coords = partition['coords']\n fpgaBoard.allocate_region(start_coords, end_coords, partition['resources'])\n\n topologia[node_id]['FPGA'][pos] = fpgaBoard\n\n\n\n return topologia\n\n\ndef export_topology_to_files(topology):\n return\n","repo_name":"akferreira/tcc_fpga_akferreira_1","sub_path":"src/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":13081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7541348954","text":"import paddlenlp as ppnlp\r\nfrom paddlenlp.datasets import load_dataset\r\nfrom paddlenlp.transformers import *\r\nfrom functools import partial\r\nfrom paddlenlp.data import Stack, Tuple, Pad\r\nfrom utils import convert_example, create_dataloader\r\n\r\n\r\n\r\n# 语义表示\r\n# model = AutoModel.from_pretrained('ernie-3.0-medium-zh')\r\n\r\nMODEL_NAME = \"ernie-1.0\"\r\n\r\ntokenizer = ppnlp.transformers.ErnieTokenizer.from_pretrained(MODEL_NAME)\r\nernie_model = ppnlp.transformers.ErnieModel.from_pretrained(MODEL_NAME)\r\n\r\n# print(model.pooler)\r\n# print(\"out_features:\",model.pooler.dense.weight.shape[0]) #获取预训练模型最后一层的输出特征数\r\n\r\nclass ErnieWithFC(nn.Layer):\r\n def __init__(self, ernie_model, fc_size, num_classes, dropout_prob=0.1):\r\n super(ErnieWithFC, self).__init__()\r\n self.ernie = ernie_model\r\n self.dropout = nn.Dropout(dropout_prob)\r\n self.fc = nn.Linear(fc_size, num_classes)\r\n\r\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\r\n _, pooled_output = self.ernie(input_ids, token_type_ids, position_ids)\r\n pooled_output = self.dropout(pooled_output) # 应用dropout层\r\n output = self.fc(pooled_output)\r\n return output\r\n\r\n def save_pretrained(self,model_path):\r\n\r\n # assert not os.path.isfile(model_path), \"Saving directory ({}) should be a directory, not a file\".format(model_path)\r\n os.makedirs(model_path, exist_ok=True)\r\n\r\n paddle.save(self.state_dict(), model_path+\"/ErnieWithFC.pdparams\")\r\n\r\nmodel = ErnieWithFC(ernie_model,ernie_model.pooler.dense.weight.shape[0],2)\r\n\r\n\r\n# res = ernie_model(single_seg_input['input_ids'],single_seg_input['token_type_ids'])\r\n# print(\"ernie_model res : \",res)\r\n\r\ntrain_ds, dev_ds, test_ds = load_dataset(\r\n \"chnsenticorp\", splits=[\"train\", \"dev\", \"test\"])\r\n\r\n# 模型运行批处理大小\r\nbatch_size = 32\r\nmax_seq_length = 128\r\n\r\ntrans_func = partial(\r\n convert_example,\r\n tokenizer=tokenizer,\r\n max_seq_length=max_seq_length)\r\nbatchify_fn = lambda samples, fn=Tuple(\r\n Pad(axis=0, pad_val=tokenizer.pad_token_id), # input\r\n Pad(axis=0, pad_val=tokenizer.pad_token_type_id), # segment\r\n Stack(dtype=\"int64\") # label\r\n): [data for data in fn(samples)]\r\ntrain_data_loader = create_dataloader(\r\n train_ds,\r\n mode='train',\r\n batch_size=batch_size,\r\n batchify_fn=batchify_fn,\r\n trans_fn=trans_func)\r\ndev_data_loader = create_dataloader(\r\n dev_ds,\r\n mode='dev',\r\n batch_size=batch_size,\r\n batchify_fn=batchify_fn,\r\n trans_fn=trans_func)\r\n\r\n\r\n# for batch in train_data_loader:\r\n# print(\"batch 0 :\",batch)\r\n# break\r\n'''\r\n一个batch堆叠出来的数据如下图所示\r\nbatch 0 : [Tensor(shape=[32, 128], dtype=int32, place=Place(gpu_pinned), stop_gradient=True,\r\n [[1 , 328 , 188 , ..., 0 , 0 , 0 ],\r\n [1 , 75 , 47 , ..., 0 , 0 , 0 ],\r\n [1 , 335 , 15 , ..., 0 , 0 , 0 ],\r\n ...,\r\n [1 , 47 , 10 , ..., 4 , 1172, 2 ],\r\n [1 , 317 , 42 , ..., 2 , 0 , 0 ],\r\n [1 , 185 , 45 , ..., 21 , 4 , 2 ]]), Tensor(shape=[32, 128], dtype=int32, place=Place(gpu_pinned), stop_gradient=True,\r\n [[0, 0, 0, ..., 0, 0, 0],\r\n [0, 0, 0, ..., 0, 0, 0],\r\n [0, 0, 0, ..., 0, 0, 0],\r\n ...,\r\n [0, 0, 0, ..., 0, 0, 0],\r\n [0, 0, 0, ..., 0, 0, 0],\r\n [0, 0, 0, ..., 0, 0, 0]]), Tensor(shape=[32, 1], dtype=int64, place=Place(gpu_pinned), stop_gradient=True,\r\n [[1],\r\n [0],\r\n [0],\r\n [1],\r\n [0],\r\n [1],\r\n [0],\r\n [0],\r\n [1],\r\n [0],\r\n [0],\r\n [1],\r\n [1],\r\n [1],\r\n [0],\r\n [1],\r\n [1],\r\n [0],\r\n [0],\r\n [0],\r\n [1],\r\n [1],\r\n [0],\r\n [0],\r\n [1],\r\n [0],\r\n [0],\r\n [0],\r\n [1],\r\n [0],\r\n [1],\r\n [1]])]\r\n'''\r\n\r\n\r\n# 设置Fine-Tune优化策略,接入评价指标\r\nfrom paddlenlp.transformers import LinearDecayWithWarmup\r\n\r\n# 训练过程中的最大学习率\r\nlearning_rate = 5e-5\r\n# 训练轮次\r\nepochs = 1 #3\r\n# 学习率预热比例\r\nwarmup_proportion = 0.1\r\n# 权重衰减系数,类似模型正则项策略,避免模型过拟合\r\nweight_decay = 0.01\r\n\r\nnum_training_steps = len(train_data_loader) * epochs\r\nlr_scheduler = LinearDecayWithWarmup(learning_rate, num_training_steps, warmup_proportion)\r\noptimizer = paddle.optimizer.AdamW(\r\n learning_rate=lr_scheduler,\r\n parameters=model.parameters(),\r\n weight_decay=weight_decay,\r\n apply_decay_param_fun=lambda x: x in [\r\n p.name for n, p in model.named_parameters()\r\n if not any(nd in n for nd in [\"bias\", \"norm\"])\r\n ])\r\n\r\ncriterion = paddle.nn.loss.CrossEntropyLoss()\r\nmetric = paddle.metric.Accuracy()\r\n\r\nimport paddle.nn.functional as F\r\nfrom utils import evaluate\r\n\r\n# global_step = 0\r\n# for epoch in range(1, epochs + 1):\r\n# for step, batch in enumerate(train_data_loader, start=1):\r\n# input_ids, segment_ids, labels = batch\r\n# logits = model(input_ids, segment_ids)\r\n# loss = criterion(logits, labels)\r\n# probs = F.softmax(logits, axis=1)\r\n# correct = metric.compute(probs, labels)\r\n# metric.update(correct)\r\n# acc = metric.accumulate()\r\n#\r\n# global_step += 1\r\n# if global_step % 10 == 0 :\r\n# #每10步打印一次\r\n# print(\"global step %d, epoch: %d, batch: %d, loss: %.5f, acc: %.5f\" % (global_step, epoch, step, loss, acc))\r\n# loss.backward()\r\n# optimizer.step()\r\n# lr_scheduler.step()\r\n# optimizer.clear_grad()\r\n# evaluate(model, criterion, metric, dev_data_loader)\r\n\r\n# 如果有已经训练好的保存了的模型,可以直接加载模型参数\r\nparam_path = \"./checkpoint_art/ErnieWithFC.pdparams\"\r\nparam_dict = paddle.load(param_path)\r\nmodel.set_dict(param_dict)\r\nevaluate(model, criterion, metric, dev_data_loader)\r\n# model.save_pretrained('./checkpoint_art')\r\n# tokenizer.save_pretrained('./checkpoint_art')\r\n\r\nfrom utils import predict\r\n\r\ndata = [\r\n {\"text\":'这个宾馆比较陈旧了,特价的房间也很一般。总体来说一般'},\r\n {\"text\":'怀着十分激动的心情放映,可是看着看着发现,在放映完毕后,出现一集米老鼠的动画片'},\r\n {\"text\":'作为老的四星酒店,房间依然很整洁,相当不错。机场接机服务很好,可以在车上办理入住手续,节省时间。'},\r\n]\r\nlabel_map = {0: 'negative', 1: 'positive'}\r\n\r\nresults = predict(\r\n model, data, tokenizer, label_map, batch_size=batch_size)\r\nfor idx, text in enumerate(data):\r\n print('Data: {} \\t Lable: {}'.format(text, results[idx]))\r\n","repo_name":"Dachui61/NLP_Subject","sub_path":"ChnSenticorp_art.py","file_name":"ChnSenticorp_art.py","file_ext":"py","file_size_in_byte":6758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23528239706","text":"from django.shortcuts import get_object_or_404\nfrom django.utils.translation import ugettext as _\n\nfrom .models import (\n Collection, Group, Tile, Portfolio, Layout, Style,\n CustomizedTile, GroupColor, PalleteColor, PortfolioTile, CustomGroup\n)\nfrom .dtos import (\n CollectionDto, CollectionDetailDto, GroupDto, TileDesignDto,\n MenuCollectionDto, TileStyleDto, TileDetailDto, TileInstallationPhotosDto,\n TileSizeDto, TileOrderDto, InStockDto, CollectionsFiltersDto, PortfolioTilesDto,\n LayoutDto, LayoutTilesDto, PortfolioCustomizedTilesDto, CollectionInstallationPhotosDto,\n TileColorDto, GroupColorDto, RecentTilesDto\n)\n\n\nclass CollectionService:\n\n def get_collection(id ,language=None):\n collection = get_object_or_404(Collection, pk=id)\n collectionDto = CollectionDetailDto(collection, language)\n return collectionDto\n\n def get_collections(language=None):\n collections = Collection.objects.all()\n collectionsDto = [CollectionDto(collection, language=language)\n for collection in collections]\n return collectionsDto\n\n def get_featured_collections(language=None):\n collections = Collection.objects.filter(featured=True)\n collectionsDto = [CollectionDto(collection, language=language)\n for collection in collections]\n return collectionsDto\n\n def get_groups(collection_id, language=None):\n collection = get_object_or_404(Collection, pk=collection_id)\n groups = collection.customgroups.filter(show_in_web=True, designs__gt=0).distinct()\n groupsDto = [GroupDto(group, language)\n for group in groups]\n return groupsDto\n\n def get_menu_collections(language=None, filter=None):\n collections = Collection.objects.filter(show_in_menu=True)\n if filter: collections = collections.exclude(pk=filter)\n menuCollectionsDto = [MenuCollectionDto(collection, language = language)\n for collection in collections]\n return menuCollectionsDto\n\n def get_installation_photos(collection, language):\n tiles = Tile.objects.filter(design__group__collection=collection.id)\n\n #filter unique gallery images\n filter_photos = {photo for tile in tiles for photo in tile.installation_photos.all()}\n installation_photos_dto = [CollectionInstallationPhotosDto(photo, language)\n for photo in filter_photos]\n return installation_photos_dto\n\n\nclass GroupService:\n\n def group_show_in_web(id):\n return get_object_or_404(CustomGroup, pk=id, show_in_web=True)\n\n def get_group(id, language=None):\n group = GroupService.group_show_in_web(id)\n group_dto = GroupDto(group, language)\n return group_dto\n\n def get_group_designs(id, limit, offset, style, size, new, in_stock, specials, language):\n group = GroupService.group_show_in_web(id)\n designs = group.designs.filter(show_in_web=True).prefetch_related('tiles').filter(tiles__image__regex='[\\w-]')\n \n if style != '0': designs = designs.filter(styles__id=style)\n\n if new: designs = designs.filter(tiles__new=True)\n\n if in_stock: designs = designs.filter(tiles__custom=False)\n\n if specials: designs = designs.filter(tiles__on_sale=True)\n \n tile_designs_dto = []\n \n designs = designs.distinct()\n \n for tile_design in designs[offset:(limit+offset)]:\n tiles_filter = tile_design.tiles.exclude(image='')\n tiles_filter = tiles_filter.filter(is_active=True)\n \n if size: tiles_filter = tiles_filter.filter(size=size)\n if new: tiles_filter = tiles_filter.filter(new=True)\n if in_stock: tiles_filter = tiles_filter.filter(custom=False)\n if specials: tiles_filter = tiles_filter.filter(on_sale=True)\n \n if tiles_filter:\n if tiles_filter.filter(main=True).exists():\n main_tile = tiles_filter.filter(main=True).first()\n minor_tiles = tiles_filter.filter(main=False)\n else:\n main_tile = tiles_filter.first()\n minor_tiles = tiles_filter.exclude(pk=main_tile.id)\n \n tile_designs_dto.append(TileDesignDto(main_tile, minor_tiles, language))\n \n return tile_designs_dto\n\n def get_styles(id, language=None):\n group = GroupService.group_show_in_web(id)\n designs = group.designs.all()\n \n styles = {style for design in designs for style in design.styles.all()}\n styles_dto =[TileStyleDto(style, language) for style in styles]\n return styles_dto\n\n def get_sizes(id):\n group = GroupService.group_show_in_web(id)\n designs = group.designs.filter(show_in_web=True)\n sizes = [design.tiles.values_list('size', flat=True).distinct() for design in designs]\n\n unique_sizes = []\n for size in sizes:\n if size[0] not in unique_sizes:\n unique_sizes.append(size[0])\n\n size_dto = TileSizeDto(unique_sizes)\n return size_dto\n\n\nclass TileService:\n\n def get_tile(id, language):\n tile = get_object_or_404(Tile, pk=id)\n tiledetailDto = TileDetailDto(tile, language)\n return tiledetailDto\n\n def get_tile_installation_photos(id, language):\n tile = get_object_or_404(Tile, pk=id)\n if tile.installation_photos.exists():\n tileinstallationphotosDto = [TileInstallationPhotosDto(photo, language)\n for photo in tile.installation_photos.all()]\n else: tileinstallationphotosDto = None\n return tileinstallationphotosDto\n\n def get_tile_order(id, portfolio, language):\n tile = get_object_or_404(Tile.objects.select_related('box','sample', 'design'), pk=id)\n tile_order_dto = TileOrderDto(tile, portfolio, language)\n return tile_order_dto\n\n def get_in_stock_tiles(ids, is_sample, limit, offset, language):\n \n if ids:\n tiles = Tile.objects.filter(design__group__collection__id__in=ids)\n else:\n tiles = Tile.objects.all()\n \n if is_sample == 'true':\n tiles = tiles.filter(is_sample=True).order_by('name')\n elif is_sample == 'false' or is_sample is None:\n tiles = tiles.filter(is_sample=False).order_by('name')\n \n tiles = tiles.exclude(image='')\n tiles = tiles.filter(design__isnull=False)\n\n instock_dto = [InStockDto(tile, is_sample, language)\n for tile in tiles[offset:(limit+offset)]]\n return instock_dto\n\n def get_tiles_collections_filters(language):\n collections = Collection.objects.filter(featured=True)\n collectiondto = [CollectionsFiltersDto(collection, language) for collection in collections]\n return collectiondto\n \n \n def get_recent_tiles(language):\n recent_tiles = Tile.objects.order_by('-id')[:8]\n recent_tiles_dto = [RecentTilesDto(tile, language) for tile in recent_tiles]\n return recent_tiles_dto\n\n\nclass PortfolioService:\n\n def get_tile(id):\n return get_object_or_404(Tile, pk=id)\n\n def get_portfolio(user):\n return get_object_or_404(Portfolio, user=user)\n\n def get_portfolio_tile(id):\n return get_object_or_404(PortfolioTile, pk=id)\n\n def get_customized_tile(id):\n return get_object_or_404(CustomizedTile, pk=id)\n\n def get_layout(id):\n return get_object_or_404(Layout, pk=id)\n\n def show_tiles(user, language):\n portfolio = PortfolioService.get_portfolio(user)\n portfolio_tiles_dto = [PortfolioTilesDto(portfolio_tile.id, portfolio_tile.tile, language)\n for portfolio_tile in portfolio.tiles.all()]\n portfolio_tiles_dto += [PortfolioTilesDto(portfolio_tile.id, portfolio_tile.tile, language, isCustomTile=True, colorGroups=portfolio_tile.color_groups.all())\n for portfolio_tile in portfolio.customized_tiles.all()]\n return portfolio_tiles_dto\n\n def remove_tile(request, id):\n portfolio = PortfolioService.get_portfolio(request.user)\n if request.query_params.get('isCustomTile', False):\n CustomizedTile.objects.get(pk=id).delete()\n else:\n portfolio.tiles.get(pk=id).delete()\n\n def add_tile(request, id):\n portfolio = PortfolioService.get_portfolio(request.user)\n tile = PortfolioService.get_tile(id)\n portfolio.tiles.create(tile=tile)\n\n def show_layouts(user):\n portfolio = PortfolioService.get_portfolio(user)\n layouts_dto = [LayoutDto(layout) for layout in portfolio.layouts.all()]\n return layouts_dto\n\n def create_layout(request, id, name, length_ft, length_in, width_ft, width_in, image):\n portfolio = PortfolioService.get_portfolio(request.user)\n data = {\n 'name': name,\n 'length_ft': length_ft,\n 'length_in': length_in,\n 'width_ft': width_ft,\n 'width_in': width_in,\n 'image': image\n }\n \n portfolio.layouts.update_or_create(pk=id, defaults=data)\n \n def layout_tiles(portfolio, language):\n layout_tiles_dto = [LayoutTilesDto(portfolio_tile.tile, language)\n for portfolio_tile in portfolio.tiles.all()]\n return layout_tiles_dto\n\n def duplicate_layout(portfolio, id):\n layout = Layout.objects.get(pk=id)\n layout.id = None\n layout.name = layout.name + ' ' + _('copy')\n layout.save()\n\n def show_customized_tiles(portfolio, language):\n customized_tiles_dto = [PortfolioCustomTilesDto(custom_tile.id, custom_tile.tile, language)\n for customtile in portfolio.customized_tiles.all()]\n return customized_tiles_dto\n\n def show_customized_tile(id, language):\n customized_tile = PortfolioService.get_customized_tile(id)\n customized_tile_dto = PortfolioCustomizedTilesDto(customized_tile, language)\n return customized_tile_dto\n\n def update_or_create_customized_tile(customized_tile, color_groups):\n for color_group in color_groups:\n color = get_object_or_404(PalleteColor, pk=color_group['colorId'])\n data = {'color':color}\n\n GroupColor.objects.update_or_create(\n customized_tile=customized_tile,\n group= color_group['group'],\n defaults=data\n )\n return {'customizedTileId': customized_tile.id, 'colorGroups': color_groups}\n\n def add_customized_tile(request, tile_id, color_groups):\n portfolio = PortfolioService.get_portfolio(request.user)\n tile = PortfolioService.get_tile(tile_id)\n customized_tile = CustomizedTile.objects.create(tile=tile, portfolio=portfolio)\n\n return PortfolioService.update_or_create_customized_tile(customized_tile, color_groups)\n\n def remove_customized_tile(portfolio, customizedtile_id):\n portfolio.customized_tiles.get(pk=customizedtile_id).delete()\n\n def update_customized_tile(request, customized_tile_id, color_groups):\n portfolio = PortfolioService.get_portfolio(request.user)\n customized_tile = PortfolioService.get_customized_tile(customized_tile_id)\n\n return PortfolioService.update_or_create_customized_tile(customized_tile, color_groups)\n\n\nclass PalleteColorService:\n\n def get_pallete_colors(language):\n pallete_colors_dto = [TileColorDto(pallete_color, language) for pallete_color in PalleteColor.objects.all()]\n return pallete_colors_dto\n","repo_name":"rogergaitan/granadatiles","sub_path":"granadatiles_project/apps/tiles/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":11768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38792405294","text":"\"\"\"\n조건\n1. 실수 1개를 입력을 받아 저장합니다.\n2. 0보다 큰 양수인 경우 5를 곱해 출력합니다.\n3. 0보다 작은 음수인 경우 5로 나눠 출력합니다.\n4. 0일 경우 <연산할 대상이 없습니다>라고 출력합니다.\n\n\"\"\"\n# if/else만 사용 시\nfnum = float(input(\"실수 입력 >> \"))\nif fnum == 0:\n print(\"연산할 대상이 없습니다.\")\nelse:\n if fnum > 0:\n result = fnum * 5\n \n else:\n result = fnum / 5\n print(\"연산결과 : %.1f\"%(result))\n\n# elif문 사용시\nword = \"연산결과 : %.1f\"\nif fnum > 0 :\n fnum *= 5\n print(word(fnum))\nelif fnun < 0:\n fnum /= 5\n print(word(fnum))\nelse:\n print(\"연산할 대상이 없습니다.\")","repo_name":"LeeBG/PythonStudy","sub_path":"day08/07.조건문EX6.py","file_name":"07.조건문EX6.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30756979690","text":"# reverse a number using a while loop.\n# Sample Input: num = 12345\n# Sample Output: rev num = 54321\ndef reverse_number(number):\n reversed_num = 0\n while number > 0:\n remainder = number % 10\n reversed_num = reversed_num * 10 + remainder\n number //= 10\n return reversed_num\n\n# Sample Input\nnum = 12345\n\n# Call the function to reverse the number\nrevnum = reverse_number(num)\n\n# Print the output\nprint(\"Reversed number:\", revnum)\n","repo_name":"ghanshyam17/python_assignment","sub_path":"Beginner/Q12.py","file_name":"Q12.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72325829285","text":"# #46 – Contagem regressiva\n#Mostre na tela uma contagem regressiva para o estouro de fogos de artificio indo de 10 a 0 com uma pausa de 1 segundo entre eles\nfrom time import sleep\nn = input('Quer começar? Sim ou Não? ')\nif n == 'Sim':\n for c in range(10, -1, -1):\n print(c)\n sleep(1)\n print('FELIZ ANO NOVO!!!')\nelse:\n print('Fim do programa')\n\n\n","repo_name":"arthur-americo/Python_Study","sub_path":"18 New Year’s Countdown.py","file_name":"18 New Year’s Countdown.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13744712396","text":"import os\nimport pyodbc\nimport logging\nimport json\n\n\ndef prompt_for_database_password_if_not_set(**args) -> tuple:\n db_host = args.get('db_host')\n environment = args.get('environment')\n if not args.get('db_password'):\n args['db_password'] = input(\"What's the database password for {} ({})\".format(environment, db_host))\n return True, args\n\n\ndef set_environment_variables(**args) -> tuple:\n config = args.get('config')\n environment = args.get('environment')\n if environment == \"PROD\":\n args['db_host'] = config.PROD_DB_HOST\n args['db_name'] = config.PROD_DB_NAME\n args['db_username'] = config.PROD_DB_USERNAME\n args['db_password'] = config.PROD_DB_PASSWORD\n args['share_db'] = config.PROD_SHARE_DB\n args['share_local'] = config.PROD_SHARE_LOCAL\n else:\n args['db_host'] = config.TEST_DB_HOST\n args['db_name'] = config.TEST_DB_NAME\n args['db_username'] = config.TEST_DB_USERNAME\n args['db_password'] = config.TEST_DB_PASSWORD\n args['share_db'] = config.TEST_SHARE_DB\n args['share_local'] = config.TEST_SHARE_LOCAL\n return True, args\n\n\ndef get_database_connection_string(**args) -> tuple:\n config = args.get('config')\n connection_string = \"DRIVER={{{}}};SERVER={};DATABASE={};UID={};PWD={}\".format(\n config.ODBC_DRIVER,\n args.get('db_host'),\n args.get('db_name'),\n args.get('db_username'),\n args.get('db_password')\n )\n logging.debug(connection_string)\n args['connection_string'] = connection_string\n return True, args\n\n\ndef get_database_connection(**args) -> tuple:\n connection_string = args.get('connection_string')\n try:\n connection = pyodbc.connect(connection_string)\n cursor = connection.cursor()\n args['connection'] = connection\n args['cursor'] = cursor\n except pyodbc.DatabaseError as error:\n logging.warning(\"Unable to connect\")\n logging.warning(str(error))\n return False, args\n return True, args\n\n\ndef create_temporary_table(**args) -> tuple:\n config = args.get('config')\n header_record = args.get('header_record')\n destination_schema = args.get('destination_schema')\n cursor = args.get('cursor')\n connection = args.get('connection')\n sql = \"CREATE TABLE {} ({})\".format(\n config.TEMPORARY_TABLE_NAME,\n _create_table_columns(header_record, destination_schema))\n try:\n cursor.execute(sql)\n except pyodbc.DatabaseError as e:\n connection.rollback()\n connection.commit()\n logging.debug(\"SUCCESS: {}\".format(sql))\n return True, args\n\n\ndef _create_table_columns(header_record, destination_schema) -> str:\n result = list()\n for column_name in header_record:\n column = destination_schema[column_name]\n if column['DATA_TYPE'] == 'varchar':\n result.append(\"{} VARCHAR({})\".format(column_name, _varchar_length(column['CHARACTER_MAXIMUM_LENGTH'])))\n elif column['DATA_TYPE'] == 'numeric':\n result.append(\"{} NUMERIC({},{})\".format(\n column_name,\n column['NUMERIC_PRECISION'],\n column['NUMERIC_SCALE']))\n elif column['DATA_TYPE'] == 'smallint':\n result.append(\"{} SMALLINT\".format(column_name))\n elif column['DATA_TYPE'] == 'int':\n result.append(\"{} INT\".format(column_name))\n elif column['DATA_TYPE'] == 'date':\n result.append(\"{} DATE\".format(column_name))\n elif column['DATA_TYPE'] == 'datetime':\n result.append(\"{} DATETIME\".format(column_name))\n elif column['DATA_TYPE'] == 'datetime2':\n result.append(\"{} DATETIME2\".format(column_name))\n elif column['DATA_TYPE'] == 'time':\n result.append(\"{} TIME\".format(column_name))\n else:\n logging.critical('data type not found: {}'.format(column))\n\n result_string = \", \".join(result)\n logging.debug(result_string)\n return result_string\n\n\ndef _varchar_length(max_length: int) -> str:\n \"\"\"\n MS-SQL uses '-1' to indicate VARCHAR(MAX)\n This returns \"MAX\" when length is '-1'; otherwise length\n \"\"\"\n if max_length < 0:\n return \"MAX\"\n return str(max_length)\n\n\ndef get_destination_table_schema(**args) -> tuple:\n destination_table = args.get('destination_table')\n destination = destination_table.split('.')\n schema = dict()\n cursor = args.get('cursor')\n columns = ['UPPER(COLUMN_NAME)', 'DATA_TYPE', 'CHARACTER_MAXIMUM_LENGTH',\n 'NUMERIC_PRECISION', 'NUMERIC_SCALE', 'IS_NULLABLE']\n sql = \"SELECT {} FROM {}.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{}' AND TABLE_SCHEMA='{}';\".format(\n ','.join(columns),\n args.get('db_name'),\n destination[1],\n destination[0])\n try:\n records = cursor.execute(sql).fetchall()\n except pyodbc.DatabaseError as e:\n logging.critical(str(e))\n return False, args\n if len(records) == 0:\n logging.critical('unable to find destination table: {}'.format(destination_table))\n return False, args\n for row in records:\n column_name = row[0]\n schema[column_name] = dict(zip(columns, row))\n logging.debug(sql)\n logging.debug(\"destination table schema: {}\".format(json.dumps(schema)))\n args['destination_schema'] = schema\n return True, args\n\n\ndef get_destination_primary_keys(**args) -> tuple:\n destination_table = args.get('destination_table')\n destination = destination_table.split('.')\n primary_keys = list()\n cursor = args.get('cursor')\n sql = \" SELECT Col.Column_Name FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, \"\n sql += \"INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col \"\n sql += \"WHERE \"\n sql += \"Col.Constraint_Name = Tab.Constraint_Name \"\n sql += \"AND Col.Table_Name = Tab.Table_Name \"\n sql += \"AND Constraint_Type = 'PRIMARY KEY' \"\n sql += \"AND Col.Table_Name = '{}' \".format(destination[1])\n sql += \"AND Col.CONSTRAINT_SCHEMA = '{}'\".format(destination[0])\n\n try:\n records = cursor.execute(sql).fetchall()\n except pyodbc.DatabaseError as e:\n logging.critical(str(e))\n return False, args\n\n for row in records:\n primary_keys.append(row[0])\n if len(records) == 0:\n logging.critical('{} has no primary keys - aborting'.format(destination_table))\n return False, args\n logging.debug(sql)\n logging.debug(\"primary keys: \" + str(primary_keys))\n args['primary_keys'] = primary_keys\n return True, args\n\n\ndef count_temporary_table_records(**args) -> tuple:\n config = args.get('config')\n cursor = args.get('cursor')\n sql = \"SELECT count(*) FROM {}\".format(config.TEMPORARY_TABLE_NAME)\n row = cursor.execute(sql).fetchone()\n print(\"number of rows in {}: {}\".format(config.TEMPORARY_TABLE_NAME, row[0]))\n return True, args\n\n\ndef merge_temporary_table_into_destination(**args) -> tuple:\n header_record = args.get('header_record')\n primary_keys = args.get('primary_keys')\n filename = args.get('filename')\n destination_table = args.get('destination_table')\n is_dry_run = args.get('is_dry_run')\n config = args.get('config')\n cursor = args.get('cursor')\n connection = args.get('connection')\n sql = \"MERGE {0} c USING {1} cu ON ({2}) \".format(\n destination_table,\n config.TEMPORARY_TABLE_NAME,\n _merge_on_primary_keys(primary_keys, 'cu', 'c'))\n sql += \"WHEN MATCHED THEN UPDATE SET {} \".format(\n _comma_separated_string_of_matched_columns(header_record, \"cu\", \"c\"))\n sql += \"WHEN NOT MATCHED BY TARGET THEN INSERT ({}) VALUES ({});\".format(\n comma_separated_string_of_column_names(header_record),\n comma_separated_string_of_column_names(header_record, \"cu.\")\n )\n logging.debug(\"sql: \" + sql)\n try:\n cursor.execute(sql)\n except pyodbc.OperationalError as err:\n logging.warning(err)\n connection.rollback()\n logging.critical('rollback complete')\n return False, args\n except pyodbc.DataError as err:\n logging.warning(err)\n connection.rollback()\n logging.critical('rollback complete')\n return False, args\n except pyodbc.IntegrityError as err:\n logging.warning(err)\n connection.rollback()\n logging.critical('rollback complete')\n return False, args\n except pyodbc.ProgrammingError as err:\n logging.warning(err)\n connection.rollback()\n logging.critical('rollback complete')\n return False, args\n except pyodbc.NotSupportedError as err:\n logging.warning(err)\n connection.rollback()\n logging.critical('rollback complete')\n return False, args\n except pyodbc.DatabaseError as err:\n logging.warning(err)\n connection.rollback()\n logging.critical('rollback complete')\n return False, args\n except pyodbc.Error as err:\n logging.warning(err)\n connection.rollback()\n logging.critical('rollback complete')\n return False, args\n if not is_dry_run:\n connection.commit()\n print(\"SUCCESS: {} has been merged to into {}\".format(filename, destination_table))\n else:\n print(\"DRY RUN OPTION SELECTED - NO CHANGES COMMITTED\")\n return True, args\n\n\ndef close_database_connection(**args) -> tuple:\n cursor = args.get('cursor')\n connection = args.get('connection')\n cursor.close()\n connection.close()\n return True, args\n\n\ndef output_is_database(**args) -> tuple:\n return args.get('environment') in ['TEST', 'PROD'], args\n\n\ndef comma_separated_string_of_column_names(header_record, prefix='') -> str:\n result = list()\n for column in header_record:\n result.append(prefix + column)\n return \", \".join(result)\n\n\ndef _merge_on_primary_keys(primary_keys, prefix_a, prefix_b) -> str:\n result = list()\n for column in primary_keys:\n result.append(\"{1}.{0} = {2}.{0}\".format(\n column,\n prefix_a,\n prefix_b\n ))\n return \" AND \".join(result)\n\n\ndef _comma_separated_string_of_matched_columns(header_record, temporary: str, destination: str) -> str:\n result = list()\n for column in header_record:\n result.append(\"{1}.{0} = {2}.{0}\".format(\n column,\n destination,\n temporary\n ))\n return \", \".join(result)\n\n\ndef bulk_import_from_text_file(**args) -> tuple:\n config = args.get('config')\n share_db_path = args.get('share_db')\n destination_filename = args.get('destination_filename')\n filepath_array = os.path.split(destination_filename)\n filename = share_db_path + filepath_array[1]\n cursor = args.get('cursor')\n connection = args.get('connection')\n sql = \"BULK INSERT {} FROM '{}' WITH \".format(config.TEMPORARY_TABLE_NAME, filename)\n sql += \"(FIRSTROW = 2, FIELDTERMINATOR ='|', ROWTERMINATOR = '0x0a')\"\n\n logging.debug(\"sql: \" + sql)\n try:\n cursor.execute(sql)\n except pyodbc.DatabaseError as e:\n connection.rollback()\n logging.critical('error writing to db ' + str(e))\n return False, args\n connection.commit()\n print(\"bulk import to {} complete\".format(config.TEMPORARY_TABLE_NAME))\n return True, args\n\n","repo_name":"bcgov/mssql-csv-import-tool","sub_path":"src/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":11251,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"39194326086","text":"#!python3\n\nimport os\nimport re\n\n\ndef splitall(path):\n # thanks oreilly\n # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch04s16.html\n allparts = []\n while 1:\n parts = os.path.split(path)\n if parts[0] == path: # sentinel for absolute paths\n allparts.insert(0, parts[0])\n break\n elif parts[1] == path: # sentinel for relative paths\n allparts.insert(0, parts[1])\n break\n else:\n path = parts[0]\n allparts.insert(0, parts[1])\n return allparts\n\n\ndef replace_relative_links_for_line(line, nb_up, logger):\n re_link = r'\\[[^\\]]*\\]\\((.*)(?=\\\"|\\))(\\\".*\\\")?\\)'\n re_image = r'!' + re_link\n\n updated = False\n if '{./.}' in line:\n # process_images\n if re.search(re_image, line):\n if logger:\n logger.debug('image : {}'.format(line))\n line = line.replace('{./.}', '../' * (nb_up - 2))\n\n # process links\n elif re.search(re_link, line):\n if logger:\n logger.debug('link : {}'.format(line))\n line = line.replace('{./.}', '../' * (nb_up - 1))\n\n updated = True\n\n return line, updated\n\n\ndef compute_relative_links(file_path, logger=False):\n\n if file_path != '.md' and file_path.endswith('.md'):\n splitted = splitall(file_path)\n if logger:\n logger.debug(splitted)\n nb_up = len(splitted)\n new_lines = []\n nb_links = 0\n\n # Read file and throw updates to memory\n with open(file_path, 'r') as old_file:\n for line in old_file:\n new_line, updated = replace_relative_links_for_line(line, nb_up, logger)\n new_lines.append(new_line)\n nb_links += updated\n # Erase file with new contents\n with open(file_path, 'w') as new_file:\n new_file.writelines(new_lines)\n\n logger.info('{} link{} updated in {}'.format(nb_links if nb_links else 'no',\n 's' if nb_links > 1 else '',\n file_path))\n","repo_name":"flocurity/mdpp2MkDocs","sub_path":"files/update_links.py","file_name":"update_links.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5900680290","text":"#!/usr/bin/env python\n\nfrom AdventOfCode import read_data\n\n\ndef day(data, part):\n # Scores: 1 for Rock, 2 for Paper, and 3 for Scissors. 0 for loss, 3 for tie, 6 for win.\n # A for Rock, B for Paper, and C for Scissors\n # For part 1:\n # X for Rock, Y for Paper, and Z for Scissors\n # For part 2:\n # X for loss, Y for tie, and Z for win.\n\n score_map = {'A': 1, 'B': 2, 'C': 3}\n score = 0\n\n for line in data:\n opponent, me = line.split(' ')\n\n # Convert from the 'XYZ' format to the 'ABC' format.\n if part == 1:\n me = {'X': 'A', 'Y': 'B', 'Z': 'C'}[me]\n elif part == 2:\n if me == 'X':\n me = {'A': 'C', 'B': 'A', 'C': 'B'}[opponent]\n elif me == 'Y':\n me = opponent\n elif me == 'Z':\n me = {'A': 'B', 'B': 'C', 'C': 'A'}[opponent]\n\n # Shape score.\n score += score_map[me]\n\n # Win/loss score.\n if me == opponent:\n score += 3\n elif ( (me == 'A' and opponent == 'C') or\n (me == 'B' and opponent == 'A') or\n (me == 'C' and opponent == 'B')):\n score += 6\n # print(f\"opp: {opponent}, me: {me}, score {score}\")\n\n # print(f\"Answer for 2022 day 2 part {part}: {score}\")\n return score\n\n\ndef main():\n data = read_data(__file__)\n answer1 = day(data, part=1)\n answer2 = day(data, part=2)\n return answer1, answer2\n\n\nexpected_answers = 10941, 13071\n","repo_name":"ViridisWolf/AdventOfCode","sub_path":"y2022/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24326623457","text":"n = int(input())\nx = list(map(int, input().split()))\nmax_x = max(x)\ncnt = 0\ngroup = 0\nx.sort() #작은 것부터 봐야지 많이 할 수 있음 만약에 6개 중에 6이 젤 큰데 6부터 세면 하나밖에 못만듦\nfor i in x:\n cnt += 1\n if cnt >= i: \n group+=1\n cnt = 0\n\nprint(group)\n","repo_name":"c-min-ji/python-for-coding-test","sub_path":"algorithm/Example_Problem/adventure.py","file_name":"adventure.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28711258899","text":"from flask import Flask, request, g\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine, select, MetaData, Table\nfrom flask import jsonify\nimport json\nimport eth_account\nimport algosdk\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm import scoped_session\nfrom sqlalchemy.orm import load_only\n\nfrom models import Base, Order, Log\nengine = create_engine('sqlite:///orders.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\n\napp = Flask(__name__)\n\n#These decorators allow you to use g.session to access the database inside the request code\n@app.before_request\ndef create_session():\n g.session = scoped_session(DBSession) #g is an \"application global\" https://flask.palletsprojects.com/en/1.1.x/api/#application-globals\n\n@app.teardown_appcontext\ndef shutdown_session(response_or_exc):\n g.session.commit()\n g.session.remove()\n\n\"\"\"\n-------- Helper methods (feel free to add your own!) -------\n\"\"\"\n\ndef log_message(d):\n # Takes input dictionary d and writes it to the Log table\n pass\n\n\"\"\"\n---------------- Endpoints ----------------\n\"\"\"\n@app.route(\"/\")\ndef home():\n return \"Hello, Flask!\"\n\n\n@app.route('/trade', methods=['POST'])\ndef trade():\n if request.method == \"POST\":\n content = request.get_json(silent=True)\n print( f\"content = {json.dumps(content)}\" )\n columns = [ \"sender_pk\", \"receiver_pk\", \"buy_currency\", \"sell_currency\", \"buy_amount\", \"sell_amount\", \"platform\" ]\n fields = [ \"sig\", \"payload\" ]\n error = False\n for field in fields:\n if not field in content.keys():\n print( f\"{field} not received by Trade\" )\n print( json.dumps(content) )\n log_message(content)\n return jsonify( False )\n \n error = False\n for column in columns:\n if not column in content['payload'].keys():\n print( f\"{column} not received by Trade\" )\n error = True\n if error:\n print( json.dumps(content) )\n log_message(content)\n return jsonify( False )\n \n #Your code here\n #Note that you can access the database session using g.session\n #x = g.session.query(Order).all()\n sig = content['sig']\n pk = content['payload']['sender_pk']\n platform = content['payload']['platform']\n payload = content['payload']\n payload2= json.dumps(payload)\n order = {'sender_pk': payload['sender_pk'],\n 'receiver_pk': payload['receiver_pk'],\n 'buy_currency': payload['buy_currency'],\n 'sell_currency': payload['sell_currency'],\n 'buy_amount': payload['buy_amount'],\n 'sell_amount': payload['sell_amount'],\n 'signature':sig\n }\n order_obj = Order( sender_pk=order['sender_pk'],\n receiver_pk=order['receiver_pk'],\n buy_currency=order['buy_currency'], \n sell_currency=order['sell_currency'], \n buy_amount=order['buy_amount'], \n sell_amount=order['sell_amount'],\n signature=order['signature'] )\n\n logError = {'message':payload2}\n log_obj = Log(message = logError['message'])\n\n \n \n\n result = False\n try:\n if platform == \"Ethereum\":\n eth_encoded_msg = eth_account.messages.encode_defunct(text=payload2)\n if (eth_account.Account.recover_message(eth_encoded_msg,signature=sig) == pk):\n result = True\n elif platform == \"Algorand\":\n #result = algosdk.util.verify_bytes(message.encode('utf-8'),sig,pk)\n if algosdk.util.verify_bytes(payload2.encode('utf-8'),sig,pk):\n result = True\n else:\n result = False\n except:\n print(\"verification part throw exception\")\n result = False\n \n #If the signature verifies, store the signature, as well as all of the fields under the ‘payload’ in the “Order” \n # #table EXCEPT for 'platform’.\n if result:\n g.session.add(order_obj)\n g.session.commit()\n return jsonify(order)\n \n\n # If the signature does not verify, do not insert the order into the “Order” table.\n # Instead, insert a record into the “Log” table, with the message field set to be json.dumps(payload).\n else:\n g.session.add(log_obj)\n g.session.commit()\n return jsonify(logError)\n \n\n@app.route('/order_book')\ndef order_book():\n #Your code here\n #Note that you can access the database session using g.session\n result = []\n for u in g.session.query(Order).all():\n dic = u.__dict__\n newDic = {k:dic[k] for k in [\"sender_pk\",\"receiver_pk\",\"buy_currency\",\"sell_currency\",\"buy_amount\",\"sell_amount\",\"signature\"]}\n result.append(newDic)\n \n res2 = {\"data\":result}\n\n return jsonify(res2)\n\nif __name__ == '__main__':\n app.run(port='5002')\n","repo_name":"changleipenn/582","sub_path":"database_endpoint.py","file_name":"database_endpoint.py","file_ext":"py","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27521972331","text":"#\n# DietProblemSolver_Gurobi.py\n#\n# Gurobi version of the diet solver.\n#\n\nfrom DietProblemSolver import DietProblemSolver\n\nimport gurobipy as gp\nfrom gurobipy import GRB\n\nimport subprocess\n\n\nclass DietProblemSolver_Gurobi (DietProblemSolver):\n\n #\n # GetSolverName... returns the name and version of the solver instance\n #\n def GetSolverName (self): \n\n # this isn't the nicest way of doing this but it works for now...\n versionOutput = subprocess.check_output ('/usr/local/bin/gurobi_cl --version', shell=True)\n versionOutput = versionOutput.decode ('utf-8')\n version = versionOutput.split ('\\n')\n\n return (version[0])\n\n\n #\n # BuildModel... build a gurobi model \n #\n def BuildModel (self):\n\n # print ('DietProblemSolver_Gurobi buildModel')\n\n # make the model\n self._model = gp.Model ('DietProblem')\n\n # Create the decision variables... one by one\n self._amountsToBuy = {}\n for food in self._foodNames:\n self._amountsToBuy [food] = self._model.addVar (name=food)\n\n # make and assign the objective function\n expression = gp.LinExpr ()\n for food in self._foodNames:\n # note addTerms parameters are in the form of value then variable\n expression.addTerms (self._foodCosts [food]['unitCost'], self._amountsToBuy [food])\n\n self._model.setObjective (expression, GRB.MINIMIZE)\n\n # Add constraints...\n for category in self._nutrientNames:\n expression = gp.LinExpr ()\n for food in self._foodNames:\n expression.addTerms (self._nutrientData[food][category], self._amountsToBuy[food])\n\n self._model.addRange (expression, \\\n self._dietaryReqs[category]['min'], \\\n self._dietaryReqs[category]['max'], \\\n category) \n\n\n #\n # SolveModel... optimize the model. Note that Gurobi likes outputting a lot of text to the screen\n #\n def SolveModel (self):\n\n #print ('DietProblemSolver_Gurobi solvemodel')\n\n if self._model != None:\n # note that optimize does not return a value\n self._model.optimize ()\n\n\n #\n # PrintResults\n #\n def PrintResults (self):\n\n #print ('DietProblemSolver_Gurobi printresults')\n\n if self._model.status == GRB.OPTIMAL:\n\n print ()\n\n modelVars = self._model.getVars ()\n\n # Display the amounts to purchase of each food.\n print ('Foods to Buy: ')\n totalCost = 0\n for var in modelVars:\n if var.varName in self._foodNames and var.x > 0.0001:\n totalCost += var.x * self._foodCosts [var.varName][\"unitCost\"]\n print (f'{var.varName:25} --> {var.x:8.3f} units/servings $ {(var.x * self._foodCosts [var.varName][\"unitCost\"]):.3f}')\n\n print ()\n print (f'Objective function results: {self._model.objVal}')\n print (f'Total daily cost: {totalCost:.2f}')\n print ()\n\n print ('Nutrient amounts... ')\n for nutrient in self._nutrientNames:\n total = 0\n for var in modelVars:\n if var.varName in self._foodNames and var.x > 0.0001:\n total += var.x * self._nutrientData [var.varName][nutrient]\n\n print (f' {nutrient:15} {total:7.2f}')\n\n else: \n\n print ('No solution')\n\n\n","repo_name":"adc-code/OptimizationProblems","sub_path":"DietProblem/Solve_DietProblem_Wrapper/DietProblemSolver_Gurobi.py","file_name":"DietProblemSolver_Gurobi.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"7597333318","text":"documents = ['Hello, how are you!',\n 'Win money, win from home.',\n 'Call me now.',\n 'Hello, Call hello you tomorrow?']\n\n\n# convert all entries to lower case\nlower_case_documents = []\nfor i in documents:\n lower_case_documents.append(i.lower())\nprint(lower_case_documents)\n\n\n# remove all punctuation\nimport string\nsans_punctuation_documents = []\nfor i in lower_case_documents:\n sans_punctuation_documents.append(i.translate(None, string.punctuation))\nprint(sans_punctuation_documents)\n\n\n# tokenization\npreprocessed_documents = []\nfor i in sans_punctuation_documents:\n preprocessed_documents.append(i.split())\nprint(preprocessed_documents)\n\n\n# count frequencies\nfrequency_list = []\nimport pprint\nfrom collections import Counter\n\nfor i in preprocessed_documents:\n frequency_counts = Counter(i)\n frequency_list.append(frequency_counts)\n\nprint(frequency_list)\npprint.pprint(frequency_list)\n\n\n\n''' BoW using scikit-learn '''\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport pandas\n\ncount_vector = CountVectorizer()\ncount_vector.fit(documents) # fit documents\nprint(count_vector.get_feature_names()) # print out features' name\n\n# create matrix\n# each row = each entry/document\n# each column = frequency of tokens\ndoc_array = count_vector.transform(documents).toarray()\nprint(doc_array)\n\n# convert the matrix into a dataframe and set column names to word names\nfrequency_matrix = pandas.DataFrame(doc_array,\n columns = count_vector.get_feature_names())\nprint(frequency_matrix)","repo_name":"qdthoang/MLND-myProjects","sub_path":"P0-spamDetection-naiveBayes/bagOfWordsFromScratch.py","file_name":"bagOfWordsFromScratch.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29210259455","text":"from datetime import timedelta\nfrom unittest.mock import patch\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.cache import cache\nfrom django.core.exceptions import ValidationError\nfrom django.db import IntegrityError\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom swapper import load_model\n\nfrom openwisp_utils.tests import catch_signal\n\nfrom ..exceptions import InvalidChartConfigException, InvalidMetricConfigException\nfrom ..signals import post_metric_write, pre_metric_write, threshold_crossed\nfrom . import TestMonitoringMixin\n\nstart_time = timezone.now()\nten_minutes_ago = start_time - timedelta(minutes=10)\nMetric = load_model('monitoring', 'Metric')\nAlertSettings = load_model('monitoring', 'AlertSettings')\nNotification = load_model('openwisp_notifications', 'Notification')\n\n\nclass TestModels(TestMonitoringMixin, TestCase):\n def tearDown(self):\n cache.clear()\n super().tearDown()\n\n def test_general_metric_str(self):\n m = Metric(name='Test metric')\n self.assertEqual(str(m), m.name)\n\n def test_chart_str(self):\n c = self._create_chart()\n self.assertEqual(str(c), c.label)\n\n def test_chart_no_valid_config(self):\n c = self._create_chart()\n c.configuration = 'invalid'\n try:\n c.full_clean()\n except ValidationError as e:\n self.assertIn('configuration', e.message_dict)\n else:\n self.fail()\n\n def test_metric_no_valid_config(self):\n m = self._create_object_metric()\n m.configuration = 'invalid'\n with self.assertRaises(InvalidMetricConfigException):\n m.full_clean()\n\n def test_invalid_chart_config(self):\n c = self._create_chart(test_data=False)\n c.configuration = 'invalid'\n with self.assertRaises(InvalidChartConfigException):\n c.config_dict\n\n def test_metric_related_fields(self):\n m = self._create_object_metric()\n self.assertEqual(m.related_fields, [])\n m.configuration = 'ping'\n m.full_clean()\n self.assertEqual(m.related_fields, ['loss', 'rtt_min', 'rtt_max', 'rtt_avg'])\n\n def test_general_codename(self):\n m = Metric(name='Test metric-(1)')\n self.assertEqual(m.codename, 'test_metric_1')\n m = Metric()\n self.assertEqual(m.codename, '')\n\n def test_metric_key_contains_dash(self):\n m = self._create_general_metric(key='br-lan')\n self.assertEqual(m.key, 'br_lan')\n\n def test_metric_key_contains_dot(self):\n m = self._create_general_metric(key='eth0.2')\n self.assertEqual(m.key, 'eth0_2')\n\n def test_object_metric_str(self):\n obj = self._create_user()\n om = self._create_object_metric(name='Logins', content_object=obj)\n om.refresh_from_db()\n expected = '{0} (User: {1})'.format(om.name, obj)\n self.assertEqual(str(om), expected)\n\n def test_general_key(self):\n m = self._create_general_metric()\n self.assertEqual(m.key, m.codename)\n\n def test_object_key(self):\n om = self._create_object_metric()\n self.assertEqual(om.key, om.codename)\n\n def test_custom_get_or_create(self):\n m, created = Metric._get_or_create(name='lan', configuration='test_metric')\n self.assertTrue(created)\n m2, created = Metric._get_or_create(name='lan', configuration='test_metric')\n self.assertEqual(m.id, m2.id)\n self.assertFalse(created)\n\n def test_get_or_create_renamed(self):\n m, created = Metric._get_or_create(name='lan', configuration='test_metric')\n self.assertTrue(created)\n m.name = 'renamed'\n m.save()\n m2, created = Metric._get_or_create(name='lan', configuration='test_metric')\n self.assertEqual(m.id, m2.id)\n self.assertEqual(m2.name, m.name)\n self.assertFalse(created)\n\n def test_get_or_create_renamed_object(self):\n obj = self._create_user()\n ct = ContentType.objects.get_for_model(get_user_model())\n m, created = Metric._get_or_create(\n name='logins',\n configuration='test_metric',\n content_type_id=ct.id,\n object_id=obj.pk,\n )\n self.assertTrue(created)\n m.name = 'renamed'\n m.save()\n m2, created = Metric._get_or_create(\n name='logins',\n configuration='test_metric',\n content_type_id=ct.id,\n object_id=obj.pk,\n )\n self.assertEqual(m.id, m2.id)\n self.assertEqual(m2.name, m.name)\n self.assertFalse(created)\n\n def test_get_or_create_integrity_error(self):\n with patch.object(\n Metric.objects,\n 'get',\n side_effect=[\n Metric.DoesNotExist,\n Metric(name='lan', configuration='test_metric'),\n ],\n ) as mocked_get, patch.object(\n Metric, 'save', side_effect=IntegrityError\n ) as mocked_save:\n metric, _ = Metric._get_or_create(name='lan', configuration='test_metric')\n mocked_save.assert_called_once()\n self.assertEqual(mocked_get.call_count, 2)\n self.assertEqual(metric.name, 'lan')\n self.assertEqual(metric.configuration, 'test_metric')\n\n def test_metric_write_wrong_related_fields(self):\n m = self._create_general_metric(name='ping', configuration='ping')\n extra_values = {'reachable': 0, 'rtt_avg': 0.51, 'rtt_max': 0.6, 'rtt_min': 0.4}\n with self.assertRaisesRegex(\n ValueError, '\"reachable\" not defined in metric configuration'\n ):\n m.write(1, extra_values=extra_values)\n\n def test_batch_metric_write_wrong_related_fields(self):\n m = self._create_general_metric(name='ping', configuration='ping')\n extra_values = {'reachable': 0, 'rtt_avg': 0.51, 'rtt_max': 0.6, 'rtt_min': 0.4}\n with self.assertRaises(ValueError) as error:\n Metric.batch_write(\n [\n (\n m,\n {\n 'value': 1,\n 'extra_values': extra_values,\n },\n ),\n ]\n )\n self.assertEqual(\n error.exception.args[0]['ping'],\n '\"reachable\" not defined in metric configuration',\n )\n\n def test_tags(self):\n extra_tags = {'a': 'a', 'b': 'b1'}\n metric = self._create_object_metric(extra_tags=extra_tags)\n expected_tags = extra_tags.copy()\n expected_tags.update(\n {'object_id': metric.object_id, 'content_type': metric.content_type_key}\n )\n self.assertEqual(metric.tags, expected_tags)\n\n def test_read_general_metric(self):\n m = self._create_general_metric(name='load')\n m.write(50, check=False)\n self.assertEqual(self._read_metric(m)[0][m.field_name], 50)\n m.write(1, check=False)\n self.assertEqual(self._read_metric(m)[0][m.field_name], 50)\n self.assertEqual(self._read_metric(m, order='-time')[0][m.field_name], 1)\n\n def test_read_object_metric(self):\n om = self._create_object_metric(name='load')\n om.write(50)\n om.write(3)\n self._read_metric(om, extra_fields='*')\n self.assertEqual(self._read_metric(om)[0][om.field_name], 50)\n\n def test_alert_settings_max_seconds(self):\n m = self._create_general_metric(name='load')\n try:\n self._create_alert_settings(\n metric=m,\n custom_operator='>',\n custom_threshold=90,\n custom_tolerance=9999999,\n )\n except ValidationError as e:\n self.assertIn('custom_tolerance', e.message_dict)\n else:\n self.fail('ValidationError not raised')\n\n def test_threshold_is_crossed_error(self):\n m = self._create_general_metric(name='load')\n alert_s = self._create_alert_settings(\n metric=m, custom_operator='>', custom_threshold=90, custom_tolerance=0\n )\n with self.assertRaises(ValueError):\n alert_s._is_crossed_by(alert_s, start_time)\n\n def test_threshold_is_crossed_immediate(self):\n m = self._create_general_metric(name='load')\n alert_s = self._create_alert_settings(\n metric=m, custom_operator='>', custom_threshold=90, custom_tolerance=0\n )\n self.assertFalse(alert_s._is_crossed_by(80, start_time))\n self.assertTrue(alert_s._is_crossed_by(91, start_time))\n self.assertTrue(alert_s._is_crossed_by(100, start_time))\n self.assertTrue(alert_s._is_crossed_by(100))\n self.assertFalse(alert_s._is_crossed_by(90, start_time))\n alert_s.custom_operator = '<'\n alert_s.save()\n self.assertTrue(alert_s._is_crossed_by(80))\n\n def test_threshold_is_crossed_deferred(self):\n m = self._create_general_metric(name='load')\n alert_s = self._create_alert_settings(\n metric=m, custom_operator='>', custom_threshold=90, custom_tolerance=9\n )\n self.assertFalse(alert_s._is_crossed_by(95, start_time))\n self.assertTrue(alert_s._is_crossed_by(95, ten_minutes_ago))\n self.assertFalse(alert_s._is_crossed_by(80, start_time))\n self.assertFalse(alert_s._is_crossed_by(80, ten_minutes_ago))\n\n def test_threshold_is_crossed_deferred_2(self):\n self._create_admin()\n m = self._create_general_metric(name='load')\n self._create_alert_settings(\n metric=m, custom_operator='>', custom_threshold=90, custom_tolerance=1\n )\n m.write(60)\n m.write(99)\n m.refresh_from_db(fields=['is_healthy', 'is_healthy_tolerant'])\n self.assertEqual(m.is_healthy, False)\n self.assertEqual(m.is_healthy_tolerant, True)\n\n def test_general_check_threshold_no_exception(self):\n m = self._create_general_metric()\n m.check_threshold(1)\n\n def test_general_metric_signal_emitted(self):\n m = self._create_general_metric(name='load')\n alert_s = self._create_alert_settings(\n metric=m, custom_operator='>', custom_threshold=90, custom_tolerance=0\n )\n with catch_signal(threshold_crossed) as handler:\n m.check_threshold(91)\n handler.assert_called_once_with(\n alert_settings=alert_s,\n first_time=False,\n metric=m,\n target=None,\n sender=Metric,\n signal=threshold_crossed,\n tolerance_crossed=True,\n )\n\n def test_object_metric_signal_emitted(self):\n om = self._create_object_metric()\n alert_s = self._create_alert_settings(\n metric=om, custom_operator='>', custom_threshold=90, custom_tolerance=0\n )\n with catch_signal(threshold_crossed) as handler:\n om.check_threshold(91)\n handler.assert_called_once_with(\n alert_settings=alert_s,\n first_time=False,\n metric=om,\n target=om.content_object,\n sender=Metric,\n signal=threshold_crossed,\n tolerance_crossed=True,\n )\n\n def test_metric_pre_write_signals_emitted(self):\n om = self._create_object_metric()\n with catch_signal(pre_metric_write) as handler:\n om.write(3)\n handler.assert_called_once_with(\n sender=Metric,\n metric=om,\n values={om.field_name: 3},\n signal=pre_metric_write,\n time=None,\n current=False,\n )\n\n def test_metric_post_write_signals_emitted(self):\n om = self._create_object_metric()\n with catch_signal(post_metric_write) as handler:\n om.write(3, current=True, time=start_time)\n handler.assert_called_once_with(\n sender=Metric,\n metric=om,\n values={om.field_name: 3},\n signal=post_metric_write,\n time=start_time.isoformat(),\n current=True,\n )\n\n def test_clean_default_threshold_values(self):\n m = self._create_general_metric(configuration='ping')\n alert_s = AlertSettings(metric=m)\n with self.subTest('Store default values'):\n alert_s.custom_operator = alert_s.operator\n alert_s.custom_threshold = alert_s.threshold\n alert_s.custom_tolerance = alert_s.tolerance\n alert_s.full_clean()\n self.assertIsNone(alert_s.custom_operator)\n self.assertIsNone(alert_s.custom_threshold)\n self.assertIsNone(alert_s.custom_tolerance)\n with self.subTest('Store default and custom values'):\n alert_s.custom_operator = alert_s.operator\n alert_s.custom_threshold = 0.5\n alert_s.custom_tolerance = 2\n alert_s.full_clean()\n self.assertIsNone(alert_s.custom_operator)\n self.assertEqual(alert_s.custom_threshold, 0.5)\n self.assertEqual(alert_s.custom_tolerance, 2)\n\n def test_alert_settings_tolerance_default(self):\n m = self._create_general_metric(name='load')\n alert_s = AlertSettings(metric=m)\n self.assertIsNone(alert_s.custom_tolerance)\n\n def test_tolerance(self):\n self._create_admin()\n m = self._create_general_metric(name='load')\n self._create_alert_settings(\n metric=m, custom_operator='>', custom_threshold=90, custom_tolerance=5\n )\n with self.subTest('within tolerance, no alerts expected'):\n m.write(99, time=timezone.now() - timedelta(minutes=2))\n m.refresh_from_db(fields=['is_healthy', 'is_healthy_tolerant'])\n self.assertEqual(m.is_healthy, False)\n self.assertEqual(m.is_healthy_tolerant, True)\n self.assertEqual(Notification.objects.count(), 0)\n m.write(99, time=timezone.now() - timedelta(minutes=4))\n m.refresh_from_db(fields=['is_healthy', 'is_healthy_tolerant'])\n self.assertEqual(m.is_healthy, False)\n self.assertEqual(m.is_healthy_tolerant, True)\n self.assertEqual(Notification.objects.count(), 0)\n with self.subTest('tolerance trepassed, alerts expected'):\n m.write(99, time=timezone.now() - timedelta(minutes=6))\n m.refresh_from_db(fields=['is_healthy', 'is_healthy_tolerant'])\n self.assertEqual(m.is_healthy, False)\n self.assertEqual(m.is_healthy_tolerant, False)\n self.assertEqual(Notification.objects.count(), 1)\n with self.subTest('value back to normal, tolerance not considered'):\n m.write(71, time=timezone.now() - timedelta(minutes=7))\n m.refresh_from_db(fields=['is_healthy', 'is_healthy_tolerant'])\n self.assertEqual(m.is_healthy, True)\n self.assertEqual(m.is_healthy_tolerant, True)\n self.assertEqual(Notification.objects.count(), 2)\n\n def test_time_crossed(self):\n m = self._create_general_metric(name='load')\n a = self._create_alert_settings(\n metric=m, custom_operator='>', custom_threshold=90, custom_tolerance=5\n )\n\n now = timezone.now()\n self.assertFalse(a._time_crossed(now))\n self.assertFalse(a._time_crossed(now - timedelta(minutes=1)))\n self.assertFalse(a._time_crossed(now - timedelta(minutes=4)))\n self.assertTrue(a._time_crossed(now - timedelta(minutes=5)))\n self.assertTrue(a._time_crossed(now - timedelta(minutes=6)))\n\n def test_get_time_str(self):\n m = self._create_general_metric(name='load')\n now = timezone.now()\n self.assertEqual(m._get_time(now.isoformat()), now)\n\n def test_deleting_metric_deletes_timeseries(self):\n metric1 = self._create_general_metric(name='load')\n metric2 = self._create_general_metric(name='traffic')\n metric1.write(99)\n metric2.write(5000)\n self.assertNotEqual(self._read_metric(metric1), [])\n self.assertNotEqual(self._read_metric(metric2), [])\n metric1.delete()\n self.assertEqual(self._read_metric(metric1), [])\n # Only the timeseries data related to the deleted metric\n # should be deleted\n self.assertNotEqual(self._read_metric(metric2), [])\n\n def test_metric_invalid_field_name(self):\n metric = self._create_general_metric(configuration='test_alert_field')\n metric.field_name = 'invalid_field'\n with self.assertRaises(ValidationError) as err:\n metric.full_clean()\n metric.save()\n self.assertIn(\n f'\"{metric.field_name}\" must be one of the following metric fields',\n str(err.exception),\n )\n\n def test_alert_field_property(self):\n m = self._create_general_metric(configuration='test_alert_field')\n # When metric field_name == config['field_name']\n self.assertEqual(m.field_name, 'test_alert_field')\n # Get the alert_field from the config\n self.assertEqual(m.alert_field, 'test_related_2')\n m.field_name = 'test_related_3'\n m.full_clean()\n m.save()\n # When metric field_name != config['field_name']\n self.assertEqual(m.field_name, 'test_related_3')\n # alert_field same as field_name\n self.assertEqual(m.alert_field, 'test_related_3')\n","repo_name":"openwisp/openwisp-monitoring","sub_path":"openwisp_monitoring/monitoring/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":17465,"program_lang":"python","lang":"en","doc_type":"code","stars":131,"dataset":"github-code","pt":"52"} +{"seq_id":"3202397778","text":"#!/usr/bin/python\n# coding: utf-8\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom caPVArrayLib import caPVArray\nfrom caMonitorArrayParserLib import caMonitorArrayParser \n \ndef printOutHelp():\n print(\"python plotCaMonitor.py [<filename>]\")\n print(\"example: python plotCaMonitor.py xx.txt\")\n print(\"example stdin: cat data.log | grep -E 'thread|CPU' | python plotCaMonitor.py\")\n\ndef main():\n # Check args\n if len(sys.argv)>1:\n print(sys.argv[1])\n pos1=sys.argv[1].find('-h')\n if(pos1>=0):\n printOutHelp()\n sys.exit()\n \n if len(sys.argv)!=2 and len(sys.argv)>1: \n printOutHelp()\n sys.exit()\n \n if len(sys.argv)==2:\n fname=sys.argv[1]\n dataFile=open(fname,'r')\n\n if len(sys.argv)==1:\n fname=\"\"\n dataFile=sys.stdin;\n\n parser=caMonitorArrayParser()\n pvs=[]\n dataBuffer=np.array([]);\n for line in dataFile:\n if not parser.lineValid(line): \n continue\n\n pvName, timeVal, data=parser.getValues(line)\n dataBuffer=np.append(dataBuffer,data[:].astype(np.float))\n print(dataBuffer)\n \n y=dataBuffer\n plt.plot(y)\n plt.legend(\"Data\")\n plt.grid()\n plt.title(\"Wavform data\")\n plt.xlabel(\"time [samples in 20kHz]\")\n plt.ylabel(\"Voltage [raw]\")\n plt.show()\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"anderssandstrom/ecmccomgui","sub_path":"pyDataManip/plotCaMonitorArray.py","file_name":"plotCaMonitorArray.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15326825137","text":"import datasets\nimport transformers\n\nfrom utils import *\n\n\nclass QgDataProcessor:\n \"\"\"\n A data process is responsible for loading a dataset and prepare the input for a downstream task.\n \"\"\"\n # These tokens are for T5-based models only\n SPECIAL_TOKENS = {\n 't5': {'HLS': 'highlight:'}\n }\n path_processed_data = Path(\"models\", \"processed_qgdata\")\n\n def __init__(self, tokenizer: transformers.PreTrainedTokenizer, base_model_type='t5', max_source_len=512,\n max_target_len=32):\n self.dataset = None\n self.tokenizer = tokenizer\n self.max_source_len = max_source_len\n self.max_target_len = max_target_len\n\n # Get the special tokens defined for `base_model_type`\n self.special_tokens = self.SPECIAL_TOKENS[base_model_type]\n # Add custom tokens to the tokenizer\n self.tokenizer.add_tokens(self.special_tokens.values())\n # Get a logger for this class\n self.logger = get_my_logger(self.__class__.__name__)\n\n def load_dataset(self, dataset_name='squad'):\n \"\"\"\n Load the dataset called `dataset_name` via HF Datasets. In this study, we use SQuAD.\n See https://huggingface.co/datasets/squad for more detail about this dataset.\n \"\"\"\n\n if self.path_processed_data.exists():\n self.logger.warn(\"Reuse an existing processed QA dataset\")\n self.dataset = datasets.load_from_disk(str(self.path_processed_data))\n else:\n self.logger.info(\"Build and process a new QA dataset\")\n # Load the dataset via HF Datasets\n dataset = datasets.load_dataset(dataset_name)\n\n # Show the basic information about the dataset\n self.logger.info(f'Base dataset: {dataset_name}')\n # self.logger.info(f\"Dataset Description: {dataset['train'].description}\")\n # self.logger.info(f\"Dataset Citation: {dataset['train'].citation}\")\n # self.logger.info(f\"Dataset Homepage: {dataset['train'].homepage}\")\n # self.logger.info(f\"Dataset License: {dataset['train'].license}\")\n # self.logger.info(f\"Dataset Summary: {dataset}\")\n\n # Reserve the dataset for later processing\n self.dataset = dataset\n # Process the dataset\n self._preprocess_question_types()\n self.dataset.save_to_disk(str(self.path_processed_data))\n\n def get_tokenized_tc_tqa(self, source_prefix, target_prefix):\n \"\"\"\n Answer-aware QG: Typed Context -> Typed Question | Answer\n\n \"\"\"\n source_prefix = (source_prefix.lower() == 'true')\n target_prefix = (target_prefix.lower() == 'true')\n\n def _tokenize(item):\n source = item['context']\n target = f'{item[\"question\"]} {self.special_tokens[\"HLS\"]} {item[\"answers\"][\"text\"][0]}'\n question_type = item['quest_type']\n\n if source_prefix:\n source = f'{question_type}: {source}'\n if target_prefix:\n target = f'{question_type}: {target}'\n\n common_args = {'padding': 'max_length', 'pad_to_max_length': True, 'truncation': True}\n source_tokens = self.tokenizer(source, max_length=self.max_source_len, **common_args)\n target_tokens = self.tokenizer(target, max_length=self.max_target_len, **common_args)\n\n return {\n 'input_ids': source_tokens['input_ids'],\n 'labels': target_tokens['input_ids'],\n 'attention_mask': source_tokens['attention_mask'],\n 'source_text': source,\n 'target_text': target,\n }\n\n return self.dataset.map(_tokenize)\n\n def get_tokenized_tca_tq(self, source_prefix, target_prefix):\n \"\"\"\n Answer-aware QG: Typed Context | Answer -> Typed Question\n\n \"\"\"\n source_prefix = (source_prefix.lower() == 'true')\n target_prefix = (target_prefix.lower() == 'true')\n\n def _tokenize(item):\n source = f'{item[\"context\"]} {self.special_tokens[\"HLS\"]} {item[\"answers\"][\"text\"][0]}'\n target = item['question']\n question_type = item['quest_type']\n\n if source_prefix:\n source = f'{question_type}: {source}'\n if target_prefix:\n target = f'{question_type}: {target}'\n\n common_args = {'padding': 'max_length', 'pad_to_max_length': True, 'truncation': True}\n source_tokens = self.tokenizer(source, max_length=self.max_source_len, **common_args)\n target_tokens = self.tokenizer(target, max_length=self.max_target_len, **common_args)\n\n return {\n 'input_ids': source_tokens['input_ids'],\n 'labels': target_tokens['input_ids'],\n 'attention_mask': source_tokens['attention_mask'],\n 'source_text': source,\n 'target_text': target,\n }\n\n return self.dataset.map(_tokenize)\n\n def get_tokenized_tc_tq(self, source_prefix, target_prefix):\n \"\"\"\n QG: Typed Context -> Typed Question\n \"\"\"\n source_prefix = (source_prefix.lower() == 'true')\n target_prefix = (target_prefix.lower() == 'true')\n\n def _tokenize(item):\n context = item['context']\n question = item['question']\n question_type = item['quest_type']\n\n if source_prefix:\n # Add the question type to the context as prefix to inform the model\n context = f'{question_type}: {context}'\n if target_prefix:\n question = f'{question_type}: {question}'\n\n common_args = {'padding': 'max_length', 'pad_to_max_length': True, 'truncation': True}\n source_tokens = self.tokenizer(context, max_length=self.max_source_len, **common_args)\n target_tokens = self.tokenizer(question, max_length=self.max_target_len, **common_args)\n\n return {\n 'input_ids': source_tokens['input_ids'],\n 'labels': target_tokens['input_ids'],\n 'attention_mask': source_tokens['attention_mask'],\n 'source_text': context,\n 'target_text': question,\n }\n\n return self.dataset.map(_tokenize)\n\n def get_tokenized_tc_ta(self, source_prefix, target_prefix):\n \"\"\"\n KPE: Typed Context -> Typed Answer\n \"\"\"\n source_prefix = (source_prefix.lower() == 'true')\n target_prefix = (target_prefix.lower() == 'true')\n\n def _tokenize(item):\n source, target = item['context'], item['answers']['text'][0]\n question_type = item['quest_type']\n\n if source_prefix:\n source = f'{question_type}: {source}'\n if target_prefix:\n target = f'{question_type}: {target}'\n\n common_args = {'padding': 'max_length', 'pad_to_max_length': True, 'truncation': True}\n source_tokens = self.tokenizer(source, max_length=self.max_source_len, **common_args)\n target_tokens = self.tokenizer(target, max_length=self.max_target_len, **common_args)\n\n return {\n 'input_ids': source_tokens['input_ids'],\n 'labels': target_tokens['input_ids'],\n 'attention_mask': source_tokens['attention_mask'],\n 'source_text': source,\n 'target_text': target,\n }\n\n return self.dataset.map(_tokenize)\n\n def _preprocess_question_types(self):\n \"\"\"\n Process the loaded dataset in `load_dataset()`. This method does the following tasks:\n - Add one extra column `question_type` to denote the type of questions\n \"\"\"\n\n def _get_question_type(item):\n \"\"\"\n A helper function that decides the question type according to the question text in `item`.\n \"\"\"\n # Filter the question text and assign a new question type when anything matches\n question_words = [\"what\", \"who\", \"where\", \"when\", \"which\", \"why\", \"how\"]\n quest_type = 'other'\n lowered_question = item['question'].lower()\n for k in question_words:\n if k in lowered_question:\n quest_type = k\n break\n\n return {'quest_type': quest_type}\n\n # Assign the question type to each item\n self.dataset = self.dataset.map(_get_question_type)\n","repo_name":"rickchung/PAQG.Text2Code2Quests","sub_path":"preprocess_train_data.py","file_name":"preprocess_train_data.py","file_ext":"py","file_size_in_byte":8464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28227968116","text":"import faker\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route(\"/pipfile\")\ndef get_pipfile():\n with open(\"Pipfile.lock\", \"r\") as f:\n data = f.read()\n return data\n\n@app.route(\"/random_students\")\ndef get_random_students():\n f = faker.Faker(\"UK\")\n name = [(f.first_name() + \" \" + f.last_name()) for _ in range(10)]\n return str(name)\n\napp.run()","repo_name":"Liubov-Makohon/Python_Advanced","sub_path":"HW_2.py","file_name":"HW_2.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10659766512","text":"import pickle, os, threading\n\nfrom .users import Users, Json\n\nsave_file = os.path.join(os.path.dirname(__file__), \"SAVE_DB.PK\")\n\n\ndef load():\n try:\n data_file = open(save_file, \"rb\")\n Users.users_by_identifier = pickle.load(data_file) or Json()\n data_file.close()\n\n Users.users_by_api_key = {\n user.api_key: user for user in Users.users_by_identifier.values()\n }\n\n threading.Thread(target=Users.watch).start()\n # print(\"Loading Finished\")\n\n except (FileNotFoundError, EOFError) as e:\n # print(f\"Loading Error: {e}\")\n ...\n\n\ndef save():\n try:\n data_file = open(save_file, \"wb\")\n pickle.dump(Users.users_by_identifier, data_file)\n data_file.close()\n\n # print(\"Saving Finished\")\n except Exception as e:\n # print(f\"Saving Error: {e}\")\n ...\n\n\ndef load_t():\n threading.Thread(target=load).start()\n\n\ndef save_t():\n threading.Thread(target=save).start()\n","repo_name":"prmpsmart/temp_dev_db","sub_path":"dev_db_server/persist.py","file_name":"persist.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18573638905","text":"import torch\nimport torchvision\nfrom torchvision import transforms, models\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom torch.autograd import Variable\nimport copy\n\ntransform = transforms.Compose([transforms.Resize([224, 224]),\n transforms.ToTensor()])\n\nuse_gpu = torch.cuda.is_available()\ncnn = models.vgg16(pretrained=True).features\nif use_gpu:\n cnn = cnn.cuda()\n\n\n# Define the function to load the image\ndef imgLoad(path=None):\n img = Image.open(path)\n img = img.convert(\"RGB\")\n img = transform(img)\n img = img.unsqueeze(0)\n return img\n\n\nToPIL = torchvision.transforms.ToPILImage()\n\n\n# Define the function to show the image\ndef imgShow(img, title=None):\n img = img.clone().cpu()\n img = img.view(3, 224, 224)\n img = ToPIL(img)\n\n if title is not None:\n plt.title(title)\n plt.imshow(img)\n plt.axis('off')\n plt.show()\n\n\ncontent_img = imgLoad(\"TestPicture/image13.jpg\")\ncontent_img = Variable(content_img).cpu()\nstyle_img = imgLoad(\"TestPicture/image11.jpg\")\nstyle_img = Variable(style_img).cpu()\nprint(content_img.size())\nprint(style_img.size())\n\nimgShow(content_img, title='Content Image')\nimgShow(style_img, title='Style Image')\n\n\n# define content loss function\nclass Content_loss(torch.nn.Module):\n def __init__(self, weight, target):\n super(Content_loss, self).__init__()\n self.weight = weight\n self.target = target.detach() * weight\n self.loss_fn = torch.nn.MSELoss()\n\n def forward(self, input):\n self.loss = self.loss_fn(input * self.weight, self.target)\n self.output = input\n return self.output\n\n def backward(self):\n self.loss.backward(retain_graph=True)\n return self.loss\n\n\n# define style loss function\nclass Style_loss(torch.nn.Module):\n def __init__(self, weight, target):\n super(Style_loss, self).__init__()\n self.weight = weight\n self.target = target.detach() * weight\n self.loss_fn = torch.nn.MSELoss()\n self.gram = gram_matrix()\n\n def forward(self, input):\n self.output = input.clone()\n self.G = self.gram(input)\n self.G.mul_(self.weight)\n self.loss = self.loss_fn(self.G, self.target)\n return self.output\n\n def backward(self):\n self.loss.backward(retain_graph=True)\n return self.loss\n\n\n# define the gram_matrix\nclass gram_matrix(torch.nn.Module):\n def forward(self, input):\n a, b, c, d = input.size()\n feature = input.view(a * b, c * d)\n gram = torch.mm(feature, feature.t())\n return gram.div(a * b * c * d)\n\n\ncontent_layer = [\"Conv_5\", \"Conv_6\"]\nstyle_layer = [\"Conv_1\", \"Conv_2\", \"Conv_3\", \"Conv_4\", \"Conv_5\"]\n\ncontent_losses = []\nstyle_losses = []\n\ncontent_weight = 1\nstyle_weight = 1000\n\nnew_model = torch.nn.Sequential()\n\nmodel = copy.deepcopy(cnn)\n\ngram = gram_matrix()\n\nindex = 1\nfor layer in list(model):\n if isinstance(layer, torch.nn.Conv2d):\n name = \"Conv_\" + str(index)\n new_model.add_module(name, layer)\n if name in content_layer:\n target = new_model(content_img).clone()\n content_loss = Content_loss(content_weight, target)\n new_model.add_module(\"content_loss_\" + str(index), content_loss)\n content_losses.append(content_loss)\n\n if name in style_layer:\n target = new_model(style_img).clone()\n target = gram(target)\n style_loss = Style_loss(style_weight, target)\n new_model.add_module(\"style_loss_\" + str(index), style_loss)\n style_losses.append(style_loss)\n\n if isinstance(layer, torch.nn.ReLU):\n name = \"Relu_\" + str(index)\n new_model.add_module(name, layer)\n index = index + 1\n\n if isinstance(layer, torch.nn.MaxPool2d):\n name = \"MaxPool_\" + str(index)\n new_model.add_module(name, layer)\n\nprint(new_model)\n\ninput_img = content_img.clone()\nparameter = torch.nn.Parameter(input_img.data)\noptimizer = torch.optim.LBFGS([parameter])\n\nn_epoch = 200\n\nrun = [0]\n\n\ndef closure():\n optimizer.zero_grad()\n style_score = 0\n content_score = 0\n parameter.data.clamp_(0, 1)\n new_model(parameter)\n for sl in style_losses:\n style_score += sl.backward()\n\n for cl in content_losses:\n content_score += cl.backward()\n\n run[0] += 1\n if run[0] % 10 == 0:\n print('{} Style Loss : {:4f} Content Loss: {:4f}'.format(run[0], style_score.item(), content_score.item()))\n\n return style_score + content_score\n\n\n# Begin our transfer Process\nwhile run[0] < n_epoch:\n optimizer.step(closure)\n\nparameter.data.clamp_(0, 1)\nplt.figure()\nimgShow(parameter.data, title=\"Output Image\")\n","repo_name":"Sun-zhenghao-BU/Deep-Learning-Project--EC523","sub_path":"StyleTransfer-VGG16.py","file_name":"StyleTransfer-VGG16.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31915748480","text":"# !/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\nDatetime:2020/11/6 9:12\nauthor:乔誉萱\n说明:封装接口请求头\n'''\nfrom Test_headless.base import *\nfrom Test_headless.tests import getLoginToken\n\n\ndef get_headers():\n get_token = getLoginToken.get_token()\n headers = {\"token\": get_token,\n \"Content-Type\": \"application/json;charset=UTF-8\",\n \"channel\": \"WDGJ\"}\n return headers\n","repo_name":"qiaoyuxuan/python","sub_path":"headlessTest/Test_headless/base/headers.py","file_name":"headers.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36055685285","text":"from flask import Flask, jsonify\nfrom flask.helpers import send_from_directory\n\napp = Flask(__name__, static_folder='./build', static_url_path='/')\n\n@app.route(\"/<firstName>\", methods=[\"GET\"])\ndef find_name(firstName: str):\n if firstName == \"Noah\":\n output = \"Zamarripa\"\n else:\n output = \"User Not Found\"\n return jsonify(lastName=output)\n\n@app.route(\"/\")\ndef index():\n return send_from_directory(app.static_folder, \"index.html\")\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=False, port=os.environ.get('PORT', 80))","repo_name":"Noah13z/ee461l-hw6-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36594056418","text":"import sys\nimport glob\nimport os\nimport numpy as np\nimport cv2\nfrom cv2 import aruco\nfrom skimage import color\n\n\nclass IntrinsicCalibration:\n def __init__(self, dict_aruco=cv2.aruco.DICT_4X4_250, sqWidth=11, sqHeight=8, checkerSquareSize=0.022,\n markerSquareSize=0.016, criteria_eps=1e-9, criteria_count=10000):\n # Initialize ChArUco Board size values: default DINA4\n # Visit: https://calib.io/pages/camera-calibration-pattern-generator\n # To create: calib.io_charuco_279x215_8x11_24_DICT_4X4.pdf\n # Initialize dictionary, see more in OpenCV\n self.dict = dict_aruco\n # Amount of squares in width\n self.sqWidth = sqWidth\n # Amount of squares in heights\n self.sqHeight = sqHeight\n # Size of checker square on printed ChArUco board in meter\n self.checkerSquareSize = checkerSquareSize\n # Size of marker square on printed ChArUco board in meter\n self.markerSquareSize = markerSquareSize\n self.criteria_eps = criteria_eps\n self.criteria_count = criteria_count\n self.cameraMatrix = None\n self.distortionCoeff = None\n\n @staticmethod\n def readFileList(imgFolder, imgPattern):\n # Read all PNG files in folder\n imgFileList = glob.glob(os.path.join(imgFolder, imgPattern))\n imgFileList.sort()\n return imgFileList\n\n def calibration(self, imgFolder, imgPattern):\n # Retrieve Images\n imgFileList = self.readFileList(imgFolder, imgPattern=imgPattern)\n # All Charuco Corners\n allCorners = []\n # All Charuco Ids\n allIds = []\n decimator = 0\n # Retrieve dictionary\n dictionary = aruco.getPredefinedDictionary(self.dict)\n board = cv2.aruco.CharucoBoard_create(self.sqWidth, self.sqHeight, self.checkerSquareSize,\n self.markerSquareSize, dictionary)\n # Loop through images\n for i in imgFileList:\n print(\"Reading %s\" % i)\n # Load image to grayscale\n if imgPattern == \"*.PNG\" or imgPattern == \"*.png\":\n img = cv2.imread(i)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n elif imgPattern == \"*.npy\":\n img = np.load(i)\n if len(img.shape) > 2:\n gray = color.rgb2gray(img)\n else:\n gray = img\n else:\n print(\"Specify image pattern: PNG and npy are supported\")\n # Detect markers\n [markerCorners, markerIds, rejectedImgPoints] = cv2.aruco.detectMarkers(gray, dictionary)\n # Draw markers\n if len(markerCorners) > 0:\n [ret, charucoCorners, charucoIds] = cv2.aruco.interpolateCornersCharuco(markerCorners, markerIds, gray,\n board)\n if charucoCorners is not None and charucoIds is not None and len(charucoCorners) > 3:\n allCorners.append(charucoCorners)\n allIds.append(charucoIds)\n\n cv2.aruco.drawDetectedMarkers(img, markerCorners, markerIds, [0, 255, 0])\n cv2.aruco.drawDetectedCornersCharuco(img, charucoCorners, charucoIds, [0, 0, 255])\n\n cv2.namedWindow('Frame', cv2.WINDOW_NORMAL)\n cv2.imshow('Frame', img)\n cv2.waitKey(0) # any key\n decimator += 1\n print(\"NumImg:\", len(allCorners))\n # Try Calibration\n try:\n # Calibrate camera\n [ret, cameraMatrix, disCoeffs, rvecs, tvecs, _, _,\n perViewErrors] = cv2.aruco.calibrateCameraCharucoExtended(\n allCorners, allIds, board, (img.shape[0], img.shape[1]),\n None, None, flags=cv2.CALIB_RATIONAL_MODEL,\n criteria=(cv2.TERM_CRITERIA_EPS & cv2.TERM_CRITERIA_COUNT, self.criteria_count, self.criteria_eps))\n # Print computed calibration results\n print(\"Rep Error:\", ret)\n print(\"Camera Matrix:\", cameraMatrix)\n print(\"Per View Errors:\", perViewErrors)\n print(\"Distortion Coefficients:\", disCoeffs)\n print(\"R vecs:\", rvecs)\n # Save calibration results in dedicated folder for numpy data of calibration\n np.savez('CalibrationNumpyData/intrinsic_calibration.npz', ret=ret, mtx=cameraMatrix, dist=disCoeffs,\n rvecs=rvecs, tvecs=tvecs)\n # Set class attributes\n self.cameraMatrix = cameraMatrix\n self.distortionCoeff = disCoeffs\n except ValueError as e:\n print(e)\n except NameError as e:\n print(e)\n except AttributeError as e:\n print(e)\n except:\n print(\"calibrateCameraCharuco fail:\", sys.exc_info()[0])\n # Close windows\n print(\"Press any key on window to exit\")\n cv2.waitKey(0) # any key\n cv2.destroyAllWindows()\n\n def undistort(self, distImgFolder, imgPattern):\n # Load calibration, if necessary\n if self.cameraMatrix is None:\n self.load_calibration_data()\n # Undistort the images\n imgDistortFolder = distImgFolder\n imgDistortFilelist = self.readFileList(imgDistortFolder, imgPattern=imgPattern)\n img_num = 0\n # Loop through images to undistort\n for j in imgDistortFilelist:\n # Load specified image file pattern\n if imgPattern == \"*.PNG\" or imgPattern == \"*.png\":\n imgDistort = cv2.imread(j)\n elif imgPattern == \"*.npy\":\n imgDistort = np.load(j)\n else:\n print(\"Specify image pattern: PNG and npy are supported\")\n h = imgDistort.shape[0]\n w = imgDistort.shape[1]\n # TODO: Ask Yunhao why optimal camera matrix is not used\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(self.cameraMatrix, self.distortionCoeff,\n (w, h), 1, (w, h))\n # Undistort\n dst = cv2.undistort(imgDistort, self.cameraMatrix, self.distortionCoeff, None)\n # Save image in specified image pattern in destination folder - by default captured image/npy\n if imgPattern == \"*.PNG\" or imgPattern == \"*.png\":\n imgSavePng = os.path.join(distImgFolder, '/capture_', str(img_num) + '.PNG')\n cv2.imwrite(imgSavePng, dst)\n elif imgPattern == \"*.npy\":\n imgSaveNpy = os.path.join(distImgFolder, '/capture_', str(img_num) + '.npy')\n np.save(imgSaveNpy, dst)\n else:\n print(\"Specify image pattern: .PNG and .npy are supported\")\n img_num = img_num + 1\n\n def load_calibration_data(self):\n # Check if calibration file already exists\n if os.path.exists('CalibrationNumpyData/intrinsic_calibration.npz'):\n # Load camera matrix and distortion coefficients\n data = np.load('CalibrationNumpyData/intrinsic_calibration.npz')\n self.cameraMatrix = data['mtx']\n self.distortionCoeff = data['dist']\n else:\n print(\"Capture and calibrate camera first\")\n","repo_name":"merlzbert/SkinScan","sub_path":"Calibrations/IntrinsicCalibration.py","file_name":"IntrinsicCalibration.py","file_ext":"py","file_size_in_byte":7293,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"73547829604","text":"def cargarProducto(lista):\n\ttry:\n\t\tcodigo = int(input(\"Ingrese el codigo del producto: \"))\n\t\tif codigo == -1:\n\t\t\tprint(\"Termino de cargar\")\n\t\t\treturn 1\n\t\tnombre = input(\"Ingrese el nombre del producto: \")\n\t\tprecio = float(input(\"Ingrese el precio del producto: \"))\n\t\tstock = int(input(\"Ingrese el stock del producto: \"))\n\texcept Exception:\n\t\tprint(\"No seas malo :C\")\n\t\treturn 0\n\tif(codigo not in lista):\n\t\tlista[codigo] = [nombre,precio,stock]\n\t\tprint(lista)\n\t\treturn 0\n\telse:\n\t\tprint(\"Un valor es invalido\")\n\t\treturn 0\n\ndef printLista(lista):\n\tprint(\"Diccionario: \")\n\tfor producto in lista:\n\t\tprint(f\"{producto} => {lista[producto][0]}\\nPrecio: ${lista[producto][1]} -- Stock: {lista[producto][2]}\")\n\ndef stockCero(lista):\n\tcounter = 0\n\tfor producto in lista:\n\t\tif(lista[producto][2] == 0):\n\t\t\tprint(f\"{producto} => {lista[producto][0]}\\nPrecio: ${lista[producto][1]} -- Stock: {lista[producto][2]}\")\n\t\t\tcounter += 1\n\tif counter == 0:\n\t\tprint(\"No hay productos con stock 0\")\n\nif __name__ == \"__main__\":\n\tlista = {}\n\testado = 0\n\tprint(\"Cargue los productos\")\n\twhile(estado == 0):\n\t\testado = cargarProducto(lista)\n\testado = 0\n\tinput(\"Presione ENTER para seguir\")\n\tprint(\"==============================================\")\n\tprint(\"Mostrando todos los productos\")\n\tprintLista(lista)\n\tinput(\"Presione ENTER para seguir\")\n\tprint(\"==============================================\")\n\tprint(\"Mostrando productos con stock cero\")\n\tstockCero(lista)","repo_name":"bautistamad/LABIII-Repository","sub_path":"Guia Ejercicios 2/Listas/Eje2_5.py","file_name":"Eje2_5.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20867657547","text":"#이것이 코딩테스트다\n#Chapter12-13: 구현 기출 치킨 배달\n#https://www.acmicpc.net/problem/15686\n#해당 코드로 구현시 타임 아웃은 발생하지 않으나 수행시간이 길다\n\nfrom itertools import combinations\nn,m = map(int,input().split())\nhome =[] #집의 위치\nchicken=[]#치킨집의 위치\nINF = 1e9 #초기값은 무한대로\n#도시의 정보\nfor i in range(n):\n city = list(map(int,input().split()))\n for j in range(n):\n if city[j]==1:\n home.append((i,j))\n elif city[j]==2:\n chicken.append((i,j))\n\n#치킨집이 최대 m개일때 가능한 조합\ncomb = list(combinations(chicken,m))\nresult = INF\nfor case in comb: #가능한 모든 치킨집의 조합에 대하여\n city_distance = 0 #초기의 도시의 치킨 거리를 0\n for h in home: #각 집에 대한 치킨 거리 구하기\n home_distance = INF\n for c in case: #조합의 개별 치킨집까지의 거리 계산\n distance = abs(h[0]-c[0]) + abs(h[1]-c[1])\n home_distance = min(home_distance,distance)\n\n city_distance+=home_distance\n\n result = min(result,city_distance)\n\nprint(result)\n\n","repo_name":"giraffejin/Algorithm","sub_path":"Thisiscodingtest/Implementation/ChickenDelivery.py","file_name":"ChickenDelivery.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32702799256","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn import datasets, preprocessing\nfrom sklearn.decomposition import PCA\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.datasets.samples_generator import make_blobs\n\njanuary_path = \"C:/Users/Jasmina/Desktop/classification/january.csv\"\n\n\ndef prepare_data_for_rapid_miner():\n path = os.path.abspath(\"C:/Users/Jasmina/Documents/Faks/SIAP/avioni/flight-delays/flights.csv\")\n flights = pd.read_csv(path)\n airports = pd.read_csv(\"data/airports.csv\")\n\n flights = flights[flights['CANCELLED'] != 1]\n flights = flights[flights['DIVERTED'] != 1]\n\n flights = flights.fillna(0)\n\n flights = flights.drop(columns=['YEAR', 'DAY', 'FLIGHT_NUMBER', 'TAIL_NUMBER','LATE_AIRCRAFT_DELAY', 'AIRLINE_DELAY', 'WEATHER_DELAY', 'SECURITY_DELAY',\n 'AIR_SYSTEM_DELAY','CANCELLATION_REASON', 'CANCELLED', 'DIVERTED', 'ORIGIN_AIRPORT', 'DESTINATION_AIRPORT', 'AIRLINE'])\n\n flights = flights.sample(n=500000)\n\n\n #flights.to_csv(\"data/pca.csv\")\n return flights\n\n\ndef read_data_and_replace_missing():\n path = os.path.abspath(\"C:/Users/Jasmina/Documents/Faks/SIAP/avioni/flight-delays/flights.csv\")\n flights = pd.read_csv(path)\n return flights\n\n\ndef prepare_dataset():\n flights = read_data_and_replace_missing()\n #flights['DATE'] = pd.to_datetime(flights[['YEAR', 'MONTH', 'DAY']]) #date time value ne prolazi\n\n #flights = flights.dropna(axis=0, how='any')\n flights = flights[flights['CANCELLED'] != 1]\n flights = flights[flights['DIVERTED'] != 1]\n flights = flights.fillna(0)\n flights = flights.drop(columns=['YEAR', 'MONTH', 'DAY', 'DAY_OF_WEEK', 'FLIGHT_NUMBER', 'TAIL_NUMBER',\n 'LATE_AIRCRAFT_DELAY', 'AIRLINE_DELAY', 'WEATHER_DELAY', 'SECURITY_DELAY', 'AIR_SYSTEM_DELAY',\n 'CANCELLATION_REASON', 'CANCELLED', 'DIVERTED',\n 'AIRLINE', 'ORIGIN_AIRPORT', 'DESTINATION_AIRPORT'])\n print(flights.head())\n print(\"***\")\n print(flights.shape)\n return flights\n\n\ndef prepare_for_pca():\n flights = prepare_dataset()\n X = flights.iloc[:, 1:].values\n y = flights.iloc[:, 0].values\n\n ss = StandardScaler()\n X_std = ss.fit_transform(X)\n\n cov_mat = np.cov(X_std.T)\n eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)\n return eigen_vals, eigen_vecs, cov_mat, X_std, flights\n\n\ndef prep():\n # flights = prepare_data_for_rapid_miner()\n flights = pd.read_csv(january_path)\n flights = flights.fillna(0)\n X = flights.iloc[:, 1:].values\n y = flights.iloc[:, 0].values\n\n ss = StandardScaler()\n X_std = ss.fit_transform(X)\n\n cov_mat = np.cov(X_std.T)\n eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)\n return eigen_vals, eigen_vecs, cov_mat, X_std, flights\n\n\n# index=['PC-1', 'PC-2', 'PC-3', 'PC-4', 'PC-5', 'PC-6',\n# 'PC-7', 'PC-8', 'PC-9', 'PC-10', 'PC-11', 'PC-12', 'PC-13', 'PC-14']\n\ndef alternative_pca():\n flights = prepare_dataset()\n data_scaled = pd.DataFrame(preprocessing.scale(flights), columns=flights.columns)\n # PCA\n pca = PCA(n_components=3)\n pca.fit_transform(data_scaled)\n\n # Dump components relations with features:\n print(pd.DataFrame(pca.components_, columns=data_scaled.columns,\n index=['PC-1', 'PC-2', 'PC-3']))\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n # assign x,y,z coordinates from PC1, PC2 & PC3\n xs = pca.components_[0]\n ys = pca.components_[1]\n zs = pca.components_[2]\n\n # initialize scatter plot and label axes\n ax.scatter(xs, ys, zs, alpha=0.75, c='blue')\n ax.set_xlabel('PC1')\n ax.set_ylabel('PC2')\n ax.set_zlabel('PC3')\n\n plt.show()\n\n\ndef first_pca():\n eigen_values, eigen_vectors, cov_mat, X_std, flights = prep()\n print(\"AAAAA SHAPE\")\n print(flights.shape)\n tot = sum(eigen_values)\n # var_exp ratio is fraction of eigen_val to total sum\n var_exp = [(i / tot) for i in sorted(eigen_values, reverse=True)]\n # calculate the cumulative sum of explained variances\n cum_var_exp = np.cumsum(var_exp)\n\n #Prvi grafik\n plt.bar(range(1, 27), var_exp, alpha=0.75, align='center', label='pojedinacna varijansa komponenti')\n plt.step(range(1, 27), cum_var_exp, where='mid', label='kumulativna varijansa komponenti')\n plt.ylim(0, 1.1)\n plt.xlabel('Glavne komponente')\n plt.ylabel('Odnos varijanse')\n plt.legend(loc='best')\n plt.show()\n\n #PCA primena\n pca_2 = PCA(n_components=2) # PCA with 3 primary components 80% tacnosti\n pca_3 = PCA(n_components=3) # PCA with 4 primary components oko 85% tacnosti\n\n # fit and transform both PCA models\n X_pca_2 = pca_2.fit_transform(X_std)\n X_pca_3 = pca_3.fit_transform(X_std)\n\n # 2d grafik\n plt.scatter(X_pca_2.T[0], X_pca_2.T[1], alpha=0.75, c='blue')\n plt.xlabel('PC1')\n plt.ylabel('PC2')\n plt.show()\n\n # 3d grafik\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n # assign x,y,z coordinates from PC1, PC2 & PC3\n xs = X_pca_3.T[0]\n ys = X_pca_3.T[1]\n zs = X_pca_3.T[2]\n\n #initialize scatter plot and label axes\n ax.scatter(xs, ys, zs, alpha=0.75, c='blue')\n ax.set_xlabel('PC1')\n ax.set_ylabel('PC2')\n ax.set_zlabel('PC3')\n plt.show()\n\n plot = ax.scatter(xs, ys, zs, alpha=0.75,\n c=flights['ARRIVAL_DELAY'], cmap='viridis', depthshade=True)\n\n fig.colorbar(plot, shrink=0.6, aspect=9)\n plt.show()\n return X_pca_2\n\n\ndef treca():\n data = prepare_dataset()\n pca = PCA(0.95)\n data = StandardScaler().fit_transform(data)\n pca.fit(data)\n pca_data = pca.transform(data)\n\n plt.semilogy(pca.explained_variance_ratio_, '--o')\n plt.show()\n\n pca_headers = ['target']\n for i in range(pca.n_components_):\n pca_headers.append('PCA_component_' + str(i + 1))\n\n # pca_data.to_csv('data/new.csv')\n\n\n print(pca)\n print(pca_data)\n print(pca_headers)\n\n\ndef k_means():\n eigen_values, eigen_vectors, cov_mat, X_std, flights = prep()\n X_pca = first_pca()\n distortions = [] # sum of squared error within the each cluster\n for i in range(1, 11):\n km = KMeans(n_clusters=i,\n init='k-means++',\n n_init=10,\n max_iter=300,\n random_state=0)\n km.fit(X_std)\n distortions.append(km.inertia_)\n\n plt.plot(range(1, 11), distortions, marker='o', alpha=0.75)\n plt.xlabel('Broj klastera')\n plt.ylabel('Distorzija')\n plt.show()\n\n km = KMeans(n_clusters=6,\n init='k-means++',\n n_init=10,\n max_iter=300,\n tol=1e-04,\n random_state=0)\n\n y_km = km.fit_predict(X_pca)\n\n plt.scatter(X_pca[y_km == 0, 0],\n X_pca[y_km == 0, 1],\n c='lightgreen',\n label='Cluster 1')\n plt.scatter(X_pca[y_km == 1, 0],\n X_pca[y_km == 1, 1],\n c='orange',\n label='Cluster 2')\n plt.scatter(X_pca[y_km == 2, 0],\n X_pca[y_km == 2, 1],\n c='lightblue',\n label='Cluster 3')\n plt.scatter(X_pca[y_km == 3, 0],\n X_pca[y_km == 3, 1],\n c='red',\n label='Cluster 4')\n plt.scatter(X_pca[y_km == 4, 0],\n X_pca[y_km == 4, 1],\n c='pink',\n label='Cluster 5')\n plt.scatter(X_pca[y_km == 5, 0],\n X_pca[y_km == 5, 1],\n c='yellow',\n label='Cluster 6')\n plt.scatter(km.cluster_centers_[:, 0],\n km.cluster_centers_[:, 1],\n s=85,\n alpha=0.75,\n marker='o',\n c='black',\n label='Centroids')\n\n plt.legend(loc='best')\n plt.xlabel('PC1')\n plt.ylabel('PC2')\n plt.show()\n\n\ndef dbscan():\n X_pca = first_pca()\n dbs = DBSCAN(eps=0.75,\n min_samples=5)\n\n y_dbs = dbs.fit_predict(X_pca)\n plt.scatter(X_pca[y_dbs == -1, 0],\n X_pca[y_dbs == -1, 1],\n c='lightgreen',\n label='Cluster 1')\n plt.scatter(X_pca[y_dbs == 0, 0],\n X_pca[y_dbs == 0, 1],\n c='orange',\n label='Cluster 2')\n plt.scatter(X_pca[y_dbs == 1, 0],\n X_pca[y_dbs == 1, 1],\n c='lightblue',\n label='Cluster 3')\n plt.scatter(X_pca[y_dbs == 2, 0],\n X_pca[y_dbs == 2, 1],\n c='yellow',\n label='Cluster 4')\n plt.scatter(X_pca[y_dbs == 3, 0],\n X_pca[y_dbs == 3, 1],\n c='pink',\n label='Cluster 5')\n plt.scatter(X_pca[y_dbs == 4, 0],\n X_pca[y_dbs == 4, 1],\n c='purple',\n label='Cluster 6')\n\n plt.legend(loc='best')\n plt.xlabel('PC1')\n plt.ylabel('PC2')\n plt.show()\n\n\ndef dbscan_test():\n # #############################################################################\n # Generate sample data\n centers = [[1, 1], [-1, -1], [1, -1]]\n X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4,\n random_state=0)\n print(\"Labels\")\n print(labels_true)\n\n X = StandardScaler().fit_transform(X)\n\n # #############################################################################\n # Compute DBSCAN\n db = DBSCAN(eps=0.3, min_samples=10).fit(X)\n core_samples_mask = np.zeros_like(db.labels_, dtype=bool)\n core_samples_mask[db.core_sample_indices_] = True\n labels = db.labels_\n\n # Number of clusters in labels, ignoring noise if present.\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n\n print('Estimated number of clusters: %d' % n_clusters_)\n print(\"Homogeneity: %0.3f\" % metrics.homogeneity_score(labels_true, labels))\n print(\"Completeness: %0.3f\" % metrics.completeness_score(labels_true, labels))\n print(\"V-measure: %0.3f\" % metrics.v_measure_score(labels_true, labels))\n print(\"Adjusted Rand Index: %0.3f\"\n % metrics.adjusted_rand_score(labels_true, labels))\n print(\"Adjusted Mutual Information: %0.3f\"\n % metrics.adjusted_mutual_info_score(labels_true, labels))\n print(\"Silhouette Coefficient: %0.3f\"\n % metrics.silhouette_score(X, labels))\n\n # #############################################################################\n # Plot result\n import matplotlib.pyplot as plt\n\n # Black removed and is used for noise instead.\n unique_labels = set(labels)\n colors = [plt.cm.Spectral(each)\n for each in np.linspace(0, 1, len(unique_labels))]\n for k, col in zip(unique_labels, colors):\n if k == -1:\n # Black used for noise.\n col = [0, 0, 0, 1]\n\n class_member_mask = (labels == k)\n\n xy = X[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=14)\n\n xy = X[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=6)\n\n plt.title('Estimated number of clusters: %d' % n_clusters_)\n plt.show()\n\n\ndef dbscan_final():\n flights = prepare_data_for_rapid_miner()\n X = StandardScaler().fit_transform(flights)\n # #############################################################################\n # Compute DBSCAN\n db = DBSCAN(eps=0.8, min_samples=10).fit(X)\n core_samples_mask = np.zeros_like(db.labels_, dtype=bool)\n core_samples_mask[db.core_sample_indices_] = True\n labels = db.labels_\n\n print(labels)\n\n # Number of clusters in labels, ignoring noise if present.\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n\n print('Estimated number of clusters: %d' % n_clusters_)\n # print(\"Homogeneity: %0.3f\" % metrics.homogeneity_score(labels_true, labels))\n # print(\"Completeness: %0.3f\" % metrics.completeness_score(labels_true, labels))\n # print(\"V-measure: %0.3f\" % metrics.v_measure_score(labels_true, labels))\n # print(\"Adjusted Rand Index: %0.3f\"\n # % metrics.adjusted_rand_score(labels_true, labels))\n # print(\"Adjusted Mutual Information: %0.3f\"\n # % metrics.adjusted_mutual_info_score(labels_true, labels))\n print(\"Silhouette Coefficient: %0.3f\"\n % metrics.silhouette_score(X, labels))\n\n # #############################################################################\n # Plot result\n import matplotlib.pyplot as plt\n\n # Black removed and is used for noise instead.\n unique_labels = set(labels)\n colors = [plt.cm.Spectral(each)\n for each in np.linspace(0, 1, len(unique_labels))]\n for k, col in zip(unique_labels, colors):\n if k == -1:\n # Black used for noise.\n col = [0, 0, 0, 1]\n\n class_member_mask = (labels == k)\n\n xy = X[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=14)\n\n xy = X[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=6)\n\n plt.title('Estimated number of clusters: %d' % n_clusters_)\n plt.show()\n\n\ndef make_airline_dict():\n airlines_map = {}\n airlines_map['UA'] = 1\n airlines_map['AA'] = 2\n airlines_map['US'] = 3\n airlines_map['F9'] = 4\n airlines_map['B6'] = 5\n airlines_map['OO'] = 6\n airlines_map['AS'] = 7\n airlines_map['NK'] = 8\n airlines_map['WN'] = 9\n airlines_map['DL'] = 10\n airlines_map['EV'] = 11\n airlines_map['HA'] = 12\n airlines_map['MQ'] = 13\n airlines_map['VX'] = 14\n\n return airlines_map\n\n\ndef data_info():\n path = os.path.abspath(\"C:/Users/Jasmina/Documents/Faks/SIAP/avioni/flight-delays/flights.csv\")\n flights = pd.read_csv(path)\n airports = pd.read_csv(\"data/airports.csv\")\n airlines = pd.read_csv(\"data/airlines.csv\")\n\n #Uzimamo samo januar i jun\n january_flights = flights[flights['MONTH'] == 1]\n june_flights = flights[flights['MONTH'] == 6]\n\n #Ne gledamo letove koji su preusmereni ili otkazani\n january_flights = january_flights[january_flights['CANCELLED'] != 1]\n june_flights = june_flights[june_flights['DIVERTED'] != 1]\n\n #Menjamo airline\n airlines = make_airline_dict()\n january_flights = january_flights.replace({\"AIRLINE\" : airlines})\n june_flights = june_flights.replace({\"AIRLINE\": airlines})\n\n #Popunjavamo nedostajujuce vrednosti\n january_flights = january_flights.fillna(0)\n june_flights = june_flights.fillna(0)\n\n #Odbacujemo kodove aerodroma i koristimo geo podatke iz airports.csv\n january_flights['ORIGIN_AIRPORT_LAT'] = january_flights['ORIGIN_AIRPORT'].map(airports.set_index('IATA_CODE')['LATITUDE'])\n january_flights['ORIGIN_AIRPORT_LON'] = january_flights['ORIGIN_AIRPORT'].map(airports.set_index('IATA_CODE')['LONGITUDE'])\n january_flights['DESTINATION_AIRPORT_LAT'] = january_flights['DESTINATION_AIRPORT'].map(airports.set_index('IATA_CODE')['LATITUDE'])\n january_flights['DESTINATION_AIRPORT_LON'] = january_flights['DESTINATION_AIRPORT'].map(airports.set_index('IATA_CODE')['LONGITUDE'])\n\n june_flights['ORIGIN_AIRPORT_LAT'] = june_flights['ORIGIN_AIRPORT'].map(airports.set_index('IATA_CODE')['LATITUDE'])\n june_flights['ORIGIN_AIRPORT_LON'] = june_flights['ORIGIN_AIRPORT'].map(airports.set_index('IATA_CODE')['LONGITUDE'])\n june_flights['DESTINATION_AIRPORT_LAT'] = june_flights['DESTINATION_AIRPORT'].map(airports.set_index('IATA_CODE')['LATITUDE'])\n june_flights['DESTINATION_AIRPORT_LON'] = june_flights['DESTINATION_AIRPORT'].map(airports.set_index('IATA_CODE')['LONGITUDE'])\n\n #Odbacujemo suvisne kolone\n january_flights = january_flights.drop(columns=['YEAR', 'MONTH', 'FLIGHT_NUMBER', 'TAIL_NUMBER',\n 'CANCELLATION_REASON', 'CANCELLED', 'DIVERTED', 'ORIGIN_AIRPORT', 'DESTINATION_AIRPORT'])\n june_flights = june_flights.drop(columns=['YEAR', 'MONTH', 'FLIGHT_NUMBER', 'TAIL_NUMBER',\n 'CANCELLATION_REASON', 'CANCELLED', 'DIVERTED', 'ORIGIN_AIRPORT',\n 'DESTINATION_AIRPORT'])\n\n #Oznacavanje podataka isLate\n january_flights.loc[january_flights['ARRIVAL_DELAY'] <= 15, 'IS_LATE'] = 0\n january_flights.loc[january_flights['ARRIVAL_DELAY'] > 15, 'IS_LATE'] = 1\n june_flights.loc[june_flights['ARRIVAL_DELAY'] <= 15, 'IS_LATE'] = 0\n june_flights.loc[june_flights['ARRIVAL_DELAY'] > 15, 'IS_LATE'] = 1\n\n print(january_flights.head(1))\n print(january_flights.shape)\n print(june_flights.head(1))\n print(june_flights.shape)\n\n january_flights.to_csv(\"data/january.csv\")\n june_flights.to_csv(\"data/june.csv\")\n\n\nif __name__ == \"__main__\":\n first_pca()\n #alternative_pca()\n #treca()\n #prepare_data_for_rapid_miner()\n #k_means()\n #dbscan_test()\n #dbscan_final()\n #data_info()\n\n\n\n\n\n\n\n\n\n","repo_name":"jasmina94/siap","sub_path":"project/pca_and_clustering.py","file_name":"pca_and_clustering.py","file_ext":"py","file_size_in_byte":17448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44551095339","text":"# 1. 구슬 찾기 (골4)\r\n\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nN, M = map(int, input().split())\r\ngraph1 = [[] for _ in range(N+1)]\r\ngraph2 = [[] for _ in range(N+1)]\r\nfor i in range(M):\r\n a, b = map(int, input().split())\r\n graph1[b].append(a)\r\n graph2[a].append(b)\r\n\r\n\r\ndef dfs(v, graph):\r\n global cnt\r\n visited[v] = 1\r\n for i in graph[v]:\r\n if visited[i] == 0:\r\n cnt += 1\r\n dfs(i, graph)\r\n\r\nresult = 0\r\nfor i in range(N):\r\n visited = [0]*(N+1)\r\n cnt = 0\r\n dfs(i+1, graph1)\r\n if cnt > N//2:\r\n result += 1\r\n \r\n visited = [0]*(N+1)\r\n cnt = 0\r\n dfs(i+1, graph2)\r\n if cnt > N//2:\r\n result += 1\r\n \r\nprint(result)\r\n","repo_name":"chlwlstlf/CodingTest-Study","sub_path":"백준/Gold/2617. 구슬 찾기/구슬 찾기.py","file_name":"구슬 찾기.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26524560591","text":"# -*- coding: utf-8 -*-\n\nimport os\n# from argparse import ArgumentParser\nfrom unittest import TestCase\nfrom acquisition import AcquisitionReinjectStep\nfrom xattrfile import XattrFile\nfrom time import sleep\n\n\nclass AcquisitionReinjectTestStep(AcquisitionReinjectStep):\n\n unit_tests = True\n step_name = \"test\"\n plugin_name = \"test_plugin_name\"\n\n\ndef make_tmp_xattrfile():\n foo = AcquisitionReinjectTestStep()\n tmp_filepath = foo.get_tmp_filepath()\n with open(tmp_filepath, 'w+') as f:\n f.write(\"foo\\n\")\n return XattrFile(tmp_filepath)\n\n\nclass AcquisitionReinjectTestCase(TestCase):\n\n def setUp(self):\n self.x = AcquisitionReinjectTestStep()\n\n def test_init_failure_policy(self):\n reinject_delay = 1\n reinject_attempts = 3\n reinject_dir = self.x.get_tmp_filepath() + \"/reinject/\"\n self.x.unit_tests_args = [\n \"--failure-policy=delete\",\n \"--reinject-delay=%s\" % reinject_delay,\n \"--reinject-attempts=%s\" % reinject_attempts,\n \"--reinject-dir=%s\" % reinject_dir,\n \"DUMMY_QUEUE\"\n ]\n self.x._init()\n self.assertEqual(\"delete\", self.x.failure_policy)\n\n def test_init_mkdir(self):\n reinject_delay = 1\n reinject_attempts = 3\n reinject_dir = self.x.get_tmp_filepath() + \"/reinject/\"\n self.x.unit_tests_args = [\n \"--reinject-delay=%s\" % reinject_delay,\n \"--reinject-attempts=%s\" % reinject_attempts,\n \"--reinject-dir=%s\" % reinject_dir,\n \"DUMMY_QUEUE\"\n ]\n self.x._init()\n self.assertTrue(os.path.isdir(self.x.args.reinject_dir))\n\n def test_before_return_value(self):\n reinject_delay = 1\n reinject_attempts = 3\n reinject_dir = self.x.get_tmp_filepath() + \"/reinject/\"\n self.x.unit_tests_args = [\n \"--reinject-delay=%s\" % reinject_delay,\n \"--reinject-attempts=%s\" % reinject_attempts,\n \"--reinject-dir=%s\" % reinject_dir,\n \"DUMMY_QUEUE\"\n ]\n self.x._init()\n xaf = make_tmp_xattrfile()\n self.assertEqual(False, self.x._before(xaf))\n\n def test_before_IOError(self):\n reinject_delay = 1\n reinject_attempts = 3\n reinject_dir = self.x.get_tmp_filepath() + \"/reinject/\"\n self.x.unit_tests_args = [\n \"--reinject-delay=%s\" % reinject_delay,\n \"--reinject-attempts=%s\" % reinject_attempts,\n \"--reinject-dir=%s\" % reinject_dir,\n \"DUMMY_QUEUE\"\n ]\n self.x._init()\n xaf = make_tmp_xattrfile()\n xaf.set_filepath = \"/tmp/IDontExist\"\n self.assertEqual(False, self.x._before(xaf))\n\n def test_give_up(self):\n xaf = make_tmp_xattrfile()\n self.x.give_up(xaf)\n self.assertFalse(os.path.isfile(xaf.filepath))\n\n def test_ping_give_up(self):\n # Initialize the reinjector\n reinject_delay = 1\n reinject_attempts = 3\n reinject_dir = self.x.get_tmp_filepath() + \"/reinject/\"\n self.x.unit_tests_args = [\n \"--reinject-delay=%s\" % reinject_delay,\n \"--reinject-attempts=%s\" % reinject_attempts,\n \"--reinject-dir=%s\" % reinject_dir,\n \"DUMMY_QUEUE\"\n ]\n self.x._init()\n xaf = make_tmp_xattrfile()\n self.x._before(xaf)\n\n try:\n os.mkdir(self.x.args.reinject_dir)\n except OSError:\n pass\n new_path = self.x.args.reinject_dir + \"/\" + xaf.basename()\n old_path = xaf.filepath\n\n # Sleep to make the xaf file \"expire\"\n sleep(1)\n self.x.ping()\n\n self.assertFalse(os.path.exists(new_path))\n self.assertFalse(os.path.exists(old_path))\n\n # Clean up\n try:\n os.remove(new_path)\n except OSError:\n pass\n\n try:\n os.rmdir(self.x.args.reinject_dir)\n except OSError:\n pass\n\n def test_destroy_initial_xaf_file(self):\n # Initialize the reinjector\n reinject_delay = 1\n reinject_attempts = 3\n reinject_dir = self.x.get_tmp_filepath() + \"/reinject/\"\n self.x.unit_tests_args = [\n \"--reinject-delay=%s\" % reinject_delay,\n \"--reinject-attempts=%s\" % reinject_attempts,\n \"--reinject-dir=%s\" % reinject_dir,\n \"DUMMY_QUEUE\"\n ]\n self.x._init()\n\n # Reinject a random file\n xaf = make_tmp_xattrfile()\n self.x._before(xaf)\n self.x.ping()\n\n # Destroy the reinjector\n self.x.destroy()\n self.assertFalse(os.path.exists(xaf.filepath))\n\n # TODO Is the .t file automatically destroyed?\n def test_destroy_t_file(self):\n # Initialize the reinjector\n reinject_delay = 1\n reinject_attempts = 3\n reinject_dir = self.x.get_tmp_filepath() + \"/reinject/\"\n self.x.unit_tests_args = [\n \"--reinject-delay=%s\" % reinject_delay,\n \"--reinject-attempts=%s\" % reinject_attempts,\n \"--reinject-dir=%s\" % reinject_dir,\n \"DUMMY_QUEUE\"\n ]\n self.x._init()\n\n # Reinject a random file\n xaf = make_tmp_xattrfile()\n self.x._before(xaf)\n self.x.ping()\n\n # Destroy the reinjector\n self.x.destroy()\n self.assertFalse(os.path.exists(xaf.filepath + \".t\"))\n","repo_name":"metwork-framework/acquisition","sub_path":"tests/test_reinject.py","file_name":"test_reinject.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"568747900","text":"#-*- coding: utf-8 -*-\n'''\nCreated on 24 feb. 2019\n\n@author: d18bugaj\n'''\n\nclass Terminal():\n '''\n Implementa la clase Terminal. Un terminal tiene asociado un n�mero. Los\n terminales se pueden llamar unos a otros y el tiempo de conversaci�n corre\n para ambos.\n '''\n tiempo = 0\n\n\n def __init__(self, numero_telefono):\n self.numero_telefono = numero_telefono\n \n \n def llamar(self, objeto_terminal, tiempo):\n self.tiempo += tiempo\n objeto_terminal.tiempo += tiempo\n \n def __str__(self):\n cadena = \"N� \"+ str(self.numero_telefono)+ \" - \" + str(self.tiempo)+ \" de conversacion\"\n return cadena\n \n \n \nif __name__ == \"__main__\":\n \n t1 = Terminal(\"957655249\")\n t2 = Terminal(\"957655888\")\n t3 = Terminal(\"957655999\") \n t4 = Terminal(\"957444596\")\n print(t1)\n print(t2)\n t1.llamar(t2, 320)\n t1.llamar(t3, 200)\n print(t1)\n print(t2)\n print(t3)\n print(t4)\n \n ","repo_name":"juanbu97/Practicas1DAW","sub_path":"Prácticas1DAW/EjerciciosPOO2python/Terminal.py","file_name":"Terminal.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71855922725","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 1 22:20:21 2021\n\n@author: Leonard\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom scipy import signal # spectrogram function\nfrom matplotlib import cm # colour map\n\n# basic config\nsample_rate = 11240. # \nsig_len_secs = 10\nfrequency = 2000.\n\n# generate the signal\ntimestamps_secs = np.arange(sample_rate*sig_len_secs) / sample_rate\nmysignal = np.sin(2.0 * np.pi * frequency * timestamps_secs) \n\n# extract the spectrum\nfreq_bins, timestamps, spec = signal.spectrogram(mysignal, sample_rate)\n\n# 3d plot\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(freq_bins[:, None], timestamps[None, :], 10.0*np.log10(spec), cmap=cm.coolwarm)\nplt.show()","repo_name":"leonardin999/Audio-Processing","sub_path":"spectrgram_test.py","file_name":"spectrgram_test.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"11834548600","text":"\"\"\"\n\tProblema 1 en python\n\t@autor TIMO\n\"\"\"\n#Pedimos que se ingresen los dato\nprint(\"Ingrese el nombre del trabajador\\n\") \nnombre = input()\nprint(\"Ingrese las horas Trabajadas\\n\")\nhorasTrabajadas = input()\nprint(\"Ingrese el precio por horas\")\nprecioHoras = input()\n\n#Calculamos el sueldo \nsueldo = float(horasTrabajadas) * float(precioHoras)\ndescuento = float(sueldo) * 0.10\npagar = float(sueldo) - float(descuento)\n\n#Imprimimos el nombre y el total a pagar\nprint(\"El valor a pagar a %s es de %.2f\\n\" % (nombre, pagar))","repo_name":"concpetosfundamentalesprogramacionaa19/practica220419-JoanMBQ","sub_path":"Problema1.py","file_name":"Problema1.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17713949786","text":"import argparse, ctypes\nimport contextlib\nimport datetime\nimport json\nimport logging\nimport os\nimport pathlib\nimport platform\nimport random\nimport re\nimport subprocess\nimport sys\nimport time\nimport traceback\n\nimport psutil\nfrom colorama import Style, Fore, Back\n\nheaders_list = [\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246\",\n \"Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.94 Chrome/37.0.2062.94 Safari/537.36,\"\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0\",\n \"Mozilla/5.0 (X11; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:100.0) Gecko/20100101 Firefox/100.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.62 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.115 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.47\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.33\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.39\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 OPR/86.0.4363.59\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30\"]\n\n\ndef headers(debug=False):\n \"\"\"Picks and returns a random user agent from the list\"\"\"\n header = {'User-Agent': random.choice(headers_list)}\n if debug:\n cprint(f'Random header: {header}')\n return header\n\n\ndef str2bool(v):\n \"\"\"\n Convert a string to a boolean argument\n https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse\n \"\"\"\n if isinstance(v, bool):\n return v\n elif isinstance(v, int):\n if v == 1:\n return True\n elif v == 0:\n return False\n elif v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\n\ndef trace_error(to_log=False, q=None, time=True, to_print_error=True):\n \"\"\"\n The function traces the exceptions by printing and logging the error using cprint().\n\n :param to_log: Boolean - To log the output\n :param q: The Queue object\n :param time: To print/log time (Boolean)\n :param to_print_error: Boolean - If true, prints and logs. Else, its logs the errors in a separate txt file\n :return: None\n\n See also:\n # https://docs.python.org/3/library/traceback.html#traceback-examples\n \"\"\"\n # exc_type, exc_value, exc_traceback = sys.exc_info() # All the info from the exception\n formatted_lines = traceback.format_exc().splitlines()\n json_data = ''\n for line in formatted_lines:\n if to_print_error:\n cprint(line, to_log=to_log, q=q, time=time)\n else:\n if file_exist('errors.txt', debug=False):\n with open('errors.txt', 'r+', encoding='utf-8') as file:\n json_data = json.load(file)\n if len(json_data) == 0: # To avoid empty string in the text file\n json_data = line\n else:\n json_data.update(line)\n with open('errors.txt', 'w+', encoding='utf-8') as file:\n json.dump(json_data, file, indent=4)\n else:\n with open('errors.txt', 'w+', encoding='utf-8') as file:\n json_data.update(line)\n json.dump(json_data, file, indent=4)\n\n\ndef is_admin():\n try:\n return str2bool(ctypes.windll.shell32.IsUserAnAdmin())\n except (ctypes.WinError(), BaseException) as err:\n print(err)\n\n\ndef prompt_to_acquire_admin_rights_and_exit():\n \"\"\"https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script \"\"\"\n if is_admin():\n pass\n else:\n # Re-run the program with admin rights and exit the current instance.\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", sys.executable,\n \" \".join(sys.argv[1:]), None, 1) # Join sys.argv arguments with a space\n sys.exit()\n\n\ndef exe_name_of_miner(processName):\n \"\"\"Adds '.exe' if there is not any at the end of the given name.\"\"\"\n if '.exe' not in processName:\n processname = processName + '.exe'\n return processname\n else:\n return processName\n\n\ndef get_name_of_current_exe():\n \"\"\"\n Returns the name of the current process. For example: internet.exe\n If it's running from .py, it returns the python.exe.\n \"\"\"\n path = sys.argv[0]\n if platform.system() == 'Windows':\n # Running from a .py\n if '.py' in sys.argv[0].split('\\\\')[0]:\n return os.path.basename(sys.executable)\n # Running as an .exe\n else:\n if '\\\\' in path:\n name = path.split('\\\\')[-1]\n return name\n elif '/' in path:\n name = path.split('/')[-1]\n return name\n\n\ndef bat_name_of_miner(batname):\n \"\"\"Adds '.bat' if there is not any at the end of the given name.\"\"\"\n if '.exe' in batname:\n batname = batname.split('.exe')\n batname = batname[0]\n if '.bat' not in batname:\n batname = batname + '.bat'\n return batname\n if '.bat' not in batname:\n batname = batname + '.bat'\n return batname\n else:\n return batname\n\n\ndef get_current_time():\n time_now = datetime.datetime.now()\n dt = str(time_now.strftime(\"%d-%m-%Y %H:%M:%S\")) + f'.{Fore.LIGHTBLACK_EX}{str(round(time_now.microsecond))[:4]}' \\\n f'{Style.RESET_ALL}'\n dt = f\"[{dt}]\\t\"\n return dt\n\n\nclass DummyColorama:\n \"\"\"A class to temporarily disable Colorama Fore and Style in order to log to a file\n https://stackoverflow.com/questions/63100603/globally-turn-off-colorama-colour-codes\"\"\"\n BLACK = RED = GREEN = YELLOW = BLUE = MAGENTA = CYAN = WHITE = RESET = LIGHTBLACK_EX = \\\n LIGHTRED_EX = LIGHTGREEN_EX = LIGHTYELLOW_EX = LIGHTBLUE_EX = LIGHTMAGENTA_EX = LIGHTCYAN_EX = LIGHTWHITE_EX = \\\n RESET_ALL = \"\"\n\n\n@contextlib.contextmanager\ndef without_colorama():\n global Style\n saved_Style, Style = Style, DummyColorama\n global Fore\n saved_Fore, Fore = Fore, DummyColorama\n global Back\n saved_Back, Back = Back, DummyColorama\n yield\n Fore = saved_Fore\n Style = saved_Style\n Back = saved_Back\n\n\ndef strip_ansi_characters(text=''):\n \"\"\"https://stackoverflow.com/questions/48782529/exclude-ansi-escape-sequences-from-output-log-file\"\"\"\n try:\n ansi_re = re.compile(r'\\x1b\\[[0-9;]*m')\n return re.sub(ansi_re, '', text)\n except re.error as err:\n print(err)\n\n\ndef file_exist(name, debug=False, to_log=True, q='', sole_output=False):\n # path = pathlib.Path(os.path.join(os.path.abspath(os.path.dirname(__file__)), name))\n try:\n path = sys.argv[0].split('\\\\')\n path = '\\\\'.join(path[:-1])\n # path = 'C:\\\\'\n path = pathlib.Path(os.path.join(path, name))\n if debug and sole_output:\n cprint(f'file_exist(): {path}', to_log=to_log, q=q)\n if path.exists():\n return True\n else:\n return False\n except FileNotFoundError as err:\n cprint(f'A problem occured with the path to {name}', to_log=to_log, q=q)\n if debug:\n cprint(f'A problem occured with the path to {name}.\\n Error: {err}', to_log=to_log, q=q)\n\n\ndef get_current_time_without_color():\n with without_colorama():\n time_now = datetime.now()\n dt = str(time_now.strftime(\"%d-%m-%Y %H:%M:%S\")) + \\\n f'.{Fore.LIGHTBLACK_EX}{str(round(time_now.microsecond))[:4]}{Style.RESET_ALL}'\n dt = f\"[{dt}]\\t\"\n return dt\n\n\ndef cprint(text, to_log=False, q=None, time=True):\n \"\"\"Prints and logs the printed text\"\"\"\n text = str(text) # Be sure that text is a string.\n if time:\n if q == \"\":\n print(f'{get_current_time()}{text} >> Queue not detected')\n if to_log:\n with without_colorama():\n logging.info(f'{get_current_time()}{strip_ansi_characters(text)}')\n elif not q:\n print(f'{get_current_time()}{text} >> Queue not detected')\n if to_log:\n with without_colorama():\n logging.info(f'{get_current_time()}{strip_ansi_characters(text)}')\n elif q:\n q.put(f'{get_current_time()}{text}')\n if to_log:\n with without_colorama():\n logging.info(f'{get_current_time()}{strip_ansi_characters(text)}')\n elif not time:\n if q == \"\":\n print(f'{text} >> Queue not detected')\n if to_log:\n with without_colorama():\n logging.info(f'{strip_ansi_characters(text)}')\n elif not q:\n print(f'{text} >> Queue not detected')\n if to_log:\n with without_colorama():\n logging.info(f'{strip_ansi_characters(text)}')\n elif q:\n q.put(f'{text}')\n if to_log:\n with without_colorama():\n logging.info(f'{strip_ansi_characters(text)}')\n\n\ndef restart_whole_process(to_log=True, q=\"\"):\n try:\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", sys.executable,\n \" \".join(sys.argv[1:]), None, 1) # Join sys.argv arguments with a space\n except (BaseException, SystemExit, RuntimeError, ctypes.FormatError, ctypes.WinError,\n ctypes.ArgumentError) as err: # (ctypes.GetLastError())\n cprint(f\"restart_whole_process>Error: {err}\", to_log=to_log, q=q)\n time.sleep(2)\n finally:\n cprint(\"Exiting now..\", to_log=to_log, q=q)\n sys.exit()\n\n\nprocess_list = []\n\n\ndef checkIfProcessRunning(processName, to_print=False, to_log=True, Verbose=True, q=''):\n \"\"\"\n Check if there is any running process that contains the given name processName.\n \"\"\"\n global process_list\n process_list = [] # Clear the list\n # Iterate over all the running process\n for process in psutil.process_iter():\n try:\n # Check if process name contains the given name string.\n if processName.lower() in process.name().lower():\n process_info = process.as_dict(attrs=['name', 'pid'])\n process_list.append(process_info)\n if to_print:\n if Verbose:\n cprint(f\">>>{Fore.LIGHTYELLOW_EX}{process.name()} \"\n f\": {process.pid} {Style.RESET_ALL} \"\n f\"found and added to the process list successfully.\", to_log=to_log, q=q)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"Error in finding the process due to {err}\", to_log=to_log, q=q)\n\n if len(process_list) == 0:\n return False\n elif len(process_list) != 0:\n return True\n\n\ndef findAllProcessesRunning(processName: str, to_print=False, to_log=True, Verbose=True, q=''):\n \"\"\"\n Returns a list with dictionaries containings all the pids with the same name. If no process is found,\n it returns an empty list.\n :param processName: The name of the process to be searched\n :param to_print: Boolean\n :param to_log: Boolean\n :param Verbose:\n :param q: The Queue object.\n :return: list with dictionaries or empty list\n \"\"\"\n processes_list = [] # Clear the list\n # Iterate over all the running process\n for process in psutil.process_iter():\n try:\n # Check if process name contains the given name string.\n if processName.lower() in process.name().lower():\n process_info = process.as_dict(attrs=['name', 'pid'])\n processes_list.append(process_info)\n if to_print:\n if Verbose:\n cprint(f\">>>{Fore.LIGHTYELLOW_EX}{process.name()} \"\n f\": {process.pid} {Style.RESET_ALL} \"\n f\"found and added to the process list successfully.\", to_log=to_log, q=q)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"Error in finding the process due to {err}\", to_log=to_log, q=q)\n\n if len(processes_list) == 0:\n return []\n elif len(processes_list) != 0:\n return processes_list\n\n\ndef killiftheprocess(processName, to_log=True, q=''):\n \"\"\"\n Checking if there is a process in process_list and kills the name that matches\n exactly the given name of the Process. Adds '.exe' if there is not any at the end of the given name.\n \"\"\"\n if len(process_list) == 0:\n checkIfProcessRunning(processName, to_log=to_log, q=q)\n # TODO: modify this function to include findAllProcessesRunning()\n try:\n processName = exe_name_of_miner(processName)\n for process_dict in process_list:\n if process_dict['name'].lower() == processName.lower():\n process_name = process_dict['name']\n process_pid = process_dict['pid']\n os.kill(process_pid, 9)\n cprint(f'>>>{Fore.GREEN}The process {process_name} '\n f': {process_pid} '\n f'killed successfully{Style.RESET_ALL}', to_log=to_log, q=q)\n except Exception as err:\n cprint(f\"Error in killing the {processName} process: {err}\", to_log=to_log, q=q)\n\n\ndef countdown_to_restart_whole_process(process_main_loop_psutil, to_log, q):\n cprint(f\"{Fore.LIGHTRED_EX}A internal process is not running.{Style.RESET_ALL}\", to_log=to_log, q=q)\n cprint(f\"{Fore.LIGHTRED_EX}Restarting the script.{Style.RESET_ALL}\", to_log=to_log, q=q)\n try:\n process_main_loop_psutil.suspend() # So as not to kill the new process\n except psutil.Error as err:\n cprint(f\"countdown_to_restart_whole_process>Error: {err}\", to_log=to_log, q=q)\n time.sleep(3)\n # https://stackoverflow.com/questions/5852981/python-how-do-i-display-a-timer-in-a-terminal\n for remaining in range(5, 0, -1):\n # sys.stdout.write(\"\\r\")\n cprint(f\"{remaining:2d} seconds until restart.\", to_log=to_log, q=q)\n # sys.stdout.flush()\n time.sleep(1)\n restart_whole_process()\n\n\ndef start_the_miner(filepath=\"\", bat_file='ergo.bat', debug=False, to_log=True, q=''):\n \"\"\"Starts the bat file of the miner from the given filepath\"\"\"\n # https://queirozf.com/entries/python-3-subprocess-examples\n if filepath == \"\":\n filepath = sys.argv[0].split('\\\\')\n filepath = '\\\\'.join(filepath[:-1])\n if debug:\n cprint(f'start_the_miner(): filepath: {filepath}', to_log=to_log, q=q)\n try:\n bat = bat_name_of_miner(bat_file)\n path_to_miner = os.path.join(filepath, bat)\n if debug:\n cprint(f\"start_the_miner(): Path to miner: {path_to_miner}\", to_log=to_log, q=q)\n subprocess.Popen(path_to_miner)\n time.sleep(2) # Wait a few secs for the hashrate to reach the limit you set\n except Exception as err:\n cprint(f'Error in initiating the miner: {err}', to_log=to_log, q=q)\n if to_log:\n logging.info(f'{get_current_time()}Error in initiating the miner')\n\n\ndef start_the_oc_bat_file(Verbose=True, to_log=True, debug=False, q=''):\n # https://stackoverflow.com/questions/10965949/can-subprocess-call-be-invoked-without-waiting-for-process-to-finish\n \"\"\"A function to start the overclocking bat named 'nvidia_oc.bat'.\n Firstly, it searches the arguments.json for the path.\n If json does not contain the key 'path_oc_bat', it searches current working directory\"\"\"\n try:\n json_data = ''\n cmd_args = []\n dirpath = ''\n path = sys.argv[0].split('\\\\')\n path = '\\\\'.join(path[:-1])\n if file_exist(os.path.join(path, 'arguments.json'), debug=debug, to_log=to_log, q=q, sole_output=debug):\n with open(os.path.join(path, 'arguments.json'), 'r+', encoding='utf-8') as file:\n json_data = json.load(file)\n if 'path_oc_bat' in json_data.keys():\n dirpath = json_data['path_oc_bat']\n cmd_args.append(dirpath)\n cmd_args.append('start ')\n cmd_args.append('/wait ')\n if debug:\n cprint(f'Path_oc_bat found in arguments.json', to_log=to_log, q=q)\n else:\n dirpath = os.path.abspath(path)\n filename = \"nvidia_oc.bat\"\n cmd_args.append(os.path.join(dirpath, filename))\n cmd_args.append('start ')\n cmd_args.append('/wait ')\n else:\n dirpath = os.path.abspath(path)\n filename = \"nvidia_oc.bat\"\n cmd_args.append(os.path.join(dirpath, filename))\n cmd_args.append('start ')\n cmd_args.append('/wait ')\n # Through bat file, overclock bat file is running smoothly in the background\n bat_process = subprocess.Popen(cmd_args)\n if Verbose:\n cprint(f\">>>{Fore.LIGHTGREEN_EX}Bat file successfully \"\n f\"initiated with admin rights{Style.RESET_ALL}\", to_log=to_log, q=q)\n except Exception as err:\n cprint(f'Error in initiating the overclock bat file: {err}', to_log=to_log, q=q)\n\n\ndef suspend_resume_miner(operation='', name='miner.exe', to_log=True, debug=False, q=''):\n \"\"\"If operation is \"suspend\", it suspends the miner and its child processes\n If operation is \"resume\", it resumes them\n If \"pid\", it returns a list with the pids of the miner and its child processes\"\"\"\n name = exe_name_of_miner(name)\n # The list containing dictionaries with the name and the pid of the miner and its child processes\n process_list_of_miner = [] # Clear the list\n # Iterate over all running process\n if operation == 'suspend':\n if debug:\n cprint(f'suspend_resume_miner(): operation set to {operation}', to_log=to_log, q=q)\n for process in psutil.process_iter():\n try:\n # Check if process name contains the given name string.\n if name.lower() == process.name().lower():\n process_info = process.as_dict(attrs=['name', 'pid'])\n process_list_of_miner.append(process_info)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"Error in finding the process due to {err}\", to_log=to_log, q=q)\n for _process in process_list_of_miner:\n try:\n process_pid = _process['pid']\n children = psutil.Process(process_pid).children(recursive=True)\n for child in children:\n process_info = child.as_dict(attrs=['name', 'pid'])\n process_list_of_miner.append(process_info)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"Error in finding the process due to {err}\", to_log=to_log, q=q)\n if debug:\n cprint(f'suspend_resume_miner(): List of the process: {process_list_of_miner}', to_log=to_log, q=q)\n for process in process_list_of_miner:\n try:\n process_to_suspend = psutil.Process(process['pid'])\n if process_to_suspend.status() == psutil.STATUS_RUNNING:\n process_to_suspend.suspend()\n if not debug:\n cprint(f'Process {process_to_suspend.name()} is suspended', to_log=to_log, q=q)\n if debug:\n cprint(f'suspend_resume_miner(): {process_to_suspend} is suspended.', to_log=to_log, q=q)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"suspend_resume_miner(): Error in finding the process due to {err}\", to_log=to_log, q=q)\n elif operation == 'resume':\n if debug:\n cprint(f'suspend_resume_miner(): operation set to {operation}', to_log=to_log, q=q)\n for process in psutil.process_iter():\n try:\n # Check if process name contains the given name string.\n if name.lower() == process.name().lower():\n process_info = process.as_dict(attrs=['name', 'pid'])\n process_list_of_miner.append(process_info)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"suspend_resume_miner(): Error in finding the process due to {err}\", to_log=to_log, q=q)\n for process in process_list_of_miner:\n try:\n children = psutil.Process(process['pid']).children(recursive=True)\n for child in children:\n process_info = child.as_dict(attrs=['name', 'pid'])\n process_list_of_miner.append(process_info)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"suspend_resume_miner(): Error in finding the process due to {err}\", to_log=to_log, q=q)\n if debug:\n cprint(f'suspend_resume_miner(): List of the process: {process_list_of_miner}', to_log=to_log, q=q)\n for process in process_list_of_miner:\n try:\n process_to_suspend = psutil.Process(process['pid'])\n if process_to_suspend.status() == psutil.STATUS_STOPPED or psutil.STATUS_SLEEPING:\n process_to_suspend.resume()\n if not debug:\n cprint(f'Process {process_to_suspend.name()} is resumed', to_log=to_log, q=q)\n if debug:\n cprint(f'suspend_resume_miner(): {process_to_suspend} is resumed.', to_log=to_log, q=q)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"suspend_resume_miner(): Error in finding the process due to {err}\", to_log=to_log, q=q)\n # Return a list of dictionaries with the miner's name and pid (+ its children)\n elif operation == 'pid':\n if debug:\n cprint(f'suspend_resume_miner(): operation set to {operation}', to_log=to_log, q=q)\n for process in psutil.process_iter():\n try:\n # Check if process name contains the given name string.\n if name.lower() == process.name().lower():\n process_info = process.as_dict(attrs=['name', 'pid'])\n process_list_of_miner.append(process_info)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"suspend_resume_miner(): Error in finding the process due to {err}\", to_log=to_log, q=q)\n for process in process_list_of_miner:\n try:\n children = psutil.Process(process['pid']).children(recursive=True)\n for child in children:\n process_info = child.as_dict(attrs=['name', 'pid'])\n process_list_of_miner.append(process_info)\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as err:\n cprint(f\"suspend_resume_miner(): Error in finding the process due to {err}\", to_log=to_log, q=q)\n return process_list_of_miner\n\n\ndef check_write_update_json_arguments(debug, path_to_arguments_json, arguments: dict, to_log, q, json_data):\n \"\"\"\n Checks if the file exists, load its content, update its dictionary with the arguments and then overwrite the json.\n If it does not exist, creates a new one.\n :param debug: Boolean\n :param path_to_arguments_json: The path to arguments.json\n :param arguments: A dictionary containing all arguments\n :param to_log: Boolean\n :param q: The Queue object\n :param json_data: The data from arguments.json (if the .json exists).\n :return: None\n \"\"\"\n try:\n if file_exist('arguments.json', debug=str2bool(debug)):\n if debug:\n cprint(f'arguments.json exists', to_log=to_log, q=q)\n with open(path_to_arguments_json, 'r+', encoding='utf-8') as file:\n json_data = json.load(file)\n if len(json_data) == 0: # To avoid empty string in the text file\n json_data = arguments\n else:\n json_data.update(arguments)\n with open(path_to_arguments_json, 'w+', encoding='utf-8') as file:\n json.dump(json_data, file, indent=4)\n if debug:\n cprint(f'main(): Json data is written in {path_to_arguments_json}', to_log=to_log, q=q)\n # If it does not exist, just create a new one.\n else:\n with open(path_to_arguments_json, 'w+', encoding='utf-8') as file:\n json.dump(json_data, file, indent=4)\n if debug:\n cprint(f'main(): Json data is written in {path_to_arguments_json}', to_log=to_log, q=q)\n except BaseException as err:\n cprint(f'Error in opening json file. {err}'\n f'\\nPath_to_arguments_json: {path_to_arguments_json}')\n time.sleep(5)\n","repo_name":"ergominermonitor/ergo_miner_monitor","sub_path":"helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":28726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40071709943","text":"import numpy as np\n\n\n# Размерность матрицы A и вектора b\n\nA = [[10 ** -4, 1],\n [1, 2]]\nb = [1, 4]\n\nn = len(b)\n\n\n# Прямой ход метода Гаусса\ndef gaus(A, b, n):\n for pivot in range(n):\n # Поиск максимального элемента в текущем столбце\n max_row = pivot\n for row in range(pivot + 1, n):\n if abs(A[row][pivot]) > abs(A[max_row][pivot]):\n max_row = row\n\n # Обмен строками\n A[pivot], A[max_row] = A[max_row], A[pivot]\n b[pivot], b[max_row] = b[max_row], b[pivot]\n\n # Приведение текущего столбца к единичному значению\n pivot_elem = A[pivot][pivot]\n for j in range(pivot, n):\n A[pivot][j] /= pivot_elem\n b[pivot] /= pivot_elem\n\n # Обнуление нижних элементов столбца\n for i in range(pivot + 1, n):\n factor = A[i][pivot]\n for j in range(pivot, n):\n A[i][j] -= factor * A[pivot][j]\n b[i] -= factor * b[pivot]\n\n # Обратный ход метода Гаусса\n x = [0] * n\n for i in range(n - 1, -1, -1):\n x[i] = b[i]\n for j in range(i + 1, n):\n x[i] -= A[i][j] * x[j]\n return x\n\n\n# Вызов функции gaus для решения системы\nx = gaus(A, b, n)\n\n# Невязки\nresiduals = [b[i] - sum(A[i][j] * x[j] for j in range(n)) for i in range(n)]\n\n# Вывод решения и невязок\nprint(\"Решение 1:\")\nfor i in range(n):\n print(f\"x[{i}] = {x[i]}\")\n\nprint(\"\\nНевязки:\")\nfor i in range(n):\n print(f\"Невязка {i}: {residuals[i]}\")\n\nresiduals = np.dot(A, x) - b\n\n# Вывод невязок\nprint(\"\\nНевязки с numpy:\")\nfor i in range(n):\n print(f\"Невязка {i}: {residuals[i]}\")\n\nprint(\"\\n\")\nA = [[2.34, -4.21, -11.61],\n [8.04, 5.22, 0.27],\n [3.92, -7.99, 8.37]]\nb = [14.41, -6.44, 55.56]\n\nn = len(b)\n\nx = gaus(A, b, n)\n\n# Невязки\nresiduals = [b[i] - sum(A[i][j] * x[j] for j in range(n)) for i in range(n)]\n\n# Вывод решения и невязок\nprint(\"Решение 2:\")\nfor i in range(n):\n print(f\"x[{i}] = {x[i]}\")\n\nprint(\"\\nНевязки:\")\nfor i in range(n):\n print(f\"Невязка {i}: {residuals[i]}\")\n\nresiduals = np.dot(A, x) - b\n\n# Вывод невязок\nprint(\"\\nНевязки с numpy:\")\nfor i in range(n):\n print(f\"Невязка {i}: {residuals[i]}\")\nprint(\"\\n\")\n\n\n\nA = [[4.43, -7.21, 8.05, 1.23, -2.56],\n [-1.29, 6.47, 2.96, 3.22, 6.12],\n [6.12, 8.31, 9.41, 1.78, -2.88],\n [-2.57, 6.93, -3.74, 7.41, 5.55],\n [1.46, 3.62, 7.83, 6.25, -2.35]]\n\nb = [2.62, -3.97, -9.12, 8.11, 7.23]\n\nn = len(b)\n\nx = gaus(A, b, n)\n\n# Невязки\nresiduals = [b[i] - sum(A[i][j] * x[j] for j in range(n)) for i in range(n)]\n\n# Вывод решения и невязок\nprint(\"Решение 3:\")\nfor i in range(n):\n print(f\"x[{i}] = {x[i]}\")\n\nprint(\"\\nНевязки:\")\nfor i in range(n):\n print(f\"Невязка {i}: {residuals[i]}\")\n\nresiduals = np.dot(A, x) - b\n\n# Вывод невязок\nprint(\"\\nНевязки с numpy:\")\nfor i in range(n):\n print(f\"Невязка {i}: {residuals[i]}\")\n","repo_name":"ExizMan/others","sub_path":"pythonProject/t3-1/31.py","file_name":"31.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"26022544898","text":"#OpenCV module\nimport cv2\n#Modulo para leer directorios y rutas de archivos\nimport os\n#OpenCV trabaja con arreglos de numpy\nimport numpy\n#Se importa la lista de personas con acceso al laboratorio\nfrom listaPermitidos import flabianos\nflabs=flabianos()\n\n# Parte 1: Creando el entrenamiento del modelo\nprint('Formando...')\n\n#Directorio donde se encuentran las carpetas con las caras de entrenamiento\ndir_faces = 'att_faces/orl_faces'\n\n#Tamaño para reducir a miniaturas las fotografias\nsize = 4\n\n# Crear una lista de imagenes y una lista de nombres correspondientes\n(images, lables, names, id) = ([], [], {}, 0)\nfor (subdirs, dirs, files) in os.walk(dir_faces):\n for subdir in dirs:\n names[id] = subdir\n subjectpath = os.path.join(dir_faces, subdir)\n for filename in os.listdir(subjectpath):\n path = subjectpath + '/' + filename\n lable = id\n images.append(cv2.imread(path, 0))\n lables.append(int(lable))\n id += 1\n(im_width, im_height) = (112, 92)\n\n# Crear una matriz Numpy de las dos listas anteriores\n(images, lables) = [numpy.array(lis) for lis in [images, lables]]\n# OpenCV entrena un modelo a partir de las imagenes\nmodel = cv2.face.LBPHFaceRecognizer_create()\nmodel.train(images, lables)\n\n\n# Parte 2: Utilizar el modelo entrenado en funcionamiento con la camara\nface_cascade = cv2.CascadeClassifier( 'haarcascade_frontalface_default.xml')\ncap = cv2.VideoCapture(0)\n\nwhile True:\n #leemos un frame y lo guardamos\n rval, frame = cap.read()\n frame=cv2.flip(frame,1,0)\n\n #convertimos la imagen a blanco y negro \n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n #redimensionar la imagen\n mini = cv2.resize(gray, (int(gray.shape[1] / size), int(gray.shape[0] / size)))\n\n \"\"\"buscamos las coordenadas de los rostros (si los hay) y\n guardamos su posicion\"\"\"\n faces = face_cascade.detectMultiScale(mini)\n \n for i in range(len(faces)):\n face_i = faces[i]\n (x, y, w, h) = [v * size for v in face_i]\n face = gray[y:y + h, x:x + w]\n face_resize = cv2.resize(face, (im_width, im_height))\n\n # Intentado reconocer la cara\n prediction = model.predict(face_resize)\n \n #Dibujamos un rectangulo en las coordenadas del rostro\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)\n \n # Escribiendo el nombre de la cara reconocida\n # La variable cara tendra el nombre de la persona reconocida\n cara = '%s' % (names[prediction[0]])\n\n #Si la prediccion tiene una exactitud menor a 100 se toma como prediccion valida\n if prediction[1]<100 :\n #Ponemos el nombre de la persona que se reconoció\n cv2.putText(frame,'%s - %.0f' % (cara,prediction[1]),(x-10, y-10), cv2.FONT_HERSHEY_PLAIN,1,(0, 255, 0))\n\n #En caso de que la cara sea de algun conocido se realizara determinadas accione \n #Busca si los nombres de las personas reconocidas estan dentro de los que tienen acceso \n #flabs.TuSiTuNo(cara)\n\n #Si la prediccion es mayor a 100 no es un reconomiento con la exactitud suficiente\n elif prediction[1]>101 and prediction[1]<500: \n #Si la cara es desconocida, poner desconocido\n cv2.putText(frame, 'Desconocido',(x-10, y-10), cv2.FONT_HERSHEY_PLAIN,1,(0, 255, 0)) \n\n #Mostramos la imagen\n cv2.imshow('OpenCV Reconocimiento facial', frame)\n\n #Si se presiona la tecla ESC se cierra el programa\n key = cv2.waitKey(10)\n if key == 27:\n cv2.destroyAllWindows()\n break\n","repo_name":"futurelabmx/FaceRecognition2","sub_path":"reconocimiento.py","file_name":"reconocimiento.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"es","doc_type":"code","stars":32,"dataset":"github-code","pt":"52"} +{"seq_id":"31627539006","text":"from src.lib.twitch import *\nimport globals\n\ndef uptime():\n usage = \"!uptime\"\n \n channels_excluded = ['shedeviil_09']\n\n if globals.global_channel not in channels_excluded: \n uptime = get_stream_uptime()\n channel = globals.global_channel\n \n if get_stream_status():\n \n return \"The current !uptime is EXACTLY \" + str(uptime)\n else:\n return \"The streamer is offline, ya dingus ;)\"\n\n else:\n return\n","repo_name":"tehNinth/lorenzotherobot","sub_path":"src/lib/commands/uptime.py","file_name":"uptime.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"8356174160","text":"#This class implements the approximation automorphism for a regular tree\n#as a decorated tree structure using the AutEdge and AutNode sublasses\n#Methods of operations performbable with the AutRegTree are also implemented\n#Developed by Ewart Stone\n\nimport random\nimport json\nfrom AutNode import AutNode\nfrom AutEdge import AutEdge\n\nclass AutRegTree:\n\n def __init__(self):\n\n #List to store nodes\n self.nodes = []\n self.edges = []\n\n #aut reference\n self.reference = (-1, -1)\n\n def genInitTree(self, radius, degree, center):\n\n start = 0\n end = 0\n\n #add origin nodes\n self.nodes.append(AutNode(degree))\n\n for r in range(radius):\n for d in range(start, end + 1):\n\n targ = degree - self.nodes[d].edgeNum\n\n for count in range(0, targ):\n\n temp = AutNode(degree)\n \n #parse used edges for parent node\n #and find next unset edge\n usedEdges = self.nodes[d].getEdges()\n edgeIndex = 0\n\n for edgeIndex in range(len(usedEdges)):\n if usedEdges[edgeIndex] == None:\n break\n\n #create edge, connect nodes, and add temp to nodes\n tempEdge = AutEdge([self.nodes[d], temp])\n\n self.nodes[d].addEdge(tempEdge, edgeIndex)\n temp.addEdge(tempEdge, edgeIndex)\n\n self.nodes.append(temp)\n \n start = end + 1\n end = len(self.nodes) - 1\n\n self.assignPaths(center)\n\n def assignPaths(self, center):\n self.nodes[0].assignPath(center)\n\n def genRandomAut(self, degree, centerRef = True):\n\n #gen random node between the bound of tree nodes\n nodeRange = len(self.nodes) - 1\n\n #get ref node start\n if centerRef:\n startNodeInt = 0\n else:\n startNodeInt = random.randint(0, nodeRange)\n \n startingNode = self.nodes[startNodeInt]\n #startingNode = self.nodes[0]\n\n #get destination\n destinationNodeInt = random.randint(0, nodeRange)\n destinationNode = self.nodes[destinationNodeInt]\n #destinationNode = self.nodes[0]\n\n #set tree reference point tuple\n self.reference = (startingNode.path, destinationNode.path)\n\n startingNode.imagePath = destinationNode.path\n\n self.randomNodeAssign(startingNode, degree, -1)\n \n def randomNodeAssign(self, nodeInput, degree, lastSetLocal): \n\n #get available local actions for the node to set\n\n destColours = []\n for i in range(degree):\n destColours.append(i)\n\n if lastSetLocal != -1:\n destColours.pop(nodeInput.localAction[lastSetLocal][1])\n\n \n #for each neighbour node\n #select next available colour\n #map the neightbour node to that colour\n\n for i in range(len(nodeInput.localAction)):\n\n if i != lastSetLocal and nodeInput.localAction[i][0] != -1:\n #select random edge to map to\n destInt = random.randint(0, len(destColours) - 1)\n\n nextNode = None\n\n #fetch next node\n for x in nodeInput.edges[i].nodes:\n if nodeInput != x:\n nextNode = x\n\n #assign col in nodeinput and next node\n\n nodeLocal = (i, destColours[destInt])\n\n nodeInput.localAction[i] = nodeLocal\n nextNode.localAction[i] = nodeLocal\n\n #record image path in next node\n imagePath = nodeInput.imagePath.copy()\n backward = False\n if len(imagePath) > 0:\n\n #print(imagePath[len(imagePath) - 1])\n\n if imagePath[len(imagePath) - 1] == destColours[destInt]:\n backward = True\n\n if backward:\n #step back\n imagePath.pop(len(imagePath) - 1)\n else:\n #step forward\n imagePath.append(destColours[destInt])\n \n nextNode.imagePath = imagePath\n\n destColours.pop(destInt)\n\n #call next recursive call\n self.randomNodeAssign(nextNode, degree, i)\n\n ################################################################################\n #Automorphism Analysis Functions\n\n def typeCheck(self):\n\n #establish path\n refPoint = self.reference[0].copy()\n refPointAut = self.reference[1].copy()\n\n path = self.createPath(refPoint, refPointAut)\n\n left = 0\n right = len(path) - 1\n\n startNode = self.getNode(self.reference[0])\n leftNode = startNode\n\n if(len(path) == 0 or len(path) == 1):\n print(\"Fixed Automorphism\")\n results = self.getFixedPoints(leftNode)\n\n print(\"Fixed Nodes: \")\n for each in results:\n print(\"Node %s\" % (each))\n return\n \n #print(path)\n #print(\"%s %s\" % (left, right))\n\n while left < right:\n #step left node along path and check local actions support this\n \n #print(\"node %s\" % leftNode.path)\n #print(\"image %s\" % leftNode.imagePath)\n #print(\"testing %s != %s\" % (leftNode.localAction[path[left]][1], path[right]))\n\n #determine next colour step to take in path\n #leftStep\n if(len(path[left]) < len(path[left + 1])):\n leftStep = path[left + 1][len(path[left + 1]) - 1]\n else:\n leftStep = path[left][len(path[left]) - 1]\n\n #rightStep\n if(len(path[right]) < len(path[right - 1])):\n rightStep = path[right - 1][len(path[right - 1]) - 1]\n else:\n rightStep = path[right][len(path[right]) - 1]\n\n #print(\"left %s right %s\" % (leftStep, rightStep))\n\n #check if local action of left matches right\n if(len(leftNode.localAction) - 1 < leftStep or leftNode.localAction[leftStep][1] != rightStep):\n print(\"Translation Automorphism\")\n\n print(\"Distance: %s\" % (right - left))\n\n if(left != 0):\n #generate minimal path\n minPath = []\n\n for count in range(left, right + 1):\n minPath.append(path[count])\n else:\n minPath = path\n \n #print all along axis of translation using minPath and leftNode\n vertices = self.getTranslationAxisVertices(leftNode, minPath)\n print(vertices)\n return\n \n #if nodes match then continue to next nodes\n leftNode = leftNode.getNode(leftStep)\n\n left += 1\n right -= 1\n\n if left > right:\n #reflected along axis\n print(\"Reflected Automorphism\")\n \n print(\"Axis of reflection: \")\n print(\"%s, %s\" % (path[right], path[left]))\n\n\n elif left == right:\n #fixed node\n print(\"Fixed Automorphism\")\n results = self.getFixedPoints(leftNode)\n\n print(\"Fixed Nodes: \")\n for each in results:\n print(\"Node %s\" % (each))\n\n #Fixed Point Aut Analysis\n #preconditions: fixedNode is a reference to a fixedNode in the Aut\n #postconditions: returns an array of the paths of all fixed nodes in the aut\n def getFixedPoints(self, fixedNode):\n \n #for local action at \"central\" fixed node\n #if assigned and (x, y) where x == y\n #record node as fixed\n #call algorithm on that node\n results = []\n\n results.append(fixedNode.path)\n \n self.checkFixedPoint(fixedNode, results, -1)\n\n return results\n\n #preconditions: fixedNode is fixed, results not null, origin is an int\n #postconditions: recursively populates results with the paths of fixedNodes\n # connected to fixedNode\n def checkFixedPoint(self, fixedNode, results, origin):\n\n #origin: index of local action traversed to reach fixedNode\n\n #for local action at fixed node\n #if assigned and (x, y) where x == y\n #record node as fixed\n #call algorithm on that node\n\n for tuple in fixedNode.localAction:\n if tuple[0] != origin and tuple[0] != -1 and tuple[1] != -1 and tuple[0] == tuple[1]:\n\n next = fixedNode.getNode(tuple[0])\n results.append(next.path)\n self.checkFixedPoint(next, results, tuple[0])\n\n\n #translation aut analysis\n #preconditions: aut is a translation type and path is a subpath of the path of translation\n #postconditions: returns a list of nodes identified by path on the axis of translation\n def getTranslationAxisVertices(self, leftNode, path):\n\n #left going right\n rightPath = path.copy()\n endOfAxis = False\n currentNode = leftNode\n pathIndex = 0\n\n while not endOfAxis:\n \n #get next step\n nextStep = self.getNextInSequence(rightPath[pathIndex], rightPath[pathIndex + 1])\n\n if len(currentNode.localAction) - 1 < nextStep:\n #end of axis as not enough info\n endOfAxis = True\n #check if currentNode has mapping for nextStep\n elif currentNode.localAction[nextStep][1] != -1:\n \n #form next on path and append\n rightPath.append(self.pathFromStep(rightPath[len(rightPath) - 1],\n currentNode.localAction[nextStep][1]))\n\n #iterate to next node in path sequence\n currentNode = currentNode.getNode(nextStep)\n pathIndex += 1\n\n #else end of axis as not enough info\n else: \n endOfAxis = True\n\n\n #right going left\n leftOut = []\n leftPath = path.copy()\n pathIndex = len(leftPath) - 1\n currentNode = leftNode\n endOfAxis = False\n\n while not endOfAxis:\n\n nextStep = self.getNextInSequence(leftPath[pathIndex - 1], leftPath[pathIndex])\n laFound = False\n\n #for each local action find the la corresponding\n #to nextstep under the mapping\n for la in currentNode.localAction:\n if la[1] == nextStep:\n #target local action found\n laFound = True\n\n currentNode = currentNode.getNode(la[0])\n\n leftPath.insert(0, currentNode.path)\n leftOut.insert(0, currentNode.path)\n break\n \n if not laFound:\n endOfAxis = True\n\n leftOut.extend(rightPath)\n return leftOut\n \n #preconditions: origin is a valid int array, step is an integer step\n #postconditions: returns an array that is the result of taking the input step from origin\n def pathFromStep(self, origin, step):\n\n if len(origin) - 1 < 0:\n out = origin.copy()\n out.append(step)\n return out\n\n if origin[len(origin) - 1] == step:\n out = origin.copy()\n out.pop()\n return out\n else:\n out = origin.copy()\n out.append(step)\n return out\n\n #preconditions: p1 and p2 are arrays of positive integers\n #postconditions: creates a path from p1 to p2 and returns an array result\n def createPath(self, p1, p2):\n\n if(self.compareList(p1, p2)):\n return [p1.copy()]\n\n pathPrefix = []\n pathSuffix = []\n\n pathPrefix.append(p1.copy())\n pathSuffix.append(p2.copy())\n\n matchingPos = 0\n\n for count in range(0, len(p1)):\n\n if count >= len(p2):\n break \n\n if p1[count] == p2[count]:\n matchingPos += 1\n else:\n break\n\n #while path halves have not met\n while p1 != p2:\n #add p1 onto prefix and p2 onto suffix\n #pathPrefix.append(p1)\n #pathSuffix.insert(0, p2)\n\n #determine if p1 increases or decreases\n if len(p1) > matchingPos:\n #decrease\n #pathPrefix.append(p1[len(p1) - 1])\n\n pathPrefix.append(pathPrefix[len(pathPrefix) - 1].copy())\n pathPrefix[len(pathPrefix) - 1].pop()\n \n p1.pop(len(p1) - 1)\n else:\n #increases\n #pathPrefix.append(p2[matchingPos])\n pathPrefix.append(pathPrefix[len(pathPrefix) - 1].copy())\n pathPrefix[len(pathPrefix) - 1].append(p2[matchingPos])\n\n p1.append(p2[matchingPos])\n\n matchingPos += 1\n\n if(self.compareList(pathPrefix[len(pathPrefix) - 1], pathSuffix[0])):\n pathPrefix.pop()\n\n #check if path is now complete\n if self.compareList(p1, p2):\n #is complete\n #break loop\n break\n\n\n #determine if p2 increases or decreases\n if len(p2) > matchingPos:\n #decrease\n #pathSuffix.insert(0, p2[len(p2) - 1])\n pathSuffix.insert(0, pathSuffix[0].copy())\n pathSuffix[0].pop()\n p2.pop(len(p2) - 1)\n else:\n #increases\n #pathSuffix.insert(0, p1[matchingPos])\n pathSuffix.insert(0, pathSuffix[0].copy())\n pathSuffix[0].append(p1[matchingPos])\n p2.append(p1[matchingPos])\n\n matchingPos += 1\n\n if(self.compareList(pathPrefix[len(pathPrefix) - 1], pathSuffix[0])):\n pathSuffix.pop(0)\n\n #check if path is now complete\n if self.compareList(p1, p2):\n #is complete\n break\n\n pathPrefix.extend(pathSuffix)\n\n #print(pathPrefix)\n return pathPrefix\n \n #preconditions: l1 and l2 are arrays\n #postconditions: a True False result is returned\n # representing a comparison on the contents of the arrays\n # i.e., contents are equal, in same order, etc.\n def compareList(self, l1, l2):\n if len(l1) != len(l2):\n return False\n \n for i in range(len(l1)):\n if l1[i] != l2[i]:\n return False\n \n return True\n \n #precodntions: nodePath is either None or an array of integers\n # representing a valid path in the tree\n #postconditions: returns the reference to the node at the address nodePath\n def getNode(self, nodePath = None):\n\n #print(nodePath)\n\n if nodePath == None:\n return self.nodes[0]\n \n #parse tree and retrieve node\n pos = 0\n current = self.nodes[0]\n \n found = False\n\n while not found:\n if self.compareList(current.path, nodePath):\n found = True\n break\n\n #get next step\n nextStep = self.getNextInSequence(current.path, nodePath)\n\n #print(nodePath)\n #print(current.path)\n #print(nextStep)\n\n #take step\n current = current.getNode(nextStep)\n\n if current == None:\n break\n\n #while pos < len(nodePath):\n #\n # if current.edges[nodePath[pos]] == None:\n # return None\n #\n # current = current.edges[nodePath[pos]].nodes[1]\n #\n # pos += 1\n\n return current\n \n def getNextInSequence(self, current, destination):\n #find where matching\n\n matchingIndex = -1\n\n shortest = current if len(current) <= len(destination) else destination\n\n #iterate and find highest matching \n for count in range(len(shortest)):\n if current[count] == destination[count]:\n matchingIndex += 1\n\n #if matching == -1 then shortest is the empty string\n if current != shortest or matchingIndex != len(current) - 1:\n return current[len(current) - 1]\n else:\n return destination[matchingIndex + 1]\n \n ################################################################################\n #Mutator Functions\n #\n #Return a third aut resultant of this aut, and the input aut\n\n #############################\n #Inverse\n\n def getInverse(self):\n\n #get reference node\n current = self.getNode(self.reference[0])\n\n #count degree and radius\n degree = self.findMaxColour(current)\n\n #init inverse and reverse reference direction\n inverseTree = AutRegTree()\n\n #create center node\n inverseTree.nodes.append(AutNode(degree))\n\n inverseTree.reference = (self.reference[1], self.reference[0])\n \n inverse = inverseTree.nodes[0]\n\n inverse.path = current.imagePath.copy()\n\n self.inverseNode(current, inverse, -1, inverseTree)\n\n return inverseTree\n \n def inverseNode(self, thisNode, inverseNode, step, inverseTree):\n \n #for each local action of thisNode\n #set inverse on inverseNode\n #call this method on next node\n\n inverseNode.imagePath = thisNode.path.copy()\n\n for tuple in thisNode.localAction:\n\n if tuple[0] != -1:\n\n inverseNode.localAction[tuple[1]] = (tuple[1], tuple[0])\n\n #if step is not already recorded\n if tuple[0] != step:\n \n #get next node info\n next = thisNode.getNode(tuple[0])\n degree = self.findMaxColour(next)\n\n\n #create connected node in inverse tree\n temp = AutNode(degree)\n tempEdge = AutEdge([inverseNode, temp])\n inverseNode.setEdge(tempEdge, tuple[1])\n temp.setEdge(tempEdge, tuple[1])\n\n inverseTree.nodes.append(temp)\n\n #set path\n temp.path = self.pathFromStep(inverseNode.path, tuple[1])\n\n \n\n self.inverseNode(next,\n temp, tuple[0], inverseTree)\n \n def findMaxColour(self, node):\n max = -1\n\n for la in node.localAction:\n if la[0] > max:\n max = la[0]\n if la[1] > max:\n max = la[1]\n\n return max + 1\n\n #############################\n #Merge\n\n def merge(self, targetAut):\n \n #return tree of merged if compatible\n #else return null\n out = AutRegTree()\n\n out.nodes.append(AutNode(0))\n\n\n #search for shared node\n #check node is agreed on\n #span out on adjacent shared nodes\n\n startingTargNode = None\n startingNode = None\n\n compatible = False\n \n for node in targetAut.nodes:\n\n if node != None:\n startingNode = self.getNode(node.path) \n\n if startingNode != None:\n #match\n startingTargNode = node\n\n if(self.compatibleNodeCheck(startingNode, startingTargNode)):\n\n out.nodes[0].path = startingNode.path.copy()\n out.nodes[0].imagePath = startingNode.imagePath.copy()\n\n out.reference = (out.nodes[0].path.copy(), out.nodes[0].imagePath.copy())\n\n compatible = True\n\n #iterate through longest local action array\n #if mapped to -1 then use other list if in range\n #copy action, add coressponding edge and node to toSearch\n toSearch = []\n toAdd = []\n\n if len(startingNode.localAction) >= len(startingTargNode.localAction):\n longer = startingNode\n shorter = startingTargNode\n else:\n longer = startingTargNode\n shorter = startingNode\n\n for count in range(len(longer.localAction)):\n\n #0th local action tuple -1 if not assigned\n\n if longer.localAction[count][0] == -1 and len(shorter.localAction) > count and shorter.localAction[count][0] != -1:\n toAdd.append(shorter.getNode(shorter.localAction[count][0]))\n out.nodes[0].localAction.append((shorter.localAction[count][0], shorter.localAction[count][1]))\n\n elif longer.localAction[count][0] != -1:\n\n ######\n if len(shorter.localAction) <= count:\n toAdd.append(longer.getNode(count))\n elif shorter.localAction[count][0] == -1:\n toAdd.append(longer.getNode(count))\n else:\n toSearch.append((longer.getNode(count), shorter.getNode(count)))\n\n out.nodes[0].localAction.append((count, longer.localAction[count][1]))\n\n else:\n out.nodes[0].localAction.append((-1, -1))\n\n out.nodes[0].edges.append(None)\n\n #for each in to search\n #call recursive mergeNode\n for tuple in toSearch:\n result = self.mergeSharedNode(out.nodes[0], tuple[0], tuple[1], out)\n\n if not result:\n compatible = False\n break\n\n if compatible:\n #for each in to add\n #call recursive mergeAddNode\n for node in toAdd:\n self.mergeSingleNode(out.nodes[0], node, out)\n\n else:\n #not compatible\n pass\n\n break\n\n if not compatible:\n print(\"Trees are not compatible for merging\")\n return None\n\n return out\n \n def mergeSharedNode(self, prevOutNode, nodeA, nodeB, newTree):\n\n #record last step\n if len(prevOutNode.path) > len(nodeA.path):\n lastStep = prevOutNode.path[len(prevOutNode.path) - 1]\n else:\n lastStep = nodeA.path[len(nodeA.path) - 1]\n\n if len(nodeA.localAction) >= len(nodeB.localAction):\n longer = nodeA\n shorter = nodeB\n else:\n longer = nodeB\n shorter = nodeA\n\n #check nodeA and nodeB are compatible\n if(self.compatibleNodeCheck(nodeA, nodeB)):\n\n #create new node and edge\n #populate with info\n newNode = AutNode(len(longer.localAction))\n newTree.nodes.append(newNode)\n\n newNode.path = nodeA.path.copy()\n newNode.imagePath = nodeA.imagePath.copy()\n\n newEdge = AutEdge([prevOutNode, newNode])\n\n #connect edge to nodes\n newNode.addEdge(newEdge, lastStep)\n \n #prevOutNode.addEdge(newEdge, lastStep)\n prevOutNode.edges[lastStep] = newEdge\n prevOutNode.edgeNum += 1\n\n #set local actions\n #iterate through longest local action array\n #if mapped to -1 then use other list if in range\n #copy action, add coressponding edge and node to toSearch\n toSearch = []\n toAdd = []\n\n for count in range(len(longer.localAction)):\n\n #if tuple is only in longer action then it can be merged\n if count >= len(shorter.localAction):\n\n #if la is defined\n if longer.localAction[count][0] != -1:\n if lastStep != count:\n toAdd.append(longer.getNode(longer.localAction[count][0]))\n\n #set local action in new node\n newNode.localAction[count] = (longer.localAction[count][0], longer.localAction[count][1])\n\n #0th local action tuple -1 if not assigned\n elif longer.localAction[count][0] == -1 and shorter.localAction[count][0] != -1:\n \n if lastStep != count:\n toAdd.append(shorter.getNode(shorter.localAction[count][0]))\n\n newNode.localAction[count] = (shorter.localAction[count][0], shorter.localAction[count][1])\n\n elif longer.localAction[count][0] != -1:\n\n if lastStep != count:\n if len(shorter.localAction) <= count:\n toAdd.append(longer.getNode(count))\n elif shorter.localAction[count][0] == -1:\n toAdd.append(longer.getNode(count))\n else:\n toSearch.append((longer.getNode(count), shorter.getNode(count)))\n\n newNode.localAction[count] = (count, longer.localAction[count][1])\n\n else:\n #newNode.localAction.append((-1, -1))\n pass\n\n\n #continue recursive call\n #for each in to search\n #call recursive mergeNode\n for tuple in toSearch:\n result = self.mergeSharedNode(newNode, tuple[0], tuple[1], newTree)\n \n #if not compatible\n if not result:\n return False\n\n #for each in to add\n #call recursive mergeAddNode\n for node in toAdd:\n self.mergeSingleNode(newNode, node, newTree)\n\n else:\n #trees are not compatible so merge cannot be completed\n return False\n \n return True\n\n def mergeSingleNode(self, prevOutNode, node, newTree):\n\n #record last step\n if len(prevOutNode.path) > len(node.path):\n lastStep = prevOutNode.path[len(prevOutNode.path) - 1]\n else:\n lastStep = node.path[len(node.path) - 1]\n\n #create new node and edge\n newNode = AutNode(len(node.localAction))\n newTree.nodes.append(newNode)\n\n newNode.path = node.path.copy()\n newNode.imagePath = node.imagePath.copy()\n\n newEdge = AutEdge([prevOutNode, newNode])\n\n #connect edge to nodes\n newNode.addEdge(newEdge, lastStep)\n prevOutNode.edges[lastStep] = newEdge\n prevOutNode.edgeNum += 1\n\n #set local actions\n #iterate through longest local action array\n #if mapped to -1 then use other list if in range\n #copy action, add coressponding edge and node to toSearch\n toAdd = []\n\n for count in range(len(node.localAction)):\n if node.localAction[count][0] != -1:\n if count != lastStep:\n toAdd.append(node.getNode(count))\n\n #assign tuple\n newNode.localAction[count] = (count, node.localAction[count][1])\n else:\n #newNode.localAction.append((-1, -1))\n pass\n\n #continue recursive call\n #for each in to add call recursive mergeAddNode\n for node in toAdd:\n self.mergeSingleNode(newNode, node, newTree)\n\n #preconditions: nodeA and nodeB are two AutNodes\n #postconditions: return true if nodeA and nodeB are compatible\n # in the context of merging and false if incompatible\n # matching path and image, non-conflicting localAction\n def compatibleNodeCheck(self, nodeA, nodeB):\n if not self.compareList(nodeA.path, nodeB.path):\n return False\n \n if not self.compareList(nodeA.imagePath, nodeB.imagePath):\n return False\n\n for count in range(len(nodeA.localAction)):\n if count > len(nodeB.localAction) - 1:\n break\n\n if ((nodeA.localAction[count][0] != nodeB.localAction[count][0] or \n nodeA.localAction[count][1] != nodeB.localAction[count][1]) and \n nodeB.localAction[count][0] != -1 and nodeA.localAction[count][1] != -1):\n return False\n\n return True\n \n ###################################\n #composition\n\n #preconditions: targetAut is a valid AutRegTree\n #postconditions: returns a composed tree of the operation: this composes targetAut\n def compose(self, targetAut):\n\n composedTree = targetAut.copyTree()\n \n #targetAut.getRadius(), len(targetAut.nodes[0].edges)\n\n #composedTree.printAut()\n\n #search for at least one node with it's image in this tree\n startingTargNode = None\n startingNode = None\n\n for node in targetAut.nodes:\n\n if node.imagePath != None:\n #print(node.imagePath)\n\n startingNode = self.getNode(node.imagePath) \n\n #startingNode.print() \n\n if startingNode != None:\n #print(startingNode.path)\n startingTargNode = node\n break\n \n #if no nodes matching to compose then return null\n if startingTargNode == None:\n return None\n\n composedTreeNode = composedTree.getNode(startingTargNode.path)\n\n if startingTargNode != None:\n self.composedNode(startingTargNode, startingNode, composedTreeNode, -1, composedTree)\n\n refNode = composedTree.getNode(composedTree.reference[0])\n composedTree.reference = (refNode.path.copy(), refNode.imagePath.copy())\n\n #if no nodes are shared then returned in an empty tree \n return composedTree\n\n #preconditions:\n #postconditions: composes the composedTreeNode from this composes target\n # and recursively does so for the rest of the operation\n def composedNode(self, targetAutNode, currentNode, composedTreeNode, sourceIndex, composedTree):\n \n #print(targetAutNode.path)\n #print(composedTreeNode.path)\n #print(composedTreeNode.imagePath)\n #print(currentNode.imagePath)\n\n #write image and local action details to composedTreeNode\n composedTreeNode.imagePath = currentNode.imagePath.copy()\n\n for tuple in targetAutNode.localAction:\n\n #if tuple has defined local action and is in currentNode range of defined actions\n if tuple[1] != -1 and tuple[1] < len(currentNode.localAction):\n result = currentNode.localAction[tuple[1]][1]\n\n if result != -1:\n composedTreeNode.localAction[tuple[0]] = (tuple[0], result)\n\n #if tuple was not the source edge to this node\n if sourceIndex != tuple[0]:\n\n #perform composition on nodes corresponding to local action\n nextTargNode = targetAutNode.getNode(tuple[0])\n nextComposedNode = composedTreeNode.getNode(tuple[0])\n nextCurrentNode = currentNode.getNode(tuple[1])\n\n #recursive composition\n self.composedNode(nextTargNode, nextCurrentNode, nextComposedNode, tuple[0], composedTree)\n\n else:\n #redefined to -1 value\n \n #recursivly record connected nodes from tree\n output = []\n composedTree.addNodeToList(tuple[0], composedTreeNode.getNode(tuple[0]), output)\n\n #remove recorded nodes\n for node in output:\n composedTree.nodes.remove(node)\n\n #remove connection to nodes\n composedTreeNode.localAction[tuple[0]] = (-1, -1)\n composedTreeNode.edges[tuple[0]] = None\n composedTreeNode.edgeNum -= 1\n\n\n\n elif tuple[1] != -1:\n #not defined in composer therefore remove\n \n #recursivly record connected nodes from tree\n output = []\n self.addNodeToList(tuple[0], composedTreeNode.getNode(tuple[0]), output)\n\n #remove recorded nodes\n for node in output:\n self.nodes.remove(node)\n\n #remove connection to nodes\n composedTreeNode.localAction[tuple[0]] = (-1, -1)\n composedTreeNode.edges[tuple[0]] = None\n composedTreeNode.edgeNum -= 1\n \n def addNodeToList(self, source, currentNode, output):\n output.append(currentNode)\n\n for la in currentNode.localAction:\n if la[0] != -1 and la[0] != source:\n self.addNodeToList(la[0], currentNode.getNode(la[0]), output)\n\n def copyTree(self):\n out = AutRegTree()\n\n firstNode = self.nodes[0]\n\n out.reference = (self.reference[0].copy(), self.reference[1].copy())\n\n copy = AutNode()\n\n out.nodes.append(copy)\n\n copy.path = firstNode.path.copy()\n copy.imagePath = firstNode.imagePath.copy()\n\n for la in firstNode.localAction:\n copy.localAction.append((la[0], la[1]))\n copy.edges.append(None)\n\n self.copyNode(out, copy, firstNode.getNode(la[0]), la[0])\n\n return out\n\n def copyNode(self, copyTree, prevCopyNode, targetNode, step):\n\n copyNode = AutNode()\n copyTree.nodes.append(copyNode)\n\n copyNode.path = targetNode.path.copy()\n copyNode.imagePath = targetNode.imagePath.copy()\n\n for la in targetNode.localAction:\n copyNode.localAction.append((la[0], la[1]))\n copyNode.edges.append(None)\n\n if la[0] == step:\n #add edge\n newEdge = AutEdge([prevCopyNode, copyNode])\n prevCopyNode.setEdge(newEdge, step)\n\n copyNode.setEdge(newEdge, step)\n elif la[0] != -1:\n self.copyNode(copyTree, copyNode, targetNode.getNode(la[0]), la[0]) \n \n \n\n\n\n ################################################################################\n #Output functiones\n\n #output to console\n def printAut(self):\n print(\"\\nRef \", self.reference)\n\n for count in range(len(self.nodes)):\n print(\"Node \", count)\n print(\"Path \", self.nodes[count].path)\n print(\"Image Path \", self.nodes[count].imagePath)\n print(\"Local Action \", self.nodes[count].localAction)\n\n #preconditions: self is a \"complete\" finite subsection of a tree aut\n #i.e., consistent number of neighbours for each node except leaves\n #save to json file as specified folder path with filename\n def saveToJsonFile(self, filepath = \"\", fileName = \"defaultAutFileName\"):\n\n print(\"Warning: This function is only guaranteed to work with automorphisms \\n generated with the random construction procedure.\")\n\n degree = len(self.nodes[0].edges)\n\n jsonDict = {\n \"degree\": degree,\n \"reference\": self.reference\n }\n\n #count radius\n numberOfNodes = len(self.nodes)\n\n #start at 1 radius measurement\n total = degree + 1\n c = degree\n radius = 1\n while(total != numberOfNodes):\n c = c * (degree - 1)\n total += c\n radius += 1\n\n #store local action set in list for dict\n imageSet = []\n localActionSet = []\n\n for count in range(len(self.nodes)):\n imageSet.append(self.nodes[count].imagePath)\n localActionSet.append(self.nodes[count].localAction)\n\n #add calculated values to dict\n jsonDict[\"center\"] = self.nodes[0].path.copy()\n jsonDict[\"radius\"] = radius\n jsonDict[\"localActions\"] = localActionSet\n jsonDict[\"images\"] = imageSet\n\n #write to file\n targetFP = \"\"\n if(filepath != \"\"):\n targetFP += filepath\n targetFP += \"/\"\n\n targetFP += fileName + \".json\"\n\n with open(targetFP, \"w\") as outfile:\n json.dump(jsonDict, outfile)\n\n def initFromFile(self, filePath):\n with open(filePath, \"r\") as openFile:\n jsonObj = json.load(openFile)\n\n self.reference = (jsonObj[\"reference\"][0], jsonObj[\"reference\"][1])\n\n self.genInitTree(jsonObj[\"radius\"], jsonObj[\"degree\"], jsonObj[\"center\"])\n\n images = jsonObj[\"images\"]\n localActions = jsonObj[\"localActions\"]\n\n for count in range(len(self.nodes)):\n self.nodes[count].localAction = localActions[count]\n self.nodes[count].imagePath = images[count]\n\n def loadFromFile(self, filePath):\n self.nodes = []\n self.edges = []\n\n self.initFromFile(filePath)","repo_name":"Ewart-Stone/ComputationWithRegTreeAutomorphisms","sub_path":"AutRegTree.py","file_name":"AutRegTree.py","file_ext":"py","file_size_in_byte":37512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38131827381","text":"# Gaussian Kernel Regression\n# Please have a look at the article https://www.kaggle.com/kunjmehta/gaussian-kernel-regression-from-scratch\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport math\n\nclass GKR:\n \n def __init__(self, x, y, b):\n self.x = x\n self.y = y\n self.b = b\n \n '''Implement the Gaussian Kernel'''\n def gaussian_kernel(self, z):\n return (1/math.sqrt(2*math.pi))*math.exp(-0.5*z**2)\n \n '''Calculate weights and return prediction'''\n def predict(self, X):\n kernels = [self.gaussian_kernel((xi-X)/self.b) for xi in self.x]\n weights = [len(self.x) * (kernel/np.sum(kernels)) for kernel in kernels]\n return np.dot(weights, self.y)/len(self.x)\n \n \n def visualize_kernels(self, precision):\n plt.figure(figsize = (10,5))\n for xi in self.x:\n x_normal = np.linspace(xi - 3*self.b, xi + 3*self.b, precision)\n y_normal = stats.norm.pdf(x_normal, xi, self.b)\n plt.plot(x_normal, y_normal)#, label='Kernel at xi=' + str(xi))\n \n plt.ylabel('Kernel Weights wi')\n plt.xlabel('x')\n #plt.legend()\n \n def visualize_predictions(self, precision, X):\n plt.figure(figsize = (10,5))\n max_y = 0\n for xi in self.x:\n x_normal = np.linspace(xi - 3*self.b, xi + 3*self.b, precision)\n y_normal = stats.norm.pdf(x_normal, xi, self.b)\n max_y = max(max(y_normal), max_y)\n plt.plot(x_normal, y_normal, label='Kernel at xi=' + str(xi))\n \n plt.plot([X,X], [0, max_y], 'k-', lw=1,dashes=[2, 2])\n plt.ylabel('Kernel Weights wi')\n plt.xlabel('x')\n #plt.legend()\n","repo_name":"sampittko/tuke-beautofuel","sub_path":"src/updater/app/lib/packages/eda_quality/GaussianKernel.py","file_name":"GaussianKernel.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"22209144319","text":"import json, collections\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem.rdchem import AtomMonomerType\nfrom rdkit import RDLogger\n\nRDLogger.DisableLog('rdApp.*')\n\nroot = __file__\nroot = root[:root.rfind(\"/\")]\nAMINOACID_CONNECTIVITY = json.load(open(f\"{root}/aminoacid_connectivity.txt\", \"r\"))\n\n\nBOND_TYPES = {1:Chem.BondType.SINGLE,\n 2:Chem.BondType.DOUBLE,\n 3:Chem.BondType.TRIPLE,\n 4:Chem.BondType.AROMATIC}\n\n\ndef parse_structure(mol):\n\n\n structure = {}\n\n for i, atom in enumerate(mol.GetAtoms()):\n pdbinfo = atom.GetPDBResidueInfo()\n\n atom_name = pdbinfo.GetName().strip()\n residue_num = pdbinfo.GetResidueNumber()\n residue_name = pdbinfo.GetResidueName().strip()\n chain = pdbinfo.GetChainId().strip()\n insertion_code = pdbinfo.GetInsertionCode()\n\n if chain not in structure:\n structure[chain] = {}\n\n if f\"{residue_name}{residue_num}{insertion_code}\" not in structure[chain]:\n structure[chain][f\"{residue_name}{residue_num}{insertion_code}\"] = {}\n\n if atom_name not in structure[chain][f\"{residue_name}{residue_num}{insertion_code}\"]:\n structure[chain][f\"{residue_name}{residue_num}{insertion_code}\"][atom_name] = i\n\n return structure\n\n\ndef assign_bonds(mol, mol_structure, params):\n\n mol_editable = Chem.RWMol(mol)\n\n for bond in mol.GetBonds():\n a1 = bond.GetBeginAtomIdx()\n a2 = bond.GetEndAtomIdx()\n\n mol_editable.RemoveBond(a1, a2)\n\n for chain, residues in mol_structure.items():\n\n previous_residue_idx = None\n previous_residue_number = None\n\n for residue_idx in sorted(residues, key=lambda x: int(x[3:-1])):\n\n residue_name = residue_idx[:3]\n residue_number = int(residue_idx[3:-1])\n\n if residue_name in AMINOACID_CONNECTIVITY:\n\n if residue_name == \"LYS\":\n mol_editable.GetAtomWithIdx(mol_structure[chain][residue_idx][\"NZ\"]).SetFormalCharge(1)\n\n if residue_name == \"ARG\":\n mol_editable.GetAtomWithIdx(mol_structure[chain][residue_idx][\"NE\"]).SetFormalCharge(1)\n\n if residue_name == \"HIS\":\n mol_editable.GetAtomWithIdx(mol_structure[chain][residue_idx][\"ND1\"]).SetFormalCharge(1)\n\n # add connections between backbone N of residue i and backbone C of residue i - 1\n\n if previous_residue_number is None:\n pass\n\n elif previous_residue_number + 1 == residue_number:\n mol_editable.AddBond(mol_structure[chain][residue_idx][\"N\"], mol_structure[chain][previous_residue_idx][\"C\"], BOND_TYPES[1])\n\n previous_residue_idx = residue_idx\n previous_residue_number = residue_number\n\n # add connections inside residue i\n\n for atom_name, atom_idx in residues[residue_idx].items():\n\n # if amino acid is terminal then add terminal atoms\n\n if atom_name in [\"1H\", \"2H\", \"3H\"]:\n mol_editable.AddBond(atom_idx, mol_structure[chain][residue_idx][\"N\"], BOND_TYPES[1])\n mol_editable.GetAtomWithIdx(mol_structure[chain][residue_idx][\"N\"]).SetFormalCharge(1)\n continue\n\n if atom_name == \"OXT\":\n mol_editable.AddBond(atom_idx, mol_structure[chain][residue_idx][\"C\"], BOND_TYPES[1])\n continue\n\n elif atom_name in AMINOACID_CONNECTIVITY[residue_name]:\n for atom2_name, bond_order in AMINOACID_CONNECTIVITY[residue_name][atom_name]:\n if atom2_name in mol_structure[chain][residue_idx]:\n mol_editable.AddBond(atom_idx, mol_structure[chain][residue_idx][atom2_name], BOND_TYPES[bond_order])\n\n elif residue_name in params:\n\n bond_props = params[residue_name][0]\n atom_props = params[residue_name][1]\n\n for atom_name, atom_idx in residues[residue_idx].items():\n if atom_name in bond_props:\n for atom2_name, bond_order in bond_props[atom_name]:\n if atom2_name in mol_structure[chain][residue_idx]:\n mol_editable.AddBond(atom_idx, mol_structure[chain][residue_idx][atom2_name], BOND_TYPES[bond_order])\n\n for atom_name, atom_idx in residues[residue_idx].items():\n if atom_name in atom_props:\n atom = mol_editable.GetAtomWithIdx(atom_idx)\n atom.UpdatePropertyCache(strict=False)\n atom.SetFormalCharge(atom_props[atom_name])\n atom.SetNoImplicit(True)\n\n else:\n print(f\"Residue {residue_name} {residue_number} is not recognized\")\n\n return mol_editable.GetMol()\n\n\ndef extract_structure_properties(mol):\n\n BOND_TYPES = {1.0:1,\n 2.0:2,\n 3.0:3,\n 1.5:4}\n\n atom_properties = {}\n bond_properties = {}\n\n for i, a in enumerate(mol.GetAtoms()):\n formal_charge = a.GetFormalCharge()\n atom_properties[i] = formal_charge\n\n for i, b in enumerate(mol.GetBonds()):\n begin_idx = b.GetBeginAtomIdx()\n end_idx = b.GetEndAtomIdx()\n b_order = b.GetBondTypeAsDouble()\n bond_properties[i] = [begin_idx, end_idx, BOND_TYPES[b_order]]\n\n return atom_properties, bond_properties\n\n\ndef create_skeleton_mol(connectivity):\n\n chem_symbols = [\"Al\", 'Si', 'Se', 'Ca', 'Mg', 'Mn', 'Fe', 'Zn', 'Co', 'Cu', 'Ni', 'Cd', 'Br', 'Cl', 'C', 'H', 'O', 'N', 'P', 'S', 'I', 'F', 'B']\n\n atoms = list(set([cc for c in connectivity for cc in c[:2]]))\n chem_symbols = [[s for s in chem_symbols if \"\".join([aa for aa in a if not aa.isdigit()]).capitalize().startswith(s)][0] for a in atoms]\n\n if len(atoms) != len(chem_symbols):\n raise Exception(\"Restoring connectivity failed\")\n\n skeleton_mol = Chem.RWMol()\n\n for a, symbol in zip(atoms,chem_symbols):\n idx = skeleton_mol.AddAtom(Chem.Atom(symbol))\n skeleton_mol.GetAtomWithIdx(idx).SetProp(\"_Name\", a)\n\n for begin_idx, end_idx, bond_order in connectivity:\n begin_idx = atoms.index(begin_idx)\n end_idx = atoms.index(end_idx)\n skeleton_mol.AddBond(begin_idx, end_idx, order=BOND_TYPES[bond_order])\n\n return skeleton_mol\n\n\ndef parse_params(paramsstring):\n\n smiles = \"None\"\n name = None\n connectivity = []\n\n for s in paramsstring.split(\"\\n\"):\n\n if s.startswith(\"#SMILES: \"):\n smiles = s.split(\" \")[1]\n\n if s.startswith(\"IO_STRING\"):\n name = s.split(\" \")[1]\n\n if s.startswith(\"BOND\"):\n s = list(filter(lambda x: x != \"\", s.split(\" \")))\n connectivity.append([s[1], s[2], int(s[-1].replace(\"#ORGBND\", \"\"))])\n\n smiles_params = Chem.SmilesParserParams()\n smiles_params.removeHs = False\n template = Chem.MolFromSmiles(smiles, smiles_params)\n \n if template is None:\n smiles = \"None\"\n \n skeleton_mol = create_skeleton_mol(connectivity)\n \n if smiles != \"None\":\n skeleton_mol = AllChem.AssignBondOrdersFromTemplate(template, skeleton_mol)\n\n if template.HasSubstructMatch(skeleton_mol):\n skeleton_atom_props = {} \n skeleton_bonds_props = {}\n\n match = template.GetSubstructMatch(skeleton_mol)\n\n for i, j in enumerate(match):\n ref_atom = template.GetAtomWithIdx(j)\n target_atom = skeleton_mol.GetAtomWithIdx(i)\n\n target_atom.SetFormalCharge(ref_atom.GetFormalCharge())\n\n elif skeleton_mol.HasSubstructMatch(template):\n skeleton_atom_props = {} \n skeleton_bonds_props = {}\n\n match = skeleton_mol.GetSubstructMatch(template)\n\n for j, i in enumerate(match):\n ref_atom = template.GetAtomWithIdx(j)\n target_atom = skeleton_mol.GetAtomWithIdx(i)\n\n target_atom.SetFormalCharge(ref_atom.GetFormalCharge())\n\n\n atom_names = [atom.GetProp(\"_Name\") for atom in skeleton_mol.GetAtoms()]\n skeleton_atom_props, skeleton_bonds_props = extract_structure_properties(skeleton_mol)\n\n skeleton_atom_props = {atom_names[idx]:props for idx, props in skeleton_atom_props.items()}\n skeleton_bonds_props = [[atom_names[props[0]], atom_names[props[1]], props[2]] for _, props in skeleton_bonds_props.items()]\n\n reshaped_skeleton_bonds_props = {}\n\n for node in atom_names:\n reshaped_skeleton_bonds_props[node] = []\n \n to_delete = []\n for i, c in enumerate(skeleton_bonds_props):\n\n if node not in c:\n continue\n \n node2 = c[1] if c.index(node) == 0 else c[0]\n bond_order = c[-1]\n\n reshaped_skeleton_bonds_props[node].append([node2, bond_order])\n\n to_delete.append(i)\n\n for i in sorted(to_delete, reverse=True):\n del skeleton_bonds_props[i]\n\n reshaped_skeleton_bonds_props = {k:v for k, v in reshaped_skeleton_bonds_props.items() if len(v) != 0}\n\n return name, reshaped_skeleton_bonds_props, skeleton_atom_props\n\n\ndef load_pdbstring(pdbstring, params=[]):\n\n mol = Chem.MolFromPDBBlock(pdbstring, removeHs=False, proximityBonding=False, sanitize=False)\n mol_structure = parse_structure(mol)\n\n params = [parse_params(p) for p in params]\n params = {name:[bonds_props, atom_props] for name, bonds_props, atom_props in params}\n\n mol = assign_bonds(mol, mol_structure, params)\n # mol.UpdatePropertyCache()\n\n problems = Chem.DetectChemistryProblems(mol)\n\n Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_KEKULIZE)\n \n return mol\n\n\ndef prepare_amino_acids_connectivity():\n\n root = pkgutil.get_loader(\"pyrosetta\").path\n root = root[:root.rfind(\"/\")] + \"/database/chemical/residue_type_sets/fa_standard/residue_types\"\n \n aas = {}\n \n for f in glob.glob(f\"{root}/l-caa/*params\"):\n name, connectivity = parse_canonical_params(open(f,\"r\").read())\n aas[name] = connectivity\n\n if \"DELOCALIZED\" in set([aa[2] for aa in connectivity]):\n print(f, name)\n\n print(set([aa[2] for a in aas.values() for aa in a]))\n\n\ndef read_mol2(mol2fname):\n\n bonds_dict = {\"ar\":Chem.BondType.AROMATIC,\n \"am\":Chem.BondType.SINGLE,\n \"1\" :Chem.BondType.SINGLE,\n \"2\" :Chem.BondType.DOUBLE,\n \"3\" :Chem.BondType.TRIPLE}\n\n\n mol2 = open(mol2fname, \"r\").read()\n\n # obabel case\n if len(mol2.split(\"\\n\")[1].split(\" \")) == 2:\n smiles = mol2.split(\"\\n\")[1].split(\" \")[-1]\n try:\n mol = Chem.MolFromSmiles(smiles)\n if Chem.MolFromSmiles(smiles) is not None:\n mol = Chem.AddHs(mol)\n return smiles\n except:\n mol = Chem.RWMol()\n else:\n mol = Chem.RWMol()\n\n # openeye case\n\n atoms_mol2 = [r for r in mol2.split(\"@\") if r.startswith(\"<TRIPOS>ATOM\\n\")][0]\n atoms_mol2 = atoms_mol2.split(\"<TRIPOS>ATOM\\n\")[-1]\n\n atoms_mol2 = [[rr for rr in r.split(\" \") if rr != \"\"] for r in atoms_mol2.split(\"\\n\") if len(r) != 0]\n atoms_mol2 = {r[0]:r[5].split(\".\")[0] for r in atoms_mol2}\n\n atoms_rdkit = {idx:mol.AddAtom(Chem.Atom(symbol)) for idx, symbol in atoms_mol2.items()}\n atoms_rdkit_reverse = {v:k for k,v in atoms_rdkit.items()}\n\n bonds = [r for r in mol2.split(\"@\") if r.startswith(\"<TRIPOS>BOND\\n\")][0]\n bonds = bonds.split(\"<TRIPOS>BOND\\n\")[-1]\n\n bonds = [[rr for rr in r.split(\" \") if rr != \"\"] for r in bonds.split(\"\\n\") if len(r) != 0]\n bonds = [r[1:] for r in bonds]\n\n for begin_idx, end_idx, b_order in bonds:\n begin_idx = atoms_rdkit[begin_idx]\n end_idx = atoms_rdkit[end_idx]\n \n mol.AddBond(begin_idx, end_idx, order=bonds_dict[b_order])\n\n explicit_valence = {\"O\":2, \"N\":3, \"C\":4, \"H\":1}\n\n for i, a in enumerate(mol.GetAtoms()):\n a_symbol = a.GetSymbol()\n a.UpdatePropertyCache(strict=False)\n a.SetNoImplicit(True)\n\n if a_symbol in explicit_valence:\n formal_charge = a.GetExplicitValence() - explicit_valence[a_symbol]\n a.SetFormalCharge(formal_charge)\n\n if mol.GetNumAtoms() != Chem.AddHs(mol).GetNumAtoms():\n return None\n\n if Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_KEKULIZE, catchErrors=True) != 0:\n return None\n \n return Chem.MolToSmiles(mol)\n","repo_name":"gandrianov/vScreenML","sub_path":"vScreenML/utils/rdkit_utils.py","file_name":"rdkit_utils.py","file_ext":"py","file_size_in_byte":12743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"523539759","text":"from email.utils import quote\nfrom werkzeug.utils import redirect\nfrom ..import auth\nfrom ..auth.forms import LoginForm\nfrom flask import render_template , request ,url_for ,abort\nfrom . import main\nfrom ..models import User ,Blog, Comment\nfrom flask_login import login_required , current_user\nfrom .. import db\nfrom .forms import BlogForm , CommentForm\nfrom app.main import forms\nfrom ..request import get_quotes\n\n@main.route('/')\ndef index():\n blog = Blog.query.all()\n\n title = 'Home'\n quotes = get_quotes()\n \n return render_template('home.html' , title = title ,quotes = quotes,blogs = blog )\n\n\n@main.route('/pitches/new/', methods = ['GET','POST'])\n@login_required\ndef new_blog():\n form = BlogForm()\n\n if form.validate_on_submit():\n content = form.content.data\n name = form.name.data\n \n new_blog = Blog(name = name , content = content ,owner_id = current_user.id)\n db.session.add(new_blog)\n db.session.commit()\n\n return redirect(url_for('main.index'))\n\n return render_template('blog.html' , form = form)\n\n\n@main.route('/comment/new/<int:blog_id>', methods = ['GET','POST'])\n@login_required\ndef new_comment(blog_id):\n commentform = CommentForm()\n blog= Blog.query.get(blog_id)\n if commentform.validate_on_submit():\n comment = commentform.description.data\n\n new_comment = Comment(comment = comment, user_id = current_user.id,blog_id = blog_id)\n new_comment.save_comment()\n\n db.session.add(new_comment)\n db.session.commit()\n\n return redirect(url_for('.new_comment' ,blog_id = blog_id))\n all_comments = Comment.query.filter_by(blog_id = blog_id).all()\n return render_template('comments.html', form = commentform, comment = all_comments, blog = blog )\n@main.route('/delete/new/<int:id>', methods = ['GET','POST'])\n@login_required\ndef deleteComment(id):\n todele = Comment.query.filter_by(id = id).first()\n db.session.delete(todele)\n db.session.commit()\n return redirect(url_for('main.index'))\n# function of deleting blog\n@main.route('/delete/new/<int:id>', methods = ['GET','POST'])\n@login_required\ndef deleteBlog(id):\n todele =Blog.query.filter_by(id=id).delete()\n if todele is None:\n abort(404)\n \n db.session.delete(todele)\n db.session.commit()\n return redirect(url_for('main.index'))\n\n\n\n\n\n","repo_name":"sngina/consultancy","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12310702985","text":"from telemetry.page import legacy_page_test\nfrom telemetry.timeline import model as model_module\nfrom telemetry.value import trace\nfrom telemetry.web_perf.metrics import smoothness\nfrom telemetry.web_perf import smooth_gesture_util\nfrom telemetry.web_perf import timeline_interaction_record as tir_module\nfrom telemetry.timeline import tracing_config\n\nfrom metrics import timeline\n\n\ndef _CollectRecordsFromRendererThreads(model, renderer_thread):\n records = []\n for event in renderer_thread.async_slices:\n if tir_module.IsTimelineInteractionRecord(event.name):\n interaction = tir_module.TimelineInteractionRecord.FromAsyncEvent(event)\n # Adjust the interaction record to match the synthetic gesture\n # controller if needed.\n interaction = (\n smooth_gesture_util.GetAdjustedInteractionIfContainGesture(\n model, interaction))\n records.append(interaction)\n return records\n\n\nclass Rendering(legacy_page_test.LegacyPageTest):\n\n def __init__(self):\n super(Rendering, self).__init__()\n self._results = None\n\n @classmethod\n def CustomizeBrowserOptions(cls, options):\n options.AppendExtraBrowserArgs('--enable-gpu-benchmarking')\n options.AppendExtraBrowserArgs('--touch-events=enabled')\n\n def WillNavigateToPage(self, page, tab):\n config = tracing_config.TracingConfig()\n config.enable_chrome_trace = True\n config.enable_platform_display_trace = True\n\n # Basic categories for smoothness.\n config.chrome_trace_config.SetLowOverheadFilter()\n\n # Extra categories from commandline flag.\n if self.options and self.options.extra_chrome_categories:\n config.chrome_trace_config.category_filter.AddFilterString(\n self.options.extra_chrome_categories)\n\n tab.browser.platform.tracing_controller.StartTracing(config)\n\n def ValidateAndMeasurePage(self, _, tab, results):\n self._results = results\n trace_result = tab.browser.platform.tracing_controller.StopTracing()\n\n # TODO(charliea): This is part of a three-sided Chromium/Telemetry patch\n # where we're changing the return type of StopTracing from a TraceValue to a\n # (TraceValue, nonfatal_exception_list) tuple. Once the tuple return value\n # lands in Chromium, the non-tuple logic should be deleted.\n if isinstance(trace_result, tuple):\n trace_result = trace_result[0]\n\n trace_value = trace.TraceValue(\n results.current_page, trace_result,\n file_path=results.telemetry_info.trace_local_path,\n remote_path=results.telemetry_info.trace_remote_path,\n upload_bucket=results.telemetry_info.upload_bucket,\n cloud_url=results.telemetry_info.trace_remote_url)\n results.AddValue(trace_value)\n\n model = model_module.TimelineModel(trace_result)\n renderer_thread = model.GetRendererThreadFromTabId(tab.id)\n records = _CollectRecordsFromRendererThreads(model, renderer_thread)\n\n smoothness_metric = smoothness.SmoothnessMetric()\n smoothness_metric.AddResults(model, renderer_thread, records, results)\n\n thread_times_metric = timeline.ThreadTimesTimelineMetric()\n thread_times_metric.AddResults(model, renderer_thread, records, results)\n\n def DidRunPage(self, platform):\n if platform.tracing_controller.is_tracing_running:\n trace_result = platform.tracing_controller.StopTracing()\n if self._results:\n\n # TODO(charliea): This is part of a three-sided Chromium/Telemetry patch\n # where we're changing the return type of StopTracing from a TraceValue\n # to a (TraceValue, nonfatal_exception_list) tuple. Once the tuple\n # return value lands in Chromium, the non-tuple logic should be deleted.\n if isinstance(trace_result, tuple):\n trace_result = trace_result[0]\n\n trace_value = trace.TraceValue(\n self._results.current_page, trace_result,\n file_path=self._results.telemetry_info.trace_local_path,\n remote_path=self._results.telemetry_info.trace_remote_path,\n upload_bucket=self._results.telemetry_info.upload_bucket,\n cloud_url=self._results.telemetry_info.trace_remote_url)\n\n self._results.AddValue(trace_value)\n","repo_name":"kiwibrowser/src","sub_path":"tools/perf/measurements/rendering.py","file_name":"rendering.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"73274402724","text":"import re\nimport subprocess\n\nfrom pystarport import ports\n\nfrom .utils import wait_for_block, wait_for_port\n\n\ndef wait_relayer_ready(cluster):\n for cli in cluster.values():\n for i in range(cli.nodes_len()):\n wait_for_port(ports.grpc_port(cli.base_port(i)))\n\n for cli in cluster.values():\n # wait for at least 3 blocks, because\n # \"proof queries at height <= 2 are not supported\"\n wait_for_block(cli, 3)\n\n # all clusters share the same root data directory\n data_root = next(iter(cluster.values())).data_root\n return [\"hermes\", \"--config\", data_root / \"relayer.toml\"]\n\n\ndef search_target(query, key, chains):\n results = []\n for chain in chains:\n raw = subprocess.check_output(query + [chain]).decode(\"utf-8\")\n results.append(re.search(r\"\" + key + r\"-\\d*\", raw).group())\n return results\n\n\ndef start_and_wait_relayer(\n cluster,\n port=\"transfer\",\n chains=[\"ibc-0\", \"ibc-1\"],\n start_relaying=True,\n init_relayer=True,\n):\n relayer = wait_relayer_ready(cluster)\n if init_relayer:\n # create connection and channel\n subprocess.run(\n relayer\n + [\n \"create\",\n \"channel\",\n \"--a-port\",\n port,\n \"--b-port\",\n port,\n \"--a-chain\",\n chains[0],\n \"--b-chain\",\n chains[1],\n \"--new-client-connection\",\n \"--yes\",\n ],\n check=True,\n )\n\n # start relaying\n if start_relaying:\n cluster[chains[0]].supervisor.startProcess(\"relayer-demo\")\n\n query = relayer + [\"query\", \"channels\", \"--chain\"]\n return search_target(query, \"channel\", chains)\n","repo_name":"crypto-org-chain/chain-main","sub_path":"integration_tests/ibc_utils.py","file_name":"ibc_utils.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":460,"dataset":"github-code","pt":"52"} +{"seq_id":"11155364125","text":"# *** 함수, 객체지향프로그래밍, 모듈과 패키지 개념 정리 및 연습문제 ***\n\n# 1. print(), sum(), range()와 같은 함수를 무슨 함수라고 하나요.\n# 내장(built-in)함수\n\n# 2. 함수를 정의하는 키워드를 쓰세요.\n# def\n\n# 3. 주어진 input에 대해 의도된 output을 전달하는 역할을 하는 것을 프로그래밍에서는 무엇이라고 하나요?\n# 함수\n\n# 4. 리스트, 튜플과 같은 원소의 개수를 output하는 함수명을 적으세요.\n# len\n\n# 5. 함수에 전달되는 입력을 무엇이라고 하는지 아는대로 적으세요.\n# argument, parameter\n\n# 6. 매개변수를 지정하지 않을 경우, 지정된 기본값으로 대체되는데 이러한 인자를 무엇이라고 하나요?\n# default parameter(기본 인자)\n\n# 7. 위의 문제에 해당하는 내장 함수의 예를 들어보세요.\n# print() 함수의 end = ‘\\n’\n\n# 8. 함수의 종료를 명시하는 키워드는 무엇인가요?\n# return\n\n# 9. 위 문제의 키워드가 생략된 경우 반환값은 무엇인지 적으세요\n# None\n\n# 10. 함수의 반환값은 어디로 리턴되나요?\n# 함수 호출자(caller)\n\n\n# 11. 다음 중 틀린 표현은 몇 번째 인가요?\n# def test(a, b, c = 1)\n# def test(a, b = 1, c)\n# def test(a = 1, b = 1, c = 3)\n# 2번째\n\n# 12. 키워드 파라미터를 관례적으로 어떻게 표현하는지 직접 함수의 선언부를 작성해보세요\n# (인수의 갯수는 고정되지 않음, 함수명은 임의로 정하세요)\n# def test2(**kwargs):\n\n# 13. 특정 코드 블록(함수 안)에서 선언된 변수를 무엇이라고 하나요?\n# 지역(local) 변수\n\n# 14. 프로그램 종료 전까지 유지되는 변수를 무슨 변수라고 하나요?\n# 전역(global) 변수\n\n# 15. 위와 같은 변수의 범위를 영어로 무엇이라고 하나요?\n# scope\n\n# 16. 13번, 14번 답 중 우선순위가 높은 것(먼저 적용되는 것)은?\n# 지역(local) 변수\n\n# 17. 파라미터를 튜플 형태로 전달하는 함수의 선언부를 작성해보세요. (인자의 갯수가 고정되지 않음, 함수명은 임의로..)\n# def test(*args):\n\n\n# 18. 두개의 입력을 받아 합, 차, 곱의 결과를 튜플로 동시에 반환하는 함수를 정의 하고 실행해보세요.\n\ndef fn_plus_minus_mul(num1, num2):\n return (num1 + num2, num1 - num2, num1 * num2)\n\nprint(fn_plus_minus_mul(10,21))\n\n# 19. 다음과 같은 함수를 정의하고 실행해보세요.(조건문을 이용)\n'''\n 함수명 : return_fruit\n 입력 : color\n 기능 : \n color가 red 이면 apple을 반환\n color가 yellow 이면 banana를 반환\n color가 green 이면 water melon을 반환\n 위�� color가 아니면 I don't know를 반환 \n'''\n\ndef return_fruit(color):\n if color == 'red':\n return 'apple'\n elif color == 'yellow':\n return 'banana'\n elif color == 'green':\n return 'water melon'\n else:\n return \"I don't know\"\n\n# 20. 위의 문제를 아래 예시된 딕셔너리를 이용하여 함수를 정의하세요.\n'''\nfruit_dic = {\n 'red': 'apple',\n 'yellow': 'banana',\n 'green': 'water melon'\n}\n'''\n\nfruit_dic = {\n 'red': 'apple',\n 'yellow': 'banana',\n 'green': 'water melon'\n}\n\ndef return_fruit(color):\n return fruit_dic.get(color, \"I don't know\") # get함수의 두번째 인자: color값이 없을 때 리턴되는 값\n\nres = return_fruit('blue')\nprint(res)\n\n# 21. 입력 값 보다 작은 Fibonacci 수열을 출력하는 함수를 작성하세요\n# 함수명 : fibonacci\n# 피보나치 수열 : 0번째 원소를 0, 1번째 원소를 1로 두고 시작하여, 다음 2번째 원소는 앞의 두수의 합 1(0+1)을 놓고,\n# 3번째 원소는 앞의 두수의 합 2(1 + (0+1))을, 4번째 원소는 역시 앞의 두수의 합 3(1 + 2)을 배치하는 방식으로\n# 나열되는 수열을 말한다.\n# e.g) 0, 1, 1, 2, 3, 5, 8, 13, 21, ....\n\ndef fibonacci(n):\n a, b = 0, 1\n\n while a < n:\n print(a, end=' ')\n a,b = b, a+b\n\n print()\n\nfibonacci(10)\n\n# 22. 위의 문제에서 수열을 리스트에 출력하도록 함수를 수정하세요.\ndef fibonacci2(n):\n result = []\n a, b = 0,1\n while a < n:\n result.append(a)\n a,b = b, a+b\n\n return result\n\nresult = fibonacci2(10)\nprint(result)\n\n# 23. 인자의 갯수가 하나 또는 두개만 허용된다고 가정하고, 하나인 경우는 제곱을 두개인 경우에는 두수의 곱을 반환하는 \n# 함수를 정의해보세요. 함수명(var_arg)\ndef var_arg(*args):\n num = len(args)\n if num == 1:\n return args[0] ** 2\n elif num == 2:\n return args[0] * args[1]\n\nval = var_arg(1, 2)\nprint(val)\n\nval = var_arg(3)\nprint(val)\n\n# 24. a, b 두수 중 큰 값을 출력하는 코드를 삼항연산자(조건부 표현식)를 이용하여 작성하세요.\na = 10\nb = 100\n\nprint('a :', a) if a > b else print('b :', b)\n\n\n# 25. 23번 문제를 default parameter와 파이썬 삼항 연산자(조건부 표현식)를 이용하여 함수를 정의하세요.\n# 함수명 : default_arg\ndef default_arg(x, y = None):\n return x * (y if y else x)# 삼항연산자(조건부 표현식)\n\nprint(default_arg(10))\nprint(default_arg(10, 2))\n\n# 26. 모듈(또는 객체) 안에 어떤 함수나 변수가 있는지 이름들을 확인하는 내장 함수는 무엇인지 쓰세요.\n# dir()\n\n# 27. m_test 모듈안에 두수의 합을 리턴하는 함수(add)와, name 변수를 선언하는 모듈을 만든 후,\n# 26번 답(내장함수)을 이용하여 m_test모듈안의 이름들을 출력하는 코드를 작성하여 실행하세요.\n'''\n# m_test.py\n\ndef add(x, y):\n n = x + y\n return n\n\nname = '홍길동' \n\n'''\nimport m_test\nprint(dir(m_test))\n\n# 28. 위에서 만든 모듈을 mt라는 별칭을 이용하여 add함수를 호출하여 결과값을 출력하는 코드를 작성하세요.\n\nimport m_test as mt\nres = mt.add(1,12)\nprint(res)\nprint(mt.add(1,1))\n\n# 29. 람다함수의 키워드를 쓰세요.\n# lamda\n\n# 30. 람다함수와 일반함수의 차이점에 대해서 간략히 정리해보세요.\n# 일회성(코드상에서 한번만 사용할 때)\n# 익명성\n\n# 31. 람다 함수가 유용하게 사용되는 3개의 함수를 적으세요.\n# map, filter, reduce\n\n# 32. 주어진 리스트에서 5(포함) ~ 10(포함)사이의 값을 출력하는 코드를 작성하는데\n# 위의 문제 3개의 함수 중 하나를 이용하여 작성하세요.\n# nums = [1,2,3,6,8,9, 10, 11, 13, 15]\n\nnums = [1,2,3,6,8,9, 10, 11, 13, 15]\nprint(list(filter(lambda n : n>=5 and n<=10, nums)))\n\n# 33. 31번 문제 3개의 함수 중 하나를 이용하여 다음과 같이 369 게임에 맞게 코드를 작성하세요.\n# [1, 2, '박수', 4, 5, '박수', 7, 8, '박수'] (1 ~ 10범위)\n \nprint(list(map(lambda x: '박수' if x % 3 == 0 else x, range(1, 10))))\n\n# 34. 위의 문제에서 범위를 1 ~ 20까지 했을 때 코드를 작성하세요. (find함수 사용)\n# [1, 2, '박수', 4, 5, '박수', 7, 8, '박수', 10, 11, 12, '박수', 14, 15, '박수', 17, 18, '박수'] (1 ~ 20범위)\n# find() : 문자열에서 해당 문자의 index를 반환, 만일 없으면 -1을 반환 \n# e.g> 'abcde'.find('b') 실행 후 확인해보세요.\n\nprint(list(map(lambda x: '박수' if str(x).find('3') >= 0 or str(x).find('6') >= 0 or str(x).find('9') >= 0 else x, range(1, 20))))\n\n\n# 35. 리스트 컴프리핸션과 람다 함수를 이용하여 구구단을 가로로 출력하는 리스트를 만들어 보세요\n# e.g> ['2 x 1 = 2', '2 x 2 = 4', '2 x 3 = 6', ... ]\n# 람다함수는 익명함수 즉, 람���표현식(매개변수) 형식으로 표현가능하다.\n\nres = [ (lambda a, b : f'{a} x {b} = {a * b}')(x, y) for x in range(2, 10) for y in range(1, 10) ]\nprint(res)\n\n# 36. 35번 문제와는 다른 형식의 리스트 컴프리핸션과 람다 함수를 이용하여 구구단을 가로로 출력하는 리스트를 만들어 보세요\n# e.g> ['2 x 1 = 2', '2 x 2 = 4', '2 x 3 = 6', ... ]\nres = [ f'{x} x {y} = {(lambda x: x * y)(x)}' for x in range(2, 10) for y in range(1, 10) ]\nprint(res)\n\n# 38. 단위 테스트용으로 사용되는 구문을 적으세요.\n# if __name__ == '__main__':\n\n# 39. 다음 예시대로 실행 후 결과를 출력하고 __name__ 내장변수에 대해 생각해보세요.\n'''\n# greet.py \n\ndef greeting():\n print('hello!!')\n\nprint('greet의 __name__ :', __name__)\n----------------------\n\n# greet.py를 import 하여 다음과 같이 실행한 후 결과를 확인하세요.\n\nimport greet\n\nprint('현재 모듈의 __name__ :', __name__)\ngreet.greeting()\n\n''' \n\nimport greet\n\nprint('현재 모듈의 __name__ :', __name__)\ngreet.greeting()\n\n\n# 40. 다음 예시와 같이 학생의 수를 입력받아 학생의 점수와 평균, 평균과의 차이를 구하여 출력하는\n# 프로그램을 구현하세요. (함수를 이용하여 구현하세요) \n\n# 참고 사항 : 전체적인 구현을 먼저 한 후 부분 부분 함수를 정의해보세요.\n\n# 학생 수를 입력받는다.\n# 학생의 점수는 리스트에 append() 함수를 이용하여 학생수 만큼 루프를 돌려 추가시킨다.\n# 리스트의 평균을 구한다.\n# 평균미만자 수 : 구한 평균 미만의 점수를 카운트 한다.(루프 활용)\n# 반복문을 활용하여 출력한다.\n\n''' [ 프로그램 실행 화면 ]\n\n학생 수를 입력하세요 : 4\n\n1번 학생의 점수 : 88\n2번 학생의 점수 : 79\n3번 학생의 점수 : 85\n4번 학생의 점수 : 78\n------------------------------\n 번호 \t 점수 \t 평균과의 차이\n------------------------------\n 1 \t 88 \t 5.50\n\n 2 \t 79 \t -3.50\n\n 3 \t 85 \t 2.50\n\n 4 \t 78 \t -4.50\n------------------------------\n전체 평균 : 82.5\n------------------------------\n평균 미만자 수 : 2\n------------------------------\n'''\n\n# 학생점수 입력받기\ndef input_score(n):\n score = []\n for i in range(1, n+1):\n score.append(int(input(str(i)+'번 학생의 점수 : ')))\n return score\n\n# 평균 구하기\ndef mean(score):\n avg = sum(score) / len(score)\n return avg\n \n# 평균미만자 수 구하기\ndef under_avg_cnt(avg, score):\n cnt = 0\n for i in score:\n if i < avg:\n cnt += 1\n return cnt \n\n# 화면 출력하기\ndef res_output(avg, score, cnt): \n print('------------------------------')\n print(' 번호 \\t 점수 \\t 평균과의 차이')\n print('------------------------------')\n \n for idx, value in enumerate(score):\n print()\n print(f' {idx+1} \\t {value} \\t {value - avg:.2f}')\n \n print('------------------------------') \n print('전체 평균 : ', avg) \n print('------------------------------') \n print('평균 미만자 수 : ', under_cnt)\n print('------------------------------') \n \n# main process\nnum = int(input('학생수를 입력하세요 : ')) \n\nscore = input_score(num)\n\navg = mean(score)\nunder_cnt = under_avg_cnt(avg, score)\n\nres_output(avg, score, under_cnt)\n\n# 41. 파일 입출력 시 자주 사용되는 3가지 모드를 쓰세요.\n# 참고 사이트 : https://docs.python.org/3.7/library/functions.html#open \n# r, w, a\n\n# 42. 파일을 모드별로 읽어올 때 사용하는 함수를 쓰세요.\n# open\n\n# 43. 파일의 전체 내용을 읽을 때 사용하는 함수를 쓰세요.\n# read\n\n# 44. 파일의 내용을 한 줄씩 읽을 때 사용하는 함수를 쓰세요.\n# readline\n\n# 45. 파일을 모드별로 연 후 리소스(메모리)를 반환 하기 위해 반드시 사용하는 함수를 적으세요.\n# close()\n\n# 46. 리소스 반환을 자동으로 해주는 구문을 적으세요.\n# with\n\n# 47. 파일에 내용을 쓸 때 사용하는 모드를 아는대로 적으세요.\n# w, a\n\n# 48. 파일을 열 때 한글이 깨지는 현상을 막기 위해 사용하는 파라미터를 적으세요.\n# encoding = 'utf8'\n\n# 49. 파일 내용을 읽어올 때 앞뒤 공백을 없애주는 함수를 적으세요.\n# strip()\n\n# 50. 다음 예시대로 프로그램을 구현 해보세요.\n'''\n다음과 같이 score.txt를 만든다.(resource 폴더안에)\n# score.txt\n\n90\n80\n78\n88\n67\n\n위 파일의 점수를 리스트에 추가한다.\n평균을 구한다.\n\n출력\n[ 90, 80, 78, 88, 67 ]\n \nAverage : **.***\n'''\nwith open('./resource/score.txt', 'r') as f:\n score = []\n for line in f:\n score.append(int(line))\n print(score)\n print('Average : {:6.3f}'.format(sum(score) / len(score)))\n\n# 51. 로또 번호를 랜덤하게 생성하여 파일에 저장하는 코드를 작성하여 실행하세요.\nfrom random import randint\n\nwith open('./resource/score2.txt', 'w') as f:\n for cnt in range(6):\n f.write(str(randint(1, 50)))\n f.write(' ')\n\n\n# 52. 객체지향 프로그래밍을 영문3글자로 표현하세요.\n# OOP\n\n# 53. 객체지향언어에서 '설계도'에 비유되는 것을 무엇이라고 하나요?\n# 클래스\n\n# 54. 객체지향 언어의 특징 중 오버라이딩과 관련 있는 것을 아는대로 쓰세요.\n# 다형성, 상속성\n\n# 55. 객체지향 프로그래밍의 4가지 핵심 특징 중 다음 문구와 관계있는 것은?\n# \" 복잡한 것은 과감히 버리고, 필요한 것만 표현 하는 것\"\n# 추상화\n\n# 56. 클래스를 정의하는 키워드는?\n# class\n\n# 57. 클래스의 멤버(구성)를 아는대로 적으세요.\n# 생성자, 메소드, 속성, 소멸자\n\n# 58. attribute와 behavior를 뽑아내는 과정을 무엇이라고 하나요?\n# 추상화, 객체 모델링\n\n# 59. 오버라이드(Override)를 간단하게 표현해보세요\n# 재정의\n\n# 60. 클래스를 통해 만들어지는 객체를 다른 용어로 무엇이라고 하나요?\n# 인스턴스(instance)\n\n''' 문제 : 61 ~ 71 [ 예시 코드 ]\nclass Person:\n name = '아무개'\n\n def __init__(self, name):\n self.name = name \n\n def _info(self):\n print('인스턴스 변수 : ', A)\n\n def info():\n print('클래스 변수 :', B) \n'''\n\n# 61. 위의 예시 코드에서 인스턴스 변수와 클래스 변수를 구분해보세요.\n\n# 클래스 변수 : name\n# 인스턴스 변수 : self.name\n\n# 62. 위의 예시 코드에서 인스턴스 메소드와 클래스 메소드를 구분해보세요.\n# 클래스 메소드 : info()\n# 인스턴스 메소드 : _info()\n\n\n# 63. 위의 예시 코드에서 인스턴스 변수에 접근하는 코드를 작성하세요.\n# p1 = Person('홍말똥')\n# print(p1.name)\n\n# 64. 위의 예시 코드에서 클래스 변수에 접근하는 코드를 작성하세요.\n# Person.name\n\n# 65. 위의 예시 코드에서 A, B에 알맞는 코드를 작성하세요.\n# A : self.name\n# B : Person.name\n\n# 66. self에 대해 간략하게 설명해 보세요.\n# self는 만들어질 인스턴스(객체)를 의미하며, \n# 인스턴스가 만들어지면 자동으로 파이썬에서 self에 전달해줌\n\nclass Person:\n name = '아무개'\n\n def __init__(self, name):\n self.name = name \n\n def _info(self):\n print('인스턴스 변수 : ', self.name)\n\n def info():\n print('클래스 변수 :', Person.name) \n\np1 = Person('홍말똥')\nprint(p1.name)\np1._info()\n\nPerson.info()\n\n# 67. 위의 예시코드를 완성하여 인스턴스 메소드와 클래스 메소들를 호출해 보세요.\n# p1 = Person('홍말똥')\n# print(p1.name)\n# p1._info()\n\n# Person.info()\n\n# 68. Person 객체의 네임 스페이스를 확인하는 코드를 작성하세요.\n# print(Person.__dict__)\n\n# 69. Person 객체가 갖고 있는 변수 또는 메소드의 이름을 확인하기 위한 코드를 작성하세요.\n# print(dir(Person))\n\n# 70. 위의 Person 클래스를 상속 받는 학생(Student) 객체를 만들어 다음과 같이 동작할 수 있도록 만들고,\n# 실행해 보세요.\n# study 메소드를 호출 시 : \"홍길동님은 열심히 공부합니다.\" \nclass Student(Person):\n def study(self):\n print(f'{self.name}님은 열심히 공부합니다.')\n\nstudent = Student('김말똥')\nstudent.study()\n\n\n# 71. 위의 Person 클래스를 상속 받는 선생(Teacher) 객체를 다음과 같이 동작할 수 있도록 만들어 보세요.\n# teach 메소드를 호출 시 : \"홍길동님은 열심히 학생을 가르칩니다..\" \nclass Teacher(Person):\n def teach(self):\n print(f'{self.name}님은 열심히 학생을 가르칩니다.')\n\nteacher = Teacher('홍길동') \nteacher.teach()\n\n# 수고하셨습니다.. ^^\n","repo_name":"tmd9936/ys_study","sub_path":"python_basic/개념정리_연습문제_answer.py","file_name":"개념정리_연습문제_answer.py","file_ext":"py","file_size_in_byte":16535,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70518606884","text":"import requests\n\ndef get_forum_board(client_id):\n headers = {\n 'X-MAL-CLIENT-ID': client_id\n }\n\n return requests.get('https://api.myanimelist.net/v2/forum/boards', headers=headers).json()\n\n\ndef get_topic_details(client_id, topic_id, limit, offset):\n url = f'https://api.myanimelist.net/v2/forum/topic/{topic_id}'\n headers = {\n 'X-MAL-CLIENT-ID': client_id\n }\n\n params = {\n 'limit': limit,\n 'offset': offset\n }\n\n return requests.get(url, headers=headers, params=params).json()\n\n\ndef get_forum_topics(client_id, kwargs):\n url = 'https://api.myanimelist.net/v2/forum/topics'\n headers = {\n 'X-MAL-CLIENT-ID': client_id\n }\n params = {}\n for k, v in kwargs.items():\n params[k] = str(v)\n\n return requests.get(url, headers=headers, params=params).json()","repo_name":"itsKorzie/MyAnimeList.py","sub_path":"src/fun/forum.py","file_name":"forum.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18623081017","text":"import pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.manifold import TSNE\n\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.metrics import calinski_harabasz_score\nfrom sklearn.metrics import davies_bouldin_score\n\n''' Визуализация метрик кластеризации для разбиения на кластеры от 2 до 9:\n\n - inertia: коэфициент \"инерции\";\n \n - silhouette: коэффициент \"силуэта\";\n \n - calinski_harabasz: коэфициент Калински-Харабаса;\n \n - davis_bouldin: коэффициент Дэвиса-Болдина\n'''\ndef plot_metrics(df):\n \n inertia = []\n silhouette = []\n calinski_harabasz = []\n davis_bouldin = []\n \n for n_clusters in range(2, 9):\n kmeans = KMeans(n_clusters=n_clusters, random_state=42)\n kmeans.fit(df)\n \n inertia.append(kmeans.inertia_)\n silhouette.append(silhouette_score(df, kmeans.labels_))\n calinski_harabasz.append(calinski_harabasz_score(df, kmeans.labels_))\n davis_bouldin.append(davies_bouldin_score(df, kmeans.labels_))\n \n fig, ax = plt.subplots(1, 4, figsize=(24,5))\n \n ax[0].plot(range(2, 9), inertia, 's-', label='inertia')\n ax[1].plot(range(2, 9), silhouette, 's-', label='silhouette')\n ax[2].plot(range(2, 9), calinski_harabasz, 's-', label='calinski-harabasz')\n ax[3].plot(range(2, 9), davis_bouldin, 's-', label='davis-bouldin')\n ax[0].legend(prop={'size': 16})\n ax[1].legend(prop={'size': 16})\n ax[2].legend(prop={'size': 16})\n ax[3].legend(prop={'size': 16});\n fig.supxlabel('n clusters')\n\ndef plot_coef(df, labels, flag=True,):\n \n # визуализация проекции признакового пространства на плоскость \n tsne = TSNE(n_components=2, perplexity=50, init='pca',\n learning_rate='auto', random_state=42)\n df_tsne = pd.DataFrame(tsne.fit_transform(df))\n df_tsne['Кластер'] = labels\n fig = plt.figure()\n sns.scatterplot(x=df_tsne[0],\n y=df_tsne[1],\n hue=df_tsne['Кластер'],\n palette='bright')\n fig.suptitle('Визуализация проекции признакового пространства на плоскость', fontsize=14);\n \n score_list=[]\n \n silhouette = silhouette_score(df, labels) \n calinski_harabasz = calinski_harabasz_score(df, labels) \n davies_bouldin = davies_bouldin_score(df, labels)\n \n if flag == True:\n print('Коэфициент силуэта: %.3f' % silhouette)\n print('Коэфициент Калински-Харабаса: %.3f' % calinski_harabasz)\n print('Коэфициент Дэвиса-Болдина: %.3f' % davies_bouldin)\n \n \n\n\nsilhouette=[] # список коэффициентов \"силуэта\" моделей\ncalinski_harabasz=[] # список коэффициентов Калински-Харабаса моделей\ndavies_bouldin=[] # список коэффициентов Дэвиса_Болдина моделей\n\ndef make_metrics_tabl(df,labels): \n coef_silhouette = silhouette_score(df, labels) \n coef_calinski_harabasz = calinski_harabasz_score(df, labels) \n coef_davies_bouldin = davies_bouldin_score(df, labels)\n \n silhouette.append(coef_silhouette)\n calinski_harabasz.append(coef_calinski_harabasz)\n davies_bouldin.append(coef_davies_bouldin)\n \n \n \n \n \n \n","repo_name":"Punich-Pavel/Final_Project","sub_path":"Part_3/tools/clusters.py","file_name":"clusters.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"ru","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"27546370716","text":"# -*- coding: utf-8 -*-\n# @author WuJing\n# @created 2023/3/2\n\nfrom tensorlayerx.dataflow import DataLoader, Dataset\nimport tensorlayerx as tlx\nfrom gammagl.loader.utils import DataLoaderIter, filter_graph\n# Dataset based on edges, support multi-type edges\nfrom gammagl.sampler.neighbor_sampler import SamplerOutput\n\n\nclass LinkDataset(Dataset):\n def __init__(self, edge_label_index, edge_label):\n super().__init__()\n self.edge_label_index = edge_label_index\n self.edge_label = edge_label\n\n def __getitem__(self, idx: int):\n return (\n self.edge_label_index[0, idx],\n self.edge_label_index[1, idx],\n self.edge_label[idx],\n )\n\n def __len__(self) -> int:\n return self.edge_label_index.shape[1]\n\n\nclass LinkLoader(DataLoader):\n r\"\"\"A graph loader that performs neighbor sampling from link information,\n using a generic :class:`~gammagl.sampler.BaseSampler`\n implementation that defines a :meth:`sample_from_edges` function and is\n supported on the provided input :obj:`graph` object.\n\n Args:\n graph (gammagl.data.graph.Graph or gammagl.data.heterograph.HeteroGraph):\n The :class:`~gammagl.data.graph.Graph` or\n :class:`~gammagl.data.heterograph.HeteroGraph` graph object.\n link_sampler (gammagl.sampler.BaseSampler): The sampler\n implementation to be used with this loader. Note that the\n sampler implementation must be compatible with the input graph\n object.\n edge_label_index (Tensor or EdgeType or Tuple[EdgeType, Tensor]):\n The edge indices for which neighbors are sampled to create\n mini-batches.\n If set to :obj:`None`, all edges will be considered.\n In heterogeneous graphs, needs to be passed as a tuple that holds\n the edge type and corresponding edge indices.\n (default: :obj:`None`)\n edge_label (Tensor, optional): The labels of edge indices for\n which neighbors are sampled. Must be the same length as\n the :obj:`edge_label_index`. If set to :obj:`None` its set to\n `tlx.zeros(...)` internally. (default: :obj:`None`)\n neg_sampling_ratio (float, optional): the number of negative samples\n to include as a ratio of the number of positive examples\n (default: 0).\n **kwargs (optional): Additional arguments of\n :class:`tensorlayerx.dataflow.DataLoader`, such as :obj:`batch_size`,\n :obj:`shuffle`, :obj:`drop_last`.\n \"\"\"\n\n def __init__(self, graph, link_sampler, edge_label_index=None, edge_label=None, neg_sampling_ratio=0.0, **kwargs):\n self.graph = graph\n self.link_sampler = link_sampler\n self.edge_label_index = edge_label_index\n self.edge_label = edge_label\n self.neg_sampling_ratio = neg_sampling_ratio\n\n if self.edge_label_index is None:\n edge_label_index = graph.edge_index\n if self.edge_label is None:\n # edge_label = tlx.zeros(edge_label_index.size(1))\n edge_label = tlx.zeros(edge_label_index.shape[1])\n\n super(LinkLoader, self).__init__(LinkDataset(edge_label_index, edge_label),\n collate_fn=self.collate_fn,\n **kwargs)\n\n def collate_fn(self, index):\n out = self.link_sampler.sample_from_edges(\n index,\n negative_sampling_ratio=self.neg_sampling_ratio,\n )\n return out\n\n def filter_fn(self, out: SamplerOutput):\n\n edge_label_index, edge_label = out.metadata\n graph = filter_graph(self.graph, out.node, out.row, out.col, out.edge,\n self.link_sampler.edge_permutation)\n graph.edge_label_index = edge_label_index\n graph.edge_label = edge_label\n\n return graph\n\n def _get_iterator(self):\n return DataLoaderIter(super(LinkLoader, self)._get_iterator(), self.filter_fn)\n\n def __repr__(self) -> str:\n return f'{self.__class__.__name__}()'\n","repo_name":"BUPT-GAMMA/GammaGL","sub_path":"gammagl/loader/link_loader.py","file_name":"link_loader.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"52"} +{"seq_id":"17410577150","text":"from PIL import Image\r\nimport requests\r\nimport streamlit as st\r\nfrom streamlit_option_menu import option_menu\r\nfrom streamlit_lottie import st_lottie\r\nst.set_page_config(page_title=\"Access your social media accounts\", page_icon=\":smile:\", layout=\"wide\")\r\nst.title(\"Access.com\")\r\nst.subheader(\"Gain access to your Social media accounts in seconds\")\r\nst.sidebar.success(\"select a page\")\r\nleft_column, right_column= st.columns(2)\r\n\r\n\r\ndef load_lottieurl(url):\r\n r= requests.get(url)\r\n if r.status_code !=200:\r\n return None\r\n return r.json()\r\n#use local css\r\ndef local_css(file_name):\r\n with open(file_name)as f:\r\n st.markdown(f\"<style>{f.read()}</style>\", unsafe_allow_html=True)\r\n\r\nlocal_css(\"styles/style.css\")\r\n#load asset\r\nlottie_coding=load_lottieurl(\"https://assets4.lottiefiles.com/packages/lf20_T4XJOLEPj5.json\")\r\n\r\ninstagram = Image.open(\"Images\\instagram.png\")\r\n\r\n#----Login to your facebook account----\r\nwith st.container():\r\n st.write(\"---\")\r\n st.subheader(\"Login to your Facebook account\")\r\n st.write(\"Click the link below to login to your Facebook account\")\r\n st.write(\"[Login >](https://www.facebook.com/login/)\")\r\n\r\n#----Login to your Whatsapp account----\r\nwith st.container():\r\n st.write(\"---\")\r\n st.subheader(\"Login to your Whatsapp account\")\r\n st.write(\"Click the link below to login to your Whatsapp account to start messaging\")\r\n st.write(\"[Login >](https://web.whatsapp.com/login/)\")\r\n\r\n#----Login to your Instagram account----\r\nwith st.container():\r\n st.write(\"---\")\r\n st.subheader(\"Login to your Instagram account\")\r\n st.write(\"Click the link below to login to your Instagram account\")\r\n st.write(\"[Login >](https://www.instagram.com/login/)\")\r\n\r\n#----Login to your Quora account----\r\nwith st.container():\r\n st.write(\"---\")\r\n st.subheader(\"Login to your Quora account\")\r\n st.write(\"Click the link below to login to your Quora account\")\r\n st.write(\"[Login >](https://www.quora.com/login/)\")\r\n\r\n#----Login to your Linked in account----\r\nwith st.container():\r\n st.write(\"---\")\r\n st.subheader(\"Login to your LinkedIn account\")\r\n st.write(\"Click the link below to login to your LinkedIn account\")\r\n st.write(\"[Login >](https://www.LinkedIn.com/login/)\")\r\n\r\n#contact form\r\nwith st.container():\r\n st.write(\"---\")\r\n st.header(\"Give us feedback, we'd appreciate..\")\r\n st.write(\"##\")\r\n\r\n #https://formsubmit.co\r\n contact_form=\"\"\"\r\n <form action=\"https://formsubmit.co/goldcod3@gmail.com\" method=\"POST\">\r\n <input type=\"hidden\" name=\"_captcha value=\"false\">\r\n <input type=\"text\" name=\"name\" placeholder=\"Your name\" required>\r\n <input type=\"email\" name=\"email\" placeholder=\"Your Email\" required>\r\n <textarea name=\"message\" placeholder=\"Your message here\" required></textarea>\r\n <button type=\"submit\">Send</button>\r\n </form>\r\n \"\"\"\r\n left_column, right_column = st.columns(2)\r\n with left_column:\r\n st.markdown(contact_form, unsafe_allow_html=True)\r\n with right_column:\r\n st_lottie(lottie_coding, height=400, key='coding')\r\n\r\n","repo_name":"GoldCode001/accessaccounts","sub_path":"Social/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26042808491","text":"\"\"\"CALCULADORA_2\"\"\"\r\n#Suma\r\ndef suma():\r\n num = int(input(\"Ingrese el numero: \"))\r\n num2 = int(input(\"Ingrese la cantidad que aumentará: \"))\r\n\r\n print(num + num2)\r\n#Resta\r\ndef resta():\r\n num = int(input(\"Ingrese el numero: \"))\r\n num2 = int(input(\"Ingrese la cantidad que le restará: \"))\r\n\r\n print(num - num2)\r\n#Divide\r\ndef division():\r\n num = int(input(\"Ingrese el numero: \"))\r\n num2 = int(input(\"Ingrese por cuanto lo dividirá: \"))\r\n\r\n print(num / num2)\r\n#Multiplica\r\ndef multiplicacion():\r\n num = int(input(\"Ingrese el primer numero: \"))\r\n num2 = int(input(\"Ingrese por cuanto lo multiplicará: \"))\r\n\r\n print(num * num2)\r\n\r\ndef elevar():\r\n num = int(input(\"Ingrese el numero que desea elevar: \"))\r\n num2 = int(input(\"A cuanto lo elevará: \"))\r\n print (num ** num2)\r\n\r\n\r\ndef divbaja():\r\n num = int(input(\"Ingrese el primer numero: \"))\r\n num2 = int(input(\"Ingrese la cantidad por la cual se hara la división baja: \"))\r\n\r\n print(num // num2)\r\n\r\ndef resto():\r\n num = int(input(\"Ingrese el primer numero: \"))\r\n num2 = int(input(\"Ingrese el numero por el cual se dividira para conseguir el resto: \"))\r\n\r\n resultado = num % num2\r\n\r\n print(resultado)\r\n if resultado == 0:\r\n print(\"Los numeros son divisibles\")\r\n\r\nwhile True:\r\n operacion = input(\"\"\"Que operación desea hacer\r\n(suma/resta/multiplicación/división/elevar/resto/división baja): \"\"\")\r\n\r\n if operacion.lower() == \"suma\":\r\n suma()\r\n\r\n elif operacion.lower() == \"resta\":\r\n resta()\r\n\r\n elif operacion.lower() == \"multiplicación\":\r\n multiplicacion()\r\n\r\n elif operacion.lower() == \"división\":\r\n division()\r\n\r\n elif operacion.lower() == \"elevar\":\r\n elevar()\r\n\r\n elif operacion.lower() == \"división baja\":\r\n divbaja()\r\n\r\n elif operacion.lower() == \"resto\":\r\n resto()\r\n\r\n else:\r\n print(\"Entrada no valida\")\r\n\r\n\r\n repetir = input(\"¿Desea realizar otra operación? (s/n): \")\r\n if repetir.lower() != \"s\":\r\n print(\"\"\"Gracias por usar la calculadora ver:2 creada por Mrm10n el 20/05/2023.\r\n Un programa hecho para el arte de las matematicas.\"\"\")\r\n break\r\n","repo_name":"MrM10n/CosasParaMatematicas","sub_path":"Calc-Series/calculadora-2.py","file_name":"calculadora-2.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"43841408782","text":"#Modules Imported\r\nimport time\r\nimport webbrowser as web\r\nimport pywhatkit as kit\r\n\r\n#Program loop started\r\nwhile True: \r\n print()\r\n print (\"Would you like to find a song (Y/N)?\")\r\n Answer = input (\"Answer: \").upper()\r\n print()\r\n if Answer == \"N\":\r\n print (\"Thank you for using this program\" )\r\n time.sleep(1)\r\n print (\"Closing in...\")\r\n i = 4\r\n while i > 1: #Loop for countdown to exit\r\n i = i - 1\r\n time.sleep(0.5)\r\n print (i)\r\n time.sleep(0.5)\r\n break\r\n elif Answer == \"Y\":\r\n Song = input (\"Enter song name: \").capitalize()\r\n while True: #Loop for artist name\r\n print()\r\n print (\"Do you know the artist for this song (Y/N)?\")\r\n answer_a = input (\"Answer: \").upper()\r\n print ()\r\n if answer_a == \"N\":\r\n break\r\n elif answer_a == \"Y\":\r\n Artist = input (\"Enter artist name: \").title()\r\n Song = Song + \" by \" + Artist\r\n break\r\n else:\r\n print (\"Invalid answer\")\r\n while True: #Loop for search only or play\r\n print ()\r\n print (\"Shall I also play it for you (Y/N)?\")\r\n answer_b = input (\"Answer: \").upper()\r\n print ()\r\n if answer_b == \"N\":\r\n web.open (f'https://www.youtube.com/results?search_query={Song}')\r\n print (\"The song \" + Song + \" has been searched in your browser.\")\r\n break\r\n elif answer_b == \"Y\":\r\n kit.playonyt (Song)\r\n print (\"The song \" + Song + \" is playing in your browser.\")\r\n print (\"There may be an ad first. Sorry I cannot skip it for you...yet.\")\r\n break\r\n else:\r\n print (\"Invalid answer.\")\r\n else:\r\n print (\"Invalid Answer\")\r\n","repo_name":"AditiSharma2053/Learning-Python","sub_path":"Song-Search-Play.py","file_name":"Song-Search-Play.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32754468777","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n# sPycialist - Specialist PC Emulator\r\n# (C) Stanislav Yudin (CityAceE)\r\n# http://zx-pk.ru\r\n#\r\n# ver.0.5, 20th January 2019\r\n\r\nimport pygame\r\nimport pygame.surfarray\r\nimport pygame.transform\r\nimport numpy as np\r\n\r\nimport i8080 as cpu\r\nimport spyc_loader\r\nimport spyc_keyboard\r\n\r\nGAME = 'zoo.rks'\r\nROM = 'system.rom'\r\nSHOW_FPS = True\r\nCPU_CLOCK = 2 # In MHz. Default Intel 8080 frequency is 2 MHz\r\n\r\nspyc_loader.rom(ROM, 0xc000)\r\ncpu.sp = 0x7FFF\r\ncpu.pc = 0\r\ncpu.pc = spyc_loader.game(GAME)\r\n\r\ndebug = True\r\nrunning = True\r\nint_ticks = int(CPU_CLOCK * 1000000 / 50)\r\nscreen_w = 384\r\nscreen_h = 256\r\nscreen = pygame.display.set_mode((screen_w, screen_h), flags=pygame.RESIZABLE, depth=8)\r\ncaption = \"sPycialist\"\r\npygame.display.set_caption(caption)\r\n\r\n\r\ndef blitsurface():\r\n mem = np.reshape(cpu.memory[0x9000:0xc000], (256, 48), 'F')\r\n bits = np.unpackbits(mem) * 255\r\n bits = np.reshape(bits, (256, 384)).T\r\n srf = pygame.surfarray.make_surface(bits)\r\n\r\n scr_ratio = 384.0/256.0\r\n new_h, new_w = (screen_h, \r\n int(screen_h*scr_ratio)) if screen_w/screen_h >= scr_ratio else (int(screen_w/scr_ratio), \r\n screen_w)\r\n\r\n srf = pygame.transform.scale(srf, (new_w, new_h))\r\n screen.blit(srf, (screen_w/2-new_w/2, screen_h/2-new_h/2))\r\n\r\ntry:\r\n clock = pygame.time.Clock()\r\n while running:\r\n\r\n # START OF MAIN LOOP\r\n\r\n # # FOR DEBUGGING\r\n # if (cpu.pc == 0xc1ff): # and (cpu.reg_h == 0x3d) and (cpu.reg_l == 0xf8): # Trap conditions\r\n # debug = True\r\n # # print('PC:', hex(cpu.pc))\r\n # pass\r\n #if debug:\r\n #blitsurface()\r\n #pygame.display.flip()\r\n #cpu.display_regs() # Set breakpoint here\r\n\r\n cpu.core()\r\n if cpu.ticks > int_ticks:\r\n cpu.ticks = 0\r\n blitsurface()\r\n pygame.display.flip()\r\n clock.tick(52)\r\n\r\n # END OF MAIN LOOP\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n elif event.type == pygame.KEYDOWN:\r\n spyc_keyboard.keydown(event.key)\r\n elif event.type == pygame.KEYUP:\r\n spyc_keyboard.keyup(event.key)\r\n elif event.type == pygame.VIDEORESIZE:\r\n screen_w, screen_h = event.w, event.h\r\n\r\n if SHOW_FPS:\r\n fps = clock.get_fps()\r\n with_fps = \"{} - {:.0f} FPS\".format(caption, fps)\r\n pygame.display.set_caption(with_fps)\r\n\r\n pygame.quit()\r\nexcept SystemExit:\r\n pygame.quit()\r\n","repo_name":"Albom/sPycialist","sub_path":"spycialist.py","file_name":"spycialist.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"15301969534","text":"import re\nfrom db import insert_list, insert, raw, select, update\nfrom utils import cn_re\nfrom tqdm import tqdm\nimport traceback\n\nwith open('./src/data/raw/2_dict/cedict_1_0_ts_utf-8_mdbg.txt') as file:\n text = file.read()\n lines = text.split('\\n')\n dict_lines = list(lines)\n list_of_dicts = []\n\n def is_vowel(char):\n all_vowels = 'aeiou'\n return char in all_vowels\n\n def split_pinyin_tone(pinyin):\n if pinyin:\n syllable = pinyin.rstrip('0123456789')\n tone = pinyin[len(syllable):]\n\n syl_split = [\"\", \"\"]\n index = 0\n for i in range(len(syllable)):\n char = syllable[i]\n if is_vowel(char) and index == 0:\n index = 1\n syl_split[index] += char\n return [syl_split[0], syl_split[1], tone]\n return [None] * 3\n\n# define functions\n\n def parse_line(line):\n parsed = {}\n if line == '':\n dict_lines.remove(line)\n return 0\n line = line.rstrip('/')\n line = line.split('/')\n if len(line) <= 1:\n return 0\n # Rejoin english definitions\n english = \"/\".join([e for i, e in enumerate(line) if i > 0])\n char_and_pinyin = line[0].split('[')\n characters = char_and_pinyin[0]\n characters = characters.split()\n traditional = characters[0]\n simplified = characters[1]\n pinyin = char_and_pinyin[1]\n pinyin = pinyin.rstrip()\n pinyin = pinyin.rstrip(\"]\")\n # pinyin_split = split_pinyin_tone(pinyin)\n parsed['traditional'] = traditional\n parsed['simplified'] = simplified\n parsed['pinyin'] = pinyin\n parsed['english'] = english\n list_of_dicts.append(parsed)\n\n removables = [\n \"Suzhou numeral system\",\n \"zero\",\n \"iteration mark\",\n \"component in Chinese characters\",\n \"character used in Taiwan as a substitute for a real name\",\n \"euphemistic variant of 屄\",\n \"(slang) (Tw) to steal\",\n \"percent (Tw)\",\n \"swastika\",\n ]\n\n def contains(definition, content_list):\n for x in range(0, len(content_list), 1):\n rem = content_list[x]\n if rem in definition:\n return True\n return False\n\n def contains_removable(entry):\n is_invalid_pinyin = False\n is_contain_unwanted = False\n for key in entry:\n value = entry[key]\n if key == \"pinyin\":\n if not value or (\"xx5\" in value) or len(value) <= 1:\n is_invalid_pinyin = True\n break\n else:\n if contains(value, removables):\n is_contain_unwanted = True\n break\n return is_contain_unwanted or is_invalid_pinyin\n\n radicals = [\n \"radical in Chinese character\",\n \"Kangxi radical\",\n \"grass radical\"\n ]\n\n def is_radical(definition):\n return contains(definition, radicals)\n\n def remove():\n for x in range(len(list_of_dicts)-1, -1, -1):\n # Remove surnames, Suzhou numeral system\n is_remove = False\n definition = list_of_dicts[x]['english']\n if (\"surname \" in definition and # Remove surnames\n list_of_dicts[x]['traditional'] == list_of_dicts[x+1]['traditional']) or contains_removable(list_of_dicts[x]):\n is_remove = True\n\n if is_remove:\n list_of_dicts.pop(x)\n\n def parse_d():\n # make each line into a dictionary\n print(\"Parsing dictionary . . .\")\n for line in tqdm(dict_lines):\n parse_line(line)\n\n # remove entries for surnames from the data (optional):\n\n print(\"Removing unwanted values . . .\")\n remove()\n return list_of_dicts\n\n\nparsed_dict = parse_d()\n\n# # Write to DB\ndef write_lines_db(parsed_dict):\n print(\"Writing to DB . . .\")\n try:\n for l in tqdm(range(0, len(parsed_dict), 1)):\n line = parsed_dict[l]\n # Check if word already exists in dictionary\n word_ex = select(\"words\", [\"id\", \"simplified\", \"traditional\", \"pinyin\", \"english\"], \"simplified = %s AND traditional = %s AND pinyin = %s AND english = %s\", (line[\"simplified\"], line[\"traditional\"], line[\"pinyin\"], line[\"english\"]))\n \n # If word not in dictionary, insert it\n if len(word_ex) == 0:\n # If it is a character\n if len(line[\"traditional\"]) == 1:\n # Word\n word = insert(\"words\", line)\n variant = 'ts' if line[\"traditional\"] == line[\"simplified\"] else 't'\n \n # Characters - create if no pre-existing, check based on traditional characters\n char_t_ex = select(\"characters\", [\"id\"], \"character = %s AND (variant = 't' OR variant = 'ts')\", (line[\"traditional\"]))\n char_t = char_t_ex[0] if len(char_t_ex) > 0 else None\n char_s = None\n \n # No existing character, insert character\n if char_t is None:\n new_vals = {\n \"character\": line[\"traditional\"],\n \"variant\": variant\n }\n # If same character for trad/simp, insert trad character only\n char_t = insert(\"characters\", new_vals)\n \n if variant == 't':\n # Otherwise, also insert simp with traditional_id reference\n char_s = insert(\"characters\", {\n \"character\": line[\"simplified\"],\n \"variant\": 's',\n \"traditional_id\": char_t[0]\n })\n \n if char_t:\n char_word_vals = (\n (word[0], char_t[0], \"0\"),\n (word[0], char_s[0], \"0\")\n ) if char_s is not None else (\n (word[0], char_t[0], \"0\"),\n )\n # Characters to words\n insert_list(\"characters_words\", [\"word_id\", \"character_id\", \"positions\"], values=char_word_vals)\n else:\n word = insert(\"words\", line)\n except (Exception) as error:\n traceback.print_exc()\n\ndef fill_char_words(chars_list):\n print(\"Referencing compound words\")\n variant_key = \"traditional\"\n \n for char_ind in tqdm(range(0, len(chars_list), 1)):\n char = chars_list[char_ind]\n # Select words containing character\n words = select(\"words\", [\"id\", variant_key, \"pinyin\"], (variant_key + \" LIKE '%%%s%%' AND LENGTH(\" + variant_key + \") > 1\") % (char[1],))\n \n chregex = re.compile(char[1])\n upd_vals = []\n \n # Find matching words\n for word in words:\n positions = []\n matches = re.finditer(chregex, word[1])\n for m in matches:\n positions.append(str(m.start()))\n posstr = \",\".join(positions)\n upd_vals.append((word[0], char[0], posstr))\n \n # Save word-character link\n insert_list(\"characters_words\", [\"word_id\", \"character_id\", \"positions\"], values=tuple(upd_vals))\n\nwrite_lines_db(parsed_dict)\nt_chars = select(\"characters\", [\"id\", \"character\", \"variant\", \"traditional_id\"], \"(variant = 't' OR variant = 'ts')\")\nfill_char_words(t_chars)","repo_name":"JackC90/zh_learn","sub_path":"src/procedures/2_parse_dict.py","file_name":"2_parse_dict.py","file_ext":"py","file_size_in_byte":7710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27449245491","text":"import time\nimport math\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport cv2\nimport numpy as np\nimport signal\nimport sys\nimport matplotlib.pyplot as plt\nfrom Bebop import Bebop\nfrom DroneVision import DroneVision\nfrom preprocess import preprocess\n\ndef rightArc():\n# #rotate in an arc to the right\n bebop.fly_direct(roll=15, pitch=0, yaw=0, vertical_movement=0, duration=3)\n bebop.fly_direct(roll=0, pitch=15, yaw=0, vertical_movement=0, duration=3)\n bebop.fly_direct(roll=0, pitch=0, yaw=20, vertical_movement=0, duration=4)\n print('right')\n return\n\ndef leftArc():\n bebop.fly_direct(roll=-15, pitch=0, yaw=0, vertical_movement=0, duration=3)\n bebop.fly_direct(roll=0, pitch=-15, yaw=0, vertical_movement=0, duration=3)\n bebop.fly_direct(roll=0, pitch=0, yaw=-5, vertical_movement=0, duration=4)\n print('left')\n return\n\ndef land():\n active = False\n print('land')\n return\n\ndef flip():\n bebop.flip(back)\n print('flip')\n return\n\ndef resolveAction(gesture):\n actions = {\n 0 : rightArc,\n 1 : leftArc,\n 2 : land,\n 3 : flip # TODO: Replace this with do nothing command?\n }\n actions[gesture]\n return\n\ndef kill(signal, frame):\n \"\"\" Catches SIGINT and lands the drone \"\"\"\n\n print(\"Ctrl+C registed - exiting gracefully\")\n bebop.smart_sleep(5)\n bebop.safe_land(10)\n print(\"Landed successfully. Now exiting\")\n bebop.disconnect()\n sys.exit(0)\n\nsignal.signal(signal.SIGINT, kill)\n\nclass UserVision:\n def __init__(self, vision):\n self.index = 0\n self.vision = vision\n\n def save_pictures(self, args):\n #print(\"saving picture\")\n img = self.vision.get_latest_valid_picture()\n\n # filename = \"test_image_%06d.png\" % self.index\n #cv2.imwrite(filename, img)\n self.index +=1\n\n def detect(self, args):\n img = self.vision.get_latest_valid_picture()\n\nmodel = load_model('4_gesture_model.h5')\n\nbebop = Bebop()\n\nsuccess = bebop.connect(5)\n\nactive = True\nCOUNT_EVERY = 20\n\nif (success):\n # start up the video\n bebopVision = DroneVision(bebop, is_bebop=True)\n userVision = UserVision(bebopVision)\n bebopVision.set_user_callback_function(userVision.save_pictures, user_callback_args=None)\n success = bebopVision.open_video()\n\n if success:\n bebopVision = DroneVision(bebop, is_bebop=True)\n userVision = UserVision(bebopVision)\n bebopVision.set_user_callback_function(userVision.save_pictures, user_callback_args=None)\n success = bebopVision.open_video()\n\n\n\n print(\"Vision successfully started!\")\n #removed the user call to this function (it now happens in open_video())\n #bebopVision.start_video_buffering()\n\n # skipping actually flying for safety purposes indoors - if you want\n # different pictures, move the bebop around by hand\n print(\"Fly me around by hand!\")\n bebop.smart_sleep(5)\n print(\"Moving the camera using velocity\")\n # bebop.pan_tilt_camera_velocity(pan_velocity=0, tilt_velocity=-2, duration=4)\n\n bebop.safe_takeoff(10)\n # bebop.fly_direct(roll=0, pitch=0, yaw=0, vertical_movement=20, duration=1)\n bebop.smart_sleep(5)\n\n count = 0\n scale = 4\n\n while active:\n if count % COUNT_EVERY == 0:\n #TODO: How to get individual frames from video stream in bebop?\n img = userVision.vision.get_latest_valid_picture()\n # cv2.imwrite('curr_frame.png', img)\n # img = image.load_img('curr_frame.png', grayscale=True)\n img = image.img_to_array(img)\n print(img.shape)\n # plt.imshow(img)\n # img = preprocess(img, 4)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(img,(5,5),0)\n # ret, img = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n img = cv2.resize(img, (img.shape[1]//scale, img.shape[0]//scale))\n img = np.resize(img, (1, img.shape[0], img.shape[1],1))\n prediction = model.predict(img)\n print(prediction)\n if len(prediction) > 0:\n gesture = np.argmax(prediction[0])\n #print(gesture, prediction)\n resolveAction(gesture)\n count += 1\n if count == 2000:\n break\n\nbebop.smart_sleep(5)\nbebop.safe_land(10)\nprint(\"Done - Disconnecting\")\n\nbebop.disconnect()\n","repo_name":"UAVs-at-Berkeley/flywave","sub_path":"drone_movement.py","file_name":"drone_movement.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"21687451015","text":"#\n# DellDeviceGroup.py -- Classes to facilitate reading computer status\n# from Dell's OpenManage Server Administrator (OMSA) software. We use\n# SNMP (Simple Network Management Protocol) messages to communicate\n# with the OMSA. The classes in this file are designed to get\n# information from the OMSA's Device Group, whose top-level OID is\n# 1.3.6.1.4.1.674.10892.1.1100.\n#\n# For more information on the Dell OMSA Device Group, see:\n# http://support.dell.com/support/edocs/software/svradmin/6.5/en/SNMP/HTML/snmpc14a.htm\n#\n# See also the DellOMSA.py file for classes used by this file.\n#\n# Russell Kackley - 23 May 2011\n#\nfrom DellOMSA import *\n\nclass DellMemoryDeviceType(DellOMSAStateType):\n \"\"\"\n The DellMemoryDeviceType class implements the data values from\n Table 14-16 in the Dell OMSA Reference Guide - Device Group\n \"\"\"\n states = {\n 1: 'deviceTypeIsOther',\n 2: 'deviceTypeIsUnknown',\n 3: 'deviceTypeIsDRAM',\n 4: 'deviceTypeIsEDRAM',\n 5: 'deviceTypeIsVRAM',\n 6: 'deviceTypeIsSRAM',\n 7: 'deviceTypeIsRAM',\n 8: 'deviceTypeIsROM',\n 9: 'deviceTypeIsFLASH',\n 10: 'deviceTypeIsEEPROM',\n 11: 'deviceTypeIsFEPROM',\n 12: 'deviceTypeIsEPROM',\n 13: 'deviceTypeIsCDRAM',\n 14: 'deviceTypeIs3DRAM',\n 15: 'deviceTypeIsSDRAM',\n 16: 'deviceTypeIsSGRAM',\n 17: 'deviceTypeIsRDRAM',\n 18: 'deviceTypeIsDDR',\n 19: 'deviceTypeIsDDR2',\n 20: 'deviceTypeIsDDR2FBDIMM',\n 24: 'deviceTypeIsDDR3',\n 25: 'deviceTypeIsFBD2'\n };\n\nclass DellMemoryDeviceFailureModes(DellOMSAStateType):\n \"\"\"\n The DellMemoryDeviceFailureModes class implements the data values from\n Table 14-19 in the Dell OMSA Reference Guide - Device Group\n \"\"\"\n noFaults = 0\n eccSingleBitCorrectionWarningRate = 1\n eccSingleBitCorrectionFailureRate = 2\n eccMultiBitFault = 4\n eccSingleBitCorrectionLoggingDisabled = 8\n deviceDisabledBySpareActivation = 16\n okStates = ('none')\n states = {\n 0: 'none',\n 1: 'eccSingleBitCorrectionWarningRate',\n 2: 'eccSingleBitCorrectionFailureRate',\n 4: 'eccMultiBitFault',\n 8: 'eccSingleBitCorrectionLoggingDisabled',\n 16: 'deviceDisabledBySpareActivation'\n };\n def __init__(self, state):\n self.state = state\n\n def __str__(self):\n retString = ''\n if self.state == self.noFaults:\n retString = self.states[self.noFaults]\n else:\n if self.state & self.eccSingleBitCorrectionWarningRate:\n retString = self.states[self.eccSingleBitCorrectionWarningRate]\n if self.state & self.eccSingleBitCorrectionFailureRate:\n if len(retString) > 0:\n retString += '_and_'\n retString += self.states[self.eccSingleBitCorrectionFailureRate]\n if self.state & self.eccMultiBitFault:\n if len(retString) > 0:\n retString += '_and_'\n retString += self.states[self.eccMultiBitFault]\n if self.state & self.eccSingleBitCorrectionLoggingDisabled:\n if len(retString) > 0:\n retString += '_and_'\n retString += self.states[self.eccSingleBitCorrectionLoggingDisabled]\n if self.state & self.deviceDisabledBySpareActivation:\n if len(retString) > 0:\n retString += '_and_'\n retString += self.states[self.deviceDisabledBySpareActivation]\n return retString\n\nclass DeviceGroup(DellOMSAGroup):\n \"\"\"\n The DeviceGroup class is a container that holds the Dell OMSA\n Device Group objects\n \"\"\"\n OID = DellChassisOID.OID + '.1100'\n logFilename = 'DeviceGroup'\n groupName = 'Device'\n\n def __init__(self, connection):\n super(DeviceGroup, self).__init__(connection)\n self.contents = {\n 'MemoryDeviceTable': MemoryDeviceTable(connection),\n 'PciDeviceTable': PciDeviceTable(connection)\n }\n\n def __str__(self):\n retString = super(DeviceGroup, self).__str__()\n return retString\n\nclass MemoryDeviceTable(DellOMSATable):\n \"\"\"\n The MemoryDeviceTable class is a container that holds the Dell\n OMSA Memory Device objects\n \"\"\"\n OID = DeviceGroup.OID + '.50.1'\n tableName = 'Memory Device'\n\n def __init__(self, connection):\n super(MemoryDeviceTable, self).__init__(connection)\n self.contents = {\n 'MemoryDeviceStateCapabilities': MemoryDeviceStateCapabilities(connection),\n 'MemoryDeviceStateSettings': MemoryDeviceStateSettings(connection),\n 'MemoryDeviceStatus': MemoryDeviceStatus(connection),\n 'MemoryDeviceType': MemoryDeviceType(connection),\n 'MemoryDeviceLocationName': MemoryDeviceLocationName(connection),\n 'MemoryDeviceFailureModes': MemoryDeviceFailureModes(connection)\n }\n\n def __str__(self):\n retString = super(MemoryDeviceTable, self).__str__()\n i = 0\n for n in self.contents['MemoryDeviceLocationName'].value:\n ss = self.contents['MemoryDeviceStateSettings'].value[i]\n if str(ss) == 'enabled':\n retString += '\\nLocation: %s: Settings: %s Status: %s Faults: %s' % \\\n (n,\n ss,\n self.contents['MemoryDeviceStatus'].value[i],\n self.contents['MemoryDeviceFailureModes'].value[i])\n else:\n retString += '\\n%s: Settings: %s' % (n, ss)\n i += 1\n return retString\n\nclass MemoryDeviceStateCapabilities(DellOMSAState):\n OID = MemoryDeviceTable.OID + '.3.1'\n stateClass = DellStateCapabilities\n\nclass MemoryDeviceStateSettings(DellOMSAState):\n OID = MemoryDeviceTable.OID + '.4.1'\n stateClass = DellStateSettings\n\nclass MemoryDeviceStatus(DellOMSAState):\n OID = MemoryDeviceTable.OID + '.5.1'\n stateClass = DellStatusProbe\n\nclass MemoryDeviceType(DellOMSAState):\n OID = MemoryDeviceTable.OID + '.7.1'\n stateClass = DellMemoryDeviceType\n\n def overallStatus(self):\n return DellOverallStatus(DellOverallStatus.okState)\n\nclass MemoryDeviceLocationName(DellOMSALocationName):\n OID = MemoryDeviceTable.OID + '.8.1'\n\nclass MemoryDeviceFailureModes(DellOMSAState):\n OID = MemoryDeviceTable.OID + '.20.1'\n stateClass = DellMemoryDeviceFailureModes\n\nclass PciDeviceTable(DellOMSATable):\n \"\"\"\n The PciDeviceTable class is a container that holds the Dell\n OMSA PCI Device objects\n \"\"\"\n OID = DeviceGroup.OID + '.80.1'\n tableName = 'PCI Device'\n\n def __init__(self, connection):\n super(PciDeviceTable, self).__init__(connection)\n self.contents = {\n 'PciDeviceStateCapabilities': PciDeviceStateCapabilities(connection),\n 'PciDeviceStateSettings': PciDeviceStateSettings(connection),\n 'PciDeviceStatus': PciDeviceStatus(connection),\n 'PciDeviceDescriptionName': PciDeviceDescriptionName(connection),\n 'PciDeviceAdapterFault': PciDeviceAdapterFault(connection)\n }\n\n def __str__(self):\n retString = super(PciDeviceTable, self).__str__()\n i = 0\n for n in self.contents['PciDeviceDescriptionName'].value:\n ss = self.contents['PciDeviceStateSettings'].value[i]\n if str(ss) == 'enabled':\n retString += '\\nDescription: %s: Settings: %s Status: %s Adapter Fault: %s' % \\\n (n,\n ss,\n self.contents['PciDeviceStatus'].value[i],\n self.contents['PciDeviceAdapterFault'].value[i])\n else:\n retString += '\\n%s: Settings: %s' % (n, ss)\n i += 1\n return retString\n\nclass PciDeviceStateCapabilities(DellOMSAState):\n OID = PciDeviceTable.OID + '.3.1'\n stateClass = DellStateCapabilities\n\nclass PciDeviceStateSettings(DellOMSAState):\n OID = PciDeviceTable.OID + '.4.1'\n stateClass = DellStateSettings\n\nclass PciDeviceStatus(DellOMSAState):\n OID = PciDeviceTable.OID + '.5.1'\n stateClass = DellStatusProbe\n\nclass PciDeviceDescriptionName(DellOMSALocationName):\n OID = PciDeviceTable.OID + '.9.1'\n def update(self):\n # Call our base class's update method to get the current\n # values from the Dell OMSA. The results will be stored as a\n # list of items in our value attribute.\n super(PciDeviceDescriptionName, self).update()\n\n # It looks like Dell OMSA puts a newline characer at the end\n # of the DescriptionName. Strip it off here.\n value = []\n for v in self.value:\n value.append(v.rstrip('\\r\\n'))\n self.value = value\n \n\nclass PciDeviceAdapterFault(DellOMSAState):\n OID = PciDeviceTable.OID + '.11.1'\n stateClass = DellBooleanFalseOk\n","repo_name":"scexao-org/Instrument-Control-Main","sub_path":"src/lib/python/gen2/tools/dell_omsa/DellDeviceGroup.py","file_name":"DellDeviceGroup.py","file_ext":"py","file_size_in_byte":9024,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"20538718966","text":"# 解法1 使用雙指針(索引) 索引i遍歷數組 索引j在num[i] != 0時進行調換並+1\ndef moveZeroes(nums: list[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n j = 0\n for i in range(len(nums)):\n # 0為假值(Falsy) 兩兩調換且J+1\n if nums[i]:\n nums[i], nums[j] = nums[j], nums[i]\n j += 1\n","repo_name":"CivilAisys/LeetCode","sub_path":"283.Move Zeroes/283.Move Zeroes.py","file_name":"283.Move Zeroes.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3728965367","text":"import json\nimport requests\nimport os.path\nfrom os import path\n\n\n\n\nif path.exists(\"courses.json\"):\n with open(\"courses.json\",\"r+\") as count:\n data=json.load(count)\nelse:\n url=\"http://saral.navgurukul.org/api/courses\"\n w = requests.get(url).text\n # print (w)\n with open(\"cours.json\",\"w+\") as count:\n count.write(w)\n data = json.loads(w)\n\nprint (data)\n\n\n\na=1 \ncourses=[]\nids =[]\nfor i in data[\"availableCourses\"]:\n courses.append(i[\"name\"])\n ids.append(i['id'])\n dic=a,i[\"name\"]\n a=a+1\n print(dic)\nuser = int(input(\"enter what you went\"))\nprint(courses[user-1])\nvar=(ids[user-1])\n\n\n\n\nnew_url = 'http://saral.navgurukul.org/api/courses/'+str(ids[user-1])+'/exercises'\npage = requests.get(new_url).text\nwar=json.loads(page)\nb=war[\"data\"]\nnum=1\nfor j in b:\n dr=(num,j[\"name\"])\n print (dr)\n num=num+1 \nprint(j[\"slug\"])\nuser1=int(input(\"enter your slugs\"))\nf=(war[\"data\"])\nslug1 = f[user1-1][\"slug\"]\nslug_url='http://saral.navgurukul.org/api/courses/{}/exercise/getBySlug?slug={}'.format(var,slug1)\npage1=requests.get(slug_url)\nloads=page1.json()\nreads=loads[\"content\"]\nprint(reads)\n\n\n\n\n","repo_name":"aadilraza339/Get_course_from_api","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"40474540128","text":"import cv2\nfrom imutils.video import VideoStream\n\nthres = 0.5 # Threshold to detect objects\n\n\n# img = cv2.imread('Shubham.jpg')\n# cap = cv2.VideoCapture(0) # Using cv2\ncap = VideoStream(src=0).start()\n# cap = VideoStream(src=\"http://192.168.0.102:8080/video\").start()\n# cap.set(3, 640)\n# cap.set(4, 480)\n\nclassNames = []\nclassFile = 'objects.names'\nwith open(classFile, 'rt') as f:\n classNames = f.read().rstrip('\\n').split('\\n')\n\nconfigPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'\nweightsPath = 'frozen_inference_graph.pb'\n\nnet = cv2.dnn_DetectionModel(weightsPath, configPath)\nnet.setInputSize(320, 320)\nnet.setInputScale(1.0/ 127.5)\nnet.setInputMean((127.5, 127.5, 127.5))\nnet.setInputSwapRB(True)\n\n\nwhile True:\n img = cap.read()\n classIds, confs, bbox = net.detect(img, confThreshold=thres)\n # print(classIds, bbox)\n\n if len(classIds) != 0:\n for classId, confidence, box in zip(classIds.flatten(), confs.flatten(), bbox):\n cv2.rectangle(img, box, color=(0, 255, 0), thickness=3)\n cv2.putText(img, classNames[classId-1].upper(), (box[0]+10, box[1]+30), cv2.FONT_HERSHEY_COMPLEX, 1,\n (0, 255, 0), 2)\n cv2.putText(img, str(confidence), (box[0]+30, box[1] + 50), cv2.FONT_HERSHEY_COMPLEX, 0.5,\n (255, 0, 0), 2)\n\n\n cv2.imshow('[TERMINATORS] Drone cam Stream', img)\n cv2.waitKey(0)\n","repo_name":"CERTIFIED2003/Items-Detector-AI","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"71510518564","text":"# -*- coding: utf-8 -*-\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nimport os\nimport string\nfrom io import BytesIO\nimport scrapy\nimport re\nfrom PIL import Image\nfrom lanvshen.items import LanvshenItem\n\n\nclass SlanSpider(CrawlSpider):\n name = 'slan'\n allowed_domains = ['lanvshen.com', 'hywly.com']\n start_urls = ['https://www.lanvshen.com/']\n\n rules = (\n Rule(LinkExtractor(allow=r'[%s]/\\d+' % string.ascii_letters), follow=True, callback='parse_list'),\n )\n\n def parse_list(self, response):\n item = LanvshenItem()\n item[\"idd\"] = os.path.split(response.url)[0].split(\"/\")[-1]\n item[\"title\"] = response.xpath(\"//div[@class='weizhi']/h1/text()\").get()\n item[\"shoot\"] = response.xpath(\"//*[contains(text(), '拍摄机构:')]/a/text()\").get()\n item[\"quantity\"] = response.xpath(\"//*[contains(text(), '图片数量:')]/text()\").get()\n item[\"name\"] = response.xpath(\"//*[contains(text(), '出镜模特:')]/a[1]/text()\").get()\n item[\"nickname\"] = response.xpath(\"//*[contains(text(), '出镜模特:')]/a[2]/text()\").get()\n item[\"birthday\"] = response.xpath(\"//*[contains(text(), '出镜模特:')]/text()\").re_first(\"生日:(.*?);\")\n item[\"height\"] = response.xpath(\"//*[contains(text(), '出镜模特:')]/text()\").re_first(\"身高:(.*?);\")\n if item[\"name\"]:\n yield item\n url_list = re.findall(\"(https://img.hywly.com/.*?)\\\"\", response.text)\n for url in url_list:\n yield scrapy.Request(url, callback=self.parse_item, priority=10)\n\n def parse_item(self, response):\n file, name = os.path.split(response.url)\n file_path = f\"./images/{file.split('com/')[-1]}\"\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n img = Image.open(BytesIO(response.body))\n img.save(f\"{file_path}/{name}\")\n","repo_name":"majiajue/lanvshen","sub_path":"lanvshen/spiders/slan.py","file_name":"slan.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12507608295","text":"import logging\nimport multiprocessing\nimport pandas # pylint: disable=import-error\nimport sys\n\n\n# Worker implementations override this value\nProcess = NotImplemented # pylint: disable=invalid-name\n\n\ndef ProgressIndicator(label, iterable, stream=None):\n if stream is None:\n stream = sys.stdout\n stream.write(label)\n stream.flush()\n for _ in iterable:\n stream.write('.')\n stream.flush()\n stream.write('\\n')\n stream.flush()\n\n\ndef Run(label, worker, args, items, stream=None):\n \"\"\"Use a pool of workers to concurrently process a sequence of items.\n\n Args:\n label: A string displayed by the progress indicator when the job starts.\n worker: A function with the worker implementation. See example above.\n args: An argparse.Namespace() object used to initialize the workers. The\n value of args.processes is the number of processes used by the pool.\n items: An iterable with items to process by the pool of workers.\n stream: A file-like object for the progress indicator output, defaults to\n sys.stdout.\n\n Returns:\n Total time in seconds spent by the pool to process all items.\n \"\"\"\n pool = multiprocessing.Pool(\n processes=args.processes, initializer=worker, initargs=(args,))\n time_started = pandas.Timestamp.utcnow()\n ProgressIndicator(label, pool.imap_unordered(_Worker, items), stream=stream)\n time_finished = pandas.Timestamp.utcnow()\n return (time_finished - time_started).total_seconds()\n\n\ndef _Worker(item):\n try:\n Process(item)\n except KeyboardInterrupt:\n pass\n except:\n logging.exception('Worker failed with exception')\n raise\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/experimental/soundwave/soundwave/worker_pool.py","file_name":"worker_pool.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"2822559194","text":"def readFile():\n sequence = []\n file = open(\"diceSequences.csv\", \"r\")\n for line in file:\n sequence.append(line.strip(\"\\n\").split(','))\n file.close()\n return sequence\n\ndef Viterbi(sequence, PI, B, A):\n T = len(sequence)\n\n # initialization\n type = sequence[0]\n delta = []\n fai = []\n for l in range(0, len(PI)):\n delta.append([PI[l] * B[l][type]])\n fai.append([0])\n\n # iteration for t\n for t in range(1, T):\n for i in range(0, len(PI)):\n tmp_max1 = -1.0\n pos1 = 0\n for j in range(0, len(PI)):\n tmp1 = delta[j][t - 1] * A[j][i]\n if tmp1 >= tmp_max1:\n tmp_max1 = tmp1\n pos1 = j\n type_t = sequence[t]\n delta[i].append(tmp_max1 * B[i][type_t])\n fai[i].append(pos1)\n\n # finalization\n i_star = []\n tmp_max2 = -1.0\n pos2 = 0\n for m in range(0, len(PI)):\n tmp2 = delta[m][T - 1]\n if tmp2 >= tmp_max2:\n tmp_max2 = tmp2\n pos2 = m\n P_star = tmp_max2\n i_star.insert(0, pos2)\n\n # backward\n for t in range(0, T - 1):\n i_star.insert(0, fai[i_star[0]][T - t - 1])\n\n I = i_star\n string = \"\"\n for n in range(0,len(I)):\n string = string+\"D\"+str(I[n]+1)+\" \"\n return [string,P_star]\n\ndef main():\n pi_1 = 1/3\n pi_2 = 1/3\n pi_3 = 1/3\n PI = [pi_1,pi_2,pi_3]\n sequence = readFile()\n A = [[0.5, 0.125, 0.125], [0.125, 0.5, 0.125], [0.125, 0.125, 0.5]]\n B = [{\"1\": 0.6, \"2\": 0.2, \"3\": 0.2}, {\"1\": 0.2, \"2\": 0.6, \"3\": 0.2}, {\"1\": 0.2, \"2\": 0.2, \"3\":0.6}]\n for i in range(0,len(sequence)):\n res = Viterbi(sequence[i], PI, B, A)\n print(\"-------The number \"+str(i+1)+\" sequence----------\")\n print(\"The possible states sequence is:\")\n print(res[0])\n print(\"The probability of this sequence is:\")\n print(res[1])\n print()\n\nmain()","repo_name":"irisgyq/hmm","sub_path":"hmm1.py","file_name":"hmm1.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71045544806","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom ..items import KeyWordItem\n\n\nclass KeyWordSpiderSpider(scrapy.Spider):\n name = 'keywords_spider'\n allowed_domains = ['https://www.zhaopin.com/']\n start_urls = ['https://www.zhaopin.com/']\n\n def parse(self, response):\n\n for items in response.xpath('//*[@id=\"root\"]/div[2]/div[2]/div[1]/ol/li'):\n item=KeyWordItem()\n item['Industy_name']=items.xpath('./div[1]/text()').extract_first()\n item['Job_keywords']=items.xpath('./div[2]/div/div[position()>1]/a/text()').extract()\n yield item\n\n\n","repo_name":"Chauncey2/zhaopin_spider","sub_path":"Zhaoping/spiders/keywords_spider.py","file_name":"keywords_spider.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"} +{"seq_id":"17882182394","text":"import time\nimport chromedriver_binary\nfrom selenium import webdriver\n\nfrom rakuten_settings import *\n\nclass RakutenKeiba:\n @classmethod\n def depositting(cls):\n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n options.add_argument(\"--no-sandbox\")\n\n # driver = webdriver.Chrome()\n driver = webdriver.Chrome(options=options)\n driver.maximize_window()\n\n # Open Rakuten-keiba web page\n driver.get('https://keiba.rakuten.co.jp/')\n\n try:\n # Click \"depositting\" button\n driver.find_element_by_id('noBalanceStatus').click()\n\n # Waiting for open the new tab page\n time.sleep(20)\n\n # Change tab\n handle_array = driver.window_handles\n driver.switch_to.window(handle_array[1])\n\n # Inpit user name and Password \n driver.find_element_by_id('loginInner_u').send_keys(RAKUTEN_ID)\n driver.find_element_by_id('loginInner_p').send_keys(RAKUTEN_PW)\n\n # Click \"login\" button\n driver.find_element_by_css_selector('#loginInner > p:nth-child(3) > input').click()\n\n # Input depositting price\n driver.find_element_by_id('depositingInputPrice').send_keys('100')\n driver.find_element_by_id('depositingInputButton').click()\n\n # Input PIN\n driver.find_element_by_css_selector('#depositingConfirmForm > div > table:nth-child(3) > tbody > tr > td > div.inputArea > input.tealeaf_masking.definedNumber').send_keys(RAKUTEN_PIN)\n driver.find_element_by_id('depositingConfirmButton').click()\n\n except:\n print(\"Error!!\")\n\n driver.save_screenshot('rakutekeiba_results.png')\n\n driver.quit()\n\nif __name__ == \"__main__\":\n RakutenKeiba.depositting()","repo_name":"rohisama/rakuten-bank-happy","sub_path":"script/rakuten_keiba.py","file_name":"rakuten_keiba.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"3546483928","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 19 15:57:29 2019\n\n@author: faisalg\n\"\"\"\n\nimport layers as lay\n\ndef make_model(input_shape,n_layer):\n \n model = []\n neurons=int(input(\"Enter number of neuron for layer 1 : \"))\n model.append(lay.Layer_D(input_shape,neurons))\n model.append(lay.rectified_linear())\n for i in range(1,n_layer):\n prev_neuron=neurons\n msg= \"enter number of neuron for layer\"+ str(i+1)+ \" : \"\n neurons=int(input(msg))\n model.append(lay.Layer_D(prev_neuron,neurons))\n model.append(lay.rectified_linear())\n return model\n","repo_name":"engrfaisal90/NTHU-Deep-Learning-Course-2019","sub_path":"Assignment 2/code/create_model.py","file_name":"create_model.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32160086377","text":"import cv2\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\n\ntrain_dir = r'C:\\Users\\user\\Boulot'\nit = 0\nfor elem in os.listdir(train_dir + \"/datamatrix\"):\n img = cv2.imread(train_dir + \"/datamatrix/\" + elem)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = cv2.resize(img, (30, 30))\n\n new_img = []\n for i in img:\n for elem in i:\n if elem == 255:\n elem = elem - 100\n new_img.append(elem)\n\n else:\n elem = elem + 50\n new_img.append(elem)\n\n new_img = np.reshape(new_img, (30, 30))\n new_img = np.array(new_img, dtype=np.uint8)\n plt.imshow(new_img)\n\n cv2.imwrite(train_dir + \"/dirty_datama/\" + img + '.jpg', new_img)\n","repo_name":"marvmey/Computer-vision","sub_path":"SRGAN/script/Make_dirty.py","file_name":"Make_dirty.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73411057444","text":"import sys\nfrom itertools import permutations\n\nclass Moon:\n\n x_velocity = 0\n y_velocity = 0\n z_velocity = 0\n new_x_velocity = 0\n new_y_velocity = 0\n new_z_velocity = 0\n\n def __init__(self, name, coordinates):\n self.name = name\n (self.x_position, self.y_position, self.z_position) = coordinates\n\n def __str__(self):\n return f\"pos=<x={self.x_position}, y={self.y_position}, z={self.z_position}>, vel=<x={self.x_velocity}, y={self.y_velocity}, z={self.z_velocity}, pot={self.potential_energy()}, kin={self.kinetic_energy()}>\"\n\n def calculate_gravity(self, other_moon):\n for axis in [\"x\", \"y\", \"z\"]:\n current_position = getattr(self, f\"{axis}_position\")\n current_velocity = getattr(self, f\"{axis}_velocity\")\n new_velocity = getattr(self, f\"new_{axis}_velocity\")\n other_current_position = getattr(other_moon, f\"{axis}_position\")\n if DEBUG: print(f\"{self.name} ({axis}): current_pos: {current_position}, current_velocity: {current_velocity}\")\n if DEBUG: print(f\"{other_moon.name} ({axis}): current_pos: {other_current_position}\")\n if current_position < other_current_position:\n if DEBUG: print(f\"setting new_{axis}_velocity to {new_velocity + 1}\")\n setattr(self, f\"new_{axis}_velocity\", new_velocity + 1)\n if current_position > other_current_position:\n if DEBUG: print(f\"setting new_{axis}_velocity to {new_velocity - 1}\")\n setattr(self, f\"new_{axis}_velocity\", new_velocity - 1)\n\n def update_position(self):\n for axis in [\"x\", \"y\", \"z\"]:\n # apply gravity\n current_axis_position = getattr(self, f\"{axis}_position\")\n new_velocity = getattr(self, f\"new_{axis}_velocity\")\n setattr(self, f\"{axis}_velocity\", new_velocity)\n # apply velocity\n new_position = current_axis_position + new_velocity\n setattr(self, f\"{axis}_position\", new_position)\n\n def potential_energy(self):\n return abs(self.x_position) + abs(self.y_position) + abs(self.z_position)\n\n def kinetic_energy(self):\n return abs(self.x_velocity) + abs(self.y_velocity) + abs(self.z_velocity)\n\n def total_energy(self):\n return self.potential_energy() * self.kinetic_energy()\n\n\nio = Moon(\"Io\", (1, 3, -11))\neuropa = Moon(\"Europa\", (17, -10, -8))\nganymede = Moon(\"Ganymede\", (-1, -15, 2))\ncallisto = Moon(\"Callisto\", (12, -4, -4))\n\nmoons = [io, europa, ganymede, callisto]\nmoon_permutations = permutations(moons, 2)\nmoon_pairs = list(moon_permutations)\n\nDEBUG = False\ntime_steps = 1001\nfor time_step in range(1, time_steps):\n if DEBUG: print(f\"---------------- Step {time_step} -------------\")\n for moon_pair in moon_pairs:\n (moon, other_moon) = moon_pair\n moon.calculate_gravity(other_moon)\n\n for moon in moons:\n moon.update_position()\n print(str(moon))\n\ntotal_energy = sum(moon.total_energy() for moon in moons)\nprint(total_energy)\n","repo_name":"bilherron/advent-of-code","sub_path":"2019/Day 12/12.1.py","file_name":"12.1.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30376909679","text":"# -*- coding: utf-8 -*-\n\nimport json\n\nfrom aqt.qt import *\n\nfrom .main import ConfigHolder\n\nCURDIR = os.path.dirname(os.path.realpath(__file__))\n\n\n# noinspection PyPep8Naming,PyMethodMayBeStatic\nclass ConfigView(QDialog):\n def __init__(self, myParent: QWidget):\n self._config = ConfigHolder()\n\n QDialog.__init__(self, myParent)\n self.setWindowTitle(\"Anki Web Browser :: Config\")\n self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)\n self.setWindowFlags(\n Qt.WindowType.WindowMinMaxButtonsHint\n | Qt.WindowType.WindowCloseButtonHint\n )\n self.setFixedSize(1080, 600)\n self.setWindowModality(Qt.WindowModality.ApplicationModal)\n\n mainLayout = QVBoxLayout(self)\n mainLayout.setContentsMargins(0, 0, 0, 0)\n mainLayout.setSpacing(0)\n\n self.setLayout(mainLayout)\n\n browser = QWebEngineView(self)\n browser.page().loadFinished.connect(self.onLoadFinish)\n browser.setUrl(QUrl.fromLocalFile(os.path.join(CURDIR, \"web\", \"config.html\")))\n browser.contextMenuEvent = self.contextMenu\n browser.setZoomFactor(1)\n mainLayout.addWidget(browser)\n\n widgetActions = QWidget(mainLayout.widget())\n widgetActions.setFixedHeight(50)\n widgetActions.setObjectName(\"widgetActions\")\n\n btActionsBox = QHBoxLayout(widgetActions)\n btActionsBox.setSpacing(20)\n btActionsBox.setObjectName(\"btActionsBox\")\n\n btSave = QPushButton(widgetActions)\n btSave.setObjectName(\"btSave\")\n btSave.setText(\"Save\")\n btSave.setFixedSize(150, 35)\n btSave.clicked.connect(lambda: self.onSaveClick())\n btActionsBox.addWidget(btSave)\n\n btCancel = QPushButton(widgetActions)\n btCancel.setObjectName(\"btCancel\")\n btCancel.setText(\"Cancel\")\n btCancel.setFixedSize(150, 35)\n btCancel.clicked.connect(lambda: self.onCancelClick())\n btActionsBox.addWidget(btCancel)\n\n btSave.setIcon(self.getIcon(QStyle.StandardPixmap.SP_DialogApplyButton))\n btCancel.setIcon(self.getIcon(QStyle.StandardPixmap.SP_DialogCancelButton))\n\n mainLayout.addWidget(widgetActions)\n\n self.web = browser\n\n def getIcon(self, qtStyle):\n return QIcon(QApplication.style().standardIcon(qtStyle))\n\n def onLoadFinish(self, result):\n self.web.page().runJavaScript(\n \"loadConfig(%s)\" % json.dumps(self._config.toDict())\n )\n\n def onSaveClick(self):\n jsReadConfig = \"saveAndGetConfig()\"\n\n def storeConfig(cfg):\n conf = ConfigHolder(**cfg)\n if self.save(conf):\n self.close()\n\n self.web.page().runJavaScript(jsReadConfig, storeConfig)\n\n def save(self, config: ConfigHolder) -> bool:\n raise Exception(\"Not implemented\")\n\n def onCancelClick(self):\n self.close()\n\n def open(self, currentConfig: ConfigHolder) -> None:\n self._config = currentConfig\n self.web.reload()\n\n self.show()\n self.raise_()\n self.activateWindow()\n\n def contextMenu(self, event):\n pass\n","repo_name":"ssricardo/anki-web-browser","sub_path":"src/config/config_view.py","file_name":"config_view.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"52"} +{"seq_id":"38387877625","text":"import socket\nimport queue\nimport threading\nimport logging\nimport collections\nimport time\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n\n# Container for an HTTP Request\nRequest = collections.namedtuple('Request', [\n 'method',\n 'path',\n 'http_version',\n 'sock',\n])\n\n\nclass HttpServerWithPriorities:\n \"\"\"\n HTTP Server that has different priorities based on the request.\n This is a toy http server that has two queues, one with high priority and one with low priority. All requests go to\n the low priority queue except for the requests that go to '/ping'. The high priority queue will be checked first by\n any thread that is looking for a new request to process thus giving it priority. If `num_high_priority_threads` is\n specified, a thread pool will be created to process only high priority requests.\n \"\"\"\n\n def __init__(self, sock=None, port=8081, host='0.0.0.0', num_threads=4, num_high_priority_threads=0, debug_queues=False):\n \"\"\"\n Constructor for HttpServerWithPriorities. Will create the socket and bind it (if a socket is not provided). Will\n also create the threadpool specified. None of the threads will be started, call the `run()` method to start\n the server.\n :param sock: optionally specify the socket (if not specified, a new socket will be created).\n :param port: port to bind the socket to (only relevant if a socket is not passed).\n :param host: host to bind the socket to (only relevant if a socket is not passed).\n :param num_threads: number of threads that will fulfill the HTTP Requests (should be greater than 0).\n :param num_high_priority_threads: number of threads that will fulfill high priority HTTP Requests (can be zero).\n :param debug_queues: True to create a monitor thread that reports on the status of the queues.\n \"\"\"\n if sock is None:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((host, port))\n sock.listen()\n self._sock = sock\n self._sock = sock\n self._queues = {\n 'high': queue.Queue(),\n 'low': queue.Queue(),\n }\n self._cv = threading.Condition()\n self.request_queue = queue.Queue()\n self._threads = [threading.Thread(target=self._worker_target) for _ in range(num_threads)]\n self._high_priority_threads = [threading.Thread(target=self._high_priority_target) for _ in range(num_high_priority_threads)]\n\n self._queue_monitor = threading.Thread(target=self._monitor_queues) if debug_queues else None\n self._running = True\n\n def run(self):\n \"\"\"\n Starts the worker threads, the high priority threads and the queue monitor thread (if needed). Then starts\n accepting connections.\n :return: None\n \"\"\"\n logger.info('Starting %s worker threads', len(self._threads))\n for t in self._threads:\n t.start()\n\n logger.info('Starring %s high priority worker threads', len(self._high_priority_threads))\n for t in self._high_priority_threads:\n t.start()\n\n if self._queue_monitor:\n self._queue_monitor.start();\n\n while self._running:\n logger.debug(\"Waiting for connection...\")\n (client_socket, address) = self._sock.accept()\n logger.info(\"Connection from %s\", address)\n # Maybe add to a queue instead? Right now we're creating a thread per request to enqueue it.\n threading.Thread(target=self._request_triage, args=(client_socket,)).start()\n\n def clean(self):\n \"\"\"\n Stops all threads and closes the sockets.\n :return: None\n \"\"\"\n logger.info(\"Stopping the server\")\n self._running = False\n\n self._cv.acquire()\n self._cv.notify_all()\n self._cv.release()\n \n logger.info(\"Waiting for threads to finish...\")\n for t in self._threads:\n t.join()\n \n for t in self._high_priority_threads:\n t.join()\n \n if self._queue_monitor:\n self._queue_monitor.join()\n \n logger.info(\"Closing socket\")\n self._sock.close()\n\n def _worker_target(self):\n \"\"\"\n This is the target for the threadpool.\n Checks the queue when notified and processes handles the request. Tries to get from the higher priority queue\n first.\n :return: None\n \"\"\"\n while self._running:\n self._cv.acquire()\n while not self._something_in_queue():\n if not self._running:\n self._cv.release()\n return \n self._cv.wait()\n logger.debug(\"_worker_target notified\")\n request = self._get_existing_request()\n logger.info(\"worker thread dequeued request(%s)\", request)\n self._cv.release()\n\n self._handle_request(request)\n\n def _high_priority_target(self):\n while self._running:\n self._cv.acquire()\n while not self._something_in_high_priority_queue():\n if not self._running:\n self._cv.release()\n return \n self._cv.notify() # we're swallowing a notify if we don't process a low priority request\n self._cv.wait()\n logger.debug(\"_high_priority_target notified\")\n request = self._get_existing_request() # should be guaranteed to be high priority\n logger.info(\"High priority thread dequeued request(%s)\", request)\n self._cv.release()\n\n self._handle_request(request)\n\n def _handle_request(self, request):\n \"\"\"\n Depending on the request path will write a response body. If the request path is '/long', it will sleep to\n emulate a request that takes a while and then will send the response. Also, closes the socket.\n :param request: Request object.\n :return: None\n \"\"\"\n body = b'Hello world'\n if request.path == '/ping':\n body = b'healthy'\n elif request.path == '/long':\n logger.debug(\"Sleeping for one second to simulate a long request\")\n time.sleep(1)\n logger.debug('Woke up from thread.sleep')\n body = b'Long long'\n\n self._write_response(request, body)\n request.sock.close()\n\n def _monitor_queues(self):\n \"\"\"\n Target for the queue_monitor thread. Checks the state of ach queue and prints a debug message.\n :return: None\n \"\"\"\n while self._running:\n for priority in self._queues:\n logger.debug(\"queues[%s].empty() = %s\", priority, self._queues[priority].empty())\n time.sleep(3)\n\n def _get_existing_request(self):\n \"\"\"\n Gets an existing request from one of the queues. It will try to get the Request from the 'high' priority queue\n first giving it priority. This should be called with a lock and being sure that one of the queues has one\n request.\n :return: Request the enqueued request.\n \"\"\"\n if not self._queues['high'].empty():\n return self._queues['high'].get_nowait() # Should be guaranteed\n return self._queues['low'].get_nowait()\n\n def _something_in_high_priority_queue(self):\n \"\"\"\n Returns True if there is at least one Request in the 'high' priority queue. Must be called with the lock held.\n :return: boolean\n \"\"\"\n return not self._queues['high'].empty()\n\n def _something_in_queue(self):\n \"\"\"\n Returns True if there is at least one Request in any of the queues. Must be called holding the lock held.\n :return boolean\n \"\"\"\n for key in self._queues:\n if not self._queues[key].empty():\n return True\n return False\n\n def _request_triage(self, client_socket):\n \"\"\"\n Get the request and enqueue it in the right queue.\n :return None\n \"\"\"\n # might return None if there's an error\n request = self._get_request(client_socket)\n if request:\n logger.info(\"request(%s)\", request)\n self._enqueue_request(request)\n\n def _enqueue_request(self, request):\n \"\"\"\n Enqueues the request in the appropriate queue.\n :param request: request to enqueue.\n :return: None\n \"\"\"\n self._cv.acquire()\n request_queue = self._get_request_queue(request)\n request_queue.put(request)\n self._cv.notify()\n self._cv.release()\n\n def _get_request_queue(self, request):\n \"\"\"\n Returns the request queue based on the priority that the request has.\n :param request: request to enqueue.\n :return: queue for the request.\n \"\"\"\n priority = self._get_request_priority(request)\n logger.debug(\"%s has priority(%s)\", request, priority)\n return self._queues[priority]\n\n def _get_request_priority(self, request):\n \"\"\"\n Returns the request priority depending on the request's path.\n :param request: Request to get the priority from.\n :return: str 'high'/'low' depending of the priority of the request.\n \"\"\"\n if request.path == '/ping':\n return 'high'\n return 'low'\n\n def _get_request(self, client_socket):\n \"\"\"\n Reads the first line of the HTTP request and returns a Request object. Returns None if there is an error reading\n or parsing the request.\n :param client_socket: socket to read the HTTP request from.\n :return: Request or None if there is an error.\n \"\"\"\n logger.debug(\"Reading data\")\n data = b''\n while True:\n temp_data = client_socket.recv(1024)\n if not temp_data:\n break\n\n data += temp_data\n if b'\\r\\n' in data:\n break\n\n first_line = str(data.split(b'\\r\\n')[0], encoding='UTF-8')\n\n try:\n method, path, version = first_line.split()\n return Request(method=method, path=path, http_version=version, sock=client_socket)\n except:\n logger.error(\"First line seems to be wrong '%s'\", first_line)\n logger.info(\"Ignoring error and closing socket\")\n client_socket.close()\n return None\n\n def _write_response(self, request, body):\n \"\"\"\n Writes the response to a request.\n :param request: request to write a response to.\n :param body: body of the response in bytes.\n :return: None\n \"\"\"\n client_socket = request.sock\n length = len(body) + 1 # not sure why + 1\n response = b\"\\n\".join([\n b'HTTP/1.1 200 OK',\n b'Connection: Close',\n b'Content-Length: ' + bytes(str(length), encoding='UTF-8'),\n b\"\\n\",\n body,\n ])\n client_socket.send(response)\n\n\ndef main():\n import argparse\n\n ap = argparse.ArgumentParser()\n ap.add_argument('-H', '--host', required=False, default='0.0.0.0', help='host to bind the socket to.')\n ap.add_argument('-p', '--port', required=False, type=int, default=8081, help='port to bind the socket to.')\n ap.add_argument('-n', '--num-threads', required=False, type=int, default=4, help='number of worker threads that will be processing http requests')\n ap.add_argument('-i', '--num-high-priority-threads', required=False, type=int, default=0, help='number of high priority threads that will be processing high priority http requests')\n ap.add_argument('-d', '--debug-queues', required=False, action='store_true', help='activate an extra thread to report on status of queues')\n \n args = vars(ap.parse_args())\n \n logger.debug(\"Running with args %s\", args)\n\n server = HttpServerWithPriorities(**args)\n try:\n server.run()\n except KeyboardInterrupt:\n server.clean()\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"nicolasmesa/http-server-with-priorities","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":12175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3959043671","text":"# 영어 끝말잇기\n# 2022-05-05\n\ndef solution(n, words):\n answer = [0, 0]\n sn, last, wordlist = 1, '', []\n for i in range(0, len(words), n):\n wordset = words[(sn - 1)*n:(sn)*n]\n for word in wordset:\n if word not in wordlist and len(word) > 1:\n if not last or last == word[0]:\n last = word[-1]\n elif last and last != word[0]:\n return [wordset.index(word) + 1, sn]\n wordlist.append(word)\n else:\n return [wordset.index(word) + 1, sn]\n sn += 1\n\n return answer\n\nprint(solution(3, [\"tank\", \"kick\", \"know\", \"wheel\", \"land\", \"dream\", \"mother\", \"robot\", \"tank\"]))","repo_name":"hybae430/Programmers","sub_path":"12981.py","file_name":"12981.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17011249163","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nsys.path.insert(\n 0,\n os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"..\"\n )\n)\n\nimport logging\nfrom os import environ\nfrom time import sleep\nfrom pymongo import MongoClient\nfrom recommender.infrastructure.spotify import SpotifyService\nfrom recommender.infrastructure.repository.mongodb import MongoDBSpotifyAudioFeaturesRepository, MongoDBTracksRepository\n\n\nlogging.basicConfig(\n format='%(asctime)s - %(levelname)s - %(message)s',\n level=getattr(logging, os.getenv(\"LOG_LEVEL\", \"INFO\"))\n)\n\n\nspotify = SpotifyService(\n logging.getLogger(),\n os.environ[\"SPOTIPY_USERNAME\"],\n os.environ[\"SPOTIPY_CLIENT_ID\"],\n os.environ[\"SPOTIPY_CLIENT_SECRET\"],\n os.environ[\"SPOTIPY_REDIRECT_URL\"]\n)\n\nclient = MongoClient()\ndb = client.mgr\ntracks_repository = MongoDBTracksRepository(db.playedtracks)\naudio_features_repository = MongoDBSpotifyAudioFeaturesRepository(\n db.spotify_audiofeatures\n)\n\n\nif __name__ == \"__main__\":\n\n count = 0\n\n for track in tracks_repository.all():\n\n logging.info(f\"Processed {count}\")\n count += 1\n if count < 45900:\n continue\n\n if audio_features_repository.load(track):\n logging.info(f\"Skipping {track} features already in DB.\")\n continue\n\n features = spotify.get_audio_features(track)\n if features:\n audio_features_repository.save(features)\n logging.info(f\"Got audio features for {track}\")\n\n sleep(1)\n","repo_name":"jramcast/music-recommender","sub_path":"scripts/download_spotify.py","file_name":"download_spotify.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"22001366117","text":"import os\nimport numpy as np\nimport pytest\nimport optimisers\nimport data\nfrom .util import get_random_network, get_output_dir\n\n# Get name of output directory, and create it if it doesn't exist\noutput_dir = get_output_dir(\"Line search\")\n\n@pytest.mark.parametrize(\"seed\", [3217, 3132, 3523])\ndef test_gradient_descent_line_search(seed):\n \"\"\"\n Test gradient descent, using a line-search. A line-search should guarantee\n that each iteration reduces the error function, so this is tested using\n assert statements after calling the gradient_descent function.\n \"\"\"\n # Set the random seed\n np.random.seed(seed)\n # Generate random number of iterations, network, data, and results file\n n_iters = np.random.randint(10, 20)\n n = get_random_network(input_dim=1, output_dim=1)\n sin_data = data.Sinusoidal(input_dim=1, output_dim=1, freq=1)\n results_filename = (\n \"Test gradient descent with line-search, seed = %i.txt\" % seed\n )\n results_path = os.path.join(output_dir, results_filename)\n results_file = open(results_path, \"w\")\n result = optimisers.Result(\n name=\"SGD with line search\", \n verbose=True,\n file=results_file\n )\n # Add step size column to result\n ls = optimisers.LineSearch(max_its=int(1e10))\n result.add_column(optimisers.results.columns.StepSize(ls))\n # Call gradient descent function\n result_ls = optimisers.gradient_descent(\n n,\n sin_data,\n terminator=optimisers.Terminator(i_lim=n_iters),\n evaluator=optimisers.Evaluator(i_interval=1),\n line_search=ls,\n result=result\n )\n # Make sure each iteration reduces the training error\n train_error_list = result.get_values(optimisers.results.columns.TrainError)\n for i in range(len(train_error_list) - 1):\n assert train_error_list[i + 1] < train_error_list[i]\n \n results_file.close()\n","repo_name":"jakelevi1996/backprop2","sub_path":"Tests/test_line_search.py","file_name":"test_line_search.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26454338140","text":"# Databricks notebook source\nimport mlflow\nimport mlflow.azureml\nimport azureml.mlflow\nimport azureml.core\nfrom azureml.core import Workspace\nfrom azureml.mlflow import get_portal_url\n\nprint(\"AzureML SDK version:\", azureml.core.VERSION)\nprint(\"MLflow version:\", mlflow.version.VERSION)\n\n# COMMAND ----------\n\nfrom azureml.core.authentication import ServicePrincipalAuthentication\ndef service_principal_auth():\n return ServicePrincipalAuthentication(\n tenant_id=tenant_id,\n service_principal_id=sp_id,\n service_principal_password=sp_secret)\n \n\n# COMMAND ----------\n\nfrom azureml.core.authentication import InteractiveLoginAuthentication\ndef interactive_auth():\n return InteractiveLoginAuthentication(tenant_id=tenant_id)\n\n# COMMAND ----------\n\ndef azureml_workspace(auth_type='interactive'):\n if auth_type == 'interactive':\n auth = interactive_auth()\n elif auth_type == 'service_princpal':\n auth = service_principal_auth()\n \n ws = Workspace.create(name = workspace_name,\n resource_group = resource_group,\n subscription_id = subscription_id,\n exist_ok=True,\n auth=auth)\n return ws\n\n# COMMAND ----------\n\ndef auzreml_mlflow_tracking_uri(workspace):\n return workspace.get_mlflow_tracking_uri()\n\n# COMMAND ----------\n\nfrom azureml.core.webservice import AciWebservice, Webservice\nimport random\nimport string\n\ndef azureml_build_deploy(runid, workspace, model_name, image_name, deploy_name):\n # Build an Azure ML Container Image for an MLflow \n azure_image, azure_model = mlflow.azureml.build_image(model_uri='runs:/{}/{}'.format(runid, MODEL_SAVE_PATH),\n workspace=workspace,\n model_name=model_name,\n image_name=image_name,\n synchronous=True)\n \n \n # Deploy the image to Azure Container Instances (ACI) for real-time serving\n aci_config = AciWebservice.deploy_configuration()\n deployment_stub = ''.join([random.choice(string.ascii_lowercase) for i in range(5)])\n print(\"Deploying as \"+deploy_name+\"-\"+deployment_stub)\n webservice = Webservice.deploy_from_image(\n image=azure_image, workspace=workspace, name=deploy_name+\"-\"+deployment_stub, deployment_config=aci_config)\n\n webservice.wait_for_deployment()\n \n return webservice\n","repo_name":"joelcthomas/ml-azuredatabricks","sub_path":"azureml/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"52"} +{"seq_id":"18598104371","text":"from unicodedata import name\nfrom loader import dp\nfrom states import register\nfrom keyboards.default import kb_menu\n\nfrom aiogram import types\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.dispatcher.filters import Command\nfrom aiogram.types import ReplyKeyboardMarkup, KeyboardButton\n\n# /register (Starting registration)\n@dp.message_handler(Command('register')) \nasync def register_start(message: types.Message):\n # Keybort with username buttons\n name = ReplyKeyboardMarkup(\n keyboard=[\n [\n KeyboardButton(text=f'{message.from_user.first_name}'),\n ]\n ], resize_keyboard=True\n )\n\n await message.answer('Привет, ты начал регистрацию, \\nВведи своё имя:', reply_markup=name)\n await register.register1.set() # Set first state\n\n# Catch all message users in first state (State of inputing name)\n@dp.message_handler(state=register.register1)\nasync def register_state1(message: types.Message, state: FSMContext):\n answer = message.text\n\n await state.update_data(register1=answer)\n await message.answer(f'{answer} Сколько тебе лет?')\n await register.register2.set() # Set second state\n\n\n@dp.message_handler(state=register.register2)\nasync def register_state2(message: types.Message, state: FSMContext):\n answer = message.text\n\n await state.update_data(register2=answer)\n data = await state.get_data()\n await message.answer(f'Регистрация успешно завершена\\n'\n f'Твоё имя {data[\"register1\"]} \\n'\n f'Тебе {data[\"register2\"]} лет', reply_markup=kb_menu)\n\n await state.finish()","repo_name":"Denis-Bez/Education_Python_01","sub_path":"07_Education_Telegram_Redly/handlers/users/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29971058707","text":"# Pillow 事实上已经是一个Python的图像处理标准库了\nfrom PIL import Image, ImageFilter # 操作图像\nim = Image.open('/home/nifer/Pictures/Wallpapers/tt.jpg')\nw, h = im.size\nprint('图像的大小为:', im.size, '图像的格式:', im.format, '图像的模式:', im.mode) # 图像的相关信息\nim.thumbnail((w // 2, h // 2)) # 缩放50%\nprint('缩放后的大小为:', im.size)\nim.save('thumbnail.jpg', 'jpeg') # 把缩放后的图像用jpeg格式保存:\n\n# 图像模糊效果\nim = im.filter(ImageFilter.BLUR)\nim.save('blur.jpg', 'jpeg')\n","repo_name":"Myfour/Python_Basic","sub_path":"python_Pillow.py","file_name":"python_Pillow.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33642349010","text":"\nimport multiprocessing\nimport ftp,sftp,snow,snowqa,s3_source,s3_sink,teradata\nfrom datetime import datetime \nfrom multiprocessing.pool import ThreadPool\nimport os, numpy as np\nimport pandas as pd\nimport datacompy\nimport logging\n\n#logging.basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",filename='Output/logs.log', encoding='utf-8', level=logging.DEBUG)\n\n\n#start 4 worker processes\npool = ThreadPool(processes=multiprocessing.cpu_count())\n#print(multiprocessing.cpu_count())\n\n\nstatus=''\ndef get_dfs(source,source_path,sink,sink_path):\n if source in ['s3_source','teradata','ftp', 'sftp'] and sink in ['s3_sink', 'snow', 'snowqa']:\n async_result1 = pool.apply_async(eval(source).dataframe,(source_path,)) \n async_result2 = pool.apply_async(eval(sink).dataframe,(sink_path,)) \n df_source=async_result1.get() \n df_sink=async_result2.get()\n #logging.info(\"Dataframes created\")\n return df_source,df_sink\n else:\n print('source error')\n #logging.error(\"Dataframes not created\")\n \n\n\ndef main(source,sink,source_path,sink_path):\n with open('Output/report.txt', 'w') as f:\n f.write(\"--------- Summary Report ----------\\n\")\n with open('Output/errors.txt', 'w') as f:\n f.write(\"-------- Error Logs --------\\n\")\n\n with open('Output/Duplicate_records_sink.csv', 'w') as f:\n f.write(\"\")\n with open('Output/Matched_records.csv', 'w') as f:\n f.write(\"\")\n with open('Output/Mismatched_records.csv', 'w') as f:\n f.write(\"\")\n with open('Output/Compared_records.csv', 'w') as f:\n f.write(\"\")\n with open('Output/Missing_records.csv', 'w') as f:\n f.write(\"\")\n\n start = datetime.now().replace(microsecond=0) # Start time\n print(\"starts at --\",start,\"\\n\")\n # Select the Source and Sink \n df_source,df_sink=get_dfs(source,source_path,sink,sink_path)\n \n # End of Threads and Now Source and Sink dataframes are ready to compare\n # It will compare and generate reports \n reports(df_source,df_sink)\n # It will compare and store data into CSV file\n process(df_source,df_sink)\n \n end=datetime.now().replace(microsecond=0) # End time\n print(\"\\nends at - - \",end)\n print(\"Total Time took - - :\",end-start) # Total time took\n with open('Output/report.txt', 'a',newline='') as f:\n f.write(f\"\\nTotal Time took - - : {end-start}\")\n #os.system(\"pause\")\n \n\n\ndef reports(df_source,df_sink):\n try:\n compare = datacompy.Compare(\n df_source,\n df_sink,\n join_columns=list(df_source.columns), #You can also specify a list of columns\n abs_tol=0, #Optional, defaults to 0\n rel_tol=0, #Optional, defaults to 0\n df1_name='Source', #Optional, defaults to 'df1'\n df2_name='Sink' #Optional, defaults to 'df2'\n )\n with open('Output/report.txt', 'a') as f:\n f.write(compare.report())\n\n except Exception as e:\n print(e)\n with open('Output/errors.txt', 'a',newline='') as f: # Write unmatched records to csv file\n f.write(f\"\\n--- Exception {datetime.now().replace(microsecond=0)} ---\\n{e}\\n\")\n\n \ndef compare(source_df,sink_df):\n try:\n comp=source_df.compare(sink_df,align_axis=0).rename(index={'self': 'Source', 'other': 'Sink'}, level=-1) # Compare the dataframes\n print(comp)\n if comp.shape[0]>0: # If there are any differences in dataframes\n with open('Output/Compared_records.csv', 'w', newline='') as f: # Write the differences to csv file\n comp.to_csv(f)\n f.write(\"\\n\")\n except Exception as e:\n print(e)\n with open('Output/errors.txt', 'a',newline='') as f: # Write unmatched records to csv file\n f.write(f\"\\n\\n--- Exception {datetime.now().replace(microsecond=0)}---\\n{e}\\n\")\n\n# Get unmatched records from Source and Sink & compare both dataframes\ndef process(source_df,sink_df):\n global status\n #print(source_df,sink_df)\n #compare - If Rows and columns are same but values are different then write the different data to csv\n #print(\"--------------------------- compare -----------------------------------\")\n compare(source_df,sink_df)\n\n try:\n if sink_df.equals(source_df): # Check if both dataframes are equal\n print(\"\\nDataframe is Equal\")\n # global status\n status=\"STATUS: Dataframe is equal\"\n elif source_df.columns.equals(sink_df.columns):\n\n #source_df.sort_values(by=list(source_df.columns)[:2],inplace=True)\n #sink_df.sort_values(by=list(sink_df.columns)[:2],inplace=True)\n print(\"---- Source Dataframe ----\\n\",source_df)\n print(\"---- Sink Dataframe ----\\n\",sink_df)\n # source_df['xid']=source_df.index\n # sink_df['xid']=sink_df.index\n # source_df=source_df.reset_index(drop=True) # Reset index of ftp dataframe\n # sink_df=sink_df.reset_index(drop=True) # Reset index of s3 dataframe\n\n source_df['count'] = source_df.groupby(list(source_df.columns)).cumcount()\n sink_df['count'] = sink_df.groupby(list(sink_df.columns)).cumcount()\n\n source_df['index']=source_df.index\n source_df = source_df.reset_index(drop=True)\n sink_df['index']=sink_df.index\n sink_df = sink_df.reset_index(drop=True)\n\n # Get the unmatched records from Source and Sink using outer join method\n # Note: It will compare based on count with all the fileds on dataframes to avoid duplicates\n un_df=source_df.merge(sink_df,how='outer',on=list(source_df.columns[:-1]),indicator=True)\n # print(un_df)\n # Rename the column value of _merge to Source or Sink insted of left_only or right_only\n un_df[\"_merge\"].replace({\"left_only\": \"Source\", \"right_only\": \"Sink\"}, inplace=True)\n # Rename the column index_x to Source_index and index_y to Sink_index\n un_df.rename(columns = {'index_x':'Source_index','index_y':\"Sink_index\"}, inplace = True)\n un_df[\"Source_index\"].replace({np.nan: \"Missing\"}, inplace=True)\n un_df[\"Sink_index\"].replace({np.nan: \"Missing\"}, inplace=True)\n \n \n if un_df[lambda x: x['_merge']=='both'].shape[0]>0:\n #print(\"\\nDataframe is Not Equal\\n\")\n with open('Output/Matched_records.csv', 'w',newline='') as f: # Write unmatched records to csv file\n un_df[lambda x: x['_merge']=='both'].drop(['count'], axis=1).to_csv(f)\n f.write(\"\\n\")\n\n if un_df[(un_df[\"_merge\"] == 'Sink') & (un_df[\"count\"] != 0)].shape[0]>0:\n #print(\"\\nDataframe is Not Equal\\n\")\n with open('Output/Duplicate_records_sink.csv', 'w',newline='') as f: # Write unmatched records to csv file\n un_df[(un_df[\"_merge\"] == 'Sink') & (un_df[\"count\"] != 0)].groupby(un_df.columns.tolist()[:-4]).size().reset_index().rename(columns={0:'records_count'}).to_csv(f)\n f.write(\"\\n\")\n\n if un_df[(un_df[\"_merge\"] == 'Source') & (un_df[\"count\"] == 0)].shape[0]>0:\n #print(\"\\nDataframe is Not Equal\\n\")\n with open('Output/Missing_records.csv', 'w',newline='') as f: # Write unmatched records to csv file\n un_df[(un_df[\"_merge\"] == 'Source') & (un_df[\"count\"] == 0)].drop(['count'], axis=1).to_csv(f)\n f.write(\"\\n\")\n\n if un_df[lambda x: x['_merge']!='both'].shape[0]>0:\n #print(\"\\nDataframe is Not Equal\\n\")\n with open('Output/Mismatched_records.csv', 'w',newline='') as f: # Write unmatched records to csv file\n un_df[lambda x: x['_merge']!='both'].drop(['count'], axis=1).to_csv(f)\n f.write(\"\\n\")\n with open('Output/errors.txt', 'a',newline='') as f: # Write unmatched records to csv file\n f.write(f\"\\n--- Message {datetime.now().replace(microsecond=0)} ---\\nDataframe have suffled/mismatched records\")\n print(\"\\nDataframe have suffled/mismatched records\")\n status=\"STATUS: Dataframe have suffled/mismatched records\"\n # else:\n # with open('Output/errors.txt', 'a',newline='') as f: # Write unmatched records to csv file\n # f.write(f\"\\n--- Message {datetime.now().replace(microsecond=0)} ---\\nDataframe have suffled/mismatched records\")\n # print(\"\\nDataframe have suffled/mismatched records\")\n # status=\"STATUS: Dataframe have suffled/mismatched records\"\n else:\n with open('Output/errors.txt', 'a',newline='') as f: # Write unmatched records to csv file\n f.write(f\"\\n--- Message {datetime.now().replace(microsecond=0)} ---\\nSource and Sink Dataframes have different columns.\")\n print(\"\\nDataframes have different columns.....\")\n status=\"STATUS: Source and Sink Dataframes have different columns. \"\n except Exception as e:\n print(e)\n with open('Output/errors.txt', 'a',newline='') as f: # Write unmatched records to csv file\n f.write(f\"\\n--- Exception {datetime.now().replace(microsecond=0)} ---\\n{e}\")\n status=\"ERROR: Something Went Wrong! Plaese provide correct details!!\"\n\n\ndef details(source,sink,source_path,sink_path):\n global status\n try:\n with open('Output/basic_details.txt', 'w') as f:\n f.write(\"Basic Comaprison\\n\")\n f.write(\"----------------\\n\")\n\n pool.apply_async(eval(source).details,(source_path,)).get()\n \n pool.apply_async(eval(sink).details,(sink_path,)).get() \n\n print(\"\\nBasic Details function done !\\n\")\n \n except Exception as e: \n print(e)\n status=f\"ERROR:{e}\"\n\n\n\n\n \n \n\n","repo_name":"rohitrsp898/AMT-tool","sub_path":"main_webm.py","file_name":"main_webm.py","file_ext":"py","file_size_in_byte":9983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17148979847","text":"import random;\nimport string;\nimport math;\n\nclass rsa:\n abc = list(string.ascii_letters + string.digits + string.punctuation + \" \"); # List of all lowercase letters, uppercase letters, numbers and punctuation plus a whitespace\n\n # Generates a public and private key pair\n def generateKeyPair(p, q):\n n = p * q;\n phi = (p - 1)*(q - 1) ;\n e = rsa.generateE(phi);\n d = rsa.egcd(e, phi) # Generates private key using extended euclidean algorithm\n\n return ((e, n), (d, n)); # Returns public key (e,n) and private key (d,n) as tuple;\n\n # Extended Euclidean algorithm - This was taken from https://www.tutorialspoint.com/python-program-for-extended-euclidean-algorithms and tweaked to suit my needs\n def egcd(e: int, phi: int):\n d = 0;\n x1 = 0;\n x2 = 1;\n y1 = 1;\n tempPhi = phi;\n\n while e > 0:\n temp1 = tempPhi//e;\n temp2 = tempPhi - temp1 * e;\n tempPhi = e;\n e = temp2;\n\n x = x2 - temp1 * x1;\n y = d - temp1 * y1;\n\n x2 = x1;\n x1 = x;\n d = y1;\n y1 = y;\n\n if tempPhi == 1:\n return d + phi;\n\n # Generates e. E is a coprime of phi because the only factor in common is 1.\n def generateE(phi: int):\n e = random.SystemRandom().randrange(1, phi); # Generate test e (less than phi)\n if math.gcd(e, phi) != 1: # If the test e is not a coprime of phi\n return rsa.generateE(phi); # Recursively call this function until e is a coprime of phi\n return e;\n\n # Encrypt using a generate public key and a userdefined plainText\n def encrypt(publicKey: int, plainText: str):\n # Iterates through plainText\n # Turns each character into a number using abc (an array of characters and numbers)\n # Runs the (p^e)%n using provided public key\n # Returns the cipherText as bytes\n\n return bytes([(rsa.abc.index(char)**publicKey[0] % publicKey[1]) for char in plainText]);\n\n # Encrypt using a generate private key and a userdefined cipherText\n def decrypt(privateKey: int, cipherText: str):\n # Iterates through cipherText\n # Turns each character into a number using abc (an array of characters and numbers)\n # Runs the (c^e)%n using provided private key where c is the ciphertext\n # Returns the plainText\n\n return \"\".join([rsa.abc[(char**privateKey[0]) % privateKey[1]] for char in cipherText]);\n\n \n# Driver Code\np = 11; # Prime 1\nq = 13; # Prime 2\npublicKey, privateKey = rsa.generateKeyPair(p, q); # Generate keypair\n\nencrypted = rsa.encrypt(publicKey,\"This is a test!\");\ndecrypted = rsa.decrypt(privateKey, encrypted);\n\nprint(encrypted);\nprint(decrypted);\n","repo_name":"tywil04/rsa","sub_path":"RSA.py","file_name":"RSA.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71281025126","text":"from django.urls import path, include\nfrom .import views \n#from rest_framework.authtoken import views as drf_view\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nurlpatterns=[\n path('course/', views.CourseListView.as_view(), name=\"course\"),\n path('course/<int:pk>/', views.CourseDetail.as_view(), name=\"course\"),\n # path(\"token_login/\", obtain_auth_token, name=\"token_login\"),\n path('auth/', include('djoser.urls')),\n path('auth/', include('djoser.urls.authtoken')),\n path('students/', views.StudentApiView.as_view(), name=\"students\"),\n path('teacher/', views.TeacherListView.as_view(), name=\"teacher\"),\n path('students/<int:pk>/', views.StudentDetailView.as_view(), name=\"students\"),\n # path('user/', views.CreateNewUser.as_view(), name=\"new_user\"),\n\n\n]","repo_name":"Zi2le/School-Management-API","sub_path":"schooldetails/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9427219273","text":"import tensorflow as tf\nimport numpy as np\nfrom distutils.version import LooseVersion\n\n# LooseVersion handles things \"1.2.3a\" or \"4.5.6-rc7\" fairly sensibly.\n_is_tensorflow2 = LooseVersion(tf.__version__) >= LooseVersion(\"2.0.0\")\n\nif _is_tensorflow2:\n import tensorflow.compat.v1 as tf\n\n tf.disable_v2_behavior()\n\n\n\ndef load_pb(path_to_pb):\n with tf.gfile.GFile(path_to_pb, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n with tf.Graph().as_default() as graph:\n tf.import_graph_def(graph_def, name='')\n\n #with tf.Session(graph=graph) as sess:\n # writer = tf.summary.FileWriter('./TestGraphs', sess.graph)\n\n return graph\n\ndef get_ActionContinuous(observations):\n\n # get the trained graph from the pb file\n PATH = './Graphs/frozen_graph_def.pb'\n graph = load_pb(PATH)\n\n # get the tensors for the Fetch and FeedDict Paramters\n fetchTensor = graph.get_tensor_by_name('action:0')\n\n obsTensor = graph.get_tensor_by_name('vector_observation:0')\n epsilonTensor = graph.get_tensor_by_name('epsilon:0')\n\n # create the feed dict with the observatrions from the mlAgents env\n feed_dict = {}\n feed_dict[obsTensor] = observations\n feed_dict[epsilonTensor] = np.zeros((12, 2), dtype=int)\n\n sess = tf.Session(graph=graph)\n\n return sess.run(fetchTensor, feed_dict=feed_dict)\n\ndef get_ActionForBasic(observations):\n\n # get the trained graph from the pb file\n PATH = './Graphs/Basic/frozen_graph_def.pb'\n graph = load_pb(PATH)\n\n # get the tensors for the Fetch and FeedDict Paramters\n fetchTensor = graph.get_tensor_by_name('action:0')\n #fetchTensor = graph.get_tensor_by_name('Identity')\n\n obsTensor = graph.get_tensor_by_name('vector_observation:0')\n\n actionMaskTensor = graph.get_tensor_by_name('action_masks:0')\n\n # create the feed dict with the observatrions from the mlAgents env\n feed_dict = {}\n feed_dict[obsTensor] = observations\n #feed_dict[actionMaskTensor] = np.zeros((1, 3), dtype=int)\n feed_dict[actionMaskTensor] = np.ones((1, 3), dtype=int)\n\n sess = tf.Session(graph=graph)\n\n return sess.run(fetchTensor, feed_dict=feed_dict)\n\ndef get_ActionForGridworld(observations, actionMaskArray):\n\n # get the trained graph from the pb file\n PATH = './Graphs/Gridworld/frozen_graph_def.pb'\n graph = load_pb(PATH)\n\n # get the tensors for the Fetch and FeedDict Paramters\n fetchTensor = graph.get_tensor_by_name('action:0')\n #fetchTensor = graph.get_tensor_by_name('Identity')\n\n obsTensor = graph.get_tensor_by_name('visual_observation_0:0')\n actionMaskTensor = graph.get_tensor_by_name('action_masks:0')\n\n # create the feed dict with the observatrions from the mlAgents env\n feed_dict = {}\n feed_dict[obsTensor] = observations\n #feed_dict[actionMaskTensor] = actionMaskArray\n testArray = np.ones((1, 5), dtype=int)\n\n # the nn expects a action mask with 1 for enabled and 0 for disabled\n # the ml agent mask codes it the other way round with false meaning not blocked -> enabled\n\n testArray[0][0] = 1\n testArray[0][1] = actionMaskArray[0][1]\n testArray[0][2] = actionMaskArray[0][2]\n testArray[0][3] = actionMaskArray[0][3]\n testArray[0][4] = actionMaskArray[0][4]\n feed_dict[actionMaskTensor] = testArray\n #feed_dict[actionMaskTensor] = np.zeros((1, 5), dtype=int)\n\n sess = tf.Session(graph=graph)\n\n return sess.run(fetchTensor, feed_dict=feed_dict)\n\n\nprint(\"done\")","repo_name":"R-Carver/MArbeit","sub_path":"EigeneMLLoop/GraphHelper.py","file_name":"GraphHelper.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40469170887","text":"from odoo import fields, models\n\n\nclass ResConfig(models.TransientModel):\n \"\"\"\n This is an Odoo model for configuration settings. It inherits from the\n 'res.config.settings' model and extends its functionality by adding\n fields for low stock alert configuration\n\n \"\"\"\n _inherit = 'res.config.settings'\n\n is_low_stock_alert = fields.Boolean(\n string=\"Low Stock Alert\",\n help='This field determines the minimum stock quantity at which a low '\n 'stock alert will be triggered.When the product quantity falls '\n 'below this value, the background color for the product will be '\n 'changed based on the alert state.',\n config_parameter='low_stocks_product_alert.is_low_stock_alert')\n min_low_stock_alert = fields.Integer(\n string='Alert Quantity', default=0,\n help='Change the background color for the product based'\n 'on the Alert Quant.',\n config_parameter='low_stocks_product_alert.min_low_stock_alert')\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"low_stocks_product_alert/models/res_config_settings.py","file_name":"res_config_settings.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"3108116057","text":"# A robot is located at the top-left corner of a m x n grid (marked 'Start' in t\n# he diagram below). \n# \n# The robot can only move either down or right at any point in time. The robot \n# is trying to reach the bottom-right corner of the grid (marked 'Finish' in the d\n# iagram below). \n# \n# How many possible unique paths are there? \n# \n# \n# Above is a 7 x 3 grid. How many possible unique paths are there? \n# \n# Note: m and n will be at most 100. \n# \n# Example 1: \n# \n# \n# Input: m = 3, n = 2\n# Output: 3\n# Explanation:\n# From the top-left corner, there are a total of 3 ways to reach the bottom-righ\n# t corner:\n# 1. Right -> Right -> Down\n# 2. Right -> Down -> Right\n# 3. Down -> Right -> Right\n# \n# \n# Example 2: \n# \n# \n# Input: m = 7, n = 3\n# Output: 28 \n# Related Topics Array Dynamic Programming\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nfrom functools import lru_cache\n\n\n@lru_cache(None)\ndef paths(i, j):\n if i == 0 or j == 0:\n return 1\n else:\n return paths(i, j - 1) + paths(i - 1, j)\n\n\nclass Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n for i in range(m):\n for j in range(n):\n paths(i, j)\n return paths(m - 1, n - 1)\n\n\n@lru_cache(None)\ndef factorial(m):\n if m == 0:\n return 1\n\n return m * factorial(m - 1)\n\n\ndef num_paths(m, n):\n for i in range(m + n - 1):\n factorial(i)\n return factorial(m + n - 2) // (factorial(m - 1) * factorial(n - 1))\n\n\ndef test():\n ts = [(3, 2, 3), (7, 3, 28)]\n s = Solution()\n for m, n, ans in ts:\n assert num_paths(m, n) == ans\n assert s.uniquePaths(m, n) == ans\n# leetcode submit region end(Prohibit modification and deletion)\n","repo_name":"sunilnandihalli/leetcode","sub_path":"editor/en/[62]Unique Paths.py","file_name":"[62]Unique Paths.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72853517286","text":"from TreeViewItem.TreeViewItem import TreeViewItem\n\nclass TreeViewItemFace(TreeViewItem):\n indent = 1\n\n def visit(self,treeViewItem):\n super(TreeViewItemFace, self).visit()\n\n if self.expanded:\n treeViewItem.data = self.deleteChild(treeViewItem.data, self)\n self.expanded = False\n else:\n raise Exception(\"TreeViewItemFace: Visit photos with faces\")\n","repo_name":"yvanross/snu-photo-manager","sub_path":"TreeViewItem/TreeViewItemFace.py","file_name":"TreeViewItemFace.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10944226026","text":"\"\"\"Simple work with DataBase.\"\"\"\n\nimport sqlite3\nimport datetime\n\nDB_NAME = 'users.db'\nDB_TABLE_NAME = 'users'\n\n\nclass DataBaseConn:\n \"\"\"Context Manager, which work with sqlite3.\"\"\"\n\n def __init__(self, db_name):\n self._db_name = db_name\n\n def __enter__(self):\n self._conn = sqlite3.connect(self._db_name)\n return self._conn\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self._conn.commit()\n self._conn.close()\n if exc_val:\n raise\n\n\nclass UsersDB:\n \"\"\"Class works with DataBase of users.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor.\n\n Create table 'users' if it isn't exist.\n\n \"\"\"\n with DataBaseConn(DB_NAME) as conn:\n cursor = conn.cursor()\n cursor.execute(f'''CREATE TABLE if not exists \n {DB_TABLE_NAME}\n (user_id text,\n first_name text,\n last_name text,\n message text,\n time text)\n '''\n )\n\n @classmethod\n def push_user(cls, about_user: {}, message: str):\n \"\"\"Push info about user to DataBase.\n\n :param about_user: info about user, which send msg\n :param message: message, which user send\n\n \"\"\"\n sql = '''INSERT INTO {} VALUES\n ('{}','{}','{}','{}', '{}')\n '''.format(DB_TABLE_NAME,\n about_user.get('id', ''),\n about_user.get('first_name', ''),\n about_user.get('last_name', ''),\n message,\n datetime.datetime.now()\n )\n with DataBaseConn(DB_NAME) as conn:\n conn.cursor().execute(sql)\n","repo_name":"Elaskinok/VK_bot","sub_path":"db_users.py","file_name":"db_users.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11719753031","text":"from zenoss.protocols.protobufs.zep_pb2 import (\n SEVERITY_CLEAR,\n SEVERITY_WARNING,\n SEVERITY_ERROR\n )\n\ncurrent = int(float(evt.current))\n\n# Example: caching|caching_state|Status\nif (evt.eventKey.startswith('caching|caching_')\n and evt.eventKey.endswith('|Status')):\n\n name = evt.eventKey.replace('caching|caching_', '').replace('|Status', '')\n if name.endswith('Status'):\n name = name[:-6]\n\n state_dict = dict()\n state_dict['Registration'] = {\n -1: 'is not registered',\n 0: 'is attempting registration',\n 1: 'is registered',\n }\n state_dict['Cache'] = {\n 1: 'is OK',\n 2: 'is low on space',\n }\n state_dict['Startup'] = {\n 1: 'startup is OK',\n 2: 'startup is pending',\n 3: 'startup has failed',\n 4: 'startup is not auto-enabled',\n }\n state_dict['state'] = {\n 1: 'is running',\n 2: 'is starting',\n 3: 'is stopped',\n }\n state_dict['RegistrationError'] = {\n 3: 'registration error: wireless portable is not supported',\n 4: 'registration error: invalid IP range',\n 5: 'registration error: public IP not in range',\n 6: 'registration error: too many private addresses',\n 7: 'registration error: invalid device',\n 8: 'registration error: not activated',\n }\n state_dict['Active'] = {\n 0: 'is not active',\n 1: 'is active',\n }\n state_dict['DiskExceededCustom'] = {\n 1: 'size is within available volume capacity',\n 2: 'size exceeds available volume capacity',\n }\n\n status = state_dict.get(name, dict()).get(\n current,\n '{0} value unknown'.format(name)\n )\n evt.summary = 'Content Cache {0}'.format(status)\n\n sev_dict = {\n -1: SEVERITY_ERROR,\n 0: SEVERITY_WARNING,\n 1: SEVERITY_CLEAR,\n 2: SEVERITY_WARNING,\n 3: SEVERITY_ERROR,\n 4: SEVERITY_ERROR,\n 5: SEVERITY_ERROR,\n 6: SEVERITY_ERROR,\n 7: SEVERITY_ERROR,\n 8: SEVERITY_ERROR,\n }\n evt.severity = sev_dict.get(current, SEVERITY_WARNING)\n\n # ZPL Components look for events in /Status rather than\n # /Status/ClassName to determine up/down status\n if current != 2 and name != 'DiskExceededCustom':\n evt.eventClass = '/Status'\n\n if (name in ['Active', 'state']\n and component\n and hasattr(component, 'Active')):\n bool_dict = {\n 0: False,\n 1: True,\n 3: False,\n }\n if component.Active != bool_dict.get(current, False):\n @transact\n def updateDb():\n component.Active = bool_dict.get(current, False)\n updateDb()\n\nelif 'Peers|Peers_healthy|PeerHealth' == evt.eventKey:\n health_dict = {\n 0: 'not healthy',\n 1: 'healthy',\n }\n\n status = health_dict.get(current, 'unknown')\n evt.summary = 'Peer {0} is {1}'.format(evt.component, status)\n\n sev_dict = {\n 0: SEVERITY_WARNING,\n 1: SEVERITY_CLEAR,\n }\n evt.severity = sev_dict.get(current, SEVERITY_WARNING)\n\n evt.eventClass = '/Status'\n\n if component and hasattr(component, 'healthy'):\n bool_dict = {\n 0: False,\n 1: True,\n }\n if component.healthy != bool_dict.get(current, False):\n @transact\n def updateDb():\n component.healthy = bool_dict.get(current, False)\n updateDb()\n","repo_name":"daviswr/ZenPacks.daviswr.OSX.Server.Caching","sub_path":"ZenPacks/daviswr/OSX/Server/Caching/transforms/Status/MacContentCache/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"74375472484","text":"from utils import *\nfrom customModel_iterative import *\nimport time\n\ndef BANNvarEM(X, y, centered=False, numModels=20, tol=1e-4, maxiter=1e4, show_progress = True):\n\t'''\n\tX is the genotype matrix with n by p\n\ty is the phenotype with dimension of n\n\tnumModels is the number of initialized models for computing LB \n\ttol is the convergence tolerance\n\tmaxiter is the maximum iterations\n\t'''\n\t### convert data to numpy array\n\tX=np.asarray(X)\n\ty=np.asarray(y)\n\t### normalizing inputs\n\tif centered==False:\n\t\ty = (y-np.mean(y))/np.std(y)\n\t\tfor i in range(X.shape[1]):\n\t\t\tX[:,i] = (X[:,i]- np.mean(X[:,i]))/np.std(X[:,i])\n\t### number of samples\n\tn=X.shape[0]\n\t### number of features\n\tp=X.shape[1]\n\t### precompute xy\n\txy=np.matmul(y,X)\n\t### precompute diagonal elements of X^TX\n\td=diagsq(X)\n\tprint(\"initializing variables\")\n ### initialize variance hyper-param\n\ttau=np.repeat(np.var(y),numModels)*1.0\n\tsigma=np.repeat(1,numModels)*1.0\n\t### fixed hyper-parameter (pi_k in the paper)\n\tlogodds=np.linspace(-np.log10(p),-1, num=numModels).reshape(1,numModels)\n\talpha=rand(p,numModels)\n\talpha=alpha/rep_row(np.sum(alpha,axis=0),p)\n\tmu=randn(p,numModels)\n\tupdate_order=np.arange(p)\n ### normalized importance weights for SNP layer\n\tlogw=np.repeat(0, numModels)*1.0\n\ts=np.zeros((p,numModels))\n\tb=np.zeros((1,numModels))\n\tI=np.ones((n,1))\n\tSIy= np.matmul(y,I)*1.0/n\n\tSIX= np.matmul(np.transpose(I),X)*1.0/n\n\t### Finding the best initialization\n\tfor i in range(0,numModels):\n\t\tif show_progress == True:\n\t\t\tprint(\"Initialize model \" + str(i+1) + \"/\" + str(numModels))\n\t\tout=outerloop(X, I, y, xy, d, SIy, SIX, tau[i],sigma[i],logodds[:,i],alpha[:,i],mu[:,i],update_order,\n\t\t\t\t\t tol,maxiter,i)\n\t\tlogw[i] = out[\"logw\"]\n\t\ttau[i] = out[\"tau\"]\n\t\tsigma[i] = out[\"sigma\"]\n\t\tb[:,i] = out[\"b\"]\n\t\talpha[:,i] = out[\"alpha\"]\n\t\tmu[:,i] = out[\"mu\"]\n\t\ts[:,i] = out[\"s\"]\n\ti = np.argmax(logw)\n\talpha = rep_col(alpha[:,i],numModels)\n\tmu = rep_col(mu[:,i],numModels)\n\ttau = np.repeat(tau[i],numModels)*1.0\n\tsigma = np.repeat(sigma[i],numModels)*1.0\n\t### Loop for optimizing\n\tfor i in range(0,numModels):\n\t\tif show_progress == True:\n\t\t\tprint(\"Updating model \" + str(i+1) + \"/\" + str(numModels))\n\t\tout=outerloop(X, I, y, xy, d, SIy, SIX, tau[i],sigma[i],logodds[:,i],alpha[:,i],mu[:,i],update_order,\n\t\t\t\t\t tol,maxiter,i)\n\t\tlogw[i] = out[\"logw\"]\n\t\ttau[i] = out[\"tau\"]\n\t\tsigma[i] = out[\"sigma\"]\n\t\tb[:,i] = out[\"b\"]\n\t\talpha[:,i] = out[\"alpha\"]\n\t\tmu[:,i] = out[\"mu\"]\n\t\ts[:,i] = out[\"s\"]\n\t### normalize weights etc\n\tw = normalizelogweights(logw)\n\tpip = np.matmul(alpha,w)\n\tbeta = np.matmul((alpha*mu),w)\n\tbeta_cov = np.matmul(b,w)\n\t### summarize results\n\ttemp_res = {\"b\":b,\"logw\":logw, \"w\":w, \"tau\":tau, \"sigma\":sigma,\"logodds\":logodds, \"alpha\":alpha,\n\t\t\t \"mu\":mu, \"s\":s, \"pip\":pip, \"beta\":beta, \"beta_cov\":beta_cov}\n\t### estiamte model PVE\n\tpve = estimatePVE(temp_res, X, nr = 1000)\n\tresults = {\"b\":b,\"logw\":logw, \"w\":w, \"tau\":tau, \"sigma\":sigma,\"logodds\":logodds, \"alpha\":alpha,\n\t\t\t \"mu\":mu, \"s\":s, \"pip\":pip, \"beta\":beta, \"beta_cov\":beta_cov, \"pve\":pve}\n\treturn results\n\n\ndef BANN(X, mask, y, centered=False, numModels=20, tol=1e-4, maxiter=1e4, show_progress = True):\n\t'''\n\tX is the genotype matrix with dimension n-by-p\n\tmask is the annotation file with dimension p-by-g\n\ty is the phenotype with dimension n\n\tnumModels is the number of initialized models for computing LB \n\ttol is the convergence tolerance\n\tmaxiter is the maximum iterations\n\tshow_progress is the indicator for printing out the progress\n\t'''\n\t### number of SNPs\n\tp = X.shape[1]\n\t### number of genes\n\tg = mask.shape[1]\n\t### optimizing SNP layer\n\tSNP_res=BANNvarEM(X = X, y = y, centered = centered, numModels = numModels, tol = tol, maxiter = maxiter, show_progress = show_progress)\n\t### summarize weights\n\tw = rep_row(SNP_res[\"w\"], p)\n\tbH=rep_col(np.sum(SNP_res[\"w\"]*SNP_res[\"mu\"]*SNP_res[\"alpha\"], axis = 1),mask.shape[1])*mask\n\tG = leakyrelu(np.matmul(X, bH))\n\t### optimizing gene layer with normalization\n\tSNPset_res = BANNvarEM(X = G, y = y, centered = False, numModels = numModels, tol = tol, maxiter = maxiter, show_progress = show_progress)\n\t### summarize results\n\tresults = {\"SNP_res\":SNP_res, \"SNPset_res\": SNPset_res}\n\treturn results\n\n\n\n\n\n\n","repo_name":"lcrawlab/BANNs","sub_path":"BANN_numpy/BANNs_iterative.py","file_name":"BANNs_iterative.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"21899546834","text":"from typing import Optional\n\n#######################################################################\n# # Secure Provisioning SDK Exceptions\n#######################################################################\n\n\nclass SPSDKError(Exception):\n \"\"\"Secure Provisioning SDK Base Exception.\"\"\"\n\n fmt = \"SPSDK: {description}\"\n\n def __init__(self, desc: Optional[str] = None) -> None:\n \"\"\"Initialize the base SPSDK Exception.\"\"\"\n super().__init__()\n self.description = desc\n\n def __str__(self) -> str:\n return self.fmt.format(description=self.description or \"Unknown Error\")\n\n\nclass SPSDKKeyError(SPSDKError, KeyError):\n \"\"\"SPSDK standard key error.\"\"\"\n\n\nclass SPSDKValueError(SPSDKError, ValueError):\n \"\"\"SPSDK standard value error.\"\"\"\n\n\nclass SPSDKTypeError(SPSDKError, TypeError):\n \"\"\"SPSDK standard type error.\"\"\"\n\n\nclass SPSDKIOError(SPSDKError, IOError):\n \"\"\"SPSDK standard IO error.\"\"\"\n\n\nclass SPSDKNotImplementedError(SPSDKError, NotImplementedError):\n \"\"\"SPSDK standard not implemented error.\"\"\"\n\n\nclass SPSDKLengthError(SPSDKError, ValueError):\n \"\"\"SPSDK parsing error of any AHAB containers.\n\n Input/output data must be of at least container declared length bytes long.\n \"\"\"\n\n\nclass SPSDKOverlapError(SPSDKError, ValueError):\n \"\"\"Data overlap error.\"\"\"\n\n\nclass SPSDKAlignmentError(SPSDKError, ValueError):\n \"\"\"Data improperly aligned.\"\"\"\n\n\nclass SPSDKParsingError(SPSDKError):\n \"\"\"Cannot parse binary data.\"\"\"\n\n\nclass SPSDKCorruptedException(SPSDKError):\n \"\"\"Corrupted Exception.\"\"\"\n\n\nclass SPSDKUnsupportedOperation(SPSDKError):\n \"\"\"SPSDK unsupported operation error.\"\"\"\n\n\nclass SPSDKSyntaxError(SyntaxError, SPSDKError):\n \"\"\"SPSDK syntax error.\"\"\"\n\n\nclass SPSDKFileNotFoundError(FileNotFoundError, SPSDKError):\n \"\"\"SPSDK file not found error.\"\"\"\n\n\nclass SPSDKAttributeError(SPSDKError, AttributeError):\n \"\"\"SPSDK standard attribute error.\"\"\"\n\n\nclass SPSDKConnectionError(SPSDKError, ConnectionError):\n \"\"\"SPSDK standard connection error.\"\"\"\n","repo_name":"nxp-mcuxpresso/spsdk","sub_path":"spsdk/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"52"} +{"seq_id":"26170898312","text":"from sqlalchemy import Column, String, Integer, ForeignKey, Date\nfrom sqlalchemy.orm import relationship\n\nfrom src.db.connection import Base\n\n\nclass CandidacyMandate(Base):\n __tablename__ = \"candidacy_mandate\"\n\n id = Column(Integer, primary_key=True)\n entity_type = Column(String)\n label = Column(String)\n api_url = Column(String)\n id_external_administration = Column(String)\n id_external_administration_description = Column(String)\n type = Column(String)\n parliament_period_id = Column(Integer, ForeignKey(\"parliament_period.id\"))\n politician_id = Column(Integer, ForeignKey(\"politician.id\"))\n party_id = Column(Integer, ForeignKey(\"party.id\"))\n start_date = Column(Date)\n end_date = Column(Date)\n info = Column(String)\n electoral_data_id = Column(Integer, ForeignKey(\"electoral_data.id\"))\n fraction_membership_id = Column(Integer, ForeignKey(\"fraction_membership.id\"))\n\n # Many to One\n parliament_period = relationship(\n \"ParliamentPeriod\", back_populates=\"candidacy_mandates\"\n )\n politician = relationship(\"Politician\", back_populates=\"candidacy_mandates\")\n party = relationship(\"Party\", back_populates=\"candidacy_mandates\")\n\n # One to One\n electoral_data = relationship(\n \"ElectoralData\", back_populates=\"candidacy_mandate\", uselist=False\n )\n fraction_membership = relationship(\n \"FractionMembership\", back_populates=\"candidacy_mandate\", uselist=False\n )\n\n # One to Many\n committee_memberships = relationship(\n \"CommitteeMembership\", back_populates=\"candidacy_mandate\"\n )\n votes = relationship(\"Vote\", back_populates=\"candidacy_mandate\")\n\n # Many to Many\n sidejobs = relationship(\n \"Sidejob\",\n secondary=\"sidejob_has_mandate\",\n back_populates=\"candidacy_mandates\",\n )\n","repo_name":"FaceTheFacts/backend","sub_path":"src/db/models/candidacy_mandate.py","file_name":"candidacy_mandate.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"4336396955","text":"from flask_wtf import FlaskForm\nfrom wtforms import Form, StringField, SubmitField, TextAreaField, validators, BooleanField, FormField, FieldList\nfrom wtforms.validators import DataRequired, Length, Email, EqualTo, NoneOf\nimport sqlite3\n\n# Turn the results from the database into a dictionary\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\ndef get_db():\n conn = sqlite3.connect('survivor.db')\n conn.row_factory = dict_factory\n c = conn.cursor()\n\n # enforce integrity constraints \n c.execute(\"PRAGMA foreign_keys=ON;\")\n return c, conn\n\nclass RegistrationForm(FlaskForm):\n username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])\n email = StringField('Email',validators=[DataRequired(), Email()])\n # password = PasswordField('Password', validators=[DataRequired()])\n # confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])\n submit = SubmitField('Sign Up')\n\nclass BlogForm(FlaskForm):\n # username = SelectField('Username', choices=[], coerce=int)\n content = TextAreaField(validators=[DataRequired()], render_kw=dict(placeholder='Send message'))\n submit = SubmitField('Submit')\n\nclass LoginForm(FlaskForm):\n username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])\n submit = SubmitField('Submit')\n\n# class LoginForm(FlaskForm):\n# username = Select\nclass EditForm(FlaskForm):\n content = TextAreaField('Edit message', validators=[DataRequired()])\n submit = SubmitField('Submit')\n cancel_btn = SubmitField('Cancel')\n\n# delete form is just a button\nclass DelForm(FlaskForm):\n # content = TextAreaField('Edit message', validators=[DataRequired()])\n delete_btn = SubmitField('Delete')\n cancel_btn = SubmitField('Cancel')\n \n# logout form is just a button\nclass LogoutForm(FlaskForm):\n # content = TextAreaField('Edit message', validators=[DataRequired()])\n logout_btn = SubmitField('Logout')\n cancel_btn = SubmitField('Cancel')\n\n# create team form\nclass CreateTeam(FlaskForm):\n teamname = StringField('Team name', validators=[DataRequired(), Length(min=2, max=20)], render_kw=dict(placeholder='Name team'))\n submit = SubmitField('Submit')\n\n\n\n","repo_name":"MrRobboWilliamson/FantasySurvivor","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12701032748","text":"\"\"\"\nLICENSE\n\nThis file is part of Speech recognition with CTC in Keras.\nThe project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public\nLicense as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later\nversion.\nThe project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied\nwarranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with this project.\nIf not, see http://www.gnu.org/licenses/.\n\n\"\"\"\n\nfrom itertools import groupby\n\nimport numpy as np\n\nfrom text_utils import int_to_text_sequence\nfrom wer_utils import wers\n\n\ndef predict_on_batch(data_gen, test_func, batch_index):\n \"\"\"\n Produce a sample of predictions at given batch index from data in data_gen\n\n :param data_gen: DataGenerator to produce input data\n :param test_func: Keras function that takes preprocessed audio input and outputs network predictions\n :param batch_index: which batch to use as input data\n :return: List containing original transcripts and predictions\n \"\"\"\n input_data, _ = data_gen.__getitem__(batch_index)\n\n x_data = input_data.get(\"the_input\")\n y_data = input_data.get(\"the_labels\")\n\n res = max_decode(test_func, x_data)\n predictions = []\n\n for i in range(y_data.shape[0]):\n original = \"\".join(int_to_text_sequence(y_data[i]))\n predicted = \"\".join(int_to_text_sequence(res[i]))\n predictions.append([original,predicted])\n\n return predictions\n\n\ndef calc_wer(test_func, data_gen):\n \"\"\"\n Calculate WER on all data from data_gen\n\n :param test_func: Keras function that takes preprocessed audio input and outputs network predictions\n :param data_gen: DataGenerator to produce input data\n :return: array containing [list of WERs from each batch, average WER for all batches]\n \"\"\"\n out_true = []\n out_pred = []\n for batch in xrange(0, data_gen.__len__(), data_gen.batch_size):\n input_data, _ = data_gen.__getitem__(batch)\n x_data = input_data.get(\"the_input\")\n y_data = input_data.get(\"the_labels\")\n\n for i in y_data:\n out_true.append(\"\".join(int_to_text_sequence(i)))\n\n decoded = max_decode(test_func, x_data)\n for i in decoded:\n out_pred.append(\"\".join(int_to_text_sequence(i)))\n\n out = wers(out_true, out_pred)\n\n return out\n\n\ndef max_decode(test_func, x_data):\n \"\"\"\n Calculate network probabilities with test_func and decode with max decode/greedy decode\n\n :param test_func: Keras function that takes preprocessed audio input and outputs network predictions\n :param x_data: preprocessed audio data\n :return: decoded: max decoded network output\n \"\"\"\n y_pred = test_func([x_data])[0]\n\n decoded = []\n for i in range(0,y_pred.shape[0]):\n\n decoded_batch = []\n for j in range(0,y_pred.shape[1]):\n decoded_batch.append(np.argmax(y_pred[i][j]))\n\n temp = [k for k, g in groupby(decoded_batch)]\n temp[:] = [x for x in temp if x != [28]]\n decoded.append(temp)\n\n return decoded\n","repo_name":"holm-aune-bachelor2018/ctc","sub_path":"utils/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"52"} +{"seq_id":"652885807","text":"# Flipkart Items Price finder - Prints the price of the item from the URL given as arguments.\r\n\r\n#Necessary Modules\r\nimport bs4 as bs\r\nimport urllib.request\r\nimport os\r\n\r\ndef flipkart_price(url):\r\n ''' Prints the price of the Items' URLs provided as argument.'''\r\n source = urllib.request.urlopen(url).read()\r\n soup = bs.BeautifulSoup(source, 'lxml')\r\n\r\n #Getting the name of the item\r\n item_name = soup.find('p').text\r\n\r\n #Getting the price of item\r\n price = soup.find('div', class_ = '_30jeq3 _16Jk6d').text\r\n\r\n msg = \"Current price of \\\"{}\\\" is: Rs. {}/-\".format(item_name, price)\r\n print(msg)\r\n\r\n#List of URLs of items on Flipkart.\r\nmy_list = ['https://www.flipkart.com/redmi-8-onyx-black-64-gb/p/itmaf669d074ff27', \r\n'https://www.flipkart.com/puma-flip-flops/p/itme8e4bba87778c?pid=SFFFHUNYAEH5K7KC&lid=LSTSFFFHUNYAEH5K7KCMJNJGK&marketplace=FLIPKART&store=osp%2Fcil&srno=b_1_2&otracker=hp_omu_Deals%2Bof%2Bthe%2BDay_6_4.dealCard.OMU_P44HQ9IPWEIN_3&otracker1=hp_omu_SECTIONED_manualRanking_neo%2Fmerchandising_Deals%2Bof%2Bthe%2BDay_NA_dealCard_cc_6_NA_view-all_3&fm=neo%2Fmerchandising&iid=e55f055b-fb3c-4f3a-9810-f9a098386d8d.SFFFHUNYAEH5K7KC.SEARCH&ppt=browse&ppn=browse&ssid=vuxg3ldyio0000001623222842094',\r\n \r\n ]\r\n\r\nfor i in my_list:\r\n flipkart_price(i)\r\n\r\n\r\n","repo_name":"Ram-95/Python_Applications","sub_path":"Flipkart_price_finder/Flipkart_Price_Finder.py","file_name":"Flipkart_Price_Finder.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"37795773656","text":"import re\nfrom shiny import *\nfrom shinywidgets import output_widget, register_widget, render_widget\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nfrom datetime import date\n\n\ndef performance(returns):\n \"\"\"Create a table that summarizes stock performance\"\"\"\n monthly_ret = returns.copy()\n\n # Define Risk Free Rate\n risk_free_rate = 0.04\n\n # Comulative Returns\n ret_cumulative = (1 + monthly_ret).cumprod()\n\n # CAGR - Annualied Returns\n annualized_returns = (1 + monthly_ret.mean()) ** 12 - 1\n\n # Volatility\n annualied_std_deviation = monthly_ret.std() * np.sqrt(12)\n\n # Drawdown\n previous_peaks = ret_cumulative.cummax()\n drawdown = (ret_cumulative - previous_peaks) / previous_peaks\n\n # Create Summary Table\n df_risk_return = pd.DataFrame({\n \"Annualized Returns\": annualized_returns,\n \"Annualized Risk\": annualied_std_deviation,\n \"Max Drawdown\": drawdown.min() * -1\n })\n\n # Compute Sharpe Ratio\n df_risk_return['Sharpe Ratio'] = (\n df_risk_return['Annualized Returns'] - risk_free_rate) / \\\n df_risk_return['Annualized Risk']\n\n # Sort results by sharpe ratio\n df_risk_return.sort_values(\"Sharpe Ratio\", ascending=False)\n\n return df_risk_return\n\n\n\ndef plotnine_qqplot(ret):\n x = pd.DataFrame(ret)\n\n p = (ggplot(aes(sample = x)) +\n stat_qq() +\n stat_qq_line() +\n xlab(\"Theoretical Quantiles\") +\n ggtitle(\"Q-Q Plot\")\n\n )\n return p\n\n\ndef plotly_qqplot(qqplot_data):\n df_qq = pd.DataFrame({\n 'x': qqplot_data[0].get_xdata(),\n 'y': qqplot_data[0].get_ydata(),\n 'data': \"points\"\n })\n\n fig = px.scatter(df_qq, x='x', y='y',\n trendline='ols')\n fig\n\n return fig\n","repo_name":"martinbel/shiny-python","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"119897275","text":"# CREATED: 6/24/14 2:09 PM by Justin Salamon <justin.salamon@nyu.edu>\n\nimport numpy as np\nimport sklearn\nimport pickle\nimport simplejson as json\nfrom sklearn.decomposition import PCA\nfrom skm.display import visualize_clusters\n\n\nclass SKM(object):\n '''\n Class that implements the spherical k-means algorithms, including PCA\n whitening, based on: Coats & Ng, \"Learning Feature Representations with\n K-means\", 2012.\n '''\n\n __ARGS__ = ['k', 'variance_explained', 'max_epochs',\n 'assignment_change_eps', 'standardize', 'normalize',\n 'pca_whiten', 'visualize', 'do_pca']\n\n __PARAMS__ = ['k', 'variance_explained', 'epoch', 'assignment_change',\n 'max_epochs', 'assignment_change_eps', 'nfeatures',\n 'nsamples', 'D', 'assignment', 'prev_assignment', 'visualize',\n 'initialized', 'standardize', 'normalize', 'mus', 'sigmas',\n 'pca_whiten', 'do_pca']\n\n # Based on sklearn 0.15.2\n __ARGSPCA__ = ['n_components', 'copy', 'whiten']\n\n __PARAMSPCA__ = ['components_', 'explained_variance_',\n 'explained_variance_ratio_', 'mean_', 'n_components_',\n 'n_samples_', 'noise_variance_']\n\n def __init__(self, k=500, variance_explained=0.99, max_epochs=100,\n assignment_change_eps=0.01, standardize=False, normalize=False,\n pca_whiten=True, visualize=False, do_pca=True):\n\n # Initialize parameters\n self.k = k\n self.variance_explained = variance_explained\n self.epoch = 0\n self.assignment_change = np.inf\n self.max_epochs = max_epochs\n self.assignment_change_eps = assignment_change_eps\n self.nfeatures = None\n self.nsamples = None\n self.D = None # centroid dictionary\n self.assignment = None # assignment vector\n self.prev_assignment = None # previous assignment vector\n self.visualize = visualize\n self.initialized = False\n self.standardize = standardize\n self.normalize = normalize\n self.mus = None\n self.sigmas = None\n self.pca_whiten = pca_whiten\n self.do_pca = do_pca\n\n # Initialize PCA\n self.pca = PCA(n_components=self.variance_explained, copy=False, whiten=self.pca_whiten)\n\n\n def _pca_fit_transform(self, X):\n '''\n PCA fit and transform the data\n '''\n data = self.pca.fit_transform(X.T) # transpose for PCA\n return data.T # transpose back\n\n\n def _pca_fit(self, X):\n '''\n PCA fit only (don't transform the data)\n '''\n self.pca.fit(X.T)\n\n\n def _pca_transform(self, X):\n '''\n PCA transform only (must call fit or fit_transform first)\n '''\n data = self.pca.transform(X.T)\n return data.T\n\n\n def _normalize_samples(self, X):\n '''\n Normalize the features of each sample so that their values sum to one\n (might make sense for some audio data)\n '''\n data = sklearn.preprocessing.normalize(X, axis=0, norm='l1')\n return data\n\n\n def _standardize_fit(self, X):\n '''\n Compute mean and variance (of each feature) for standardization\n '''\n self.mus = np.mean(X, 1)\n self.sigmas = np.std(X, 1)\n\n\n def _standardize_transform(self, X):\n '''\n Standardize input data (assumes standardize_fit already called)\n '''\n data = X.T - self.mus\n data /= self.sigmas\n return data.T\n\n\n def _standardize_fit_transform(self, X):\n '''\n Compute means and variances (of each feature) for standardization and\n standardize\n '''\n self._standardize_fit(X)\n data = self._standardize_transform(X)\n return data\n\n\n def _init_centroids(self):\n '''\n Initialize centroids randomly from a normal distribution and normalize\n (must call _set_dimensions first)\n '''\n # Sample randomly from normal distribution\n self.D = np.random.normal(size=[self.nfeatures, self.k])\n self._normalize_centroids()\n self.initialized = True\n\n\n def _normalize_centroids(self):\n '''\n Normalize centroids to unit length (using l2 norm)\n '''\n self.D = sklearn.preprocessing.normalize(self.D, axis=0, norm='l2')\n\n # @profile\n def _update_centroids(self, X):\n '''\n Update centroids based on provided sample data X\n '''\n S = np.dot(self.D.T, X)\n # centroid_index = np.argmax(S, 0)\n centroid_index = S.argmax(0) # slightly faster\n s_ij = S[centroid_index, np.arange(self.nsamples)]\n S = np.zeros([self.k, self.nsamples])\n S[centroid_index, np.arange(self.nsamples)] = s_ij\n self.D += np.dot(X, S.T)\n self.prev_assignment = self.assignment\n self.assignment = centroid_index\n\n\n def _update_centroids_memsafe(self, X):\n '''\n Update centroids based on provided sample data X.\n Try to minimize memory usage.\n '''\n Dt = self.D.T\n centroid_index = np.zeros(X.shape[1], dtype='int')\n s_ij = np.zeros(X.shape[1])\n for n,x in enumerate(X.T):\n dotprod = np.dot(Dt, x)\n centroid_index[n] = np.argmax(dotprod)\n s_ij[n] = dotprod[centroid_index[n]]\n\n # S = np.zeros([self.k, self.nsamples])\n # S[centroid_index, np.arange(self.nsamples)] = s_ij\n # self.D += np.dot(X, S.T)\n for n in np.arange(self.k):\n s = np.zeros(X.shape[1])\n s[centroid_index==n] = s_ij[centroid_index==n]\n self.D[:,n] += np.dot(X, s)\n\n self.prev_assignment = self.assignment\n self.assignment = centroid_index\n\n # @profile\n def _update_centroids_memsafe_fast(self, X):\n '''\n Update centroids based on provided sample data X.\n Try to minimize memory usage. Use weave for efficiency.\n '''\n Dt = self.D.T\n centroid_index = np.zeros(X.shape[1], dtype='int')\n s_ij = np.zeros(X.shape[1])\n for n,x in enumerate(X.T):\n dotprod = np.dot(Dt, x)\n centroid_index[n] = np.argmax(dotprod)\n s_ij[n] = dotprod[centroid_index[n]]\n\n # S = np.zeros([self.k, self.nsamples])\n # S[centroid_index, np.arange(self.nsamples)] = s_ij\n # self.D += np.dot(X, S.T)\n S = np.zeros([self.nsamples, self.k])\n S[np.arange(self.nsamples), centroid_index] = s_ij\n self.D += np.dot(X, S)\n\n # for n in np.arange(self.k):\n # s = np.zeros(X.shape[1])\n # s[centroid_index==n] = s_ij[centroid_index==n]\n # self.D[:,n] += np.dot(X, s)\n\n # nfeatures = X.shape[0]\n # nsamples = X.shape[1]\n # s = np.zeros(nsamples)\n # k = self.k\n # D = self.D\n # dotproduct_command = r\"\"\"\n # for (int n=0; n<k; n++)\n # {\n # for (int m=0; m<nsamples; m++)\n # {\n # if (centroid_index[m]==n)\n # s[m] = s_ij[m];\n # else\n # s[m] = 0;\n # }\n #\n # for (int f=0; f<nfeatures; f++)\n # {\n # float sum = 0;\n # for (int i=0; i<nsamples; i++)\n # {\n # sum += X[f*nsamples + i] * s[i];\n # }\n # D[f*k + n] += sum;\n # }\n # }\n # \"\"\"\n # scipy.weave.inline(dotproduct_command, ['k','nsamples','centroid_index','s','s_ij','nfeatures','X','D'])\n\n self.prev_assignment = self.assignment\n self.assignment = centroid_index\n\n\n # def _update_centroids_cuda(self, X):\n # '''\n # Update centroids based on provided sample data X using GPU via cuda\n # '''\n # # S = np.dot(self.D.T, X)\n # Xcuda = cm.CUDAMatrix(X)\n # S = cm.dot(cm.CUDAMatrix(self.D).T, Xcuda)\n # # centroid_index = S.argmax(0) # slightly faster\n # centroid_index = S.asarray().argmax(axis=0)\n # # s_ij = S[centroid_index, np.arange(self.nsamples)]\n # s_ij = S.asarray()[centroid_index, np.arange(self.nsamples)]\n # S = np.zeros([self.nsamples, self.k])\n # # S[centroid_index, np.arange(self.nsamples)] = s_ij\n # S[np.arange(self.nsamples), centroid_index] = s_ij\n # self.D += cm.dot(Xcuda, cm.CUDAMatrix(S)).asarray()\n # self.prev_assignment = self.assignment\n # self.assignment = centroid_index\n\n\n def _init_assignment(self):\n '''\n Initialize assignment of samples to centroids (must call _set_dimensions\n first)\n '''\n self.prev_assignment = np.zeros(self.nsamples) - 1\n self.assignment = None\n\n\n def _set_dimensions(self, X):\n '''\n Set dimensions (number of features, number of samples) based on\n dimensions of input data X\n '''\n self.nfeatures, self.nsamples = X.shape\n\n\n def _compute_assignment_change(self):\n '''\n Compute the fraction of assignments changed by the latest centroid\n update (value between 0 to 1)\n '''\n self.assignment_change = np.mean(self.assignment != self.prev_assignment)\n\n\n def _report_status(self):\n '''\n Print current epoch and assignment change fraction\n '''\n print(\"EPOCH: {:d} CHANGE: {:.4f}\".format(self.epoch, self.assignment_change))\n\n\n def fit(self, X, memsafe=False, cuda=False):\n '''\n Fit k centroids to input data X until convergence or max number of\n epochs reached.\n '''\n\n # Normalize data (per sample)\n if self.normalize:\n X = self._normalize_samples(X)\n\n # Standardize data (across samples)\n if self.standardize:\n X = self._standardize_fit_transform(X)\n\n # PCA fit and whiten the data\n if self.do_pca:\n X = self._pca_fit_transform(X)\n\n # Store dimensions of whitened data\n self._set_dimensions(X)\n\n # Initialize centroid dictionary\n self._init_centroids()\n\n # Initialize assignment\n self._init_assignment()\n\n if self.visualize:\n visualize_clusters(self, X)\n\n # Iteratively update and normalize centroids\n while self.epoch < self.max_epochs and self.assignment_change > self.assignment_change_eps:\n if memsafe:\n self._update_centroids_memsafe_fast(X)\n # elif cuda:\n # self._update_centroids_cuda(X)\n else:\n self._update_centroids(X)\n self._normalize_centroids()\n self._compute_assignment_change()\n self.epoch += 1\n # self._report_status()\n if self.visualize:\n visualize_clusters(self, X)\n\n\n def fit_minibatch(self, X):\n '''\n Fit k centroids to input data X until convergence or max number of\n epochs reached. Assumes X is a mini-batch from a larger sample set.\n The first batch is used to initialize the algorithm (dimensions).\n '''\n\n # Normalize data (per sample)\n if self.normalize:\n X = self._normalize_samples(X)\n\n # If this is the first batch, use it to initialize\n if not self.initialized:\n # Standardize data\n if self.standardize:\n X = self._standardize_fit_transform(X)\n # PCA whiten the data\n X = self._pca_fit_transform(X)\n # Store dimensions of whitened data\n self._set_dimensions(X)\n # Initialize centroid dictionary\n self._init_centroids()\n # Initialize assignment\n self._init_assignment()\n else:\n if self.standardize:\n X = self._standardize_transform(X)\n X = self._pca_transform(X)\n # Reset epochs and assignments\n self.epoch = 0\n self._init_assignment()\n self.assignment_change = np.inf\n\n # Iteratively update and normalize centroids\n while self.epoch < self.max_epochs and self.assignment_change > self.assignment_change_eps:\n self._update_centroids(X)\n self._normalize_centroids()\n self._compute_assignment_change()\n self.epoch += 1\n self._report_status()\n if self.visualize:\n self._visualize_clusters(X)\n\n\n def transform(self, X, rectify=False, nHot=0):\n '''\n Transform samples X (each column is a feature vector) to learned feature\n space\n '''\n # print(\"DEBUG: entered skm.transform\")\n # Normalize data (per sample)\n if self.normalize:\n X = self._normalize_samples(X)\n\n # Standardize data (across samples)\n if self.standardize:\n X = self._standardize_fit_transform(X)\n\n # print(\"DEBUG: skipped normalized/standardize\")\n\n # PCA whiten\n X = self._pca_transform(X)\n # X = np.random.rand(149, 173)\n # print(\"DEBUG: did PCA\")\n\n # Dot product with learned dictionary\n X = np.dot(X.T, self.D)\n # print(\"DEBUG: did dot product\")\n\n if rectify:\n X = np.maximum(X, 0)\n\n # x-hot coding instead of just dot product\n if nHot > 0:\n indices = np.argsort(X)\n for n,x in enumerate(X):\n x[indices[n][0:-nHot]] = 0\n x[indices[n][-nHot:]] = 1\n\n return X.T\n\n\n def save(self, filepath):\n '''\n Save instance of SKM class to given filepath as pickle file\n '''\n with open(filepath, 'wb') as file:\n pickle.dump(self, file)\n file.close()\n\n\n def load(self, filepath):\n '''\n Load skm instance from disk (saved as pickle file)\n '''\n with open(filepath, 'rb') as file:\n skm = pickle.load(file)\n file.close()\n\n return skm\n\n\n @classmethod\n def load_persistent_npzhack(cls, arg_file, param_file=None):\n \"\"\"Alternate class constructor, from files.\n\n Parameters\n ----------\n arg_file : str\n Path to a JSON file of arguments.\n param_file : str, default=None\n Path to a numpy archive (npz) file of parameters, or create a\n similar object without parameters.\n\n Returns\n -------\n skm : SKM\n The instantiated object.\n \"\"\"\n args_all = json.load(open(arg_file))\n params_all = np.load(param_file) if param_file else dict()\n\n skm = cls(**args_all['args'])\n if 'params' in params_all.keys():\n # params = np.asscalar(params_all['params'])\n params = params_all['params'][()]\n for key in params:\n setattr(skm, key, params[key])\n\n pca = PCA(**args_all['args_pca'])\n if 'params_pca' in params_all.keys():\n # params_pca = np.asscalar(params_all['params_pca'])\n params_pca = params_all['params_pca'][()]\n for key in params_pca:\n setattr(pca, key, params_pca[key])\n\n skm.pca = pca\n return skm\n\n\n @classmethod\n def load_persistent(cls, arg_file, param_file=None):\n \"\"\"Alternate class constructor, from files.\n\n Parameters\n ----------\n arg_file : str\n Path to a JSON file of arguments.\n param_file : str, default=None\n Path to a numpy archive (npz) file of parameters, or create a\n similar object without parameters.\n\n Returns\n -------\n skm : SKM\n The instantiated object.\n \"\"\"\n json_dict = json.load(open(arg_file))\n npz_dict = np.load(param_file) if param_file else dict()\n\n # Extract and set all data from JSON file\n skm = cls(**json_dict['args'])\n for key in json_dict['params']:\n setattr(skm, key, json_dict['params'][key])\n\n pca = PCA(**json_dict['args_pca'])\n for key in json_dict['params_pca']:\n setattr(pca, key, json_dict['params_pca'][key])\n\n # Extract and set all data from npz file (ndarrays)\n for key in npz_dict.keys():\n if \"pca.\" in key:\n setattr(pca, key.replace(\"pca.\", \"\"), npz_dict[key])\n else:\n setattr(skm, key, npz_dict[key])\n\n skm.pca = pca\n return skm\n\n\n @property\n def params(self):\n return dict([(k, getattr(self, k)) for k in SKM.__PARAMS__ if hasattr(self, k)])\n\n @property\n def params_pca(self):\n return dict([(k, getattr(self.pca, k)) for k in SKM.__PARAMSPCA__ if hasattr(self.pca, k)])\n\n @property\n def args(self):\n return dict([(k, getattr(self, k)) for k in SKM.__ARGS__ if hasattr(self, k)])\n\n @property\n def args_pca(self):\n return dict([(k, getattr(self.pca, k)) for k in SKM.__ARGSPCA__ if hasattr(self.pca, k)])\n\n\n def save_persistent_npzhack(self, arg_file, param_file):\n # save skm arguments and parameters\n with open(arg_file, 'w') as fp:\n d = {}\n d['args'] = self.args\n d['args_pca'] = self.args_pca\n json.dump(d, fp, indent=2)\n\n p = {}\n p['params'] = self.params\n p['params_pca'] = self.params_pca\n np.savez(param_file, **p)\n\n\n def save_persistent(self, arg_file, param_file):\n\n # Save all nd-arrays into the npz\n # Save all non-ndarray attributes as JSON\n with open(arg_file, 'w') as fp:\n\n json_dict = {}\n json_dict['args'] = self.args\n json_dict['args_pca'] = self.args_pca\n\n params_skm = self.params\n params_pca = self.params_pca\n\n npz_dict = {}\n\n # find the ndarrays in skm and store them separately\n # for k in params_skm.keys():\n for k in list(params_skm):\n if type(params_skm[k]) is np.ndarray:\n npz_dict[k] = params_skm[k]\n params_skm.pop(k)\n\n # store all remaining non-ndarray attributes as json\n json_dict['params'] = params_skm\n\n # find the ndarrays in pca and store them separately\n # for k in params_pca.keys():\n for k in list(params_pca):\n if type(params_pca[k]) is np.ndarray:\n npz_dict['pca.'+k] = params_pca[k]\n params_pca.pop(k)\n\n # store all remaining non-ndarray attributes as json\n json_dict['params_pca'] = params_pca\n\n\n # save json_dict to disk\n # fix for json floats\n json_dict['params_pca']['noise_variance_'] = round(float(json_dict['params_pca']['noise_variance_']), 15)\n # fix int64\n for key in json_dict['params_pca'].keys():\n if type(json_dict['params_pca'][key]) is np.int64:\n json_dict['params_pca'][key] = int(json_dict['params_pca'][key])\n # print json_dict\n json.dump(json_dict, fp, indent=2)\n\n # save all ndararys (npz_dict) to disk\n np.savez(param_file, **npz_dict)\n\n\n\n\n\ndef spherical_kmeans_viz(X_raw, k):\n '''\n Given data input X (each column is a datapoint, number of rows if\n dimensionality of the data), and desired number of means k, compute the\n means (dictionary D) and cluster assignment S using the spherical k-means\n algorithm (cf. Coats & NG, 2012)\n\n Data is assumed to be normalized.\n '''\n\n # Step 1: whiten inputs using PCA\n n_components = 0.99 # explain 99% of the variance\n pca = PCA(n_components=n_components, copy=True, whiten=True)\n X = pca.fit_transform(X_raw.T)\n X = X.T\n # X = X_raw\n\n dim, N = X.shape\n # print X.shape\n\n # Step 2: k-means\n # Step 2.1: initialize dictionary D\n D = np.random.normal(size=[dim,k]) # sample randomly from normal distribution\n D = sklearn.preprocessing.normalize(D, axis=0, norm='l2') # normalize centroids\n # print 'D.shape', D.shape\n\n # Step 2.2: initialize code vectors (matrix) S\n\n # Step 2.2: update until convergence\n epoc = 0\n max_epocs = 100\n change = np.inf\n change_eps = 0.001\n prev_index = np.zeros(N)\n while epoc < max_epocs and change > change_eps:\n S = np.dot(D.T,X)\n # print 'S.shape', S.shape\n centroid_index = np.argmax((S), 0) # np.abs? NO!\n # print 'centroid_index.shape', centroid_index.shape\n s_ij = S[centroid_index, np.arange(N)] # dot products already calculated\n S = np.zeros([k,N])\n S[centroid_index, np.arange(N)] = s_ij\n D += np.dot(X,S.T)\n D = sklearn.preprocessing.normalize(D, axis=0, norm='l2') # normalize\n\n # Compute change\n change = np.mean(centroid_index != prev_index)\n prev_index = centroid_index\n epoc += 1\n print(\"EPOC: {:d} CHANGE: {:.4f}\".format(epoc,change))\n\n # # Visualize clustering\n # pl.figure()\n # colors = ['b','r','g', 'c', 'm', 'y', 'k']\n # for n,point in enumerate(X.T):\n # pl.plot(point[0],point[1], colors[centroid_index[n]] + 'o')\n # pl.axhline(0, color='black')\n # pl.axvline(0, color='black')\n # for n,centroid in enumerate(D.T):\n # # centroid = pca.inverse_transform(centroid)\n # pl.plot(centroid[0],centroid[1],colors[n] + 'x')\n # pl.show()\n\n","repo_name":"justinsalamon/skm","sub_path":"skm/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":21482,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"36686342334","text":"from geopy.distance import geodesic\nimport datetime\nimport numpy as np\n\n\ndef find_max_in_dict(dictionary):\n \"\"\"\n Find the maximum value in a dictionary\n :param dictionary: dictionary to use\n :return: max key from dictionary\n \"\"\"\n max_key = ''\n max_value = 0\n for key in dictionary.keys():\n value = dictionary[key]\n if value > max_value:\n max_key = key\n return max_key\n\n\ndef sort_dictionary(dictionary):\n \"\"\"\n Sorts a dictionary by value\n :param dictionary: dictionary to be sorted\n :return: sorted dictionary by key\n \"\"\"\n sorted_values = sorted(dictionary.values()) # Sort the values\n sorted_dict = {}\n for i in sorted_values:\n for k in dictionary.keys():\n if dictionary[k] == i:\n sorted_dict[k] = dictionary[k]\n break\n return sorted_dict\n\n\ndef get_head_of_dict(dictionary, length):\n \"\"\"\n Gets the head of dictionary\n :param dictionary: dictionary to get head of\n :param length: size of head\n :return: top of dictionary of size length\n \"\"\"\n head = {}\n for x in range(length):\n key = list(dictionary.keys())[x]\n head[key] = dictionary[key]\n return head\n\n\ndef str_to_coordinates(str_coordinates):\n \"\"\"\n Converts comma separated coordinates to dictionary object of coordinates\n :param str_coordinates: comma separated (no spaces) coordinates in str tag\n :return: dictionary {lat:[latitude], 'lng':[longitude]}\n \"\"\"\n return {'lat': str_coordinates.split(\" \")[0], 'lng': str_coordinates.split(\" \")[1]}\n\n\ndef convert_to_datetime(start_time, end_time, date):\n \"\"\"\n Converts string start_time, end_time and date into datetime objects\n :param start_time: String start time\n :param end_time: String end time\n :param date: String date in format DDMMYYYY\n :return: start_time and end_time with dates in datetime format\n \"\"\"\n try:\n _format_str = '%d%m%Y%H:%M'\n # should be in format DDMMYYYY\n _date_str = date\n start = datetime.datetime.strptime(_date_str + start_time,\n _format_str)\n end = datetime.datetime.strptime(_date_str + end_time, _format_str)\n if start.time() > end.time():\n end = end + datetime.timedelta(days=1)\n return start, end\n # converts date and time into datetime object\n\n except Exception as e:\n print('Error when transferring into datetime object')\n print('Probably invalid format for conversion')\n print(e)\n\n\ndef api_to_timings(periods):\n days = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']\n opening = {}\n closing = {}\n for i, day in enumerate(periods):\n close = day['close']\n open = day['open']\n opening[days[i]] = open['time']\n closing[days[i]] = close['time']\n return opening, closing\n\n\ndef date_str_to_weekday(date):\n \"\"\"\n Converts date to weekday as MON, TUE, WED ...\n :param date: date as string\n :return: day of week as MON, TUE, WED, THU, ...\n \"\"\"\n format_str = \"%d%m%Y\"\n d = datetime.datetime.strptime(date, format_str)\n return d.strftime(\"%a\").upper()\n\n\ndef get_distance_between_coords(current_location, y_coordinates):\n \"\"\"\n Gets distance as crow flies between two addresses\n\n :param current_location: Users current location in coordinates\n :param y_coordinates: location to travel to in coordinates\n :return: Distance in miles between coordinates\n \"\"\"\n # use geopy geodesic module to get distance in miles and return it to function call\n return geodesic((y_coordinates['lat'], y_coordinates['lng']),\n (current_location['lat'], current_location['lng'])).miles\n\n\ndef delete_duplicates(all_venues, venues_to_delete):\n \"\"\"\n Deletes all venues in used_venues from new_venues\n :param all_venues: all venues as list of venue objects\n :param venues_to_delete: venues to delete as list of venue objects\n :return: all_venues without venues_to_delete\n \"\"\"\n return_list = []\n ids = [x.get_id for x in venues_to_delete]\n for venue in all_venues:\n if venue.get_id not in ids:\n return_list.append(venue)\n\n return return_list\n\n\ndef db_to_type(type, restaurant, club):\n \"\"\"\n Turns tag, restaurant and club attributes into 5 bit code to identify categories of venues\n :param type: tag of venue string\n :param restaurant: boolean value as to whether the venue is a restaurant or not\n :param club: boolean value as to whether the venue is a club or not\n :return: 5 bit code of tag of venue\n \"\"\"\n type_to_bin = {'pub': '000', 'bar': '001', 'club': '010', 'other': '011', 'live': '100'}\n return type_to_bin[type.lower()] + str(restaurant) + str(club)\n\n\ndef str_to_vector(vector_str):\n \"\"\"\n turns string from DB to numpy matrix\n :param vector_str: string of vector. Values space separated\n :return: numpy matrix of (1, 300) of vector\n \"\"\"\n vector_str = vector_str.split(' ')\n vec = ''\n for val in vector_str:\n if val == '':\n continue\n else:\n vec = vec + ' ' + val\n return np.array([float(x) for x in vec.split(' ')[1:]]).reshape(1, 300)\n","repo_name":"benlongcroft/Nitely-Code-Base","sub_path":"nitely_core/Toolbox.py","file_name":"Toolbox.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13495239021","text":"usr = input(\"Do you want to convert c to f or f to c (c/f) \")\r\n\r\ndef Celcius():\r\n celcius = int(input(\"Enter temperature in Degrees Celcius: \"))\r\n celcius = celcius * 0.55555555555\r\n celcius = celcius + 32\r\n print(f\"{celcius} degrees farenheit\")\r\n\r\n\r\n\r\n\r\ndef Fareheit():\r\n farenheit = int(input(\"Enter temperature in Degrees Fareheit: \"))\r\n farenheit = farenheit - 32\r\n farenheit = farenheit * 0.55555555555\r\n print(f\"{farenheit} degrees celcius\")\r\n\r\n\r\n\r\n\r\n\r\nif usr == \"c\":\r\n Celcius()\r\nelif usr == \"f\":\r\n Fareheit()\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"JamesBradleyBigCreative/Classroom_Exercises","sub_path":"Haitham Mohammed/Temperature/Temperature.py","file_name":"Temperature.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"3822709090","text":"\n\nclass Employee():\n\n\n def __init__(self, years_exp, position_name, employee_name):\n self.years_exp = years_exp\n self.position_name = position_name\n self. employee_name = employee_name\n\n\n def calculate_salary(self):\n salary = 2500\n if self.years_exp >= 0 and self.years_exp <= 2:\n salary += 1500\n elif self.years_exp > 2 and self.years_exp <= 5:\n salary += 2500\n elif self.years_exp > 5:\n salary += 3500\n else:\n print(\"Invalid information.\")\n print(\"The salary for %s is %s\" %(self.employee_name, salary))\n return salary\n\n\n def candidate_for_bonus(self, salary):\n if \"front-end\" in self.position_name and self.years_exp <= 2:\n salary = salary + 1/10*salary\n elif self.years_exp > 2:\n salary = salary + 2/10*salary\n else:\n print(\"%s can't get bonus.\" %self.employee_name)\n print(\"The salary with the bonus for %s is %s\" %(self.employee_name, salary))\n return salary\n\n\nclass Programmer (Employee):\n\n def __init__(self, years_exp, position_name, employee_name, years_old):\n self.years_exp = years_exp\n self. position_name = position_name\n self.employee_name = employee_name\n self.years_old = years_old\n super().__init__(years_exp, position_name, employee_name)\n\n\n def programmer_info(self):\n print(\"The name of the programmer is %s, he is %s years old and his position is %s.\" %(self.employee_name, self.years_old, self.position_name))\n\n\nemployee1 = Employee(1, \"front-end\", \"Joseph\")\nemployee2 = Employee(6, \"senior_devops\", \"Dan\")\nemployee3 = Programmer(3, \"back-end\", \"Rick\", 28)\nprint(\"\\n\")\nemp1_salary = employee1.calculate_salary()\nemployee1.candidate_for_bonus(emp1_salary)\nprint(\"\\n\")\nemp2_salary = employee2.calculate_salary()\nemployee2.candidate_for_bonus(emp2_salary)\nprint(\"\\n\")\nemployee3.programmer_info()\nemp3_salary = employee3.calculate_salary()\nemployee3.candidate_for_bonus(emp3_salary)\nprint(\"\\n\")\n","repo_name":"Raycho01/Basic-Python-Programs","sub_path":"project_9.py","file_name":"project_9.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41879538068","text":"from bisect import bisect_left\nN=int(input())\nWH=[list(map(int, input().split())) for _ in range(N)]\ndp = [float(\"inf\")] * N\nsortwh = sorted(WH, key=lambda x: (x[0], -x[1]))\nfor h,w in sortwh:\n ind = bisect_left(dp, w)\n dp[ind] = w\nfor i in reversed(range(N)):\n if dp[i] < float(\"inf\"):\n print(i+1)\n exit()","repo_name":"tokumaru-y/competitive_program_python","sub_path":"antBook/re_solve/200/33.py","file_name":"33.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74791911204","text":"class A:\r\n def __init__(self,*args):\r\n print(f\"{A.__name__} class executed\")\r\n self.a=args[0]\r\n self.b=args[1]\r\n def __str__(self):\r\n return f\"{self.a} and {self.b}\"\r\n\r\nclass B(A):\r\n def __init__(self,*args):\r\n super().__init__(*args)\r\n self.c=args[2]\r\n print(f\"{B.__name__} executed\")\r\n\r\n def __str__(self):\r\n return f\"{self.a},{self.b} and {self.c}\"\r\n \r\n\r\n\r\nif __name__==\"__main__\":\r\n m=B(1,2,3)\r\n print(m.__dict__)\r\n print(m)\r\n a=A(1,2)\r\n print(a.__dict__)\r\n print(a)\r\n\r\n","repo_name":"babiswas/Python-Design-Patterns","sub_path":"testC4.py","file_name":"testC4.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25066986866","text":"import random\nimport string\n\n\ndef keygen(size=15, chars=string.ascii_letters + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef create_key(instance, size=15):\n new_keygen = keygen(size=size)\n EmailAppClass = instance.__class__\n qs_exists = EmailAppClass.objects.filter(secret=new_keygen).exists()\n\n if qs_exists:\n return create_key(size=size)\n\n return new_keygen\n","repo_name":"mansonul/events","sub_path":"config/key_generator.py","file_name":"key_generator.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27035076951","text":"import random\r\nsuits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\r\nranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\r\nvalues = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':11, 'Queen':12, 'King':13, 'Ace':1}\r\nclass Card:\r\n \r\n def __init__(self,suit,rank):\r\n self.suit = suit\r\n self.rank = rank\r\n \r\n def __str__(self):\r\n return self.rank+' of '+self.suit\r\nclass Deck:\r\n \r\n def __init__(self):\r\n self.deck = [] # start with an empty list\r\n for suit in suits:\r\n for rank in ranks:\r\n self.deck.append(Card(suit,rank))\r\n \r\n def __str__(self):\r\n deck_comp = ''\r\n for card in self.deck:\r\n deck_comp += '\\n' + card.__str__()\r\n return \"The deck has: \" + deck_comp\r\n\r\n def shuffle(self):\r\n random.shuffle(self.deck)\r\n \r\n def deal(self):\r\n single_card = self.deck.pop()\r\n return single_card\r\nclass Hand:\r\n def __init__(self,name):\r\n self.cards = [] # start with an empty list as we did in the Deck class\r\n self.fours = [] #how many fours there are in a hand\r\n self.name = name\r\n \r\n def add_card(self,card):\r\n #Card passed in from Deck.deal()\r\n self.cards.append(card)\r\n \r\n def check_four(self):\r\n for rank in ranks:\r\n count = []\r\n for card in self.cards:\r\n if card.rank == rank:\r\n count.append(card)\r\n if len(count) == 4:\r\n for card in count:\r\n self.cards.remove(card)\r\n self.fours.append(rank)\r\n print('\\n' + self.name.upper() + 'HAS COMPLETED A SET OF FOUR WITH ' + rank.upper() + 'S!\\n')\r\n else:\r\n count = []\r\n \r\n def fin(self):\r\n print(self.name.upper() + \"'S SETS OF FOURS\\n\")\r\n if len(self.fours) > 0:\r\n for four in self.fours:\r\n print(four)\r\n else:\r\n print(\"FISHING FAILURE\\n\")\r\n \r\n def sort(self):\r\n newlist = []\r\n while self.cards != []:\r\n greatest = 0\r\n greatcard = None\r\n for card in self.cards:\r\n value = values[card.rank]\r\n if value > greatest:\r\n greatest = value\r\n greatcard = card\r\n newlist.append(greatcard)\r\n self.cards.remove(greatcard)\r\n self.cards = newlist\r\n \r\n def __str__(self):\r\n hand_comp = ''\r\n for card in self.cards:\r\n hand_comp += '\\n' + card.__str__()\r\n return '\\n' + self.name + \"'s hand consists of \" + hand_comp + '\\n'\r\ndef showcards(numPlayers, player,player1,player2,player3,player4):\r\n print(player,end='\\n')\r\n if player != player1:\r\n print(player1.name + ' has ' + str(len(player1.cards)) + ' cards.\\n')\r\n if player != player2:\r\n print(player2.name + ' has ' + str(len(player2.cards)) + ' cards.\\n')\r\n if numPlayers > 2 and player != player3:\r\n print(player3.name + ' has ' + str(len(player3.cards)) + ' cards.\\n')\r\n if numPlayers > 3 and player != player4:\r\n print(player4.name + ' has ' + str(len(player4.cards)) + ' cards.\\n')\r\ndef fishing(player1,player2,rank,deck):\r\n count = 0\r\n for card in player2.cards:\r\n if card.rank == rank:\r\n player1.cards.append(card)\r\n player2.cards.remove(card)\r\n player1.sort()\r\n count += 1\r\n if count > 0:\r\n print('\\n' + player1.name + ' has fished ' + str(count) + ' ' + rank + '(s) from ' + player2.name)\r\n return True\r\n else: \r\n player1.cards.append(deck.deal())\r\n player1.sort()\r\n return False\r\ndef askingfish(player,players,player1,player2,player3,player4,numPlayers):\r\n if numPlayers == 2:\r\n if player == player1:\r\n fishperson = player2\r\n elif player == player2:\r\n fishperson = player1\r\n \r\n else:\r\n while True:\r\n fish = input(\"Who would you like to 'fish' from, \" + player.name + '? ')\r\n if fish == player.name or fish not in players:\r\n print('Please enter a valid player')\r\n else:\r\n if fish == player1.name:\r\n fishperson = player1\r\n elif fish == player2.name:\r\n fishperson = player2\r\n elif fish == player3.name:\r\n fishperson = player3\r\n elif fish == player4.name:\r\n fishperson = player4\r\n break\r\n return fishperson\r\ndef askingrank(player):\r\n while True:\r\n rank = input(\"What card rank would you like to steal? \")\r\n rank.capitalize()\r\n rankin = False\r\n for card in player:\r\n if card.rank == rank:\r\n rankin = True\r\n if rank not in ranks or rankin:\r\n print('Please enter a valid rank')\r\n else:\r\n return rank\r\n break\r\nwhile True:\r\n deck = Deck()\r\n deck.shuffle()\r\n order = 1\r\n print(\"Hello and Welcome to Mika's Go Fish Game!\")\r\n print('Other games by Mika: Blackjack, Roll the Pig, Hangman\\n')\r\n print('Players start with 7 cards each, with minimum 2 and maximum 4 players.\\nThe objective of the game is to get the most sets of 4 cards, like 4 Aces.')\r\n print(\"During their turn, a player can choose another player to go 'fishing' from.\")\r\n print(\"While 'fishing', a player picks a certain rank (ex: ace),\\nand if the player they chose has one or more of that rank,\")\r\n print(\"that player gives all their cards of that rank to the player 'fishing'.\\nIf not, the player 'fishing' draws a card from the deck.\\n\\n\")\r\n \r\n while True:\r\n try:\r\n numPlayers = int(input(\"How many people are playing? \"))\r\n except: \r\n print('Please enter a valid number')\r\n else:\r\n if numPlayers > 4 or numPlayers < 2:\r\n print('Please enter a valid number')\r\n else:\r\n break\r\n forbiddenames = []\r\n name1 = input(\"What would you like to be called, Player 1? \")\r\n if name1 in forbiddenames:\r\n name1 == \"Player 1\"\r\n forbiddenames.append(name1)\r\n name2 = input(\"What would you like to be called, Player 2? \")\r\n if name2 in forbiddenames:\r\n name2 == \"Player 2\"\r\n forbiddenames.append(name2)\r\n if numPlayers > 2:\r\n name3 = input(\"What would you like to be called, Player 3? \")\r\n if name3 in forbiddenames:\r\n name3 == \"Player 3\"\r\n forbiddenames.append(name3)\r\n if numPlayers > 3:\r\n name4 = input(\"What would you like to be called, Player 4? \")\r\n if name4 in forbiddenames:\r\n name4 == \"Player 4\"\r\n forbiddenames.append(name4)\r\n player1 = Hand(name1)\r\n player2 = Hand(name2)\r\n players = [player1,player2]\r\n if numPlayers > 2:\r\n player3 = Hand(name3)\r\n players.append(player3)\r\n if numPlayers > 3:\r\n player4 = Hand(name4)\r\n players.append(player4)\r\n for player in range(1,numPlayers+1):\r\n if player == 1:\r\n current = player1\r\n elif player == 2:\r\n current = player2\r\n elif player == 3:\r\n current = player3\r\n elif player == 4:\r\n current = player4\r\n for i in range(1,8):\r\n current.add_card(deck.deal())\r\n for player in players:\r\n player.sort()\r\n while len(deck.deck) > 0:\r\n if order % numPlayers == 1:\r\n active = player1\r\n elif order % numPlayers == 2:\r\n active = player2\r\n elif order % numPlayers == 3:\r\n active = player3\r\n elif order % numPlayers == 0:\r\n if numPlayers == 2:\r\n active = player2\r\n elif numPlayers == 3:\r\n active = player3\r\n elif numPlayers == 4:\r\n active = player4\r\n fishy = True\r\n print('\\n' + active.name.upper() + \"'S TURN\")\r\n quit = input(\"Would you like to quit the game? \")\r\n if 'yes' in quit:\r\n deck.deck = []\r\n fishy = False\r\n while fishy:\r\n showcards(numPlayers,active,player1,player2,player3,player4)\r\n fish = askingfish(active,players,player1,player2,player3,player4,numPlayers)\r\n rank = askingrank(active)\r\n fishy = fishing(active,fish,rank,deck)\r\n active.check_four()\r\n if fishy:\r\n print('Go again, ' + active.name)\r\n else:\r\n print(\"Go fish, \" + active.name + \", your turn is over.\")\r\n break\r\n order += 1\r\n \r\n print(\"\\nSETS OF FOUR\")\r\n player1.fin()\r\n player2.fin()\r\n if numPlayers > 2:\r\n player3.fin()\r\n if numPlayers > 3:\r\n player4.fin()\r\n \r\n # check who wins\r\n if len(player1.fours) > len(player2.fours):\r\n winner = [player1]\r\n highest = len(player1.fours)\r\n elif len(player1.fours) < len(player2.fours):\r\n winner = [player2]\r\n highest = len(player2.fours)\r\n else:\r\n winner = [player1,player2]\r\n highest = len(player1.fours)\r\n if numPlayers > 2:\r\n if len(player3.fours) > highest:\r\n winner = [player3]\r\n elif len(player3.fours) == highest:\r\n winner.append(player3)\r\n if numPlayers > 3:\r\n if len(player4.fours) > highest:\r\n winner = [player4]\r\n elif len(player4.fours) == highest:\r\n winner.append(player4)\r\n \r\n if len(winner) == numPlayers:\r\n print(\"\\nTIE GAME\")\r\n elif len(winner) != numPlayers and len(winner) > 1:\r\n print(\"\\nTIE WIN; \",end=\"\")\r\n count = 0\r\n for person in winner:\r\n print(person.name.upper,end=\"\")\r\n if count + 1 == len(winner):\r\n print(\" and \",end=\"\")\r\n count += 1\r\n print(\" WIN!\")\r\n elif len(winner) == 1:\r\n print(winner[0].name.upper() + \" WINS!\")\r\n \r\n new_game = input(\"\\nWould you like to play another hand? \")\r\n if 'yes' in new_game.lower():\r\n deck = Deck()\r\n continue\r\n else:\r\n print(\"Please come visit us at Mika's Go Fish Game (or another of Mika's games) again soon!\")\r\n break\r\n\r\n","repo_name":"mika-okamoto/Past-Python-Projects","sub_path":"Go Fish.py","file_name":"Go Fish.py","file_ext":"py","file_size_in_byte":10529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7103451924","text":"# Extract the title and references of papers stored in .txt format\n#\n# How to use\n# Argument: a directory containing the paper's text files\n\nimport errno\nimport os\nimport sys\n\ndef referenceParse( line ):\n year = \"\"\n title = \"\"\n valid = False\n i = 0\n while i < len(line) - 4:\n if line[i:i+4].isdigit():\n year = line[i:i+4]\n i = i + 6\n valid = True\n break\n else:\n i = i + 1\n\n if valid:\n dot = line[i:].find('.')\n if dot != -1:\n title = line[i : i + dot]\n if year and title:\n return title + '\\n' + year\n else:\n return \"\"\n return \"\"\n\ndef extractReferences(filename):\n try:\n with open(filename, 'r') as f:\n my_title = f.readline()\n begin_references = False\n references = \"\"\n for line in f:\n if len(line)>10:\n if begin_references:\n title_year = referenceParse(line)\n if title_year != \"\":\n references += title_year + '\\n'\n if line.startswith('References') or line.startswith('REFERENCES') or line.startswith('BIBLIOGRAPHY'):\n begin_references = True\n with open(filename[:-4] + '-references.txt', 'w') as out:\n out.write(references)\n except Exception as e:\n print ('Error in file ' + filename)\n print (e)\n\nwork_dir = sys.argv[1]\nfor file in next(os.walk(work_dir))[2]:\n if file[-4:] == '.txt' and file[-10:] != 'header.txt' and file[-14:] != 'references.txt':\n print(file)\n extractReferences(work_dir + '/' + file)\n","repo_name":"duonghoangthai/siggraphpubvis","sub_path":"DataMiningScripts/referenceExtract.py","file_name":"referenceExtract.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8084107653","text":"import jinja2\nfrom typing import List\n\nfrom minerl.herobraine.hero.handlers.translation import KeymapTranslationHandler, TranslationHandlerGroup\nimport minerl.herobraine.hero.mc as mc\nfrom minerl.herobraine.hero import spaces\nimport numpy as np\n\n__all__ = ['ObservationFromCurrentLocation']\n\n\nclass ObservationFromCurrentLocation(TranslationHandlerGroup):\n \"\"\"\n Includes the current biome, how likely rain and snow are there, as well as the current light level, how bright the\n sky is, and if the player can see the sky.\n\n Also includes x, y, z, roll, and pitch\n \"\"\"\n\n def xml_template(self) -> str:\n return str(\"\"\"<ObservationFromFullStats/>\"\"\")\n\n def to_string(self) -> str:\n return \"location_stats\"\n\n def __init__(self):\n super(ObservationFromCurrentLocation, self).__init__(\n handlers=[\n _SunBrightnessObservation(),\n _SkyLightLevelObservation(),\n _LightLevelObservation(),\n _CanSeeSkyObservation(),\n _BiomeRainfallObservation(),\n _BiomeTemperatureObservation(),\n _IsRainingObservation(),\n # TODO _BiomeNameObservation(),\n _BiomeIDObservation(),\n _PitchObservation(),\n _YawObservation(),\n _XPositionObservation(),\n _YPositionObservation(),\n _ZPositionObservation(),\n _SeaLevelObservation()\n ]\n )\n\n\nclass _FullStatsObservation(KeymapTranslationHandler):\n def to_hero(self, x) -> int:\n for key in self.hero_keys:\n x = x[key]\n return x\n\n def __init__(self, key_list: List[str], space=None, default_if_missing=None):\n if space is None:\n if 'achievement' == key_list[0]:\n space = spaces.Box(low=0, high=1, shape=(), dtype=int)\n else:\n space = spaces.Box(low=0, high=np.inf, shape=(), dtype=int)\n if default_if_missing is None:\n default_if_missing = np.zeros((), dtype=float)\n\n super().__init__(hero_keys=key_list, univ_keys=key_list, space=space,\n default_if_missing=default_if_missing)\n\n def xml_template(self) -> str:\n return str(\"\"\"<ObservationFromFullStats/>\"\"\")\n\n\nclass _SunBrightnessObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['sun_brightness'], space=spaces.Box(low=0.0, high=1.0, shape=(), dtype=float),\n default_if_missing=0.94)\n\n\nclass _SkyLightLevelObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['sky_light_level'], space=spaces.Box(low=0.0, high=1.0, shape=(), dtype=float),\n default_if_missing=0.71)\n\n\nclass _XPositionObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['xpos'], space=spaces.Box(low=-640000.0, high=640000.0, shape=(), dtype=float),\n default_if_missing=0.0)\n\n\nclass _YPositionObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['ypos'], space=spaces.Box(low=-640000.0, high=640000.0, shape=(), dtype=float),\n default_if_missing=0.0)\n\n\nclass _ZPositionObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['zpos'], space=spaces.Box(low=-640000.0, high=640000.0, shape=(), dtype=float),\n default_if_missing=0.0)\n\n\nclass _PitchObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['pitch'], space=spaces.Box(low=-180.0, high=180.0, shape=(), dtype=float),\n default_if_missing=0.0)\n\n\nclass _YawObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['yaw'], space=spaces.Box(low=-180.0, high=180.0, shape=(), dtype=float),\n default_if_missing=0.0)\n\n\nclass _BiomeIDObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['biome_id'],\n space=spaces.Box(low=0, high=167, shape=(), dtype=int),\n default_if_missing=0)\n\n\nclass _BiomeRainfallObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['biome_rainfall'],\n space=spaces.Box(low=0.0, high=1.0, shape=()),\n default_if_missing=0.5)\n\n\nclass _BiomeTemperatureObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['biome_temperature'],\n space=spaces.Box(low=0.0, high=1.0, shape=()),\n default_if_missing=0.5)\n\n\nclass _SeaLevelObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['sea_level'],\n space=spaces.Box(low=0.0, high=255, shape=(), dtype=int),\n default_if_missing=63)\n\n\nclass _LightLevelObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['light_level'],\n space=spaces.Box(low=0.0, high=15, shape=(), dtype=int),\n default_if_missing=15)\n\n\nclass _IsRainingObservation(_FullStatsObservation):\n def __init__(self):\n super().__init__(key_list=['is_raining'],\n space=spaces.Box(low=0, high=1, shape=(), dtype=int),\n default_if_missing=0)\n\n\nclass _CanSeeSkyObservation(_FullStatsObservation):\n def to_hero(self, x):\n for key in self.hero_keys:\n x = x[key]\n return np.eye(2)[x]\n\n def __init__(self):\n super().__init__(key_list=['can_see_sky'],\n space=spaces.Box(low=0, high=1, shape=(), dtype=int),\n default_if_missing=1)\n","repo_name":"minerllabs/minerl","sub_path":"minerl/herobraine/hero/handlers/agent/observations/location_stats.py","file_name":"location_stats.py","file_ext":"py","file_size_in_byte":5906,"program_lang":"python","lang":"en","doc_type":"code","stars":587,"dataset":"github-code","pt":"52"} +{"seq_id":"31377471318","text":"import string\r\nimport secrets\r\nfrom time import sleep\r\n\r\nn = 0\r\nwhile True:\r\n n = n + 1\r\n total = string.digits + string.ascii_letters + string.punctuation\r\n random = secrets.choice(total)\r\n print(random, end='', flush=True)\r\n sleep(0.05) # Seconds needed for printing a character\r\n if n == 75: # Change line length\r\n print('')\r\n n = 0\r\n ","repo_name":"superbluevoid/Random-lines","sub_path":"line_generator.py","file_name":"line_generator.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13876057031","text":"from openpyxl import load_workbook\n\nfrom commands.free_room import FreeRoom\nfrom commands.help import Help\nfrom commands.load import Load\nfrom commands.room_table import RoomTable\nfrom config_tools.configuration import Configuration\nfrom spreadsheet_data.spreadsheet_data import *\nfrom interface_tools.input_tools import *\nfrom interface_tools.command_completion_tools import *\nfrom pathlib import Path\n\nCURSOR_UP_ONE = '\\x1b[1A'\nERASE_LINE = '\\x1b[2K'\n\nsys.stdout.write(CURSOR_UP_ONE)\nsys.stdout.write(ERASE_LINE)\n\n\ndef delete_last_lines(n=1):\n for _ in range(n):\n sys.stdout.write(CURSOR_UP_ONE)\n sys.stdout.write(ERASE_LINE)\n\n\nhelp_command = Help()\nroom_table_command = RoomTable()\nfree_room_command = FreeRoom()\n\nconfiguration = Configuration(filepath=\"config.json\")\n\n_workbook = None\nspreadsheet_data = None\n\n# load sheet from default location (config.json)\nsheet = Path(configuration.data['defaults_value']['path_to_sheet'])\nif sheet.is_file():\n _workbook = load_workbook(configuration.data['defaults_value'][\n 'path_to_sheet']) # debugs\n spreadsheet_data = SpreadsheetData(configuration.data, _workbook)\n available_expressions[\"free\"]['-r'] = spreadsheet_data.room_data.data\nelse:\n show_warning(\"First load data\")\n\ncmd_hist_file = open('commandHistory.txt', 'a+')\nuser_command_getter = UserCommandGetter(cmd_hist_file)\n\n\n# set sheet data and configuration\ndef set_spreadsheet_data(data):\n global spreadsheet_data\n spreadsheet_data = data\n available_expressions[\"free\"]['-r'] = spreadsheet_data.room_data.data\n\n\n# program commands\ncommand = {\n \"load\": lambda x: set_spreadsheet_data(Load.exec_command(x)),\n \"room-table\": lambda x: room_table_command.exec_command(spreadsheet_data,\n x),\n \"free\": lambda x: free_room_command.exec_command(spreadsheet_data, x),\n \"help\": lambda x: help_command.exec_command(x),\n \"exit\": lambda x: exit(0),\n}\n\n\ndef input_mode():\n # read user input\n args = user_command_getter.get_user_command()\n if spreadsheet_data is None and len(args) > 0 and args[0] != 'exit' and \\\n args[0] != 'load':\n show_warning(\"First load data\")\n return\n\n if len(args) < 1:\n print(\"unknown command\")\n else:\n if args[0] in command:\n # execute inserted command\n command[args[0]](args)\n else:\n print(\"unknown command\")\n return\n\n\ndef main():\n print(\"TIMETABLE-GENERATOR WIET 2019 - interactive mode\")\n\n while True:\n input_mode()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"piaskowyk/enroll-timetable","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"40494648059","text":"registered = {}\ncommand = input()\n\nwhile not command == \"end\":\n command = command.split(\" : \")\n course = command[0]\n student = command[1]\n if course not in registered:\n registered[course] = []\n registered[course].append(student)\n\n command = input()\nfor courses, users in registered.items():\n print(f\"{courses}: {len(users)}\")\n for student in users:\n print(f\"-- {student}\")\n\n\n","repo_name":"Rossen-Dimitrov/fundamentals_with_python","sub_path":"courses_exercise_dictionaries.py","file_name":"courses_exercise_dictionaries.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"41561644625","text":"'''\nDescription: Calculate the toxicity properties of molecule\nAuthor: Kotori Y\nDate: 2020-10-31 12:06:51\nLastEditors: Kotori Y\nLastEditTime: 2020-11-06 09:09:24\nFilePath: \\admetMesh\\admetMesh\\admetEvaluation\\toxicity.py\nAuthorMail: kotori@cbdd.me\n'''\n\nimport os\nimport sys\n\n# sys.path.append('..')\n# from models.predictor import pred_admet\nfrom rdkit import Chem\nfrom .admetConfig import SmartDir\nfrom .substructure_filter import SubstrutureFilter\nimport pandas as pd\nfrom collections.abc import Iterable\n\n\nclass Toxicity:\n\n def __init__(self, mols):\n\n self.mols = mols if isinstance(mols, Iterable) else (mols,)\n self.smis = None\n\n def ScreenToxicityFragments(self):\n res = pd.DataFrame()\n atoms = pd.DataFrame()\n files = os.listdir(SmartDir)\n\n for file in files:\n endpoint = os.path.splitext(file)[0]\n if endpoint != \"PAINS\":\n for x in SubstrutureFilter().screening(self.mols, endpoint):\n length = 0 if x[\"MatchedNames\"] == ['-'] else len(x[\"MatchedNames\"])\n res[f\"{endpoint}\"] = [length]\n # print(x[\"MatchedAtoms\"][0])\n atoms[f\"{endpoint}\"] = [x[\"MatchedAtoms\"][0]]\n return res, atoms\n\n def CalculateAllToxicityProperties(self):\n # T = self.CalculateToxicityProperties()\n # T21 = self.CalculateToxicity21Properties()\n Tsub = self.ScreenToxicityFragments()\n\n # return T, T21, Tsub\n return Tsub\n\n\nif \"__main__\" == __name__:\n import pandas as pd\n\n smi = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC'\n mol = Chem.MolFromSmiles(smi)\n\n mols = [mol] * 10\n T = Toxicity(mols)\n res, atom = T.ScreenToxicityFragments()\n print(res)\n print(atom)\n # print(Tsub.columns)\n","repo_name":"antwiser/OptADMET","sub_path":"static/media/core/toxicity.py","file_name":"toxicity.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"6287749860","text":"import torch\nimport os\nimport sys\nimport wandb\nimport pickle\nimport json\nimport pandas as pd\nimport argparse\nfrom pathlib import Path\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification\nfrom transformers import Trainer, TrainingArguments\nfrom sklearn.metrics import accuracy_score, precision_recall_fscore_support\n\n\ndef get_script_path():\n return os.path.dirname(os.path.realpath(sys.argv[0]))\n\ndef computeMetrics(pred):\n labels = pred.label_ids\n preds = pred.predictions.argmax(-1)\n precision, recall, f1, _ = precision_recall_fscore_support(labels, preds, average='weighted')\n acc = accuracy_score(labels, preds)\n return {\n 'accuracy': acc,\n 'f1': f1,\n 'precision': precision,\n 'recall': recall\n }\n\ndef labelToNumber(currentLabel: str, allLabels: list):\n #label = np.zeros(len(allLabels))\n #label[allLabels.index(currentLabel)] = 1\n return allLabels.index(currentLabel)\n\ndef labelNumberToString(labelNumber, allLabels):\n #return allLabels[np.argmax(labelNumber)]\n return allLabels[labelNumber]\n\ndef readSplit(csvFilePath, allLabels: list):\n # my split is already preprocessed and does not need to be shuffled\n df = pd.read_csv(csvFilePath)\n\n texts = []\n labels = []\n for index, row in df.iterrows():\n texts.append(row['text'])\n labels.append(labelToNumber(row['label'], allLabels))\n \n return texts, labels\n\n# dataset class from https://huggingface.co/transformers/custom_datasets.html\nclass StyleClassificationDataset(torch.utils.data.Dataset):\n def __init__(self, encodings, labels):\n self.encodings = encodings\n self.labels = labels\n \n def __getitem__(self, idx):\n item = {key: val[idx].clone().detach() for key, val in self.encodings.items()}\n item['labels'] = torch.tensor(self.labels[idx])\n return item\n\n def __len__(self):\n return len(self.labels)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--eval_batch_size', type=int, default=128)\n parser.add_argument('--data_set', type=str, required=True)\n parser.add_argument('--org_data_dir', type=str, required=True)\n parser.add_argument('--checkpoint_dir', type=str, required=True)\n parser.add_argument('--label_0', type=str, required=True)\n parser.add_argument('--label_1', type=str, required=True)\n parser.add_argument('--model_name', type=str, default='roberta-base')\n\n args = parser.parse_args()\n\n # train model\n def testCheckpoint():\n dataSet = args.data_set\n modelName = args.model_name\n gradAccumulationSteps = 1\n\n #now = datetime.datetime.now()\n runName = 'best-model-test'\n \n wandb.init(project='final-{}-{}'.format(dataSet, modelName), name=runName, entity='philno')\n wandb.config.update(args)\n outputDir = os.path.join(args.checkpoint_dir, 'temp')\n trainingArgs = TrainingArguments(\n output_dir=outputDir, # output directory\n per_device_eval_batch_size=args.eval_batch_size, # batch size for evaluation\n run_name=runName,\n dataloader_num_workers=4,\n gradient_accumulation_steps=gradAccumulationSteps,\n fp16=True\n )\n\n trainer = Trainer(\n model=model,\n args=trainingArgs,\n compute_metrics=computeMetrics\n )\n with torch.no_grad():\n model.eval()\n evalMetrics = trainer.predict(testDataset).metrics\n wandb.run.summary.update(evalMetrics)\n print(evalMetrics)\n \n with open(os.path.join(args.checkpoint_dir, '..', 'test_results.json'), 'w') as f:\n json.dump(evalMetrics, f)\n\n\n allLabels = [\n args.label_0,\n args.label_1\n ]\n numLabels = len(allLabels)\n dataSet = args.data_set\n\n # model, optimizer etc. setup from https://huggingface.co/transformers/training.html\n modelName = args.model_name\n model = AutoModelForSequenceClassification.from_pretrained(args.checkpoint_dir, num_labels=numLabels, return_dict=True)\n tokenizer = AutoTokenizer.from_pretrained(modelName)\n \n def createDataset(orgDataDir, targetDataDir):\n # prepare dataset\n ORG_DATA_DIR = orgDataDir\n \n testTexts, testLabels = readSplit(os.path.join(ORG_DATA_DIR, 'test.csv'), allLabels)\n\n def tokenizeTexts(texts):\n return tokenizer(texts, return_tensors='pt', add_special_tokens=True, truncation=True, padding='max_length', max_length=256)\n \n testEncodings = tokenizeTexts(testTexts)\n\n testDataset = StyleClassificationDataset(testEncodings, testLabels)\n\n print('Test dataset examples:')\n print(testTexts[0] + ' == ' + labelNumberToString(testLabels[0], allLabels))\n print(testTexts[-1] + ' == ' + labelNumberToString(testLabels[-1], allLabels))\n\n Path(targetDataDir).mkdir(parents=True, exist_ok=True)\n\n with open(os.path.join(targetDataDir, 'test.pickle'), 'wb') as f2:\n pickle.dump(testDataset, f2)\n\n print('dataset written')\n return testDataset\n\n targetDataDir = os.path.join(get_script_path(), 'data', dataSet)\n if (not os.path.exists(targetDataDir)):\n createDataset(args.org_data_dir, targetDataDir)\n\n print('before loading dataset from pickle')\n # testing in separate script!\n with open(os.path.join(targetDataDir, 'test.pickle'), 'rb') as f:\n testDataset = pickle.load(f)\n\n print('Model:', modelName)\n print('Dataset:', dataSet)\n print('Num of test samples:', len(testDataset))\n\n print('Num of cuda devices:', torch.cuda.device_count())\n device = torch.device('cuda:0')\n model.to(device)\n testCheckpoint()","repo_name":"caisa-lab/style-transfer-chatbots","sub_path":"style-classifier-roberta/eval_classifier.py","file_name":"eval_classifier.py","file_ext":"py","file_size_in_byte":5776,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13850440067","text":"from PIL import ImageDraw, ImageFont\nimport numpy as np\nfrom actfw_core.task import Consumer\nimport time\nimport actfw_core\nfrom consts import INFO_COLOR, JSTDT\nfrom datetime import datetime\n\n\ndef to_datetime(t):\n return datetime.fromtimestamp(float(t) + JSTDT)\n\n\nclass FPS(object):\n\n \"\"\"FPS Counter\"\"\"\n\n def __init__(self, moving_average=30):\n \"\"\"\n\n Args:\n moving_average (int): recent N frames moving average\n\n \"\"\"\n self.moving_average = moving_average\n self.prev_time = time.time()\n self.dtimes = []\n\n def update(self):\n \"\"\"\n\n Update FPS.\n\n Returns:\n fps: current fps\n\n \"\"\"\n cur_time = time.time()\n dtime = cur_time - self.prev_time\n self.prev_time = cur_time\n self.dtimes.append(dtime)\n if len(self.dtimes) > self.moving_average:\n self.dtimes.pop(0)\n return self.get()\n\n def get(self):\n \"\"\"\n\n Get FPS.\n\n Returns:\n fps: current fps\n\n \"\"\"\n if len(self.dtimes) == 0:\n return None\n else:\n return len(self.dtimes) / sum(self.dtimes)\n\n\nclass Presenter(Consumer):\n def __init__(self, preview_window, cmd, kvssink):\n super(Presenter, self).__init__()\n self.preview_window = preview_window\n self.cmd = cmd\n self.font = ImageFont.truetype(\n font=\"/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf\",\n size=int(20),\n )\n self.smallfont = ImageFont.truetype(\n font=\"/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf\",\n size=int(10),\n )\n self.font_height = self.font.getsize(\"99.9%\")[1]\n self.smallfont_height = self.smallfont.getsize(\"99.9%\")[1]\n self.fps = FPS()\n\n self.kvssink = kvssink\n\n def stop(self):\n \"\"\"Stop the activity\"\"\"\n if self.kvssink is not None:\n self.kvssink.stop()\n\n def proc(self, captured_image):\n current_time = time.time()\n result_image = captured_image.copy()\n actfw_core.heartbeat()\n\n draw = ImageDraw.Draw(result_image)\n\n # Add a black box below FPS\n draw.rectangle(\n (0, 2, self.font_height * 8, self.font_height),\n fill=(0, 0, 0),\n outline=(0, 0, 0),\n )\n\n fps = \"FPS: {:>6.3f}\".format(self.fps.update())\n draw.text((0, 0), fps, font=self.font, fill=(255, 255, 255))\n\n y = self.font_height\n\n draw.text(\n (2, y),\n to_datetime(current_time).isoformat(),\n font=self.smallfont,\n fill=INFO_COLOR,\n )\n y += self.smallfont_height\n\n if self.kvssink is not None:\n self.kvssink.add_image(result_image)\n\n self.cmd.update_image(result_image)\n\n if self.preview_window is not None:\n self.preview_window.blit(np.asarray(result_image).tobytes())\n self.preview_window.update()\n","repo_name":"Idein/actcast-app-examples","sub_path":"amazon-kinesis-video-streams/app/presenter.py","file_name":"presenter.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25115396195","text":"#!/bin/python3\n\nimport urllib.request as request\nimport json\nimport shutil\nimport os\nfrom dotenv import load_dotenv\nfrom yt_dlp import YoutubeDL\n# from email import header\n\ndef get_all_video_in_channel(channel_id):\n api_key = os.environ['YT_API_KEY']\n\n base_video_url = 'https://www.youtube.com/watch?v='\n base_search_url = 'https://www.googleapis.com/youtube/v3/search?'\n\n first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=1'.format(api_key, channel_id)\n\n video_links = []\n url = first_url\n while True:\n inp = request.urlopen(url)\n resp = json.load(inp)\n\n for i in resp['items']:\n if i['id']['kind'] == \"youtube#video\":\n video_links.append(base_video_url + i['id']['videoId'])\n\n try:\n next_page_token = resp['nextPageToken']\n url = first_url + '&pageToken={}'.format(next_page_token)\n except:\n break\n return video_links\n\ndef main():\n load_dotenv()\n\n channels = os.environ['CHANNELS'].split(',')\n\n for channel_id in channels:\n # Gets most recent video from creator\n # videos = get_all_video_in_channel('channel_id') # hard coded for now\n \n # Downloads the videos\n with YoutubeDL() as ydl:\n ydl.download('https://www.youtube.com/watch?v=D9SFvNpBTBM')\n\n # Moves downloaded videos to media destination\n dl_videos = [f for f in os.listdir() if '.mp4' in f.lower()]\n \n # Creates the save directory if it doesn't exist\n if not os.path.exists(os.environ['DL_PATH']):\n os.makedirs(os.environ['DL_PATH'])\n \n # Moves all downloaded videos\n for dl_video in dl_videos:\n new_path = os.environ['DL_PATH'] + '/' + dl_video\n shutil.move(dl_video, new_path)\n\nif __name__==\"__main__\":\n main()","repo_name":"mcreekmore/yt-archive","sub_path":"yt-archive.py","file_name":"yt-archive.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19379920590","text":"from __future__ import print_function\nimport numpy as np\nfrom six.moves import cPickle as pickle\nfrom six.moves import range\nimport numpy as np\nimport random\nimport sys\nimport heapq as hq\nimport shutil\nimport os\nfrom multiprocessing import Pool\nimport scipy.spatial.distance as dis\n\n#Load the data descriptors\nlabels_index = {}\nlabels_sum = {}\n\ndef load_data(name):\n\twith open(name, 'rb') as f:\n\t\tsave = pickle.load(f)\n\t\tdesc = save['desc']\n\t\tlabels = save['labels']\n\t\tnames = save['name']\n\t\tprint(len(desc))\n\t\tprint(len(labels))\n\t\tdel save\n\t\tprint('loaded')\n\n\treturn desc, labels, names\n\ndef distance(a,b):\n\t# return dis.braycurtis(a, b) # 61.2\n\t# return dis.cosine(a, b) # 61\n\treturn dis.euclidean(a, b) # 60.9\n\t# return dis.correlation(a, b) # 60.7\n\t# return dis.cityblock(a, b) # 60.4\n\t# return dis.canberra(a, b) # 59.5\n\t# return dis.chebyshev(a, b) # 52.3\n\t# return dis.chebyshev(a, b) # 52.3\n\ndef cbir(cbir_args):\n\t# args desc, labels, names, t_desc, t_labels, t_names, top_n, test_num, src_root, src_root2\n\tdesc = cbir_args[0]\n\tlabels = cbir_args[1]\n\tnames = cbir_args[2]\n\tt_desc = cbir_args[3]\n\tt_labels = cbir_args[4]\n\tt_names = cbir_args[5]\n\ttop_n = cbir_args[6]\n\ttest_num = cbir_args[7]\n\tsrc_root = cbir_args[8]\n\tsrc_root2 = cbir_args[9]\n\n\ttest_img = t_desc[test_num]\n\tretrievals = []\n\ttemp_Retrieval = []\n\n\tfor i in range(len(desc)):\n\t\tdist = distance(desc[i], test_img)\n\t\thq.heappush(temp_Retrieval, (-1*dist, i))\n\t\tif len(temp_Retrieval) > top_n:\n\t\t\thq.heappop(temp_Retrieval)\n\tfor x in range(top_n):\n\t\tretrievals.append(hq.heappop(temp_Retrieval))\n\tcorrect = sum([1 for j in [labels[u[1]] for u in retrievals] if j == t_labels[test_num]])\n\taccuracy = correct / top_n\n\n\tprint('(', test_num, '/', len(t_desc), ')', \"==>\", accuracy )\n\t\n\tsrc = src_root2 + t_names[test_num]\n\n\ttempR=[]\n\ttmpindex=[]\n\tfor j in range(len(retrievals)):\n\t\tsrc = src_root + names[retrievals[j][1]]\n\t\ttempR.append(src)\n\t\ttmpindex.append(retrievals[j][1])\n\t\n\t# ResultQ[test_num] = src\n\t# indexQ[test_num] = test_num\n\t# ResultR[test_num] = tempR\n\t# indexR[test_num] = tmpindex\n\treturn (src, test_num, tempR, tmpindex, accuracy)\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 5:\n\t\tprint('error : no input files (train desc file, test desc file, train dataset root, test dataset root)')\n\t\texit(1)\n\t\n\t# load data\n\tdesc, labels, names = load_data(sys.argv[1])\n\tt_desc, t_labels,t_names = load_data(sys.argv[2])\n\n\t# initialize variables\n\ttop_n = 100\n\tResultQ=[None] * len(t_desc)\n\tindexQ=[None] * len(t_desc)\n\tResultR=[[] for _ in range(len(t_desc))]\n\tindexR=[[] for _ in range(len(t_desc))]\n\n\tsrc_root = sys.argv[3]\n\tsrc_root2 = sys.argv[4]\n\n\teval_res = [None] * len(t_desc)\n\n\twith Pool() as pool:\n\t\t# args desc, labels, names, t_desc, t_labels, t_names, top_n, test_num, src_root, src_root2\n\t\tcbir_res = pool.map(cbir, [ (desc, labels, names, t_desc, t_labels, t_names, top_n, i, src_root, src_root2) for i in range(len(t_desc)) ])\n\t\tfor i in range(len(cbir_res)):\n\t\t\t# return (src, test_num, tempR, tmpindex, accuracy)\n\t\t\tResultQ[i] = cbir_res[i][0]\n\t\t\tindexQ[i] = cbir_res[i][1]\n\t\t\tResultR[i] = cbir_res[i][2]\n\t\t\tindexR[i] = cbir_res[i][3]\n\t\t\teval_res[i] = cbir_res[i][4]\n\n\tprint('[Mean Accuracy]', sum(eval_res) / len(eval_res))\n\tf = open(\"retrieval_result_fc7\", 'wb')\n\tsave = {\n\t 'query': ResultQ,\n\t \t'result': ResultR, \n\t \t'query_index': indexQ,\n\t \t'result_index': indexR,\n\t\t'acc' : sum(eval_res) / len(eval_res)\n\t}\n\tpickle.dump(save, f, pickle.HIGHEST_PROTOCOL)\n\tf.close()\n\tprint(\"saved file\")","repo_name":"robert1826/CBMIR-CNN_EHD","sub_path":"src/search_euclidean_pool.py","file_name":"search_euclidean_pool.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26636012757","text":"import zc.recipe.egg\n\n\nclass Script(zc.recipe.egg.Scripts):\n\n def __init__(self, buildout, name, options):\n options[\"relative-paths\"] = \"false\"\n deployment = buildout[options[\"deployment\"]]\n directory = deployment[\"etc-directory\"]\n super(Script, self).__init__(buildout, name, options)\n self.options[\"bin-directory\"] = directory\n # The base class initializes this, so we fix it up.\n self.options[\"_b\"] = directory\n","repo_name":"zc/zc.recipe.script","sub_path":"src/zc/recipe/script/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2257989981","text":"import configparser\nfrom wpilib import Joystick\nfrom wpilib.buttons.joystickbutton import JoystickButton\nfrom commands.release_panel import ReleasePanel\nfrom commands.extend_arm_to_position import ExtendArmToPosition\nfrom commands.retract_arm_to_position import RetractArmToPosition\nfrom commands.raise_front_wheels import RaiseFrontWheels\nfrom commands.raise_rear_wheels import RaiseRearWheels\nfrom commands.line_follow import LineFollow\n\n\nclass JoystickAxis(object):\n \"\"\"Enumerates joystick axis.\"\"\"\n LEFTX = 0\n LEFTY = 1\n RIGHTX = 4\n RIGHTY = 5\n DPADX = 11\n DPADY = 12\n\n\nclass JoystickButtons(object):\n \"\"\"Enumerates joystick buttons.\"\"\"\n X = 1\n A = 2\n B = 3\n Y = 4\n LEFTBUMPER = 5\n RIGHTBUMPER = 6\n LEFTTRIGGER = 7\n RIGHTTRIGGER = 8\n BACK = 9\n START = 10\n\n\nclass UserController(object):\n \"\"\"Enumerates the controllers.\"\"\"\n DRIVER = 0\n SCORING = 1\n\n\nclass OI:\n \"\"\"\n This class is the glue that binds the controls on the physical operator\n interface to the commands and command groups that allow control of the robot.\n \"\"\"\n _config = None\n _command_config = None\n _controllers = []\n _auto_program_chooser = None\n _starting_chooser = None\n\n FULL_SPEED_AHEAD: float = 1.0\n\n def __init__(self, robot, configfile='/home/lvuser/py/configs/joysticks.ini'):\n self.robot = robot\n self._config = configparser.ConfigParser()\n self._config.read(configfile)\n self._init_joystick_binding()\n\n for i in range(2):\n self._controllers.append(self._init_joystick(i))\n\n self._create_smartdashboard_buttons()\n\n def setup_button_bindings(self):\n # Panel grabber\n panel_button = JoystickButton(self._controllers[UserController.SCORING], JoystickButtons.A)\n panel_button.whileHeld(ReleasePanel(self.robot))\n # Wheel risers\n raise_front_wheels_button = JoystickButton(self._controllers[UserController.DRIVER], JoystickButtons.RIGHTBUMPER)\n raise_front_wheels_button.whileHeld(RaiseFrontWheels(self.robot))\n raise_rear_wheels_button = JoystickButton(self._controllers[UserController.DRIVER], JoystickButtons.LEFTBUMPER)\n raise_rear_wheels_button.whileHeld(RaiseRearWheels(self.robot))\n # Line following\n line_following_button = JoystickButton(self._controllers[UserController.DRIVER], JoystickButtons.X)\n line_following_button.whileHeld(LineFollow(self.robot, -0.2))\n\n # Arm controls\n #extend_arm_button = JoystickButton(self._controllers[UserController.SCORING], JoystickButtons.X)\n #extend_arm_button.whenPressed(ExtendArmToPosition(self.robot, 1, 1)) # need to get an encoder position\n #retract_arm_button = JoystickButton(self._controllers[UserController.SCORING], JoystickButtons.Y)\n #retract_arm_button.whenPressed(RetractArmToPosition(self.robot, 1, 1)) # need encoder position\n\n def get_axis(self, user, axis):\n \"\"\"Read axis value for specified controller/axis.\n\n Args:\n user: Controller ID to read from\n axis: Axis ID to read from.\n\n Return:\n Current position for the specified axis. (Range [-1.0, 1.0])\n \"\"\"\n controller = self._controllers[user]\n value = 0.0\n if axis == JoystickAxis.DPADX:\n value = controller.getPOV()\n if value == 90:\n value = 1.0\n elif value == 270:\n value = -1.0\n else:\n value = 0.0\n elif axis == JoystickAxis.DPADY:\n value = controller.getPOV()\n if value == 0:\n value = -1.0\n elif value == 180:\n value = 1.0\n else:\n value = 0.0\n else:\n config_section = \"JoyConfig\" + str(user)\n dead_zone = self._config.getfloat(config_section, \"DEAD_ZONE\")\n value = controller.getRawAxis(axis)\n if abs(value) < dead_zone:\n value = 0.0\n\n return value\n\n def get_button_state(self, user, button):\n return self._controllers[user].getRawButton(button)\n\n def _create_smartdashboard_buttons(self):\n pass\n\n def get_auto_choice(self):\n return self._auto_program_chooser.getSelected()\n\n def get_position(self):\n value = self._starting_chooser.getSelected()\n return value\n\n def _init_joystick(self, driver):\n config_section = \"JoyConfig\" + str(driver)\n stick = Joystick(self._config.getint(config_section, \"PORT\"))\n return stick\n\n def _init_joystick_binding(self):\n axis_binding_section = \"AxisBindings\"\n JoystickAxis.LEFTX = self._config.getint(axis_binding_section, \"LEFTX\")\n JoystickAxis.LEFTY = self._config.getint(axis_binding_section, \"LEFTY\")\n JoystickAxis.RIGHTX = self._config.getint(axis_binding_section, \"RIGHTX\")\n JoystickAxis.RIGHTY = self._config.getint(axis_binding_section, \"RIGHTY\")\n JoystickAxis.DPADX = self._config.getint(axis_binding_section, \"DPADX\")\n JoystickAxis.DPADY = self._config.getint(axis_binding_section, \"DPADY\")\n\n button_binding_section = \"ButtonBindings\"\n JoystickButtons.X = self._config.getint(button_binding_section, \"X\")\n JoystickButtons.A = self._config.getint(button_binding_section, \"A\")\n JoystickButtons.B = self._config.getint(button_binding_section, \"B\")\n JoystickButtons.Y = self._config.getint(button_binding_section, \"Y\")\n JoystickButtons.LEFTBUMPER = self._config.getint(button_binding_section, \"LEFTBUMPER\")\n JoystickButtons.RIGHTBUMPER = self._config.getint(button_binding_section, \"RIGHTBUMPER\")\n JoystickButtons.LEFTTRIGGER = self._config.getint(button_binding_section, \"LEFTTRIGGER\")\n JoystickButtons.RIGHTTRIGGER = self._config.getint(button_binding_section, \"RIGHTTRIGGER\")\n JoystickButtons.BACK = self._config.getint(button_binding_section, \"BACK\")\n JoystickButtons.START = self._config.getint(button_binding_section, \"START\")\n","repo_name":"TechnoJays/robot2019","sub_path":"src/oi.py","file_name":"oi.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2042055612","text":"\n\ndef tik_string(tekstas):\n import functools\n def wrapper(*args, **kwargs):\n for text in args:\n if type(text) != str:\n print(\"Leistinas duomenų tipas yra tik STRING!\")\n return\n\n for text in kwargs.values():\n if type(text) != str:\n print(\"Leistinas duomenų tipas yra tik STRING!\")\n else:\n return tekstas(*args, **kwargs)\n return functools.wraps(tekstas)(wrapper)\n\n@tik_string\ndef pasisveikinimas(tekstas):\n print(\"Labas,\", tekstas)\n\npasisveikinimas(\"Jonas\")\npasisveikinimas(564)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"TomasCik/Python2023","sub_path":"16/3Uzduotis.py","file_name":"3Uzduotis.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"lt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8521490805","text":"import requests\r\nimport csv\r\nimport time\r\nimport os\r\nimport random\r\n\r\n# 获取网页\r\nid = input(\"请输入爬取视频数量:\")\r\n# num = 0\r\nheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'}\r\n\r\nfor i in range(0,int(id)):\r\n num = random.randint(0,100000000)\r\n urls=\"https://api.bilibili.com/x/web-interface/archive/stat?aid=\"+str(num)\r\n #{\"code\":0,\"message\":\"0\",\"ttl\":1,\"data\":{\"aid\":540931451,\"bvid\":\"BV1Ri4y1s7Am\",\"view\":204266,\"danmaku\":377,\"reply\":1452,\"favorite\":385,\"coin\":102,\"share\":950,\"like\":12343,\"now_rank\":0,\"his_rank\":0,\"no_reprint\":1,\"copyright\":1,\"argue_msg\":\"\",\"evaluation\":\"\"}}\r\n r = requests.get(urls,headers = headers)\r\n json = r.json()\r\n code = json['code']\r\n if code == 0:\r\n data = json['data'] #拿出子字典\r\n # 通过字典获取各数据\r\n list = []\r\n aid = str(data['aid']) #视频av号\r\n list.append(aid)\r\n bvid = str(data['bvid']) #视频bv号\r\n list.append(bvid)\r\n view = str(data['view']) #观看次数\r\n list.append(view)\r\n danmaku = str(data['danmaku']) #弹幕数\r\n list.append(danmaku)\r\n favorite = str(data['favorite']) #收藏数\r\n list.append(favorite)\r\n coin = str(data['coin']) #投币数\r\n list.append(coin)\r\n share = str(data['share']) #分享数\r\n list.append(share)\r\n like = str(data['like']) #点赞数\r\n list.append(like)\r\n #print(aid,bvid,view,danmaku,like,coin,favorite,share)\r\n #print(type(bvid))\r\n print(list)\r\n\r\n #创建保存路径\r\n if not os.path.exists('biliVideo'):\r\n\r\n os.mkdir('biliVideo')\r\n\r\n with open(\"biliVideo/biliVideo_\" + str(id) + \".csv\", \"a\", newline='') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(list)\r\n print(\"写入成功\")\r\n\r\n r.close()\r\n\r\n time.sleep(2)\r\n # time.sleep(random.randint(2, 4))\r\nprint()\r\nprint(\"Complete !\")\r\n","repo_name":"ash-miku/Python","sub_path":"爬虫/biliVideo.py","file_name":"biliVideo.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39940774187","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# pylint: disable-msg=E1101\n\nimport fcntl\nimport time\nimport cPickle as pickle\n\n#FIXME: It should use sqlalchemy instead of the pickles.\n\nclass CallDB(object):\n \"\"\"Implements logging of all interesting call stats.\n It can be used for customization of the SDS, e.g. for novice or expert users.\n \"\"\"\n def __init__(self, cfg, file_name, period = 24*60*60):\n self.cfg = cfg\n self.db_fname = file_name\n self.period = period\n\n def read_database(self):\n db = dict()\n try:\n self.f = open(self.db_fname, 'r+')\n fcntl.lockf(self.f, fcntl.LOCK_EX)\n db = pickle.load(self.f)\n except (IOError, EOFError):\n pass\n\n try:\n fcntl.lockf(self.f, fcntl.LOCK_UN)\n self.f.close()\n except AttributeError:\n pass\n\n if 'calls_from_start_end_length' not in db:\n db['calls_from_start_end_length'] = dict()\n\n return db\n\n def open_database(self):\n db = dict()\n try:\n self.f = open(self.db_fname, 'r+')\n fcntl.lockf(self.f, fcntl.LOCK_EX)\n db = pickle.load(self.f)\n except (IOError, AttributeError):\n # the DB file does not exist\n self.f = open(self.db_fname, 'w+')\n fcntl.lockf(self.f, fcntl.LOCK_EX)\n\n if 'calls_from_start_end_length' not in db:\n db['calls_from_start_end_length'] = dict()\n\n return db\n\n def close_database(self, db):\n try:\n self.f.seek(0)\n self.f.truncate(0)\n pickle.dump(db, self.f)\n fcntl.lockf(self.f, fcntl.LOCK_UN)\n self.f.close()\n except AttributeError:\n pass\n\n def release_database(self):\n try:\n fcntl.lockf(self.f, fcntl.LOCK_UN)\n self.f.close()\n except AttributeError:\n pass\n\n def log(self):\n db = self.read_database()\n\n for remote_uri in db['calls_from_start_end_length']:\n num_all_calls, total_time, last_period_num_calls, last_period_total_time, last_period_num_short_calls = self.get_uri_stats(remote_uri)\n\n m = []\n m.append('')\n m.append('=' * 120)\n m.append('Remote SIP URI: %s' % remote_uri)\n m.append('-' * 120)\n m.append('Total calls: %d' % num_all_calls)\n m.append('Total time (min): %0.1f' % (total_time/60.0, ))\n m.append('Last period short calls: %d' % last_period_num_short_calls)\n m.append('Last period total calls: %d' % last_period_num_calls)\n m.append('Last period total time (min): %0.1f' % (last_period_total_time/60.0, ))\n m.append('-' * 120)\n\n m.append('-' * 120)\n m.append('')\n self.cfg['Logging']['system_logger'].info('\\n'.join(m))\n\n def log_uri(self, remote_uri):\n db = self.read_database()\n\n num_all_calls, total_time, last_period_num_calls, last_period_total_time, last_period_num_short_calls = self.get_uri_stats(remote_uri)\n\n m = []\n m.append('')\n m.append('=' * 120)\n m.append('Remote SIP URI: %s' % remote_uri)\n m.append('-' * 120)\n m.append('Total calls: %d' % num_all_calls)\n m.append('Total time (min): %0.1f' % (total_time/60.0, ))\n m.append('Last period short calls: %d' % last_period_num_short_calls)\n m.append('Last period total calls: %d' % last_period_num_calls)\n m.append('Last period total time (min): %0.1f' % (last_period_total_time/60.0, ))\n m.append('-' * 120)\n\n m.append('-' * 120)\n m.append('')\n\n return '\\n'.join(m)\n\n def get_uri_stats(self, remote_uri):\n db = self.read_database()\n\n num_all_calls = 0\n total_time = 0\n last_period_num_calls = 0\n last_period_total_time = 0\n last_period_num_short_calls = 0\n\n try:\n for s, e, l in db['calls_from_start_end_length'][remote_uri]:\n if l > 0:\n num_all_calls += 1\n total_time += l\n\n # do counts for last period hours\n if s > time.time() - self.period:\n last_period_num_calls += 1\n last_period_total_time += l\n\n if l > 0 and l < self.cfg['VoipHub']['short_calls_time_duration']:\n last_period_num_short_calls += 1\n except:\n pass\n\n\n return num_all_calls, total_time, last_period_num_calls, last_period_total_time, last_period_num_short_calls\n\n def track_confirmed_call(self, remote_uri):\n db = self.open_database()\n try:\n db['calls_from_start_end_length'][remote_uri].append([time.time(), 0, 0])\n except:\n db['calls_from_start_end_length'][remote_uri] = [[time.time(), 0, 0], ]\n\n self.close_database(db)\n\n def track_disconnected_call(self, remote_uri):\n db = self.open_database()\n\n try:\n s, e, l = db['calls_from_start_end_length'][remote_uri][-1]\n\n if e == 0 and l == 0:\n # there is a record about last confirmed but not disconnected call\n db['calls_from_start_end_length'][remote_uri][-1] = [s, time.time(), time.time() - s]\n except KeyError:\n # disconnecting call which was not confirmed for URI calling for the first time\n pass\n\n self.close_database(db)\n","repo_name":"UFAL-DSG/alex","sub_path":"alex/components/hub/calldb.py","file_name":"calldb.py","file_ext":"py","file_size_in_byte":5621,"program_lang":"python","lang":"en","doc_type":"code","stars":180,"dataset":"github-code","pt":"52"} +{"seq_id":"32035751974","text":"n=int(input(\"enter the number\"))\ni=1\nwhile i<=n:\n print(\"square of\",i,\"is\",i*i)\n i=i+1 \n\n\n\n\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n if x == \"banana\":\n break\n print(x)","repo_name":"Dularpandey-22/loops.python","sub_path":" docs 2.py","file_name":" docs 2.py","file_ext":"py","file_size_in_byte":194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6013337665","text":"\"\"\"\nThis file handles the abstract and meta data preparation\nfor the Actor entity. It is consummed by the Solr system\nand the Tastypie dehyrdate cycle\n\nBill Doran 2013/08/08\n\"\"\"\n\nimport os\nfrom django.conf import settings\n\nfrom corroborator_app.models import (\n Bulletin,\n Incident,\n ActorRole,\n Location\n)\n\n\nclass ActorPrepMeta():\n\n def prepare_assigned_user(self, object):\n if object.assigned_user is not None:\n return '/api/v1/user/{0}/'.format(object.assigned_user.id)\n else:\n return ''\n\n def prepare_actor_created_date(self, object):\n \"\"\"\n return date portion of actor created datetime field\n \"\"\"\n if object.actor_created is not None:\n return object.actor_created.date()\n else:\n return ''\n\n def prepare_actor_modified_date(self, object):\n \"\"\"\n return date portion of actor modified datetime field\n \"\"\"\n if object.actor_modified is not None:\n return object.actor_modified.date()\n else:\n return ''\n\n def prepare_most_recent_status_actor(self, object):\n \"\"\"\n Returns most recently created status update associated with a\n given Bulletin\n \"\"\"\n status = object.actor_comments.values(\n 'status__id').order_by('-comment_created')\n if len(status) > 0:\n status = status[0]\n return '/api/v1/statusUpdate/{0}/'.format(status['status__id'])\n else:\n return ''\n\n def prepare_actor_searchable_pob(self, object):\n \"\"\"\n Returns the correctly formated uri related to this actor instance\n for the tastypie api\n \"\"\"\n if object.POB is not None:\n locations = []\n\n locations.append('/api/v1/location/{0}/'.format(object.POB.id))\n if object.POB.parent_location is not None:\n locations += self.get_locations_recursively(\n object.POB.parent_location.id\n )\n\n return locations\n else:\n return ''\n\n def prepare_actor_roles_status(self, object):\n \"\"\"\n Returns a full list of the roles played by actors associate\n with this object\n \"\"\"\n roles = [\n actor_role.relation_status for actor_role in\n object.actors_role.all()]\n return roles\n\n def prepare_actor_entity_role(self, object):\n \"\"\"\n Returns a full list of all roles and relationships associated\n with this Actor instance.\n \"\"\"\n roles = [\n actor_role.get_role_status_display() for actor_role in\n ActorRole.objects.filter(actor__in=[object]).all()]\n\n result = roles\n result = filter(None, result)\n\n return list(set(result))\n\n def prepare_actor_entity_relation(self, object):\n \"\"\"\n Returns a full list of all roles and relationships associated\n with this Actor instance.\n \"\"\"\n relations = [\n actor_role.get_relation_status_display() for actor_role in\n ActorRole.objects.filter(actor__in=[object]).all()]\n\n result = relations\n result = filter(None, result)\n\n return list(set(result))\n\n def prepare_roles(self, object):\n \"\"\"\n Returns a full list of all roles and relationships associated\n with this Actor instance.\n \"\"\"\n roles = [\n actor_role.role_status for actor_role in\n ActorRole.objects.filter(actor__in=[object]).all()]\n relations = [\n actor_role.relation_status for actor_role in\n ActorRole.objects.filter(actor__in=[object]).all()]\n\n result = roles + relations\n result = filter(None, result)\n\n return list(set(result))\n\n def prepare_actors(self, object):\n \"\"\"\n Returns array of tastypie uris for the given Actor object's associated\n actors\n \"\"\"\n actors = [\n '/api/v1/actor/{0}/'.format(actor_role.actor.id)\n for actor_role in object.actors_role.all()]\n return actors\n\n def prepare_actors_role(self, object):\n \"\"\"\n Returns the correctly formated uri related to this incident instance\n for the tastypie api\n \"\"\"\n return [\n '/api/v1/actorRole/{0}/'.format(actor_role.id)\n for actor_role in object.actors_role.all()]\n\n def prepare_POB(self, object):\n \"\"\"\n Returns the correctly formated uri related to this actor instance\n for the tastypie api\n \"\"\"\n if object.POB is not None:\n return '/api/v1/location/{0}/'.format(object.POB.id)\n else:\n return ''\n\n def prepare_current_location(self, object):\n \"\"\"\n Returns the correctly formated uri related to this actor instance\n for the tastypie api\n \"\"\"\n if object.current_location is not None:\n return '/api/v1/location/{0}/'.format(object.current_location.id)\n else:\n return ''\n\n def prepare_resource_uri(self, object):\n \"\"\"\n Returns the correctly formated uri related to this actor instance\n for the tastypie api\n \"\"\"\n return '/api/v1/actor/{0}/'.format(object.id)\n\n def prepare_media(self, object):\n \"\"\"\n Returns media uri of image associated with given Actor\n \"\"\"\n if object.media is not None:\n #return object.media.media_file.name\n return '/api/v1/media/{0}/'.format(object.media.id)\n else:\n return ''\n\n def prepare_actor_searchable_current(self, object):\n \"\"\"\n Returns the correctly formated uri related to this actor instance\n for the tastypie api\n \"\"\"\n if object.current_location is not None:\n locations = []\n\n locations.append('/api/v1/location/{0}/'.format(\n object.current_location.id\n ))\n if object.current_location.parent_location is not None:\n locations += self.get_locations_recursively(\n object.current_location.parent_location.id\n )\n\n return locations\n else:\n return ''\n\n def prepare_related_bulletins(self, object):\n \"\"\"\n Return set of Bulletins associated with a given Actor\n \"\"\"\n roles = ActorRole.objects.filter(\n actor=object.id).filter(bulletin__isnull=False)\n\n related_bulletins = [\n '/api/v1/bulletin/{0}/'.format(b.id)\n for ar in roles\n for b in ar.bulletin_set.all()\n ]\n\n return related_bulletins\n\n def prepare_related_incidents(self, object):\n \"\"\"\n Return set of Incidents associated with a given Actor\n \"\"\"\n roles = ActorRole.objects.filter(\n actor=object.id).filter(incident__isnull=False)\n\n related_incidents = [\n '/api/v1/incident/{0}/'.format(b.id)\n for ar in roles\n for b in ar.incident_set.all()\n ]\n\n return related_incidents\n\n\n\n def get_locations_recursively(self, location_id):\n \"\"\"\n Recurse upwards through all parent locations and return a list of\n uri formatted locations.\n \"\"\"\n locations = []\n location = Location.objects.get(pk=location_id)\n if location.parent_location is not None:\n parent_id = location.parent_location.id\n locations += self.get_locations_recursively(parent_id)\n locations.append('/api/v1/location/{0}/'.format(location.id))\n return locations\n\n else:\n return ['/api/v1/location/{0}/'.format(location.id)]\n\n\n def prepare_thumbnail_url(self, object):\n \"\"\"\n Return AWS URL for associated thumbnail media\n \"\"\"\n if object.media is not None:\n return os.path.join(settings.MEDIA_URL, object.media.media_thumb_file.name)\n else:\n return ''\n \n def prepare_media_url(self, object):\n \"\"\"\n Return URL for associated media_file\n \"\"\"\n if object.media is not None:\n return os.path.join(settings.MEDIA_URL, object.media.media_file.name)\n else:\n return ''\n\n def prepare_media_file_type(self, object):\n \"\"\"\n Return file_type for associated media\n \"\"\"\n if object.media is not None:\n return object.media.media_file_type\n else:\n return ''\n\n def prepare_actor_comments(self, object):\n \"\"\"\n Returns the correctly formated uri related to this bulletin instance\n for the tastypie api\n \"\"\"\n return ['/api/v1/comment/{0}/'.format(comment.id)\n for comment in object.actor_comments.all()]\n\n def prepare_count_incidents(self, object):\n \"\"\"\n Returns count of incident objects associated with a given Actor\n \"\"\"\n roles = object.actorrole_set.all()\n return Incident.objects.filter(actors_role__in=roles).count()\n\n def prepare_count_bulletins(self, object):\n \"\"\"\n Returns count of bulletin objects associated with a given Actor\n \"\"\"\n roles = object.actorrole_set.all()\n return Bulletin.objects.filter(actors_role__in=roles).count()\n","repo_name":"equalitie/open-corroborator","sub_path":"corroborator_app/index_meta_prep/actorPrepIndex.py","file_name":"actorPrepIndex.py","file_ext":"py","file_size_in_byte":9346,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"73804375844","text":"\ndef isCycle(employees, friendships):\n persons = set()\n for employee in employees:\n employee = employee.split(',')\n person = int(employee[0])\n persons.add(person)\n\n parent_dict = {i: i for i in persons}\n def find(x):\n parent = parent_dict[x]\n if parent != x:\n parent_dict[x] = find(parent_dict[x])\n return parent_dict[x]\n\n def union(x, y):\n parentX = find(x)\n parentY = find(y)\n if parentX != parentY:\n parent_dict[parentY] = parentX\n\n\n for pair in friendships:\n pair = pair.split(',')\n x = int(pair[0])\n space_split = pair[1].split(' ')\n y = int(space_split[1])\n union(x, y)\n\n res_set = set()\n for v in parent_dict.values():\n res_set.add(v)\n\n return len(res_set) == 1\n\n\nemployees = [\n \"1, Bill, Engineer\",\n \"2, Joe, HR\",\n \"3, Sally, Engineer\",\n \"4, Richard, Business\",\n \"6, Tom, Engineer\",\n \"8, Amy, Engineer\",\n \"12, Jane, Engineer\"\n]\n\nfriendships = [\n \"1, 2\",\n \"1, 3\",\n \"3, 4\",\n \"4, 12\"\n]\nprint(isCycle(employees, friendships))","repo_name":"tanjingjing123/LeetcodeAlgorithms","sub_path":"friendCycleIII.py","file_name":"friendCycleIII.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13608339985","text":"\n#?Use the BeautifulSoup and requests Python packages to print out a list of all the article titles \n#?on the New York Times homepage.\n\n#*BeautifulSoup: \n#*Python library for pulling data out of HTML and XML format\n#* easily navigate, search, scrape, and modify the parsed HTML/XML content like above \n#*(bytes type) by treating everything in it as a Python Object\n\nfrom bs4 import BeautifulSoup\nimport requests\n\ndef getArticle(x):\n #*fetch the web page\n article = requests.get(x)\n #*turn page into a BeautifulSoup object\n soup = BeautifulSoup(article.text, \"html.parser\")\n\n #*h2 stand for headings2 --can view it by right-clicking on the web page and select inspects \n #*to view the structure of it\n for line in soup.find_all('h2'):\n if str(line.string) != \"None\":\n print(line.string)\n\ngetArticle('http://www.nytimes.com') \n","repo_name":"lydia0423/Machine_Learning","sub_path":"Python/Python Basic/Practice_Python/Q17.py","file_name":"Q17.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16047317334","text":"def is_colab():\n \"\"\"If running on Google Colab, return True.\"\"\"\n try:\n import google.colab # NOQA\n\n return True\n except ImportError:\n return False\n\n\ndef is_notebook():\n \"\"\"If running in a Jupyter Notebook, return True.\"\"\"\n try:\n shell = get_ipython().__class__.__name__ # type: ignore\n if shell == \"ZMQInteractiveShell\":\n return True # Jupyter notebook or qtconsole\n elif shell == \"TerminalInteractiveShell\":\n return False # Terminal running IPython\n else:\n return False # Other type\n except NameError:\n return False\n","repo_name":"r9y9/ttslearn","sub_path":"ttslearn/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":230,"dataset":"github-code","pt":"52"} +{"seq_id":"41371157479","text":"import torch\n\nchange_dict_11 = {\n # conv1 - 1 block\n \"features.0.\": \"conv1.\",\n # layer1 - 1 block\n \"features.1.\": \"layer1.0.\",\n # layer2 - 2 block\n \"features.2.\": \"layer2.0.\",\n \"features.3.\": \"layer2.1.\",\n # layer3 - 3 block\n \"features.4.\": \"layer3.0.\",\n \"features.5.\": \"layer3.1.\",\n \"features.6.\": \"layer3.2.\",\n # layer4 - 4 block\n \"features.7.\": \"layer4.0.\",\n \"features.8.\": \"layer4.1.\",\n \"features.9.\": \"layer4.2.\",\n}\nchange_dict_12 = {\n # layer4 - 4 block\n \"features.10.\": \"layer4.3.\",\n # layer5 - 3 block\n \"features.11.\": \"layer5.0.\",\n \"features.12.\": \"layer5.1.\",\n \"features.13.\": \"layer5.2.\",\n # layer6 - 3 block\n \"features.14.\": \"layer6.0.\",\n \"features.15.\": \"layer6.1.\",\n \"features.16.\": \"layer6.2.\",\n # layer7 - 1 block\n \"features.17.\": \"layer7.0.\",\n # conv2 - 1 block\n \"features.18.\": \"conv2.\",\n}\n\nckpt_path = \"/workdir/checkpoint/mobilenetv2/mv2/checkpoint-best.pth\"\nckpt = torch.load(ckpt_path)\nckpt_2 = ckpt \nckpt_2_path = \"/workdir/checkpoint/mobilenetv2/mv2/checkpoint-best_mmdet.pth\"\n\nstate_dict = ckpt[\"model\"]\nstate_dict_2 = {}\n\nfor name in state_dict:\n parameters = state_dict[name]\n print(name, parameters.shape)\n if name[:11] in change_dict_11:\n new_name = change_dict_11[name[:11]]+name[11:]\n elif name[:12] in change_dict_12:\n new_name = change_dict_12[name[:12]]+name[12:]\n else:\n continue\n state_dict_2[new_name] = parameters\n print(new_name, parameters.shape)\n\nprint(state_dict.keys())\nprint(state_dict_2.keys())\n\nckpt_2[\"model\"] = state_dict_2\ntorch.save(ckpt_2, ckpt_2_path)\n","repo_name":"yangtao2019yt/edgeformer_v2_object_detection","sub_path":"configs/mobilenetv2/make_ckpt.py","file_name":"make_ckpt.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"24128655777","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ntable = pd.read_csv('titanic.csv', delimiter=',')\n\nmen_sur = len(table.query('Sex == \"male\" & Survived == 1'))\nmen_died = len(table.query('Sex == \"male\" & Survived == 0'))\n\nwemen_sur = len(table.query('Sex == \"female\" & Survived == 1'))\nwemen_died = len(table.query('Sex == \"female\" & Survived == 0'))\n\ndf = pd.DataFrame([[men_sur, wemen_sur],\n [men_died, wemen_died]],\n ['survive', 'died'], ['men','weman'])\n\nmen = np.array([men_sur, men_died])\nwemen = np.array([wemen_sur, wemen_died])\nmylabels = [\"men survive\", \"men died\"]\n\n#df.plot(kind='pie', subplots=True, figsize=(8, 4), autopct='%1.1f%%')\n#plt.show()\n\nfirst_class_sur = len(table.query('Survived == 1 & Pclass == 1'))\nsecond_class_sur = len(table.query('Survived == 1 & Pclass == 2'))\nthird_class_sur = len(table.query('Survived == 1 & Pclass == 3'))\n\nfirst_class_die = len(table.query('Survived == 0 & Pclass == 1'))\nsecond_class_die = len(table.query('Survived == 0 & Pclass == 2'))\nthird_class_die = len(table.query('Survived == 0 & Pclass == 3'))\n\ndf = pd.DataFrame([[first_class_sur, second_class_sur, third_class_sur],\n [first_class_die, second_class_die, third_class_die]],\n ['survive','died'], ['first class', 'second class', 'third class'])\nheatmap_plot = sns.heatmap(df, center=0, cmap='gist_ncar')\nplt.show()\n\n\n#df.plot(kind='pie', subplots=True, figsize=(8, 4), autopct='%1.1f%%')\n#plt.show()\n\n\nsurvive_age = table.query(\"Survived == 1 and not Age.isna()\")['Age']\ndied_age = table.query(\"Survived == 0 and not Age.isna()\")['Age']\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 5))\n\naxs[0].set_xlabel('Age')\naxs[0].set_ylabel('Quantity')\naxs[1].set_xlabel('Age')\naxs[1].set_ylabel('Quantity')\n\n#survive_age.plot.hist(ax=axs[0], title=\"Survive\")\n#died_age.plot.hist(ax=axs[1], title=\"died\")\n#plt.show()\n\n\npoor_sur = len(table.query('Survived == 1 & Fare < 25'))\npoor_died = len(table.query('Survived == 0 & Fare < 25'))\n\nrich_sur = len(table.query('Survived == 1 & Fare >= 25'))\nrich_died = len(table.query('Survived == 0 & Fare >= 25'))\n\ndf = pd.DataFrame([[poor_sur, rich_sur],\n [poor_died, rich_died]],\n ['survive', 'died'], ['poor','rich'])\n\n\n#df.plot(kind='pie', subplots=True, figsize=(8, 4), autopct='%1.1f%%')\n#plt.show()\n","repo_name":"DanilPomortsev/SPBGU_study","sub_path":"MathPackeges/Pythone/py_lesson.py","file_name":"py_lesson.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30463920422","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path(\"search/\", views.search, name=\"search\"),\n path(\"details/<product_name>/\", views.details, name=\"details\"),\n path(\"substitutes/\", views.substitutes, name=\"substitutes\"),\n path(\"save/\", views.save, name=\"save\"),\n path(\"delete/\", views.delete, name=\"delete\"),\n]\n","repo_name":"fr0zie-OpenClassrooms/Project8","sub_path":"product/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27775687658","text":"import warnings\nimport pymc3 as pm\nimport pandas as pd\nimport arviz as az\nimport theano\n\nwarnings.filterwarnings('ignore')\ntheano.config.compute_test_value = \"warn\"\n\n\ncolnames=['age','sex','chestpain','restbp','cholestoral',\n 'bsugar','electrocardiographic','maxhr','angina',\n 'oldpeak','slopepexercise','numvessels','thal',\n 'heartdisease'\n ]\n\n#https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/\n#df=pd.DataFrame([line.split() for line in open('test/testdata/heart.dat')],columns=colnames)\ndf=pd.DataFrame([line.split() for line in open('data/raw/heart.dat')],columns=colnames)\ndf=df.astype(float)\n#Generate test data\nfor n in df[colnames[:-1]]:\n if not n in ['age','maxhr']:\n df[n]=0.0\ndf.to_csv('test/testdata/heart.csv', index = False)\n","repo_name":"duha-aldebakel/DSC180A-Replication","sub_path":"makeTestData.py","file_name":"makeTestData.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13314654028","text":"import pygame\nimport gym\nimport gym_greedy_snake\n\nfrom stable_baselines3 import DQN\nfrom stable_baselines3.common.vec_env.dummy_vec_env import DummyVecEnv\nfrom stable_baselines3.common.evaluation import evaluate_policy\n\nimport os.path\n\n\nobservation = None\nreward = None\nterminated = None\ntruncated = None\ninfo = None\n\nmodel_path = \"./model/GreddySnake-v0.model\"\nmodel_buffer_path = \"./model/GreddySnake-v0.model_buffer\"\ntensorboard_log_path = \"./tensorboard/GreddySnake-v0/\"\n\n####### test env ########\n\n# env = gym.make('GreedySnakeWorld-v0', render_mode=\"human\", render_fps=30)\n\n# observation, info = env.reset()\n\n# while True:\n# for event in pygame.event.get():\n# if event.type == pygame.QUIT:\n# env.close()\n# elif event.type == pygame.KEYDOWN:\n# isSetp = False\n# if event.key == pygame.K_UP:\n# observation, reward, terminated, truncated, info = env.step(0)\n# isSetp = True\n# elif event.key == pygame.K_DOWN:\n# observation, reward, terminated, truncated, info = env.step(1)\n# isSetp = True\n# elif event.key == pygame.K_LEFT:\n# observation, reward, terminated, truncated, info = env.step(2)\n# isSetp = True\n# elif event.key == pygame.K_RIGHT:\n# observation, reward, terminated, truncated, info = env.step(3)\n# isSetp = True\n\n# if isSetp and terminated:\n# env.reset()\n\n# for _ in range(0, 1000):\n# observation, reward, terminated, truncated, info = env.step(\n# env.action_space.sample())\n# if terminated:\n# env.reset()\n\n# env.close()\n\n####### test env ########\n\n####### learn model ########\n\nenv = gym.make('GreedySnakeWorld-v0', render_mode=\"human\",\n world_size=50, render_fps=120)\n# env = gym.make('GreedySnakeWorld-v0')\n\n# while True:\nmodel = None\n\nif os.path.exists(model_path):\n model = DQN.load(model_path)\n model.load_replay_buffer(model_buffer_path)\nelse:\n model = DQN(\n \"MlpPolicy\",\n env=env,\n learning_rate=2.3e-3,\n batch_size=64,\n buffer_size=100000,\n learning_starts=1000,\n gamma=0.99,\n target_update_interval=10,\n train_freq=256,\n gradient_steps=128,\n exploration_fraction=0.16,\n exploration_final_eps=0.04,\n policy_kwargs={\"net_arch\": [256, 256]},\n verbose=1,\n tensorboard_log=tensorboard_log_path,\n device=\"cuda\",\n )\n\nmodel.set_env(env, force_reset=True)\n\nmodel.learn(total_timesteps=1e6)\n\nmodel.save(model_path)\n\nmodel.save_replay_buffer(model_buffer_path)\n\nenv.close()\n\n####### learn model ########\n\n####### test model########\n\n# env = gym.make('GreedySnakeWorld-v0', render_mode=\"human\",\n# world_size=50, render_fps=120)\n# # env = gym.make('GreedySnakeWorld-v0')\n\n# env = DummyVecEnv([lambda: env])\n\n# model = DQN.load(model_path)\n\n# observation = env.reset()\n\n# best_score = 0\n\n# for i in range(0, 100):\n# score = 0\n# terminated = False\n\n# while not terminated:\n# action, _ = model.predict(observation=observation)\n# observation, reward, terminated, info = env.step(action)\n# score += reward\n# env.render()\n# if score > best_score:\n# best_score = score\n# print(\"index:{} score:{} best_score:{}\".format(i, score, best_score))\n\n# env.close()\n\n####### test model########","repo_name":"zengliugen/GreedySnakeML","sub_path":"Python/greedy_snake_ml/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74783472485","text":"import webbrowser\nreload(webbrowser)\n\nfrom sensor.Sensor import Sensor\nfrom utils import datatypes, i18n\n\nfrom cubicweb.dbapi import connect\n\n_ = str\n\nclass RQLSensor(Sensor):\n\n def __init__(self, *args):\n global _; _ = i18n.Translator(\"rql-desklet\")\n Sensor.__init__(self)\n # define configuration\n self._set_config_type(\"appid\", datatypes.TYPE_STRING, \"\")\n self._set_config_type(\"user\", datatypes.TYPE_STRING, \"\")\n self._set_config_type(\"passwd\", datatypes.TYPE_SECRET_STRING, \"\")\n self._set_config_type(\"rql\", datatypes.TYPE_STRING, \"\")\n self._set_config_type(\"url\", datatypes.TYPE_STRING, \"\")\n self._set_config_type(\"delay\", datatypes.TYPE_STRING, \"600\")\n # default timer\n self._add_timer(20, self.__update)\n\n def get_configurator(self):\n configurator = self._new_configurator()\n configurator.set_name(_(\"RQL\"))\n configurator.add_title(_(\"CubicWeb source settings\"))\n configurator.add_entry(_(\"ID\",), \"appid\", _(\"The application id of this source\"))\n configurator.add_entry(_(\"User\",), \"user\", _(\"The user to connect to this source\"))\n configurator.add_entry(_(\"Password\",), \"passwd\", _(\"The user's password to connect to this source\"))\n configurator.add_entry(_(\"URL\",), \"url\", _(\"The url of the web interface for this source\"))\n configurator.add_entry(_(\"RQL\",), \"rql\", _(\"The rql query\"))\n configurator.add_entry(_(\"Update interval\",), \"delay\", _(\"Delay in seconds between updates\"))\n return configurator\n\n\n def call_action(self, action, path, args=[]):\n index = path[-1]\n output = self._new_output()\n if action==\"enter-line\":\n # change background\n output.set('resultbg[%s]' % index, 'yellow')\n elif action==\"leave-line\":\n # change background\n output.set('resultbg[%s]' % index, 'black')\n elif action==\"click-line\":\n # open url\n output.set('resultbg[%s]' % index, 'black')\n webbrowser.open(self._urls[index])\n self._send_output(output)\n\n def __get_connection(self):\n try:\n return self._v_cnx\n except AttributeError:\n appid, user, passwd = self._get_config(\"appid\"), self._get_config(\"user\"), self._get_config(\"passwd\")\n cnx = connect(database=appid, login=user, password=passwd)\n self._v_cnx = cnx\n return cnx\n\n def __run_query(self, output):\n base = self._get_config('url')\n rql = self._get_config('rql')\n cnx = self.__get_connection()\n cursor = cnx.cursor()\n try:\n rset = cursor.execute(rql)\n except Exception:\n del self._v_cnx\n raise\n self._urls = []\n output.set('layout', 'vertical, 14')\n output.set('length', rset.rowcount)\n i = 0\n for line in rset:\n output.set('result[%s]' % i, ', '.join([str(v) for v in line[1:]]))\n output.set('resultbg[%s]' % i, 'black')\n try:\n self._urls.append(base % 'Any X WHERE X eid %s' % line[0])\n except Exception:\n self._urls.append('')\n i += 1\n\n def __update(self):\n output = self._new_output()\n try:\n self.__run_query(output)\n except Exception as ex:\n import traceback\n traceback.print_exc()\n output.set('layout', 'vertical, 10')\n output.set('length', 1)\n output.set('result[0]', str(ex))\n self._send_output(output)\n self._add_timer(int(self._get_config('delay'))*1000, self.__update)\n\n\ndef new_sensor(args):\n return RQLSensor(*args)\n","repo_name":"gurneyalex/cubicweb","sub_path":"cubicweb/misc/cwdesklets/rqlsensor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12930435767","text":"import blaseball_mike.database as mike\nimport gspread\nimport itertools\nimport json\nimport logging\nimport requests\nfrom sseclient import SSEClient\n\n''' phases\n e[e.Preseason = 1] = \"Preseason\",\n e[e.Earlseason = 2] = \"Earlseason\",\n e[e.EarlySiesta = 3] = \"EarlySiesta\",\n e[e.Midseason = 4] = \"Midseason\",\n e[e.LateSiesta = 5] = \"LateSiesta\",\n e[e.Lateseason = 6] = \"Lateseason\",\n e[e.SeasonEnd = 7] = \"SeasonEnd\",\n e[e.PrePostseason = 8] = \"PrePostseason\",\n e[e.EarlyPostseason = 9] = \"EarlyPostseason\",\n e[e.EarlyPostseasonEnd = 10] = \"EarlyPostseasonEnd\",\n e[e.Postseason = 11] = \"Postseason\",\n e[e.PostseasonEnd = 12] = \"PostseasonEnd\",\n e[e.Election = 13] = \"Election\"\n'''\n\ndef update(spreadsheet_ids):\n '''\n Updates tomorrow's pitchers in this season's snack spreadsheet\n '''\n\n logging.info(\"Updating tomorrow's pitchers...\")\n\n # Get current season\n sim = mike.get_simulation_data()\n season = sim['season']+1\n spreadsheet_id = spreadsheet_ids[season]\n\n # Connect to spreadsheet\n credentials = gspread.service_account()\n worksheet = credentials.open_by_key(spreadsheet_id).worksheet('Tomorrow\\'s Pitchers')\n\n # Map of team ID to shorthand\n teams = mike.get_all_teams()\n teams_shorten = {}\n for team_id in teams:\n teams_shorten[team_id] = teams[team_id]['shorthand']\n\n # Get Tomorrow\n # Preseason, Earlsiesta, and Latesiesta mess up the \"tomorrow\" thing since the day starts before games do\n if sim['phase'] in [1,3,5]:\n tomorrow = sim['day']+1\n # After the brackets have been decided but before the wildcard round begins, it's really complicated\n # Get Day 99 pitchers and the matchups for Day 100\n elif sim['phase'] in [8]:\n tomorrow = 100\n logging.info(\"Pre-Postseason detected. Getting streamData.\")\n matchups_d100 = {}\n pitchers_d99 = {}\n # Get full streamdata\n stream = SSEClient('http://blaseball.com/events/streamData')\n for message in stream:\n # At seemingly fixed intervals, the stream sends an empty message\n if not str(message):\n continue\n data = json.loads(str(message))\n # Sometimes the stream just sends fights\n if 'games' not in data['value']:\n continue\n # At this point, it's safe to process it\n games = json.loads(str(message))['value']['games']\n brackets = games.get('postseasons')\n # ... Maybe. Let's be really sure\n if not brackets:\n continue\n # Get D100 teams\n for bracket in brackets:\n matchups = bracket['allMatchups']\n for matchup in matchups:\n if matchup['awayTeam'] and matchup['homeTeam']: # Only get wildcard matchups\n matchups_d100[matchup['id']] = {\n 'awayTeam': matchup['awayTeam'],\n 'homeTeam': matchup['homeTeam']\n }\n # Get D99 pitchers to calculate D100 pitchers later\n for game in games['schedule']:\n pitchers_d99[game['awayTeam']] = game['awayPitcher']\n pitchers_d99[game['homeTeam']] = game['homePitcher']\n break # Exit the loop now that we've got the necessary streamData\n # If it's just a normal part of the season or postseason after D100, it's super easy\n else:\n # Check if today's games are finished. Tomorrow's pitchers could be wrong, otherwise.\n today = sim['day']+1\n games_today = mike.get_games(season, today).values()\n complete = [game['gameComplete'] for game in games_today]\n if not all(complete):\n logging.info(\"Games not complete. Tomorrow's pitchers might be wrong, so waiting...\")\n return\n tomorrow = sim['day']+2\n\n # Get tomorrow's game\n # mike uses 1-indexed seasons and days as input\n # blaseball.com returns 0-indexed seasons and days\n # If we're preseason, we need to manually get Day 1 pitchers (first in lineup)\n if sim['phase'] in [1]:\n # Get all teams playing\n games = mike.get_games(season, tomorrow)\n for game_id in games:\n team_home_id = games[game_id]['homeTeam']\n team_home = mike.get_team(team_home_id)\n pitcher_home_id = team_home['rotation'][0]\n pitcher_home = mike.get_player(pitcher_home_id)\n pitcher_home_name = list(pitcher_home.values())[0]['name']\n games[game_id]['homeTeam'] = team_home_id\n games[game_id]['homeOdds'] = 0.500\n games[game_id]['homePitcher'] = pitcher_home_id\n games[game_id]['homePitcherName'] = pitcher_home_name\n team_away_id = games[game_id]['awayTeam']\n team_away = mike.get_team(team_away_id)\n pitcher_away_id = team_away['rotation'][0]\n pitcher_away = mike.get_player(pitcher_away_id)\n pitcher_away_name = list(pitcher_away.values())[0]['name']\n games[game_id]['awayTeam'] = team_away_id\n games[game_id]['awayOdds'] = 0.500\n games[game_id]['awayPitcher'] = pitcher_away_id\n games[game_id]['awayPitcherName'] = pitcher_away_name\n # If pre-playoffs, we have to be more creative.\n elif sim['phase'] in [8]:\n # Get wildcard round team details\n team_ids = []\n for matchup in matchups_d100.values():\n team_ids.append(matchup['awayTeam'])\n team_ids.append(matchup['homeTeam'])\n teams_d100 = {}\n for team_id in team_ids:\n team = mike.get_team(team_id)\n teams_d100[team['id']] = team\n \n # Iterate over the playoffs matchups to get D100 pitchers\n games = {}\n inactive_mods = ['ELSEWHERE','SHELLED']\n for idx,matchup in enumerate(matchups_d100.values()):\n games[idx] = {'weather': 0}\n for team_side in ['homeTeam','awayTeam']:\n # Get the ID of the D100 home pitcher. Start by finding slot that pitched D99\n team_id = matchup[team_side]\n rotation = teams_d100[team_id]['rotation']*4\n pitcher_d99 = pitchers_d99[team_id]\n # Get enough games prior to D99 to cover every pitcher slot\n games_before_num = [98-n for n in range(len(teams_d100[team_id]['rotation'])-1)]\n games_sets_before_all = [list(mike.get_games(season, game).values()) for game in games_before_num]\n games_before_team = []\n for games_set_before_all in games_sets_before_all:\n game_before_team = [game for game in games_set_before_all if team_id in game['homeTeam'] or team_id in game['awayTeam']][0]\n games_before_team.append(game_before_team)\n # Loop through those prior games to determine the D99 pitching slot\n slot_99_idx = 0 # Need a default in case there's only one active pitcher.\n for game_idx,game in enumerate(games_before_team):\n if game['homeTeam'] == team_id:\n pitcher_before = game['homePitcher']\n elif game['awayTeam'] == team_id:\n pitcher_before = game['awayPitcher']\n if pitcher_before != pitcher_d99:\n before_idx = rotation.index(pitcher_before)+len(teams_d100[team_id]['rotation'])\n slot_99_idx = 1+game_idx+before_idx\n break\n # Now determine the D100 pitcher.\n # The algorithm is *probably* the second available pitcher after the D99 pitching slot.\n slot_100_idx = slot_99_idx + 1 # Start here\n verified_100 = False\n skippedone = False\n while not verified_100:\n pitcher_d100 = list(mike.get_player(rotation[slot_100_idx]).values())[0]\n pitcher_mods = pitcher_d100['permAttr']+pitcher_d100['seasAttr']+pitcher_d100['itemAttr']\n if not any(mod in pitcher_mods for mod in inactive_mods) and pitcher_d100['id']:\n if not skippedone: # Skip the first available pitcher\n slot_100_idx += 1\n skippedone=True\n continue\n else: # This is it!!\n verified_100 = True\n else:\n slot_100_idx += 1\n continue\n # Now that we've confirmed the pitcher for this game, add to the stand-in games object\n if team_side == 'homeTeam':\n games[idx]['homeTeam'] = team_id\n games[idx]['homeOdds'] = 0.500 # Unknown odds!\n games[idx]['homePitcher'] = pitcher_d100['id']\n games[idx]['homePitcherName'] = pitcher_d100['name']\n elif team_side == 'awayTeam':\n games[idx]['awayTeam'] = team_id\n games[idx]['awayOdds'] = 0.500 # Unknown odds!\n games[idx]['awayPitcher'] = pitcher_d100['id']\n games[idx]['awayPitcherName'] = pitcher_d100['name']\n # Otherwise, just get tomorrow's games normally\n else:\n games = mike.get_games(season, tomorrow)\n\n # Get pitchers\n pitchers = {}\n for game in games.values():\n # Pitcher is faxable if it is a home game for them, and the weather isn't Sun 2 or Black Hole\n faxable = True if game['weather'] not in [1,14] else False\n pitchers[game['homePitcher']] = {\n 'team': teams_shorten[game['homeTeam']],\n 'name': game['homePitcherName'],\n 'odds': round(game['homeOdds'],3),\n 'faxable': faxable,\n 'multiplier': 0\n }\n pitchers[game['awayPitcher']] = {\n 'team': teams_shorten[game['awayTeam']],\n 'name': game['awayPitcherName'],\n 'odds': round(game['awayOdds'],3),\n 'faxable': False,\n 'multiplier': 0\n }\n\n # Get pitcher payout multiplier\n pitcher_details = mike.get_player(list(pitchers.keys()))\n for pitcher_id in pitcher_details:\n # Determine payout multiplier\n player_mods = pitcher_details[pitcher_id]['permAttr']+pitcher_details[pitcher_id]['seasAttr']+pitcher_details[pitcher_id]['itemAttr']\n multiplier = 1\n if 'DOUBLE_PAYOUTS' in player_mods:\n multiplier += 1\n if 'CREDIT_TO_THE_TEAM' in player_mods:\n multiplier += 4\n # Check if this player has a mod preventing them from making money\n inactive_mods = ['ELSEWHERE','SHELLED','LEGENDARY','REPLICA','NON_IDOLIZED']\n can_earn = int(not any(mod in player_mods for mod in inactive_mods))\n if not can_earn:\n multiplier = 0\n pitchers[pitcher_id]['multiplier'] = multiplier\n\n # Sort by multiplier\n pitchers_lists = [list(pitcher.values()) for pitcher in pitchers.values()]\n pitchers_lists.sort(key = lambda x: x[4], reverse=True)\n\n # Pad to 24 pitchers\n while len(pitchers_lists) < 24:\n pitchers_lists.append(['','','','',''])\n\n # Get individual columns\n # teams = [[pitcher[0]] for pitcher in pitchers_lists]\n pitcher_names = [pitcher[0:2] for pitcher in pitchers_lists]\n pitcher_other = [pitcher[2:] for pitcher in pitchers_lists]\n # multipliers = [[pitcher[2]] for pitcher in pitchers_lists]\n # odds = [[pitcher[3]] for pitcher in pitchers_lists]\n # faxable = [[pitcher[4]] for pitcher in pitchers_lists]\n\n # Add tomorrow's pitchers to spreadsheet\n worksheet.update('A4:B', pitcher_names)\n worksheet.update('I4:K', pitcher_other)\n # worksheet.update('I4', odds)\n # worksheet.update('J4', faxable)\n # worksheet.update('K4', multipliers)\n worksheet.update('F1', [[tomorrow]])\n\n logging.info(\"Updated tomorrow's pitchers.\")\n\nif __name__ == \"__main__\":\n spreadsheet_ids = {\n 19: '1_p6jsPxMvO0nGE-fiqGfilu-dxeUc994k2zwAGNVNr0',\n 20: '1EAqMvv2KrC9DjlJdlXrH_JXmHtAStxRJ661lWbuwYQs',\n 21: '1DBCpsYlDOft5wve7IKTXAH-3zeoZIUy7A_R4a5uiYz8',\n 22: '1nC8ZU0dz2kyOH4w78jIcitMdhk9KhVKbKBSXC1QEkXY',\n 23: '1jAHAHGgjpZp_PGDyedEvSSJVY-7Sq9bVkMcMTZjSBtg',\n 24: '12cbSlctxlukuUIxb9T9eo2lIcMmnEqvI7dkF9906a_Q'\n }\n update(spreadsheet_ids)\n","repo_name":"alefeld/blaseball-snackonomy","sub_path":"tomorrowpitchers.py","file_name":"tomorrowpitchers.py","file_ext":"py","file_size_in_byte":12593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12923081484","text":"from flask import Flask, request, abort\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\n\nfrom linebot.exceptions import(\n InvalidSignatureError\n)\n\nfrom linebot.models import (\n MessageEvent, TextMessage, TextSendMessage,\n)\n\nimport json\n\napp = Flask(__name__)\nline_bot_api = LineBotApi(\"JO83I2aU+E2hNCuoftPDI4Mcmvp8ugsNVUPufoTYZo5paFr/7tfZpBsjlRdMnIQLo8u1SYSj5tb5zzwEdCojMDsGfqt/d8GQBMIw0ubroY24KlAqX7is7cCeBjRWvHT3CrzwWcfui8z14PSfgOKiaAdB04t89/1O/w1cDnyilFU=\")\nhandler = WebhookHandler(\"a512ec07066d617e863804ef6654ff02\")\n\n@app.route(\"/callback\",methods=[\"POST\"])\ndef callback():\n signature = request.headers[\"X-Line-Signature\"]\n body = request.get_data(as_text=True)\n json_data = json.loads(body)\n json_str = json.dumps(json_data, indent=4)\n print(json_str)\n \n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n abort(400)\n return 'OK'\n\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n json_data = json.loads(str(event))\n json_str = json.dumps(json_data, indent=4)\n print(json_str)\n \n@app.route(\"/push\")\ndef push_msg():\n try:\n line_bot_api.push_message(\"USER_ID\", TextSendMessage(\"Hi\"))\n return \"push ok\"\n except:\n return \"push error\"\nif __name__ == \"__main__\":\n app.run(port=9595)\n","repo_name":"thinktek1/line-bot","sub_path":"linebot.py","file_name":"linebot.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18074931734","text":"import pygame, random\n\nclass StaticStripesAnimation:\n def __init__(self, App, time_to_appear:int=2000, speed_frame:int=1, random_sprites_range:tuple=(0, 4), alpha=30):\n self.time_to_appear = time_to_appear\n self.timer = pygame.time.get_ticks()\n self.speed_frame = speed_frame\n self.random_sprites_range = random_sprites_range\n self.alpha = alpha\n\n self.update_dims(App)\n\n def update_dims(self, App):\n self.index = random.randint(self.random_sprites_range[0], self.random_sprites_range[1])\n self.chosen_stripe = App.assets.static_stripes[self.index]\n self.chosen_stripe.set_alpha(self.alpha)\n self.big_stripe_dims = self.chosen_stripe.get_rect()\n self.big_stripe_y_location = -self.big_stripe_dims.height\n\n def update(self, App):\n App.surface.blit(self.chosen_stripe, (0, self.big_stripe_y_location))\n self.big_stripe_y_location += self.speed_frame\n if self.big_stripe_y_location > App.dimentions[1]:\n self.big_stripe_y_location = -self.big_stripe_dims.height\n if pygame.time.get_ticks() - self.timer > self.time_to_appear:\n self.update_dims(App)\n else:\n self.timer = pygame.time.get_ticks()","repo_name":"EDUATO/fnaf-in-pygame","sub_path":"files/animations/static_stripe_animation.py","file_name":"static_stripe_animation.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37894254555","text":"import argparse\nimport os, sys\nscript_dir = os.path.dirname(os.path.realpath(__file__))\nsys.path.insert(0, os.path.join(script_dir, \"../\"))\nimport model.build_model\nimport python_server.mapping_features\nimport pandas as pd\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport glob\nfrom os.path import basename, join\nimport math\nimport cv2\nimport numpy as np\n\ndef get_frames(video_file, low_frame_idx=None, high_frame_idx=None):\n frame_count = 0\n cap = cv2.VideoCapture(video_file)\n while cap.isOpened():\n ret, frame = cap.read()\n if not ret:\n break\n\n if low_frame_idx != None and frame_count < low_frame_idx:\n frame_count += 1\n continue\n elif high_frame_idx != None and frame_count > high_frame_idx:\n break\n\n hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n frame_count += 1\n\n if frame_count % 10 == 0:\n print (\"Processed %d frames\"%frame_count)\n\n yield hsv_frame\n\ndef map_frame_to_label(bin_file):\n result = {} # frame_id to label\n frame_id = 0\n # Extracting the features from training data samples\n training_samples = python_server.mapping_features.read_samples(bin_file)\n for sample in training_samples:\n\n label = sample.label\n result[frame_id] = label\n\n frame_id += 1\n return result\n\ndef main(video_file, low_frame_idx, high_frame_idx, bin_file, outdir):\n frame_to_label = map_frame_to_label(bin_file)\n\n sat_bins = 10\n val_bins = 10\n sat_bin_size = 256 / sat_bins\n val_bin_size = 256 / val_bins\n\n data = {True: [], False: []}\n total = {True: 0, False: 0}\n\n for d in [True, False]:\n for idx in range(val_bins):\n data[d].append([0 for i in range(sat_bins)])\n \n frame_count = 0\n for f in get_frames(video_file, low_frame_idx, high_frame_idx):\n if frame_count not in frame_to_label:\n frame_count += 1\n continue\n label = frame_to_label[frame_count]\n\n print (\"Processing frame %d\"%frame_count)\n row = 0\n while row < len(f):\n col = 0\n while col < len(f[row]):\n (h, s, v) = f[row][col]\n \n if (s>0 and v>0) and ((h >= 0 and h <= 10) or (h >= 170 and h <= 180)):\n val_idx = int(v / val_bin_size)\n sat_idx = int(s / sat_bin_size)\n data[label][val_idx][sat_idx] += 1\n total[label] += 1\n col += 4\n row += 4\n frame_count += 1\n \n max_val = 0\n for label in data:\n if total[label] == 0:\n continue\n for r in range(len(data[label])):\n for c in range(len(data[label][r])):\n data[label][r][c] /= float(total[label])\n max_val = max(max_val, data[label][r][c])\n\n for label in data:\n plt.close()\n fig, ax = plt.subplots(figsize=(4,4))\n sns.heatmap(data=np.array(data[label]), ax=ax, cmap=\"BuPu\", vmin=0, vmax=max_val)\n ax.set_xlabel(\"Saturation\")\n ax.set_ylabel(\"Value\")\n fig.savefig(join(outdir, \"red_sv_heatmap_label_%s.png\"%str(label)), bbox_inches=\"tight\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Analyzing the distribution of Pixel Fraction\")\n parser.add_argument(\"-V\", \"--video-file\", dest=\"video_file\", help=\"Path to video file\")\n parser.add_argument(\"-B\", \"--bin-file\", dest=\"bin_file\", help=\"Path to the bin file\")\n parser.add_argument(\"-L\", \"--low-frame-idx\", dest=\"low_frame_idx\", help=\"Low index for frame\", type=int, default=0)\n parser.add_argument(\"-H\", \"--high-frame-idx\", dest=\"high_frame_idx\", help=\"High index for frame\", type=int, default=900)\n parser.add_argument(\"-O\", dest=\"outdir\", help=\"Directory to store output plots\")\n \n args = parser.parse_args()\n main(args.video_file, args.low_frame_idx, args.high_frame_idx, args.bin_file, args.outdir)\n","repo_name":"esaurez/LoadShedderInterface","sub_path":"src/color_analysis/read_pixel_hsv_from_video.py","file_name":"read_pixel_hsv_from_video.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13498211472","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 10 15:12:06 2018\r\nASTR 414 HW2, Problem 3\r\n@author: Ashvini Krishnan\r\nnetid: akrshnn6\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pylab\r\n\r\n\r\n\"\"\"Part a:\"\"\"\r\n#Function to generate random true distances to uniformly distributed supernovas\r\ndef truedist():\r\n#Generation of random radii with a uniform distribution\r\n radii = (np.random.uniform(low=0, high = 1, size = 100))\r\n#Stretch those radii to the spherical probability distribution and return the distances\r\n true_distances = []\r\n for value in radii:\r\n true_distances.append(((8*value)**(1/3))*10**3)\r\n return true_distances\r\n \r\nsum=0\r\ncount = 0\r\n#Find the average of many averages of different random uniformly distributed distances for a \"super average\"\r\n#for value in range(0, 100000):\r\n# sum+=np.average(truedist())\r\n# count+=1\r\n\r\n#avg = str(sum/count)\r\n#print(\"Average True Distance: \" + avg)\r\n\r\n\r\n\"\"\"Part b:\"\"\"\r\ntrue_distances = truedist()\r\nm = []\r\ncount = 0\r\nabs_magnitudes = np.random.normal(-19, 1, 100) \r\nfor i in range(len(true_distances)):\r\n m.append(5*np.log10(true_distances[i]*10**5)+abs_magnitudes[i])\r\n\r\ncount = 0\r\napp_mags = []\r\ndist = []\r\nfor i in range(len(true_distances)):\r\n if m[i]<=20:\r\n app_mags.append(m[i])\r\n dist.append(true_distances[i])\r\n count+=1\r\n \r\nprint(\"Original Average Apparent Magnitude: \" + str(np.average(m)))\r\nprint(\"Detected Average Apparent Magnitude: \" + str(np.average(app_mags)))\r\nprint(\"Number of Detected Supernovas: \" + str(count))\r\n\r\n\"\"\"Part c:\"\"\"\r\nobs_distances = []\r\nfor i in app_mags:\r\n obs_distances.append((10**(((i+19)/5)+1))*10**-6)\r\n \r\nvelocity = []\r\nfor i in obs_distances:\r\n velocity.append(72*i)\r\n \r\ntruevelocity = []\r\nfor i in dist:\r\n truevelocity.append(72*i)\r\n\r\nplt.figure()\r\n\r\n(m,b) = pylab.polyfit(dist, truevelocity,1)\r\nyp1 = pylab.polyval([m,b],dist)\r\nplt.plot(dist,yp1, label= 'True Distance vs Velocity')\r\n\r\nplt.scatter(dist, truevelocity)\r\n\r\n(m2,b2) = pylab.polyfit(obs_distances, truevelocity,1)\r\nyp2 = pylab.polyval([m2,b2],obs_distances)\r\nplt.plot(obs_distances,yp2,label = 'Observed Distance vs Velocity')\r\n\r\nplt.text(400, 90000, \"H0 = \" + str(m2))\r\nplt.scatter(obs_distances, truevelocity)\r\nplt.title('Distance (Mpc) vs Velocity')\r\nplt.xlabel('Distance (Mpc)')\r\nplt.ylabel('Velocity')\r\nplt.errorbar(obs_distances, truevelocity, yerr = np.abs(yp2-truevelocity), fmt = 'o')\r\nplt.legend()\r\n\r\nprint(\"H0 = \" + str(m2))\r\n \r\n ","repo_name":"akrshnn6/astr-414","sub_path":"HW 3/ASTR 414 HW 3.py","file_name":"ASTR 414 HW 3.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1205107835","text":"# day3.py\nimport string\n\nfile_name = \"input.txt\"\nwith open(file_name, \"r\") as file:\n data = [line.strip() for line in file]\n\nletters = {letter: num for num, letter in enumerate(string.ascii_letters)}\n\n\ndef priority_sum(rucksacks: list) -> int:\n \"\"\"Return the sum of the priorities of common elements in rucksack compartments.\n \n Split the rucksacks into compartments, find the common element in each sack and sum the priorities.\n \n Args:\n rucksacks (list): list of string rucksacks\n Returns:\n Integer sum of priorities of common elements in each sack\n \"\"\"\n _priority_sum = 0\n for rucksack in data:\n compartments = rucksack[:len(rucksack)//2], rucksack[len(rucksack)//2:]\n common_elements = [item for item in compartments[0] if item in compartments[1]]\n _priority_sum += letters[common_elements[0]]+1\n return _priority_sum\n\n\ndef badge_priority_sum(rucksacks: list) -> int:\n \"\"\"Return the sum of the priorities of common elements in groups of three.\n\n Split the data into groups of three, find the common element, sum the priorities.\n\n Args:\n rucksacks (list): list of string rucksacks\n Returns:\n Integer sum of priorities of common elements in each group of three\n \"\"\"\n groups = [rucksacks[i-3:i] for i in range(3, len(rucksacks)+1, 3)]\n _priority_sum = 0\n for group in groups:\n common_elements = [item for item in group[0] if item in group[1] and item in group[2]]\n _priority_sum += letters[common_elements[0]]+1\n return _priority_sum\n\n\nprint(priority_sum(data))\nprint(badge_priority_sum(data))\n","repo_name":"RunnersNum40/Advent-of-Code-2022","sub_path":"03/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4919102160","text":"import koji\nimport sys\nfrom concurrent.futures import ThreadPoolExecutor\n\narches = ['x86_64', 'armhfp', 'aarch64', 'ppc64', 'ppc64le', 's390x']\nkoji_urls = {'Production': 'https://koji.fedoraproject.org/kojihub',\n 'Staging': 'https://koji.stg.fedoraproject.org/kojihub'}\n\ndef pretty_table(caption, tab, footer):\n widths = [max([len(str(row[col])) for row in tab]) for col in range(0, len(tab[0]))]\n def free_text(text):\n return text + \" \" * (sum([width + 3 for width in widths]) - len(text) + 1)\n def separator_row(begin, middle, end):\n return begin + middle.join([\"─\" * (width + 2) for width in widths]) + end\n def table_row(data):\n return \"│ \" + \" │ \".join(\" \" * (width - len(str(item))) + str(item) for item, width in zip(data, widths)) + \" │\"\n return [free_text(caption), separator_row(\"┌\", \"┬\", \"┐\"), table_row(tab[0]), separator_row(\"├\", \"┼\", \"┤\")] + \\\n [table_row(row) for row in tab[1:]] + [separator_row(\"└\", \"┴\", \"┘\"), free_text(footer)]\n\ndef gather_data(env):\n session = koji.ClientSession(koji_urls[env])\n channel = session.getChannel('default')\n hosts = session.listHosts(arches, channel['id'], enabled=True)\n rows = [['arch', 'builders', 'capacity', 'load', 'rel load']]\n max_load = 0\n for arch in arches:\n arch_hosts = [host for host in hosts if arch in host['arches']]\n capacity = sum(host['capacity'] for host in arch_hosts)\n load = sum(min(host['task_load'], host['capacity']) if host['ready']\n else host['capacity'] for host in arch_hosts)\n relative_load = \"%3.2f %%\" % (100 * load / capacity) if capacity else \"N/A\"\n max_load = max(max_load, 100 * load / capacity) if capacity else max_load\n rows.append([arch, len(arch_hosts), \"%3.2f\" % capacity, \"%3.2f\" % load, relative_load])\n return pretty_table(env + \":\", rows, \"Effective load: %3.2f %%\" % max_load)\n\nwith ThreadPoolExecutor(max_workers=16) as executor:\n result = [f.result() for f in [executor.submit(gather_data, env) for env in sorted(koji_urls.keys())]]\n for a, b in zip(*result):\n print(\" \".join([a, b]))\n","repo_name":"fedora-infra/koschei","sub_path":"aux/koji-load.py","file_name":"koji-load.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"52"} +{"seq_id":"1083414845","text":"from aiohttp.web import Application\nimport asyncio\nfrom asyncio.events import TimerHandle\nfrom datetime import datetime\n\nfrom foundation.parse_format import ParseFormats\nfrom foundation.config import Config\n\nfrom utils.auction_utils import log\nfrom abc import ABC\nfrom abc import abstractmethod\n\nclass Agent(ABC):\n\n def __init__(self, config_file_name: str):\n self._pending_tasks_by_auction = {}\n\n self.config = Config(config_file_name).get_config()\n\n # Start Listening the web server application\n loop = asyncio.get_event_loop()\n self.app = Application(loop=loop)\n\n # Gets the log file\n log_file_name = self.config['DefaultLogFile']\n self.logger = log(log_file_name).get_logger()\n\n self.domain = ParseFormats.parse_int(Config().get_config_param('Main', 'Domain'))\n self.immediate_start = ParseFormats.parse_bool(Config().get_config_param('Main', 'ImmediateStart'))\n\n self._load_main_data()\n self._load_control_data()\n\n @abstractmethod\n def _load_main_data(self):\n pass\n\n def _add_pending_tasks(self, key: str, call: TimerHandle, when: float):\n \"\"\"\n Adds a pending tasks for an auctioning object identified by its key\n :param key: key of the auctioning object\n :param call: the awaitable that was scheduled to execute.\n :return:\n \"\"\"\n if key not in self._pending_tasks_by_auction:\n self._pending_tasks_by_auction[key] = {}\n\n self._pending_tasks_by_auction[key][when] = call\n\n def _remove_pending_task(self, key: str, when: float):\n \"\"\"\n Removes a pending task for an auctioning object identified by key\n and scheduled at a specific time\n\n :param key: auctioning object key\n :param when: specific time when it was scheduled.\n :return:\n \"\"\"\n if key in self._pending_tasks_by_auction:\n if when in self._pending_tasks_by_auction[key]:\n self._pending_tasks_by_auction[key].pop(when)\n\n def _load_control_data(self):\n \"\"\"\n Sets the control data defined in the configuration file\n \"\"\"\n self.logger.debug(\"Stating _load_control_data\")\n\n try:\n self.use_ssl = ParseFormats.parse_bool(Config().get_config_param('Control','UseSSL'))\n self.control_port = ParseFormats.parse_uint16(Config().get_config_param('Control','ControlPort'))\n self.log_on_connect = ParseFormats.parse_bool(Config().get_config_param('Control','LogOnConnect'))\n self.log_command = ParseFormats.parse_bool(Config().get_config_param('Control','LogCommand'))\n self.control_hosts = self.config['Control']['Access']['Host']\n self.control_user, self.control_passwd = \\\n self.config['Control']['Access']['User'].split(':')\n\n self.logger.debug(\"Ending _load_control_data\")\n\n except ValueError as verr:\n self.logger.error(\"The value for control port{0} is not a valid number\".format(\n Config().get_config_param('Control', 'ControlPort')))\n\n raise ValueError(\"The value for control port{0} is not a valid number\".format(\n Config().get_config_param('Control', 'ControlPort')))","repo_name":"lmarent/Auction_Engine","sub_path":"auction/foundation/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14337975759","text":"\"\"\"\ndictionary 字典\n 列表是有序的对象集合\n 字典是无序的对象集合\n用{}定义\n用键值对存储数据\n 键 key 是索引\n 值 value 是数据\n 键和值之间使用 : 分隔 数据之间用 , 分隔\n 键必须是唯一的\n 值可以是任意数据\n\ndict[key] 取值\ndict[key] = data 增加/修改 存在key,则是修改,不存在就是新增元素\ndict.pop(key) 删除数据\nlen(dict) 统计元素数量\ndict.update(temp_dict) 合并字典 如果被合并的字典中包含已经存在的键,会覆盖原有的值\ndict.clear() 清空字典\n\"\"\"\n\ndict = {\"name\": \"zhangsan\",\n \"gender\": True,\n \"height\": 1.75}\n\nprint(dict)\nprint(dict[\"name\"])\ndict[\"age\"] = 18\nprint(dict)\ndict[\"age\"] = 21\nprint(dict)\ndict.pop(\"age\")\nprint(dict)\n\ntemp_dic = {\"name\": \"lisi\"}\ndict.update(temp_dic)\nprint(dict)\n\nfor k in dict:\n print(k, end=\" - \")\n print(dict[k])\n\ncount_dict = {\n 'b': 2,\n 'h': 2,\n 'c': 5,\n 'e': 4,\n 'w': 3,\n 'q': 3,\n 'a': 7,\n}\n#按value从小到大排序\na = sorted(count_dict.items(), key=lambda x: x[1])\n#按value从大到小排序\na1 = sorted(count_dict.items(), key=lambda x: x[1], reverse=True)\n#按key从小到大排序\na2 = sorted(count_dict.items(), key=lambda x: x[0])\n#按key从大到小排序\na3 = sorted(count_dict.items(), key=lambda x: x[0], reverse=True)\n#切片取vlaue最大的3个\na4 = a1[:3]","repo_name":"iceknc/python_study_note","sub_path":"cn/iceknc/study/a_python_base/o_dict.py","file_name":"o_dict.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70635772645","text":"import sys\ninput = sys.stdin.readline\n\nn,m = map(int, input().split())\narr=[]\nvisited=[]\nstack=[]\nfor i in range(n):\n number = input().rstrip()\n row = list(map(int,str(number)))\n arr.append(row)\n visited.append([0]*m)\n\ndx = [0,0,1,-1]\ndy = [1,-1,0,0]\n\n\ndef dfs(i,j):\n \n for k in range(4):\n x = j+dx[k]\n y = i+dy[k]\n if x<m and x>=0 and y<n and y>=0:\n if visited[y][x]==0 and arr[y][x]==1:\n stack.append([y,x])\n visited[y][x]=1\n if x==m-1 and y ==n-1:\n print(len(stack))\n exit\n dfs(y,x)\n \n else:\n stack.pop()\n\n\nfor i in range(n):\n for j in range(m):\n if visited[i][j]==0 and arr[i][j]==1:\n stack.append([i,j])\n visited[i][j]=1\n dfs(i,j)\n\n#print(len(stack))\n","repo_name":"Youngini/Algorithm","sub_path":"BOJ/[DFS&BFS][2178]미로 탐색/ksh/dfs_틀림.py","file_name":"dfs_틀림.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35583173426","text":"\n# <-- in python, hashtags are used to tell the computer that a line is not worth reading\n# much like in social media\n \n \n##to run this you code need, python 2.7 and numpy\n \n## here we have a scripted program, the computer reads each line, line by line, and then\n#excecutes them\n \n \n## this section imports libraries the program needs (code written by other people)\nimport numpy as np\nfrom pylab import imshow, show\n \n## below is a variable, a name that stores numbers or words\nthisISaVariable = 5 #here we set the variable \"thisISaVariable\" equal to 5 as an illustration\n \n#this variable sets how many iterations we perform\nmax_iters = 20\n \n##below is a \"function\" called \"mandel\", it takes some variables \"(x, y, max_iters)\" to do some task\n## this one checks if our value in each box is bigger than 4\ndef mandel(x, y, max_iters):\n c = complex(x, y) # here we are setting c equal to the coordinate of the box\n z = 0.0j # here we set our initial conditions for z = 0\n for i in range(max_iters): #this is a \"for\" loop- it runs from i = 1 to i = max_iters \n z = z*z + c\n if (z.real*z.real + z.imag*z.imag) >= 4: #this tests if the magnitude is larger than 4\n return i #this returns to the main program how many iterations it took before z became > 4\n return max_iters\n \n \n##this is the main \"function\" of the program calls \"mandel\" at each pixel, then builds it into an image\ndef create_fractal(min_x, max_x, min_y, max_y, image, iters):\n height = image.shape[0]\n width = image.shape[1]\n \n pixel_size_x = (max_x - min_x) / width\n pixel_size_y = (max_y - min_y) / height\n \n for x in range(width): # this loops through all the points in a row\n real = min_x + x * pixel_size_x\n for y in range(height): # this loops through all the points in a column\n imag = min_y + y * pixel_size_y\n color = mandel(real, imag, iters) #this calls the mandel function on each point\n image[y, x] = color\n imshow(image) #this plots the image\n show() \n \nimage = np.zeros((1024, 1536), dtype = np.uint8) #this generates the image the data will be saved to\ncreate_fractal(-2.0, 1.0, -1.0, 1.0, image, max_iters) #this calls the main function and gives it some values\n \n# imshow(image) #this plots the image\n# show() ","repo_name":"eduvallejo/gauss","sub_path":"pythonFractal.py","file_name":"pythonFractal.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34821335841","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\n\n\n# In[2]:\n\n\n#create a file handle\nNames= open('names.txt', \"r\")\n\n\n# In[3]:\n\n\n# set total and count\ntotal = 0\ncount = 0\n\n\n# In[4]:\n\n\n#iterate over, strip spaces, split string, define age, compute total, and iterate count\nfor line in Names:\n line = line.strip()\n FName = line.split()\n age = int(FName[-1])\n total = total + age\n count = count + 1\n\n\n# In[5]:\n\n\n# compute avg and print\navg = total/count\nprint(avg)\n\n\n# In[6]:\n\n\nNames.close()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"knowledgeforall/Big_Data","sub_path":"Big Data/Module 1 Lab Python Scripting Q3.py","file_name":"Module 1 Lab Python Scripting Q3.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5876924901","text":"file = './result/result_aiops.txt'\nf = open(file)\nsum_f1 = 0.0\ncnt = 0\nfor line in f:\n lis = line.strip().split(' ')\n sum_f1 += float(lis[6])\n cnt+=1\nprint(cnt)\nprint(sum_f1/cnt)\nf.close()","repo_name":"CyberOoops/donut","sub_path":"getscore.py","file_name":"getscore.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72103521124","text":"import os\nimport sys\nimport numpy as np\nimport PIL.Image as pil\nfrom skimage.transform import resize\n\nsys.path.append('../')\n\nfrom cnn.config import Config\nfrom cnn.utils import Dataset\nfrom cnn.model import Model\n\n\nclass UltrasoundConfig(Config):\n DATA_PATH = 'sample_data/ultrasound-nerve-segmentation'\n INPUT_SHAPE = (256, 256, 1)\n SAVE_NAME = 'ultrasound-unet-small-dice'\n LOSS = 'dice'\n OPTIMIZER = {\"name\": \"Adam\", \"decay\": 0, \"momentum\": 0.95, \"epsilon\": 0}\n LEARNING_RATE = .0001\n BATCH_SIZE = 16\n NUM_CLASSES = 1\n NUM_EPOCHS = 20\n MODEL_NAME = 'u-net-small'\n TEST_SPLIT = .1\n VAL_SPLIT = .1\n\n\nclass UltrasoundDataset(Dataset):\n\n def load_data(self, path, input_shape, nonzero_only=False):\n\n # Load all of the images\n\n print('-'*100)\n print(\"Loading Images\\n\")\n files = next(os.walk(path + '/train'))[2]\n files = np.array([file for file in files if '_mask' not in file])\n\n self.X[\"all\"] = np.zeros(((len(files), ) + input_shape), np.float32)\n self.y[\"all\"] = np.zeros(((len(files),) + input_shape), np.float32)\n\n for idx, file in enumerate(files):\n tif = np.array(pil.open(os.path.join(path + '/train', file)), np.float32)\n self.X[\"all\"][idx] = resize(tif, input_shape, mode='constant', anti_aliasing=True,\n preserve_range=True) / 255 * 2 - 1\n\n tif = np.array(pil.open(os.path.join(path + '/train', file.split('.')[0] + '_mask.tif')), np.float32)\n self.y[\"all\"][idx] = resize(tif, input_shape, mode='constant', anti_aliasing=True,\n preserve_range=True) / 255\n\n if (idx + 1) % 1000 == 0:\n print(\"Loaded {} of {}\".format(idx + 1, len(files)))\n\n # Resizing the masks often creates values other than 0 or 1\n self.y[\"all\"][self.y[\"all\"] > 0] = 1\n\n # The option to train on non-empy masks only\n if nonzero_only:\n nonzero_samples = np.unique(np.nonzero(self.y[\"all\"])[0])\n print(\"\\nNumber of nonzero samples: \", nonzero_samples.size)\n\n self.X[\"all\"] = self.X[\"all\"][nonzero_samples]\n self.y[\"all\"] = self.y[\"all\"][nonzero_samples]\n\n\nif __name__ == \"__main__\":\n\n # Create the Config object\n config = UltrasoundConfig()\n\n # Create the Dataset object and load the data\n dataset = UltrasoundDataset()\n dataset.load_data(config.DATA_PATH, config.INPUT_SHAPE, nonzero_only=False)\n dataset.split_data(test_size=config.TEST_SPLIT, validation_size=config.VAL_SPLIT)\n\n # Create the model and train the model\n model = Model()\n model.train(dataset, config)\n\n # Evaluate the model on the test data and visualize some predictions\n model.evaluate_test(dataset, config, to_csv=True)\n model.visualize_patch_segmentation_predictions(dataset.X[\"validation\"], dataset.y[\"validation\"], num_predictions=3)\n","repo_name":"alexmagsam/3Screen-CNN","sub_path":"sample_scripts/ultrasound_nerve_segmentation.py","file_name":"ultrasound_nerve_segmentation.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8815715106","text":"#!/usr/bin/env python3\n\nimport boto3\nfrom boto3.dynamodb.conditions import Key\nfrom bson import json_util\nfrom datetime import date, datetime\nimport dash\nfrom dash.dependencies import Input, Output, State\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dotenv import load_dotenv\nimport json\nimport os\nimport pandas as pd\nfrom pymongo import MongoClient\nimport re\nfrom app import app, server\nfrom urllib.request import urlopen\nimport plotly.express as px\nimport plotly.graph_objects as go\n\nimport pickle\n\n# Dropdowns\nincrementals = [\"Incremental\", \"Cumulative\"]\nmetrics_list = [\"% Positive\", \"Confirmed Cases\", \"Deaths\"]\n\n# Mongo stuff general\ndef json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n\n if isinstance(obj, (datetime, date)):\n return obj.isoformat()\n raise TypeError (\"Type %s not serializable\" % type(obj))\n\n## AWS stuff\nload_dotenv(os.path.join(os.getcwd(),\"vars.env\"))\nAWS_KEY=os.getenv('AWS_KEY')\nAWS_SECRET=os.getenv('AWS_SECRET')\n\n\n\n\ns3 = boto3.client('s3',\n aws_access_key_id=AWS_KEY,\n aws_secret_access_key=AWS_SECRET,\n region_name='us-east-2')\n\n\n\n\n\n\nwith urlopen(\"https://raw.githubusercontent.com/python-visualization/folium/master/examples/data/us-states.json\"\n) as response:\n states = json.load(response)\n\n\nstates_conversion = s3.get_object(Bucket=\"us-corona-tracking-data\", Key=\"states.csv\")\nstates_conversion = pd.read_csv(states_conversion['Body']).set_index([\"Abbreviation\"])\nstates_conversion_dict = states_conversion.to_dict()[\"State\"]\n\n\nstates_conversion_index = states_conversion.reset_index().State.to_dict()\nstates_conversion_index = dict((v,k) for k,v in states_conversion_index.items())\n\nblank_graph={'data':[], 'layout':{'margin':{\"l\": 0, \"b\": 0, \"t\": 0, \"r\": 0}}}\n\napp.layout = html.Div([\n html.Div([\n # Row 1 Title\n html.H3(\"US COVID Tracking\")\n ], className=\"row_one_container\"),\n\n # Row 2: About\n html.Div([\n html.Div([\n html.P(\"This dashboard is intended to track the spread of the COVID-19 through the US. Testing data is provided by \",style={'display':'inline-block', 'margin':'5px'}),\n html.A('The COVID Tracking Project', href='https://covidtracking.com', target='_blank'),\n html.P(\" while case reports and fatalities are provided by \",style={'display':'inline-block', 'margin':'5px'}),\n html.A('JHU', href='https://github.com/CSSEGISandData/COVID-19', target='_blank'),\n html.Br(),\n html.P(\"Clicking on states in the map below will apply a state level filter. \",style={'display':'inline-block', 'margin':'5px'})\n\n ], className='about_app_blurb_container')\n ], className=\"row_two_container\"),\n\n html.Div(id=\"state_filter\", style={'display':'none'}),\n html.Div(id=\"map_data\", style={\"display\":\"none\"}),\n # Selectors\n\n html.Div([\n html.Div([html.P([\"Map Metric: \"])], className=\"dropdown_label\"),\n html.Div([\n dcc.Dropdown(\n id='metrics-dropdown',\n options=[{'label':metric, 'value':metric} for metric in metrics_list],\n value='Confirmed Cases'\n )\n ], className=\"metric_dd_container\"),\n html.Div([]),\n html.Button('Clear Geography Filter', id='clear-geo', className='geo_button_visible'),\n html.Div([]),\n html.Div([html.P([\"Metric Type: \"])], className=\"dropdown_label\"),\n html.Div([\n dcc.Dropdown(\n id='incremental-dropdown',\n options=[{'label':incremental,'value':incremental} for incremental in incrementals],\n value='Incremental')\n ], className='incremental_dd_container'),\n\n ], className='row_three_container'),\n # Graphs\n\n html.Div([\n html.Div([\n html.P(\"Title\", id=\"map_graph_label\", className=\"title_bar_default\"),\n dcc.Graph(id=\"state_map_plot\", figure=blank_graph, className='regular_graph')\n ],className=\"graph_container\"),\n html.Div([\n html.P(\"Title\", id=\"positive_graph_label\", className=\"title_bar_positive\"),\n dcc.Graph(id='testing_plot', figure=blank_graph, className='regular_graph')\n ],className=\"graph_container\"),\n html.Div([\n html.P(\"Title\", id=\"cases_graph_label\", className=\"title_bar_cases\"),\n dcc.Graph(id='confirmed_cases_plot', figure=blank_graph, className='regular_graph')\n ],className=\"graph_container\"),\n html.Div([\n html.P(\"Title\", id=\"deaths_graph_label\", className='title_bar_deaths'),\n dcc.Graph(id='deaths_plot', className='regular_graph')\n ],className='graph_container')\n ], className='graph_grid')\n\n\n],id=\"main_container\")\n\n@app.callback(\n [Output('map_graph_label', 'children'),\n Output('positive_graph_label', 'children'),\n Output('cases_graph_label', 'children'),\n Output('deaths_graph_label','children'),\n Output('map_data', 'children')\n ],\n [Input('incremental-dropdown', 'value'),\n Input('metrics-dropdown', 'value'),\n Input('state_filter', 'children')]\n)\ndef update_title_bar_labels(incremental, metric, state_filter):\n\n maps_df = s3.get_object(Bucket=\"us-corona-tracking-data\", Key=\"df_for_maps.csv\")\n maps_df = pd.read_csv(maps_df['Body'])\n map_date = maps_df['Date'].max()\n maps_df = json.dumps(maps_df.to_json()) # or, more generally, json.dumps(cleaned_df)\n\n try:\n state_name = json.loads(state_filter)[\"points\"][0][\"customdata\"][1]\n except:\n state_name = \"CW\"\n\n first_label = [incremental + \" \" + metric + \": \" + map_date]\n out = [(incremental + \" \" + metric + \" - \" + state_name) for metric in metrics_list]\n out = first_label + out + [maps_df]\n return(tuple(out))\n\n@app.callback(\n Output('map_graph_label', 'className'),\n [Input('metrics-dropdown', 'value')]\n)\ndef update_title_bar_labels(metric):\n if metric == \"% Positive\":\n out = \"title_bar_positive\"\n elif metric == \"Deaths\":\n out = \"title_bar_deaths\"\n elif metric == \"Confirmed Cases\":\n out = \"title_bar_cases\"\n return(out)\n\n@app.callback(\n [Output('testing_plot', 'figure'),\n Output('confirmed_cases_plot', 'figure'),\n Output('deaths_plot', 'figure')],\n [Input('incremental-dropdown', 'value'),\n Input('state_filter', 'children')]\n)\ndef update_graph_testing_rate(incremental, state_filter):\n try:\n state_filter = json.loads(state_filter)[\"points\"][0][\"customdata\"][0]\n except TypeError:\n state_filter = \"Countrywide\"\n\n bar_plots= s3.get_object(Bucket=\"us-corona-tracking-plots\", Key=state_filter+\"_barplot.pkl\")\n bar_plots = pickle.loads(bar_plots[\"Body\"].read())\n incremental = str.lower(incremental) + \"_plots\"\n out = (bar_plots[incremental][\"testing\"],\n bar_plots[incremental][\"confirmed\"],\n bar_plots[incremental][\"deaths\"])\n return out\n\ndef find_state_index(full_state_name):\n return(int(states_conversion_index[full_state_name]))\n\ndef add_selected_data(map, index_number=\"Countrywide\"):\n if index_number==\"Countrywide\":\n return(map)\n else:\n go_map = go.Figure(map.to_dict())\n go_map = go_map.update_traces(selectedpoints=[index_number], selected={\"marker\":{\"opacity\": 0.5}})\n return(go_map)\n\n@app.callback(\n Output('state_map_plot', 'figure'),\n [Input('incremental-dropdown', 'value'),\n Input('metrics-dropdown', 'value'),\n Input('clear-geo', \"n_clicks\"),\n Input('map_data', 'children')],\n [State('state_filter', 'children')])\ndef create_map(incremental, metric, n_clicks, map_data, state_filter):\n try:\n state_filter = int(json.loads(state_filter)['points'][0]['pointIndex'])\n except TypeError:\n state_filter = \"Countrywide\"\n\n if metric == \"% Positive\":\n col_to_plot = \"%Positive\"\n colors = \"Purpor\"\n format_type = \":.1f%\"\n elif metric == \"Confirmed Cases\":\n col_to_plot=\"Cases\"\n colors=\"Greens\"\n format_type = \":,.0f\"\n else:\n col_to_plot = \"Deaths\"\n colors = \"Blues\"\n format_type = \":,.0f\"\n\n map_data = pd.read_json(json.loads(map_data))\n\n df_to_plot = map_data[map_data[\"Incremental\"]==incremental]\n df_to_plot['color_field'] = df_to_plot[col_to_plot]/max(df_to_plot[col_to_plot])\n\n if metric == \"% Positive\":\n fig = px.choropleth_mapbox(df_to_plot, geojson=states, locations='id', color='color_field',\n color_continuous_scale=colors,\n range_color=(0, 0.5),\n mapbox_style=\"carto-positron\",\n zoom=2.5, center = {\"lat\": 37.0902, \"lon\": -95.7129},\n opacity=0.5,\n hover_data={'State':True,\n 'id':False,\n 'color_field':False,\n col_to_plot:format_type})\n else:\n fig = px.choropleth_mapbox(df_to_plot, geojson=states, locations='id', color='color_field',\n color_continuous_scale=colors,\n #range_color=(0, 40),\n mapbox_style=\"carto-positron\",\n zoom=2.5, center = {\"lat\": 37.0902, \"lon\": -95.7129},\n opacity=0.5,\n hover_data={'State':True,\n 'id':False,\n 'color_field':False,\n col_to_plot:format_type}\n )\n\n\n\n fig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0},\n coloraxis_showscale=False)\n fig.update_layout(clickmode='event+select')\n if dash.callback_context.triggered[0]['prop_id'].split('.')[0] != 'clear-geo':\n fig = add_selected_data(fig, state_filter)\n\n return(fig)\n\n\n# Grabs map query\n@app.callback(\n Output('state_filter', 'children'),\n [Input('state_map_plot', 'selectedData'),\n Input('clear-geo', 'n_clicks')])\ndef display_click_data(selectedData, n_clicks):\n #if clickData == None: return(None)\n #return(clickData[\"points\"][0][\"customdata\"][0])\n if dash.callback_context.triggered[0]['prop_id'].split('.')[0] == 'state_map_plot':\n return json.dumps(selectedData, indent=2)\n else:\n return None\n\n# Sets Geo button to Invisible\n@app.callback(\n Output('clear-geo', 'className'),\n [Input('state_map_plot', 'selectedData'),\n Input('clear-geo', 'n_clicks')])\ndef display_click_data(selectedData, n_clicks):\n if dash.callback_context.triggered[0]['prop_id'].split('.')[0] == 'clear-geo':\n return('geo_button_hidden')\n elif selectedData != None:\n return(\"geo_button_visible\")\n else:\n return 'geo_button_hidden'\n\n\nif __name__ == '__main__':\n app.run_server(debug=False)\n","repo_name":"Flyvemaskine/corona","sub_path":"dash_app/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":11132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13807214459","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# Dependency imports\n\nfrom absl.testing import absltest\nfrom disentanglement_lib.data.ground_truth import dummy_data\nfrom disentanglement_lib.evaluation.metrics import fairness\nfrom disentanglement_lib.evaluation.metrics import utils\nimport numpy as np\nimport gin.tf\n\n\nclass FairnessTest(absltest.TestCase):\n\n def test_metric(self):\n gin.bind_parameter(\"predictor.predictor_fn\",\n utils.gradient_boosting_classifier)\n ground_truth_data = dummy_data.DummyData()\n def representation_function(x):\n return np.array(x, dtype=np.float64)[:, :, 0, 0]\n random_state = np.random.RandomState(0)\n _ = fairness.compute_fairness(ground_truth_data, representation_function,\n random_state, None, 1000, 1000)\n\n def test_inter_group_fairness(self):\n counts = np.array([[0, 100], [100, 100]])\n mean_fairness, max_fairness = fairness.inter_group_fairness(counts)\n # The overall distribution is 1/3 to 2/3.\n # The first sensitive class has a distribution of 0 to 1.\n # The second sensitive class has a distribution of 1/2 to 1/2.\n # The total variation distances are hence 1/3 and 1/6 respectively.\n # The mean fairness is hence 1/3*1/3 + 2/3*1/6 = 2/9.\n self.assertAlmostEqual(mean_fairness, 2. / 9.)\n self.assertAlmostEqual(max_fairness, 1 / 3.)\n\n def test_compute_scores_dict(self):\n scores = np.array([[0., 2., 4.], [4., 0., 8.], [2., 10., 0.]])\n results = fairness.compute_scores_dict(scores, \"test\")\n shouldbe = {\n # Single scores.\n \"test:pred0:sens1\": 2.,\n \"test:pred0:sens2\": 4.,\n \"test:pred1:sens0\": 4.,\n \"test:pred1:sens2\": 8.,\n \"test:pred2:sens0\": 2.,\n \"test:pred2:sens1\": 10.,\n # Column scores.\n \"test:pred0:mean_sens\": 3.,\n \"test:pred0:max_sens\": 4.,\n \"test:pred1:mean_sens\": 6.,\n \"test:pred1:max_sens\": 8.,\n \"test:pred2:mean_sens\": 6.,\n \"test:pred2:max_sens\": 10.,\n # Column scores.\n \"test:sens0:mean_pred\": 3.,\n \"test:sens0:max_pred\": 4.,\n \"test:sens1:mean_pred\": 6.,\n \"test:sens1:max_pred\": 10.,\n \"test:sens2:mean_pred\": 6.,\n \"test:sens2:max_pred\": 8.,\n # All scores.\n \"test:mean_sens:mean_pred\": 5.,\n \"test:mean_sens:max_pred\": 22. / 3.,\n \"test:max_sens:mean_pred\": 6.,\n \"test:max_sens:max_pred\": 10.,\n \"test:mean_pred:mean_sens\": 5.,\n \"test:mean_pred:max_sens\": 22. / 3.,\n \"test:max_pred:mean_sens\": 6.,\n \"test:max_pred:max_sens\": 10.,\n }\n self.assertDictEqual(shouldbe, results)\n\n\nif __name__ == \"__main__\":\n absltest.main()\n","repo_name":"google-research/disentanglement_lib","sub_path":"disentanglement_lib/evaluation/metrics/fairness_test.py","file_name":"fairness_test.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":1328,"dataset":"github-code","pt":"52"} +{"seq_id":"17663856694","text":"import pickle\nimport shutil\nimport tempfile\nimport unittest\nimport os.path\nimport copy\nimport itertools\nfrom unittest.mock import patch, Mock\n\nimport nltk\nfrom gensim import corpora\nfrom lemmagen3 import Lemmatizer\nfrom requests.exceptions import ConnectionError\nimport numpy as np\n\nfrom orangecontrib.text import preprocess, tag\nfrom orangecontrib.text.corpus import Corpus\nfrom orangecontrib.text.preprocess import BASE_TOKENIZER, PreprocessorList\nfrom orangecontrib.text.preprocess.normalize import file_to_language, \\\n file_to_name, language_to_name, UDPipeModels\n\n\nSF_LIST = \"orangecontrib.text.preprocess.normalize.serverfiles.ServerFiles.listfiles\"\nSF_DOWNLOAD = \"orangecontrib.text.preprocess.normalize.serverfiles.ServerFiles.download\"\nSERVER_FILES = [\n (\"slovenian-sst-ud-2.0-170801.udpipe\",),\n (\"slovenian-ud-2.0-170801.udpipe\",),\n (\"english-lines-ud-2.0-170801.udpipe\",),\n (\"english-ud-2.0-170801.udpipe\",),\n (\"english-partut-ud-2.0-170801.udpipe\",),\n (\"portuguese-ud-2.0-170801.udpipe\",),\n (\"lithuanian-ud-2.0-170801.udpipe\",),\n]\n\n\ndef download_patch(_, *path, **kwargs):\n to_ = kwargs[\"target\"]\n from_ = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"data\")\n shutil.copyfile(os.path.join(from_, path[0]), to_)\n\n\nclass PreprocessTests(unittest.TestCase):\n sentence = \"Human machine interface for lab abc computer applications\"\n\n def setUp(self):\n self.corpus = Corpus.from_file(\"deerwester\")\n self.pp_list = [preprocess.LowercaseTransformer(),\n preprocess.WordPunctTokenizer(),\n preprocess.SnowballStemmer(),\n preprocess.NGrams(),\n tag.AveragedPerceptronTagger()]\n\n def test_preprocess(self):\n corpus = self.corpus # type: Corpus\n self.assertIsNone(corpus._tokens)\n self.assertIsNone(corpus.pos_tags)\n for pp in self.pp_list:\n corpus = pp(corpus)\n self.assertEqual([8, 10, 6, 8, 9, 7, 7, 10, 4],\n list(map(len, corpus._tokens)))\n self.assertIsNotNone(corpus._tokens)\n self.assertIsNotNone(corpus.pos_tags)\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 5)\n\n def test_used_preprocessors(self):\n corpus1 = self.corpus.copy()\n for pp in self.pp_list:\n corpus1 = pp(corpus1)\n self.assertEqual(len(self.corpus.used_preprocessor.preprocessors), 0)\n self.assertEqual(len(corpus1.used_preprocessor.preprocessors), 5)\n\n self.assertEqual([8, 10, 6, 8, 9, 7, 7, 10, 4],\n list(map(len, corpus1._tokens)))\n\n corpus2 = PreprocessorList(self.pp_list)(self.corpus)\n np.testing.assert_array_equal(corpus1.tokens, corpus2.tokens)\n\n def test_apply_preprocessors(self):\n corpus = PreprocessorList(self.pp_list)(self.corpus)\n self.assertEqual([8, 10, 6, 8, 9, 7, 7, 10, 4],\n list(map(len, corpus._tokens)))\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 5)\n\n def test_apply_base_preprocessors(self):\n self.assertEqual([8, 10, 6, 8, 9, 7, 7, 10, 4],\n list(map(len, self.corpus.tokens)))\n\n def test_string_processor(self):\n p = preprocess.LowercaseTransformer()\n tokens2 = self.corpus.tokens.copy()\n tokens = p(self.corpus).tokens\n np.testing.assert_equal(\n tokens,\n np.array([[t.lower() for t in doc] for doc in tokens2], dtype=\"object\")\n )\n\n def test_tokenizer(self):\n class SpaceTokenizer(preprocess.BaseTokenizer):\n @classmethod\n def _preprocess(cls, string):\n return string.split()\n\n p = SpaceTokenizer()\n array = np.array([sent.split() for sent in self.corpus.documents],\n dtype=object)\n np.testing.assert_equal(p(self.corpus).tokens, array)\n\n def test_token_normalizer(self):\n class CapTokenNormalizer(preprocess.BaseNormalizer):\n @classmethod\n def _preprocess(cls, token):\n return token.capitalize()\n\n p = CapTokenNormalizer()\n tokens2 = self.corpus.tokens.copy()\n tokens = p(self.corpus).tokens\n\n np.testing.assert_equal(\n tokens,\n np.array([[t.capitalize() for t in doc] for doc in tokens2], dtype=\"object\")\n )\n\n def test_token_filter(self):\n class LengthFilter(preprocess.BaseTokenFilter):\n def _check(self, token):\n return len(token) < 4\n\n p = LengthFilter()\n tokens = np.array([[token for token in doc.split() if len(token) < 4]\n for doc in self.corpus.documents], dtype=object)\n np.testing.assert_equal(p(self.corpus).tokens, tokens)\n\n def test_inplace(self):\n p = preprocess.RegexpTokenizer('\\w')\n corpus = p(self.corpus)\n self.assertIsNot(corpus, self.corpus)\n\n def test_retain_ids(self):\n corpus = self.corpus\n for pp in self.pp_list:\n corpus = pp(corpus)\n self.assertTrue((corpus.ids == self.corpus.ids).all())\n\n def test_filter_pos_tags(self):\n pp_list = [preprocess.LowercaseTransformer(),\n preprocess.WordPunctTokenizer(),\n tag.AveragedPerceptronTagger(),\n preprocess.StopwordsFilter()]\n corpus = self.corpus\n with corpus.unlocked():\n corpus.metas[0, 0] = \"This is the most beautiful day in the world\"\n for pp in pp_list:\n corpus = pp(corpus)\n self.assertEqual(len(corpus.tokens), len(corpus.pos_tags))\n self.assertEqual(len(corpus.tokens[0]), len(corpus.pos_tags[0]))\n self.assertEqual(corpus.tokens[0], [\"beautiful\", \"day\", \"world\"])\n self.assertEqual(corpus.pos_tags[0], [\"JJ\", \"NN\", \"NN\"])\n\n\nclass TransformationTests(unittest.TestCase):\n def setUp(self):\n class ReverseStringTransformer(preprocess.BaseTransformer):\n name = 'reverse'\n\n def _preprocess(self, string):\n return string[::-1]\n\n self.transformer = ReverseStringTransformer()\n self.corpus = Corpus.from_file(\"deerwester\")\n\n def test_transform(self):\n trans = self.transformer\n self.assertEqual(trans._preprocess('abracadabra'), 'arbadacarba')\n\n def test_call(self):\n corpus = self.transformer(self.corpus)\n text = 'snoitacilppa retupmoc cba bal rof ecafretni enihcam namuH'\n self.assertEqual(corpus.pp_documents[0], text)\n self.assertFalse(corpus.has_tokens())\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 1)\n\n def test_call_with_tokens(self):\n corpus = preprocess.WordPunctTokenizer()(self.corpus)\n corpus = self.transformer(corpus)\n tokens = ['namuH', 'enihcam', 'ecafretni', 'rof', 'bal', 'cba',\n 'retupmoc', 'snoitacilppa']\n self.assertEqual(corpus.tokens[0], tokens)\n self.assertTrue(corpus.has_tokens())\n text = 'Human machine interface for lab abc computer applications'\n self.assertEqual(corpus.documents[0], text)\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_str(self):\n self.assertIn('reverse', str(self.transformer))\n\n def test_lowercase(self):\n transformer = preprocess.LowercaseTransformer()\n self.assertEqual(transformer._preprocess('Abra'), 'abra')\n self.assertEqual(transformer._preprocess('\\u00C0bra'), '\\u00E0bra')\n\n def test_strip_accents(self):\n transformer = preprocess.StripAccentsTransformer()\n self.assertEqual(transformer._preprocess('Abra'), 'Abra')\n self.assertEqual(transformer._preprocess('\\u00C0bra'), 'Abra')\n\n def test_html(self):\n transformer = preprocess.HtmlTransformer()\n self.assertEqual(transformer._preprocess('<p>abra<b>cadabra</b><p>'),\n 'abracadabra')\n\n def test_url_remover(self):\n remover = preprocess.UrlRemover()\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = 'some link to https://google.com/'\n self.corpus.metas[1, 0] = 'some link to google.com'\n corpus = remover(self.corpus)\n self.assertListEqual(corpus.pp_documents[:2],\n ['some link to ', 'some link to google.com'])\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 1)\n\n def test_can_deepcopy(self):\n transformer = preprocess.UrlRemover()\n copied = copy.deepcopy(transformer)\n self.assertEqual(copied.urlfinder, transformer.urlfinder)\n\n def test_can_pickle(self):\n transformer = preprocess.UrlRemover()\n loaded = pickle.loads(pickle.dumps(transformer))\n self.assertEqual(loaded.urlfinder, transformer.urlfinder)\n\n\n@patch(SF_LIST, new=Mock(return_value=SERVER_FILES))\n@patch(SF_DOWNLOAD, download_patch)\nclass TokenNormalizerTests(unittest.TestCase):\n def setUp(self):\n self.stemmer = nltk.PorterStemmer().stem\n self.corpus = Corpus.from_file('deerwester')\n\n def test_str(self):\n stemmer = preprocess.PorterStemmer()\n self.assertEqual('Porter Stemmer', str(stemmer))\n\n def test_call_porter(self):\n pp = preprocess.PorterStemmer()\n self.assertFalse(self.corpus.has_tokens())\n corpus = pp(self.corpus)\n self.assertTrue(corpus.has_tokens())\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_call_snowball(self):\n pp = preprocess.SnowballStemmer()\n self.assertFalse(self.corpus.has_tokens())\n corpus = pp(self.corpus)\n self.assertTrue(corpus.has_tokens())\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_call_word_net(self):\n pp = preprocess.WordNetLemmatizer()\n self.assertFalse(self.corpus.has_tokens())\n corpus = pp(self.corpus)\n self.assertTrue(corpus.has_tokens())\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_call_UDPipe(self):\n pp = preprocess.UDPipeLemmatizer(language=\"Lithuanian\")\n self.assertFalse(self.corpus.has_tokens())\n corpus = pp(self.corpus)\n self.assertTrue(corpus.has_tokens())\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_call_lemmagen(self):\n pp = preprocess.LemmagenLemmatizer()\n self.assertFalse(self.corpus.has_tokens())\n corpus = pp(self.corpus)\n self.assertTrue(corpus.has_tokens())\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_function(self):\n stemmer = preprocess.BaseNormalizer()\n stemmer.normalizer = lambda x: x[:-1]\n self.assertEqual(stemmer._preprocess('token'), 'toke')\n\n def test_snowball(self):\n stemmer = preprocess.SnowballStemmer('french')\n token = 'voudrais'\n self.assertEqual(\n stemmer._preprocess(token),\n nltk.SnowballStemmer(language='french').stem(token))\n\n def test_udpipe(self):\n \"\"\"Test udpipe token lemmatization\"\"\"\n normalizer = preprocess.UDPipeLemmatizer(\"Lithuanian\")\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = \"esu\"\n corpus = normalizer(self.corpus)\n self.assertListEqual(list(corpus.tokens[0]), [\"būti\"])\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_udpipe_doc(self):\n \"\"\"Test udpipe lemmatization with its own tokenization\"\"\"\n normalizer = preprocess.UDPipeLemmatizer(\"Lithuanian\", True)\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = \"Ant kalno dega namas\"\n corpus = normalizer(self.corpus)\n self.assertListEqual(list(corpus.tokens[0]), [\"ant\", \"kalno\", \"degas\", \"namas\"])\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 1)\n\n def test_udpipe_pickle(self):\n normalizer = preprocess.UDPipeLemmatizer(\"Lithuanian\", True)\n # udpipe store model after first call - model is not picklable\n normalizer(self.corpus)\n loaded = pickle.loads(pickle.dumps(normalizer))\n self.assertEqual(normalizer._UDPipeLemmatizer__language,\n loaded._UDPipeLemmatizer__language)\n self.assertEqual(normalizer._UDPipeLemmatizer__use_tokenizer,\n loaded._UDPipeLemmatizer__use_tokenizer)\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = \"Ant kalno dega namas\"\n self.assertEqual(\n list(loaded(self.corpus).tokens[0]), [\"ant\", \"kalno\", \"degas\", \"namas\"]\n )\n\n def test_udpipe_deepcopy(self):\n normalizer = preprocess.UDPipeLemmatizer(\"Lithuanian\", True)\n copied = copy.deepcopy(normalizer)\n self.assertEqual(normalizer._UDPipeLemmatizer__language,\n copied._UDPipeLemmatizer__language)\n self.assertEqual(normalizer._UDPipeLemmatizer__use_tokenizer,\n copied._UDPipeLemmatizer__use_tokenizer)\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = \"Ant kalno dega namas\"\n self.assertEqual(\n list(copied(self.corpus).tokens[0]), [\"ant\", \"kalno\", \"degas\", \"namas\"]\n )\n\n def test_lemmagen(self):\n normalizer = preprocess.LemmagenLemmatizer('Slovenian')\n sentence = 'Gori na gori hiša gori'\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = sentence\n self.assertEqual(\n [Lemmatizer(\"sl\").lemmatize(t) for t in sentence.split()],\n normalizer(self.corpus).tokens[0],\n )\n\n def test_normalizers_picklable(self):\n \"\"\" Normalizers must be picklable, tests if it is true\"\"\"\n for nm in set(preprocess.normalize.__all__) - {\"BaseNormalizer\"}:\n normalizer = getattr(preprocess.normalize, nm)\n normalizer = (\n normalizer(language=\"Lithuanian\")\n if normalizer is preprocess.UDPipeLemmatizer\n else normalizer()\n )\n normalizer(self.corpus)\n loaded = pickle.loads(pickle.dumps(normalizer))\n loaded(self.corpus)\n\n def test_cache(self):\n normalizer = preprocess.UDPipeLemmatizer(\"Lithuanian\")\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = \"esu\"\n normalizer(self.corpus)\n self.assertEqual(normalizer._normalization_cache[\"esu\"], \"būti\")\n self.assertEqual(40, len(normalizer._normalization_cache))\n\n # cache should not be pickled\n loaded_normalizer = pickle.loads(pickle.dumps(normalizer))\n self.assertEqual(0, len(loaded_normalizer._normalization_cache))\n\n\n@patch(SF_LIST, return_value=SERVER_FILES)\nclass UDPipeModelsTests(unittest.TestCase):\n def test_label_transform(self, _):\n \"\"\"Test helper functions for label transformation\"\"\"\n self.assertEqual(file_to_language('slovenian-sst-ud-2.0-170801.udpipe'),\n 'Slovenian sst')\n self.assertEqual(file_to_name('slovenian-sst-ud-2.0-170801.udpipe'),\n 'sloveniansstud2.0170801.udpipe')\n self.assertEqual(language_to_name('Slovenian sst'), 'sloveniansstud')\n\n @patch(SF_DOWNLOAD, download_patch)\n def test_udpipe_model(self, _):\n \"\"\"Test udpipe models loading from server\"\"\"\n models = UDPipeModels()\n self.assertIn(\"Lithuanian\", models.supported_languages)\n self.assertEqual(7, len(models.supported_languages))\n\n local_file = os.path.join(models.local_data, \"lithuanian-ud-2.0-170801.udpipe\")\n model = models[\"Lithuanian\"]\n self.assertEqual(model, local_file)\n self.assertTrue(os.path.isfile(local_file))\n\n @patch(SF_DOWNLOAD, download_patch)\n def test_udpipe_local_models(self, sf_mock):\n \"\"\"Test if UDPipe works offline and uses local models\"\"\"\n models = UDPipeModels()\n [models.localfiles.remove(f[0]) for f in models.localfiles.listfiles()]\n # use Uyghur, it is the smallest model, we can have it in the repository\n _ = models[\"Lithuanian\"]\n sf_mock.side_effect = ConnectionError()\n self.assertIn(\"Lithuanian\", UDPipeModels().supported_languages)\n self.assertEqual(1, len(UDPipeModels().supported_languages))\n\n def test_udpipe_offline(self, sf_mock):\n \"\"\"Test if UDPipe works offline\"\"\"\n self.assertTrue(UDPipeModels().online)\n sf_mock.side_effect = ConnectionError()\n self.assertFalse(UDPipeModels().online)\n\n\nclass FilteringTests(unittest.TestCase):\n def setUp(self):\n self.corpus = Corpus.from_file('deerwester')\n self.regexp = preprocess.RegexpFilter('foo')\n\n def test_str(self):\n self.assertEqual('Regexp', str(self.regexp))\n\n def test_preprocess(self):\n class DigitsFilter(preprocess.BaseTokenFilter):\n def _check(self, token):\n return not token.isdigit()\n\n df = DigitsFilter()\n filtered = list(itertools.compress([], df._preprocess([])))\n self.assertEqual(filtered, [])\n filtered = list(itertools.compress(['a', '1'],\n df._preprocess(['a', '1'])))\n self.assertEqual(filtered, ['a'])\n\n def test_stopwords(self):\n f = preprocess.StopwordsFilter('english')\n self.assertFalse(f._check('a'))\n self.assertTrue(f._check('filter'))\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = 'a snake is in a house'\n corpus = f(self.corpus)\n self.assertListEqual([\"snake\", \"house\"], corpus.tokens[0])\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_stopwords_slovene(self):\n f = preprocess.StopwordsFilter('slovene')\n self.assertFalse(f._check('in'))\n self.assertTrue(f._check('abeceda'))\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = 'kača je v hiši'\n corpus = f(self.corpus)\n self.assertListEqual([\"kača\", \"hiši\"], corpus.tokens[0])\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_lexicon(self):\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(b'filter\\n')\n f.flush()\n f.close()\n lexicon = preprocess.LexiconFilter(f.name)\n self.assertFalse(lexicon._check('false'))\n self.assertTrue(lexicon._check('filter'))\n f.close()\n os.unlink(f.name)\n\n def test_keep_n(self):\n ff = preprocess.MostFrequentTokensFilter(keep_n=5)\n processed = ff(self.corpus)\n self.assertEqual(len(set(itertools.chain(*processed.tokens))), 5)\n self.assertEqual(len(processed.used_preprocessor.preprocessors), 2)\n\n def test_min_df(self):\n ff = preprocess.FrequencyFilter(min_df=.5)\n processed = ff(self.corpus)\n size = len(processed.documents)\n self.assertFrequencyRange(processed, size * .5, size)\n self.assertEqual(len(processed.used_preprocessor.preprocessors), 2)\n\n ff = preprocess.FrequencyFilter(min_df=2)\n processed = ff(self.corpus)\n size = len(processed.documents)\n self.assertFrequencyRange(processed, 2, size)\n self.assertEqual(len(processed.used_preprocessor.preprocessors), 2)\n\n def test_max_df(self):\n ff = preprocess.FrequencyFilter(max_df=.3)\n size = len(self.corpus.documents)\n\n corpus = ff(self.corpus)\n self.assertFrequencyRange(corpus, 1, size * .3)\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n ff = preprocess.FrequencyFilter(max_df=2)\n corpus = ff(self.corpus)\n self.assertFrequencyRange(corpus, 1, 2)\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n ff = preprocess.FrequencyFilter(min_df=5, max_df=5)\n corpus = ff(self.corpus)\n self.assertFrequencyRange(corpus, 5, size)\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def assertFrequencyRange(self, corpus, min_fr, max_fr):\n dictionary = corpora.Dictionary(corpus.tokens)\n self.assertTrue(all(min_fr <= fr <= max_fr\n for fr in dictionary.dfs.values()))\n\n def test_word_list(self):\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(b'hello\\nworld\\n')\n f.flush()\n f.close()\n lexicon = preprocess.LexiconFilter(f.name)\n self.assertIn('hello', lexicon._lexicon)\n self.assertIn('world', lexicon._lexicon)\n f.close()\n os.unlink(f.name)\n\n def test_filter_numbers(self):\n f = preprocess.NumbersFilter()\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = '1 2foo bar3 baz'\n corpus = f(self.corpus)\n self.assertEqual([\"2foo\", \"bar3\", \"baz\"], corpus.tokens[0])\n\n def test_filter_tokens_with_numbers(self):\n f = preprocess.WithNumbersFilter()\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = '1 2foo bar3 baz'\n corpus = f(self.corpus)\n self.assertEqual([\"baz\"], corpus.tokens[0])\n\n def test_regex_filter(self):\n self.assertFalse(preprocess.RegexpFilter.validate_regexp('?'))\n self.assertTrue(preprocess.RegexpFilter.validate_regexp('\\?'))\n\n reg_filter = preprocess.RegexpFilter(r'.')\n filtered = reg_filter(self.corpus)\n self.assertEqual(0, len(filtered.tokens[0]))\n self.assertEqual(len(filtered.used_preprocessor.preprocessors), 2)\n\n reg_filter = preprocess.RegexpFilter('foo')\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = 'foo bar'\n filtered = reg_filter(self.corpus)\n self.assertEqual(filtered.tokens[0], ['bar'])\n self.assertEqual(len(filtered.used_preprocessor.preprocessors), 2)\n\n reg_filter = preprocess.RegexpFilter('^http')\n corpus = BASE_TOKENIZER(self.corpus)\n corpus._tokens[0] = ['https', 'http', ' http']\n filtered = reg_filter(corpus)\n self.assertEqual(filtered.tokens[0], [' http'])\n self.assertEqual(len(filtered.used_preprocessor.preprocessors), 2)\n\n def test_pos_filter(self):\n pos_filter = preprocess.PosTagFilter(\"NN\")\n pp_list = [preprocess.WordPunctTokenizer(),\n tag.AveragedPerceptronTagger()]\n corpus = self.corpus\n for pp in pp_list:\n corpus = pp(corpus)\n filtered = pos_filter(corpus)\n self.assertTrue(len(filtered.pos_tags))\n self.assertEqual(len(filtered.pos_tags[0]), 5)\n self.assertEqual(len(filtered.tokens[0]), 5)\n\n def test_can_deepcopy(self):\n copied = copy.deepcopy(self.regexp)\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = 'foo bar'\n self.assertEqual(copied(self.corpus).tokens[0], ['bar'])\n\n def test_can_pickle(self):\n loaded = pickle.loads(pickle.dumps(self.regexp))\n with self.corpus.unlocked():\n self.corpus.metas[0, 0] = 'foo bar'\n self.assertEqual(loaded(self.corpus).tokens[0], ['bar'])\n\n\nclass TokenizerTests(unittest.TestCase):\n def test_tokenize(self):\n class DashTokenizer(preprocess.BaseTokenizer):\n def _preprocess(self, string):\n return string.split('-')\n\n tokenizer = DashTokenizer()\n self.assertEqual(list(tokenizer._preprocess('dashed-sentence')),\n ['dashed', 'sentence'])\n\n def test_call(self):\n class SpaceTokenizer(preprocess.BaseTokenizer):\n def _preprocess(self, string):\n return string.split(' ')\n\n corpus = Corpus.from_file(\"deerwester\")\n tokens = ['Human', 'machine', 'interface', 'for', 'lab', 'abc',\n 'computer', 'applications']\n corpus = SpaceTokenizer()(corpus)\n self.assertEqual(corpus.tokens[0], tokens)\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 1)\n\n def test_call_with_bad_input(self):\n pattern = '\\w+'\n tokenizer = preprocess.RegexpTokenizer(pattern=pattern)\n tokenizer.tokenizer = tokenizer.tokenizer_cls(pattern)\n self.assertRaises(TypeError, tokenizer._preprocess, 1)\n self.assertRaises(TypeError, tokenizer._preprocess, ['1', 2])\n\n def test_valid_regexp(self):\n self.assertTrue(preprocess.RegexpTokenizer.validate_regexp('\\w+'))\n\n def test_invalid_regex(self):\n for expr in ['\\\\', '[', ')?']:\n self.assertFalse(preprocess.RegexpTokenizer.validate_regexp(expr))\n\n def test_str(self):\n tokenizer = preprocess.RegexpTokenizer(pattern=r'\\S+')\n self.assertEqual('Regexp', str(tokenizer))\n\n def test_skip_empty_strings(self):\n pattern = r'[^h ]*'\n tokenizer = preprocess.RegexpTokenizer(pattern=pattern)\n tokenizer.tokenizer = tokenizer.tokenizer_cls(pattern)\n tokens = tokenizer._preprocess('whatever')\n self.assertNotIn('', tokens)\n\n def test_can_deepcopy(self):\n tokenizer = preprocess.RegexpTokenizer(pattern=r'\\w')\n copied = copy.deepcopy(tokenizer)\n corpus = Corpus.from_file('deerwester')\n self.assertTrue(all(tokenizer(corpus).tokens == copied(corpus).tokens))\n\n def test_can_pickle(self):\n tokenizer = preprocess.RegexpTokenizer(pattern=r'\\w')\n pickle.loads(pickle.dumps(tokenizer))\n\n def test_reset_pos_tags(self):\n corpus = Corpus.from_file('deerwester')\n tagger = tag.AveragedPerceptronTagger()\n tagged_corpus = tagger(corpus)\n self.assertTrue(len(tagged_corpus.pos_tags))\n tokenizer = preprocess.RegexpTokenizer(pattern=r'\\w')\n tokenized_corpus = tokenizer(corpus)\n self.assertFalse(tokenized_corpus.pos_tags)\n\n\nclass NGramsTests(unittest.TestCase):\n def setUp(self):\n self.pp = preprocess.NGrams((2, 3))\n self.corpus = Corpus.from_file('deerwester')\n\n def test_call(self):\n corpus = self.pp(self.corpus)\n self.assertEqual(next(corpus.ngrams)[0],\n \" \".join(corpus.tokens[0][:2]))\n self.assertEqual(len(corpus.used_preprocessor.preprocessors), 2)\n\n def test_retain_old_data(self):\n corpus = self.pp(self.corpus)\n self.assertIsNot(corpus, self.corpus)\n\n def test_str(self):\n self.assertEqual('N-grams Range', str(self.pp))\n\n def test_can_deepcopy(self):\n copied = copy.deepcopy(self.pp)\n self.assertEqual(copied._NGrams__range, self.pp._NGrams__range)\n\n def test_can_pickle(self):\n loaded = pickle.loads(pickle.dumps(self.pp))\n self.assertEqual(loaded._NGrams__range, self.pp._NGrams__range)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"biolab/orange3-text","sub_path":"orangecontrib/text/tests/test_preprocess.py","file_name":"test_preprocess.py","file_ext":"py","file_size_in_byte":26814,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"52"} +{"seq_id":"37286158448","text":"#\n# @lc app=leetcode id=703 lang=python3\n#\n# [703] Kth Largest Element in a Stream\n#\n# https://leetcode.com/problems/kth-largest-element-in-a-stream/description/\n#\n# algorithms\n# Easy (46.66%)\n# Likes: 354\n# Dislikes: 169\n# Total Accepted: 39.4K\n# Total Submissions: 84.2K\n# Testcase Example: '[\"KthLargest\",\"add\",\"add\",\"add\",\"add\",\"add\"]\\n' +\n#\n# Design a class to find the kth largest element in a stream. Note that it is\n# the kth largest element in the sorted order, not the kth distinct element.\n# \n# Your KthLargest class will have a constructor which accepts an integer k and\n# an integer array nums, which contains initial elements from the stream. For\n# each call to the method KthLargest.add, return the element representing the\n# kth largest element in the stream.\n# \n# Example:\n# \n# \n# int k = 3;\n# int[] arr = [4,5,8,2];\n# KthLargest kthLargest = new KthLargest(3, arr);\n# kthLargest.add(3);   // returns 4\n# kthLargest.add(5);   // returns 5\n# kthLargest.add(10);  // returns 5\n# kthLargest.add(9);   // returns 8\n# kthLargest.add(4);   // returns 8\n# \n# \n# Note: \n# You may assume that nums' length ≥ k-1 and k ≥ 1.\n# \n#\nimport heapq\n\nclass KthLargest:\n\n def __init__(self, k: int, nums: List[int]):\n self.heap = []\n self.cap = k\n for num in nums:\n self._add(num)\n\n def _add(self, val):\n if len(self.heap) < self.cap:\n heapq.heappush(self.heap, val)\n else:\n heapq.heappushpop(self.heap, val)\n \n def add(self, val: int) -> int:\n self._add(val)\n return self.heap[0]\n \n\n\n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest(k, nums)\n# param_1 = obj.add(val)\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"703.kth-largest-element-in-a-stream.py","file_name":"703.kth-largest-element-in-a-stream.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"29206824235","text":"#ler numeros e colocar em lista em ordem e sem duplicações\nlistanum = []\nwhile True:\n numeros = int(input('Digite um número:'))\n #se os numeros digitados não estiverem na lista será adicionado\n if numeros not in listanum:\n listanum.append(numeros)\n print('Valor Adicionado...')\n #caso contrário, não\n else:\n print('Valor já adicionado...Não será contado.')\n #não conseguir add o while para apenas receber respostas de 'YN'\n pergunta = str(input('Você deseja continuar? [Y/N]')).strip().upper()[0]\n if pergunta == 'N':\n break\n#primeiro coloca em ordem dps manda mostrar\nlistanum.sort()\nprint('=-' * 30)\nprint(f'Você digitou os valores {listanum}')\nprint('\\nbabou')\n#corrigido","repo_name":"Melo-Luisa/Python","sub_path":"exercicio/ex079.py","file_name":"ex079.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14004897095","text":"import sys\n\ninput = sys.stdin.readline\nn, m = map(int, input().split())\nwords = [int(input()) for _ in range(n)]\ndp = [[-1 for i in range(m)] for j in range(n)]\n\n\ndef dfs(idx, tmp):\n if idx == n - 1:\n return 0\n if dp[idx][tmp] != -1:\n return dp[idx][tmp]\n\n if tmp + 1 + words[idx + 1] < m:\n dp[idx][tmp] = min(dfs(idx + 1, tmp + 1 + words[idx + 1]),\n dfs(idx + 1, words[idx + 1] - 1) + (m - tmp - 1) * (m - tmp - 1))\n else:\n dp[idx][tmp] = dfs(idx + 1, words[idx + 1] - 1) + (m - tmp - 1) * (m - tmp - 1)\n return dp[idx][tmp]\n\n\nprint(dfs(0, words[0] - 1))\n","repo_name":"yogru/ps","sub_path":"baekjoon/2281.py","file_name":"2281.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18663673120","text":"# coding:utf-8\nimport json\nimport random\nimport re\nimport time\n\nimport jieba\nimport numpy as np\nimport pymongo\nimport requests as rq\nfrom tqdm import tqdm, trange\n\n\nclass TextParser():\n \"\"\"歌曲所在歌单文本的解析器\n \"\"\"\n \n def __init__(self):\n pass\n\n\n def clean_zh_text(self, text):\n \"\"\"清洗数据,去除特殊字符\n\n Returns:\n string: completed text\n \"\"\"\n # keep English, digital and Chinese\n comp = re.compile('[^A-Z^a-z^0-9^\\u4e00-\\u9fa5^\\s^,]')\n return comp.sub('', text)\n\n\n def stopwordslist(self, filepath):\n \"\"\"read the stopwords list from filepath\n\n Args:\n filepath (str): the path of stopwords file\n\n Returns:\n list: stopwords list\n \"\"\"\n stopwords = [line.strip() for line in open(\n filepath, 'r', encoding='utf-8').readlines()]\n # strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。\n # readlines()读取所有行并返回列表\n return stopwords\n\n\n def seg_sentence(self, sentence):\n \"\"\"Segmentation of sentences\n\n Args:\n sentence (string): [description]\n\n Returns:\n string: completed segmentation of sentences with split space\n \"\"\"\n # 分词\n sentence_seged = jieba.cut(sentence.strip())\n stopwords = self.stopwordslist(r\"./data/stopwords_cn.txt\") # 这里加载停用词的路径\n outstr = \"\"\n for word in sentence_seged:\n if word not in stopwords:\n if word != '\\t':\n # 以空格为分隔符返回词的字符串\n outstr += word\n outstr += \" \"\n return outstr\n \n \n def parse_playlist_json_to_dict(self, str_json, playlist_id):\n \"\"\"parsing playlist json info to dict\n\n Args:\n str_json (str): the json of playlist info from request\n playlist_id (int): playlist id\n\n Returns:\n dict: the processed and activity dict \n \"\"\"\n # 将json转换为dict\n data_dict = json.loads(str_json)\n # 获取所有的歌曲id\n track_ids = data_dict.get(\"playlist\").get(\"trackIds\")\n song_ids = []\n for track in track_ids:\n song_id = track.get('id')\n song_ids.append(song_id)\n # 歌单的标签列表\n tags_list = data_dict.get(\"playlist\").get(\"tags\")\n # 歌单名称\n name = data_dict.get(\"playlist\").get(\"name\")\n # 歌单订阅数量\n subscribedCount = data_dict.get(\"playlist\").get(\"subscribedCount\")\n # 歌单播放数量\n playCount = data_dict.get(\"playlist\").get(\"playCount\")\n # 将数据封装成dict\n playlist_info_dict = {\n \"_id\": playlist_id,\n \"song_ids\":song_ids,\n \"tags_list\": tags_list,\n \"name\": name,\n \"subscribedCount\": subscribedCount,\n \"playCount\": playCount,\n }\n return playlist_info_dict\n \n \n def parse_playlist_to_tags(self, playlist_str):\n \"\"\"对歌单文本进行清洗、分词、去重和标签列表化\n\n Returns:\n [list]: 去重的词列表\n \"\"\"\n # 对BGM标签的正则处理,替换\n pattern = re.compile(r'bgm|背景音乐', re.I)\n result = re.sub(pattern, 'BGM', playlist_str, 0)\n \n result = self.clean_zh_text(result)\n result = self.seg_sentence(result)\n data_list = list(set(result.split(' ')))\n # 返回清洗、分词、去重列表化的数据\n return data_list\n \n \nclass MongoDAO():\n \n def __init__(self, mongo_config):\n \"\"\"\n Args:\n mongo_config ([dict]): {'mongo_url': ***, 'db_name': ***, 'collection_name': ***}\n \"\"\"\n self.mongo_config = mongo_config\n self.set_mongo_config(self.mongo_config)\n \n \n def set_mongo_config(self, mongo_config):\n \"\"\"设置mongo的连接,选择数据库和集合\n\n Args:\n mongo_config ([dict]): {'mongo_url': ***, 'db_name': ***, 'collection_name': ***}\n \"\"\"\n self.mongo_client = pymongo.MongoClient(mongo_config.get('mongo_url'))\n self.mongo_db = self.mongo_client[mongo_config.get('db_name')]\n self.mongo_collection = self.mongo_db[mongo_config.get('collection_name')]\n \n \n def find(self, query=None):\n \"\"\"mongodb查询\n\n Args:\n query (dict): {'key': 'value'} 为null是返回collection中所有文档\n\n \"\"\"\n if query==None:\n result = self.mongo_collection.find()\n else:\n result = self.mongo_collection.find(query)\n return result\n \n \n def count_documents(self, query={}):\n \"\"\"the count of the document meet the query condition\n\n Args:\n query (dict): {'key': 'value'}\n\n Returns:\n [int]: count\n \"\"\"\n count = self.mongo_collection.count_documents(query)\n return count\n \n \n def insert_one(self, document):\n \"\"\"insert a document to the collection\n\n Args:\n document (dict): {'key': 'value'}\n \"\"\"\n try:\n self.mongo_collection.insert_one(document)\n except Exception as e:\n print(e)\n \n \n def update_one(self, query, update_task):\n \"\"\"update one document in the collection\n\n Args:\n query (dict): {'key': 'value'}\n update_task (dict): {'$set': {'key': 'value'}}\n \"\"\"\n try:\n self.mongo_collection.update_one(query, update_task)\n except Exception as e:\n print(e)\n","repo_name":"WzqProgrammer/MasterProject","sub_path":"JupyterPythonProejct/01.数据挖掘/CralwerProject/parsetools.py","file_name":"parsetools.py","file_ext":"py","file_size_in_byte":5776,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"25782610255","text":"from kafka import KafkaProducer\nimport time\nimport serial\nimport sys\nimport json\n\np = KafkaProducer(bootstrap_servers=\"pkc-43n10.us-central1.gcp.confluent.cloud:9092\",\n security_protocol=\"SASL_SSL\",\n sasl_mechanism=\"PLAIN\",\n sasl_plain_username=\"LWREB5JKVOY24U4O\",\n sasl_plain_password=\"HGVeVIlZQTMuAvMeZXpOhmXpiVwoA77uGlV10kptwtJLrbPxpenbT3MPmYNxmSPi\"\n )\n\nDWM = serial.Serial(port=\"/dev/ttyACM0\", baudrate=115200)\nvalue = \"\"\ntry:\n while True:\n if DWM.in_waiting > 0:\n value = DWM.readline()\n if value:\n data = value.decode(errors='ignore').split(\",\")\n if len(data) == 5:\n k = str.encode(data[0])\n value = str.encode(json.dumps({\"UID\" : data[0],\"FLOOR\" : data[1],\"X\" : float(data[2]),\"Y\" : float(data[3]),\"Z\" : float(data[4])}))\n p.send(\"data\", key=k, value=value)\n print(k)\n print(value)\n #time.sleep(0.2)\n\nexcept KeyboardInterrupt as ex:\n #DWM.write(\"\\r\".encode())\n print('keyboard interrupt')\n sys.exit(0)\n","repo_name":"stephenmasih/position","sub_path":"prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36296303187","text":"from PIL import Image\nimport numpy as np\nimport sys\nimport cv2\nimport argparse\nfrom pathlib import Path\n\ndef ai8x_normalize(img):\n \"\"\"\n normalize the sample as it is done in the ai8x library\n \"\"\"\n return img.sub(0.5).mul(256.).round().clamp(min=-128, max=127)\n\ndef convert(file, from_dir):\n \"\"\"\n Python utility for converting an image to a 64x64 sampledata.h file\n compatible with the model's known answer test.\n \"\"\"\n np.set_printoptions(threshold=sys.maxsize)\n \n if from_dir:\n src = np.load(file)\n else:\n src = file\n src = src.astype(np.uint8)\n \n #Get red channel from img\n red = src[0,:,:]\n red_f = red.ravel()\n\n #Get green channel from img\n green = src[1,:,:]\n green_f = green.ravel()\n\n #Get blue channel from img\n blue = src[2,:,:]\n blue_f = blue.ravel()\n\n arr_result = []\n\n # 0x00bbggrr\n for i in range(len(red_f)):\n result = red_f[i] | green_f[i]<<8 | blue_f[i]<<16\n arr_result.append((result))\n \n #convert list to numpy array\n out_arr_result = np.asarray(arr_result, dtype=np.uint32)\n\n #Write out data to the header file\n with open('sampledata_created.h', 'w') as outfile:\n outfile.write('#define SAMPLE_INPUT_0 { \\\\')\n outfile.write('\\n')\n\n for i in range(len(out_arr_result)):\n if i==0:\n outfile.write('\\t0x{0:08x},\\t'.format((out_arr_result[i])))\n\n else :\n d = i%8\n if(d!=0):\n outfile.write('0x{0:08x},\\t'.format((out_arr_result[i])))\n else:\n outfile.write('\\\\')\n outfile.write('\\n\\t')\n outfile.write('0x{0:08x},\\t'.format((out_arr_result[i])))\n\n outfile.write('\\\\')\n outfile.write('\\n')\n outfile.write('}')\n outfile.write('\\n')\n\n print(\"FINISH\")\n #sys.stdout.close()\n ","repo_name":"vinztu/MLMCU","sub_path":"Sample_Creator.py","file_name":"Sample_Creator.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15155318626","text":"import numpy as np\r\nimport math\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n#from sklearn import linear_model\r\n#from sklearn.preprocessing import PolynomialFeatures\r\n\r\ndef normalize(a):\r\n\ta=a-np.mean(a)\r\n\ta=a/np.std(a)\r\n\treturn a\r\n\r\ndata = pd.read_csv(\"Wage_dataset.csv\")\r\nyear = np.array(data[\"year\"])\r\n#year = year-np.mean(year)\r\n#year = year/np.std(year)\r\nage = np.array(data[\"age\"])\r\n#age = age-np.mean(age)\r\n#age = age/np.std(age)\r\neducation = np.array(data[\"education\"])\r\n#education = education-np.mean(education)\r\n#education = education/np.std(education)\r\nwage = np.array(data[\"wage\"])\r\n\r\n# data=np.genfromtxt('Problem_3/Problem_3/Wage_dataset.csv',delimiter=',')\r\n#\r\n# age = np.array(data[:,1])\r\n# #age = normalize(age)\r\n# year = np.array(data[:,0])\r\n# #year = normalize(year)\r\n# education = np.array(data[:,4:5])\r\n# #education = normalize(education)\r\n# wage = np.array(data[:,10:11])\r\n\r\n\r\n##################\r\n\r\nloss_array_age = np.zeros(shape=(3000,1))\r\nmin_loss_age = math.inf\r\noptimal_n = 0\r\nplt.figure()\r\nfor n in range(150,200):\r\n\tage_matrix = np.zeros(shape=(3000,n))\r\n\tfor i in range(3000):\r\n\t\tfor j in range(n):\r\n\t\t\tage_matrix[i][j] = age[i]**j\r\n\tage_weight = np.matmul(np.linalg.pinv(age_matrix),wage)\r\n\tpredicted_wage_age = np.matmul(age_matrix,age_weight)\r\n\tfor k in range(3000):\r\n\t\tloss_array_age[k] = (wage[k]-predicted_wage_age[k])**2\r\n\tloss_age = loss_array_age.sum()\r\n\t#loss_age=(2*loss_age/n)**0.5\r\n\tprint(loss_age)\r\n\tplt.plot(n,loss_age,'ro')\r\n\t# if (n==1):\r\n\t# \tmin_loss_age = loss_age\r\n\tif (loss_age <= min_loss_age):\r\n\t\tmin_loss_age = loss_age\r\n\t\toptimal_n = n\r\n\r\nplt.show()\r\nprint(optimal_n)\r\n\r\nplt.figure()\r\nplt.scatter(age,wage)\r\nplt.scatter(age,predicted_wage_age,c='g')\r\nplt.show()\r\n\r\nN = optimal_n\r\nage_matrix = np.zeros(shape=(3000,N))\r\nloss_array_age = np.zeros((3000,1))\r\nfor i in range(3000):\r\n\tfor j in range(N):\r\n\t\tage_matrix[i][j] = age[i]**j\r\nage_weight = np.matmul(np.linalg.pinv(age_matrix),wage)\r\npredicted_wage_age = np.matmul(age_matrix,age_weight)\r\n\r\n# poly = PolynomialFeatures(degree=N)\r\n# Age=age.reshape(-1,1)\r\n# x_features=poly.fit_transform(Age)\r\n# #print(x_features)\r\n# clf = linear_model.LinearRegression()\r\n# clf.fit(x_features,wage)\r\n# pred=clf.predict(x_features)\r\n\r\nx = np.arange(3000)\r\nplt.plot(x,wage,marker='o')\r\nplt.plot(x,predicted_wage_age,marker='x')\r\nplt.show()\r\n# error=np.subtract(predicted_wage_age,wage)\r\n# loss_age=np.dot(error.T,error)\r\n\r\nfor k in range(3000):\r\n\tloss_array_age[k] = (wage[k]-predicted_wage_age[k])**2\r\nloss_age = loss_array_age.sum()\r\n#loss_age=(2*loss_age/N)**0.5\r\nprint(loss_age)\r\n\r\n\r\n# poly = PolynomialFeatures(degree=N)\r\n# Age=age.reshape(-1,1)\r\n# x_features=poly.fit_transform(Age)\r\n# #print(x_features)\r\n# clf = linear_model.LinearRegression()\r\n# clf.fit(x_features,wage)\r\n# pred=clf.predict(x_features)\r\n# plt.plot(x,pred,marker='*')\r\n# plt.show()\r\n\r\n#################\r\n\r\nloss_array_year = np.zeros(3000)\r\nmin_loss_year = math.inf\r\noptimal_m = 0\r\nplt.figure()\r\nfor m in range(1,100):\r\n\tyear_matrix = np.zeros(shape=(3000,m))\r\n\tfor i in range(3000):\r\n\t\tfor j in range(0,m):\r\n\t\t\tyear_matrix[i][j] = year[i]**j\r\n\tyear_weight = np.matmul(np.linalg.pinv(year_matrix),wage)\r\n\tpredicted_wage_year = np.matmul(year_matrix,year_weight)\r\n\tfor k in range(3000):\r\n\t\tloss_array_year[k] = (wage[k]-predicted_wage_year[k])**2\r\n\tloss_year = loss_array_year.sum()\r\n\tloss_year=(2*loss_year/m)**0.5\r\n\tplt.plot(m,loss_year,'ro')\r\n\tif (m==1):\r\n\t\tmin_loss_year = loss_year\r\n\tif (loss_year < min_loss_year):\r\n\t\tmin_loss_year = loss_year\r\n\t\toptimal_m = m\r\n\r\nplt.show()\r\nprint(optimal_m)\r\n\r\nplt.figure()\r\nplt.scatter(year,wage)\r\nplt.scatter(year,predicted_wage_year,c='g')\r\nplt.show()\r\n\r\nM=optimal_m\r\nyear_matrix = np.zeros((3000,M))\r\nloss_array_year = np.zeros(3000)\r\nfor i in range(3000):\r\n\tfor j in range(0,M):\r\n\t\tyear_matrix[i][j] = year[i]**j\r\n\r\nyear_weight = np.matmul(np.linalg.pinv(year_matrix),wage)\r\npredicted_wage_year = np.matmul(year_matrix,year_weight)\r\nx = np.arange(3000)\r\nplt.plot(x,wage,marker='o')\r\nplt.plot(x,predicted_wage_year,marker='s')\r\nplt.show()\r\nfor k in range(3000):\r\n\tloss_array_year[k] = (wage[k]-predicted_wage_year[k])**2\r\nloss_year = loss_array_year.sum()\r\nloss_year=(2*loss_year/M)**0.5\r\nprint(loss_year)\r\n\r\n\r\n#############################\r\n\r\n\r\nloss_array_education = np.zeros(shape=(3000,1))\r\nmin_loss_education = math.inf\r\noptimal_l = 0\r\nplt.figure()\r\nfor l in range(1,100):\r\n\teducation_matrix = np.zeros(shape=(3000,l))\r\n\tfor i in range(3000):\r\n\t\tfor j in range(0,l):\r\n\t\t\teducation_matrix[i][j] = education[i]**j\r\n\teducation_weight = np.matmul(np.linalg.pinv(education_matrix),wage)\r\n\tpredicted_wage_education = np.matmul(education_matrix,education_weight)\r\n\tfor k in range(3000):\r\n\t\tloss_array_education[k] = (wage[k]-predicted_wage_education[k])**2\r\n\tloss_education = loss_array_education.sum()\r\n\tloss_education=(2*loss_education/l)**0.5\r\n\tplt.plot(l,loss_education,'ro')\r\n\tif (l==1):\r\n\t\tmin_loss_education = loss_education\r\n\tif (loss_education < min_loss_education):\r\n\t\tmin_loss_education = loss_education\r\n\t\toptimal_l = l\r\nplt.show()\r\nprint(optimal_l)\r\n\r\nplt.figure()\r\nplt.scatter(education,wage)\r\nplt.scatter(education,predicted_wage_education,c='g')\r\nplt.show()\r\n\r\nL=optimal_l\r\neducation_matrix = np.zeros((3000,L))\r\nloss_array_education = np.zeros(3000)\r\nfor i in range(3000):\r\n\tfor j in range(0,L):\r\n\t\teducation_matrix[i][j] = education[i]**j\r\n\r\neducation_weight = np.matmul(np.linalg.pinv(education_matrix),wage)\r\npredicted_wage_education = np.matmul(education_matrix,education_weight)\r\nx = np.arange(3000)\r\nplt.plot(x,wage,marker='o')\r\nplt.plot(x,predicted_wage_education,marker='s')\r\nplt.show()\r\nfor k in range(3000):\r\n\tloss_array_education[k] = (wage[k]-predicted_wage_education[k])**2\r\n\r\nloss_education = loss_array_education.sum()\r\nloss_education=(2*loss_education/L)**0.5\r\nprint(loss_education)\r\n","repo_name":"souradipp76/PRML","sub_path":"assignment1/P3.py","file_name":"P3.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13427039445","text":"import json\nfrom functools import cmp_to_key\nfrom math import prod\n\ndef compare(left, right):\n leftType = type(left)\n rightType = type(right)\n \n if leftType == int and rightType == int:\n return left - right\n elif leftType == list and rightType == int:\n return compare(left, [right])\n elif leftType == int and rightType == list:\n return compare([left], right)\n else:\n if len(left) > 0 and len(right) > 0:\n diff = compare(left[0], right[0])\n \n if diff != 0:\n return diff\n else:\n return compare(left[1:], right[1:])\n else:\n return len(left) - len(right)\n\nfile = open('day13/input.txt')\ninputs = file.readlines()\n\npackets = [json.loads(i.strip()) for i in inputs if i != '\\n']\npackets.append([[2]])\npackets.append([[6]])\n\nordered_packets = sorted(packets, key=cmp_to_key(compare))\nproduct = prod([(i + 1) for i in range(len(ordered_packets)) if ordered_packets[i] == [[2]] or ordered_packets[i] == [[6]]])\n \nprint(product)\n","repo_name":"BlueSCar/advent-of-code-2022","sub_path":"day13/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26548585064","text":"import unittest\n\nfrom mock import Mock\nfrom ConfigParser import SafeConfigParser as ConfigParser\n\nimport taskqueue.dispatcher\n\nclass TestDispatcher(unittest.TestCase):\n \"\"\"Tests for dispatcher.\"\"\"\n\n def setUp(self):\n config = ConfigParser()\n self.disp = taskqueue.dispatcher.Dispatcher(config)\n self.disp.channel = Mock()\n self.disp.connection = Mock()\n taskqueue.dispatcher.pika = Mock()\n\n def test_handle_delivery(self):\n \"\"\"Test handle_delivery().\"\"\"\n header = Mock()\n header.content_type = \"test/fake\"\n self.disp.handle_delivery(Mock(), Mock(), header,\n '{\"fields\": {\"params\": {\"worker_type\": \"first\"}}}')\n header.content_type = \"application/x-ruote-workitem\"\n self.disp.handle_delivery(Mock(), Mock(), header,\n '{\"fields\": {\"params\": {\"worker_type\": \"first\"}}}')\n\n def test_cleanup(self):\n \"\"\"Test Dispatcher.cleanup().\"\"\"\n self.assertRaises(SystemExit, self.disp.cleanup, None, None)\n\n def test_run(self):\n \"\"\"Test Dispatcher.run().\"\"\"\n self.disp.run()\n","repo_name":"pombredanne/taskqueue","sub_path":"tests/test_dispatcher.py","file_name":"test_dispatcher.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"30175751387","text":"from tensorflow.keras import layers\nimport tensorflow_probability as tfp\nimport tensorflow as tf\ntfd = tfp.distributions\n\nclass VectorQuantizer(layers.Layer):\n def __init__(self, num_embeddings, embedding_dim, beta=0.25, **kwargs):\n super().__init__(**kwargs)\n self.embedding_dim = embedding_dim\n self.num_embeddings = num_embeddings\n\n # The `beta` parameter is best kept between [0.25, 2] as per the paper.\n self.beta = beta\n\n # Initialize the embeddings which we will quantize.\n w_init = tf.random_uniform_initializer()\n self.embeddings = tf.Variable(\n initial_value=w_init(\n shape=(self.embedding_dim, self.num_embeddings), dtype=\"float32\"\n ),\n trainable=True,\n name=\"embeddings_vqvae\",\n )\n\n def call(self, x):\n # Calculate the input shape of the inputs and\n # then flatten the inputs keeping `embedding_dim` intact.\n input_shape = tf.shape(x)\n flattened = tf.reshape(x, [-1, self.embedding_dim])\n\n # Quantization.\n encoding_indices = get_code_indices(self, flattened)\n encodings = tf.one_hot(encoding_indices, self.num_embeddings)\n quantized = tf.matmul(encodings, self.embeddings, transpose_b=True)\n\n # Reshape the quantized values back to the original input shape\n quantized = tf.reshape(quantized, input_shape)\n\n # Calculate vector quantization loss and add that to the layer.\n commitment_loss = tf.reduce_mean((tf.stop_gradient(quantized) - x) ** 2)\n codebook_loss = tf.reduce_mean((quantized - tf.stop_gradient(x)) ** 2)\n self.add_loss(self.beta * commitment_loss + codebook_loss)\n\n # Straight-through estimator.\n quantized = x + tf.stop_gradient(quantized - x)\n return quantized\n \ndef get_code_indices(quantizer, flattened_inputs):\n # Calculate L2-normalized distance between the inputs and the codes.\n similarity = tf.matmul(flattened_inputs, quantizer.embeddings)\n distances = (\n tf.reduce_sum(flattened_inputs ** 2, axis=1, keepdims=True)\n + tf.reduce_sum(quantizer.embeddings ** 2, axis=0)\n - 2 * similarity\n )\n\n # Derive the indices for minimum distances.\n encoding_indices = tf.argmin(distances, axis=1)\n return encoding_indices","repo_name":"babe1304/VAE-models","sub_path":"VectorQuantizer.py","file_name":"VectorQuantizer.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21867371659","text":"from qtpy import QtWidgets, QtGui, QtCore\n\n\nclass Widget(QtWidgets.QSpinBox):\n def __init__(self, model, parent):\n super().__init__(parent=parent)\n self.setFocusPolicy(QtCore.Qt.StrongFocus)\n self.installEventFilter(self)\n self.editingFinished.connect(self.on_editing_finished)\n # wire into model\n self.model = model\n self.model.updated_connect(self.on_updated)\n self.on_updated(model.get())\n\n def eventFilter(self, obj, event):\n if isinstance(event, QtGui.QWheelEvent):\n return True\n else:\n return super().eventFilter(obj, event)\n\n def updated_disconnect(self):\n self.model.updated_disconnect(self.on_updated)\n\n def on_editing_finished(self):\n self.model.set({\"value\": self.value()}, from_widget=True)\n\n def on_updated(self, data):\n # minimum, maximum\n self.setMinimum(int(data[\"minimum\"]))\n self.setMaximum(int(data[\"maximum\"]))\n # tool tip\n self.setToolTip(f\"minimum:{int(data['minimum'])}\\nmaximum:{int(data['maximum'])}\")\n if not self.hasFocus():\n self.setValue(data[\"value\"])\n self.setDisabled(data[\"disabled\"])\n","repo_name":"yaq-project/qtypes","sub_path":"qtypes/_widgets/_integer.py","file_name":"_integer.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9324937310","text":"\nfrom PIL import ImageGrab\nfrom time import strftime\nimport os\n\ndef screenshot(picturename):\n now = strftime(\"%Y-%m-%d\") #获取当前时间\n path = './output/screenshots/' + now + 'screenshots/'\n if not os.path.exists(path):\n os.mkdir(path)\n im = ImageGrab.grab()\n im.save(path + picturename + \".jpeg\")","repo_name":"wuxiaoxia-stu/autotest-netca","sub_path":"testcase/common/screenshot.py","file_name":"screenshot.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15321888815","text":"import json\n\nfrom collections import defaultdict\nfrom datetime import datetime\n\nfrom log import LOG\n\n# When we are running inside PyPy, we can use the optimized StringBuilder type to\n# help serialize JSON.\ntry:\n from __pypy__.builders import StringBuilder\n from _pypyjson import raw_encode_basestring_ascii\nexcept ImportError:\n StringBuilder = None\n\n # NOTE: This is the equivalent function in CPython. Since we do not expect\n # the DruidWriter to be used very often with CPython, it is ok to have this\n # unoptimized function which slices the string after it is converted to remove the\n # enclosing quotes.\n raw_encode_basestring_ascii = lambda s: json.encoder.encode_basestring_ascii(s)[\n 1:-1\n ]\n\nINFINITY = float('inf')\nNAN = float('nan')\n\n\nclass RowMetaData:\n def __init__(self):\n self.count = 0\n self.start_date = datetime.today().strftime('%Y-%m-%d')\n self.end_date = ''\n\n def update_metadata_with_row(self, row):\n self.count += 1\n if row.date < self.start_date:\n self.start_date = row.date\n if row.date > self.end_date:\n self.end_date = row.date\n\n\nclass ErrorHandler:\n '''Class to log and optionally raise errors that are found during conversion\n from BaseRow to Druid rows.\n '''\n\n def __init__(\n self,\n allow_missing_date=False,\n allow_empty_data=True,\n allow_missing_canonical_match=False,\n ):\n self.allow_missing_date = allow_missing_date\n self.allow_empty_data = allow_empty_data\n self.allow_missing_canonical_match = allow_missing_canonical_match\n\n # The number of rows that were missing a date value.\n self.missing_date_count = 0\n\n # The number of rows that had no metrics to write (data section was\n # empty).\n self.empty_data_count = 0\n\n # Counts of input dimensions that could not be matched to a canonical.\n self.failed_matches = defaultdict(int)\n\n def missing_date(self, input_row_str):\n assert (\n self.allow_missing_date\n ), f'All output rows must have a date! Input row: {input_row_str}'\n self.missing_date_count += 1\n\n def empty_data(self, input_row_str):\n assert self.allow_empty_data, (\n 'All input rows must have a non-empty data field! '\n 'Input row: %s' % input_row_str\n )\n self.empty_data_count += 1\n\n def missing_canonical_match(\n self, input_dimensions, input_row_str, track_failed_matches=True\n ):\n assert (\n self.allow_missing_canonical_match\n ), 'Canonical matching failed for row. ' 'Dimensions: %s\\nInput row: %s' % (\n input_dimensions,\n input_row_str,\n )\n # NOTE: Multi value dimensions are lists, which cannot be hashed.\n # Convert them to a sorted tuple as the list order doesn't matter.\n key = frozenset(\n [\n (k, v if not isinstance(v, list) else tuple(sorted(v)))\n for k, v in input_dimensions.items()\n ]\n )\n if track_failed_matches:\n self.failed_matches[key] += 1\n\n def print_stats(self):\n if self.missing_date_count:\n LOG.info('Rows missing a date: %s', self.missing_date_count)\n if self.empty_data_count:\n LOG.info('Rows without any data: %s', self.empty_data_count)\n if self.failed_matches:\n rows_failed_count = sum(self.failed_matches.values())\n matches_failed_count = len(self.failed_matches)\n LOG.info('Rows with missing canonical match: %s', rows_failed_count)\n LOG.info(\n 'Input dimensions without canonical match: %s', matches_failed_count\n )\n lines = ['Row Dimensions\\tCount']\n for key, value in self.failed_matches.items():\n lines.append(f'{dict(key)}\\t{value}')\n LOG.info(\n 'Canonical mapping is missing for these dimension ' 'combinations:\\n%s',\n '\\n'.join(lines),\n )\n\n\nclass DruidWriter:\n '''Utility class for translating an input file of BaseRows into a Druid\n compatible row format containing the final canonical dimensions.\n '''\n\n @classmethod\n def run(\n cls,\n base_row_cls,\n metadata_collector,\n input_file,\n output_file,\n use_optimizations=True,\n error_handler=None,\n output_metadata_digest_writer=None,\n track_failed_matches=True,\n ):\n '''Convert rows stored in `input_file` into Druid output rows and store\n them in `output_file`.\n\n Args:\n base_row_cls: The concrete BaseRow subclass input rows are stored\n as. Example: BaseEthiopiaRow\n metadata_collector: A FullRowDimensionDataCollector instance that\n can convert the dimensions stored in an input row into canonical\n dimensions to store in the Druid output row.\n input_file: A file handle that serialized input rows will be read\n from.\n output_file: A file-like handle (supports `write(str)`) that output\n Druid rows will be written to.\n use_optimizations: Optional. If enabled, produce Druid rows using\n experimental performance improvements that attempt to reduce\n JSON parsing to the smallest amount possible.\n error_handler: Optional. An ErrorHandler instance that will collect\n and optionally raise issue found when converint an input row\n into Druid row format.\n output_metadata_digest_writer: Optional. Writer to output CSV file. for data digest.\n track_failed_matches: Optional. Whether we should track failed matches or not.\n '''\n error_handler = error_handler or ErrorHandler()\n\n # By default, use safe parsers and output row writers that will\n # deserialize the entire input row. Write output rows by serializing\n # the parsed full input row instance into druid format\n (parse_row, write_output_rows) = Parser.safe_parser(base_row_cls)\n if use_optimizations:\n # Produce Druid rows using experimental performance improvements.\n # Attempt to reduce JSON parsing to the smallest amount possible.\n # Because we know the structure of our BaseRow datatype, we can\n # exploit this knowledge to work around JSON serialization\n # limitations. JSON serialization/deserialization is one of the most\n # costly operations that is performed in this step. Most of this\n # cost comes from the large `data` object stored in the base row. It\n # is possible to remove this object from the json string before\n # deserialization and add it back in when we are ready to serialize\n # it again.\n (parse_row, write_output_rows) = Parser.optimized_parser(base_row_cls)\n\n return cls._run(\n base_row_cls,\n metadata_collector,\n input_file,\n output_file,\n error_handler,\n parse_row,\n write_output_rows,\n output_metadata_digest_writer,\n track_failed_matches,\n )\n\n @classmethod\n def _run(\n cls,\n base_row_cls,\n metadata_collector,\n input_file,\n output_file,\n error_handler,\n parse_row,\n write_output_rows,\n output_metadata_digest_writer,\n track_failed_matches,\n ):\n LOG.info('Starting processing')\n\n input_row_count = output_row_count = 0\n unmapped_keys = set(base_row_cls.UNMAPPED_KEYS)\n has_unmapped_keys = bool(unmapped_keys)\n datasource_field_metadata = defaultdict(RowMetaData)\n for input_row in input_file:\n (row, has_data, parsed_extras) = parse_row(input_row)\n input_row_count += 1\n if not row.date:\n error_handler.missing_date(input_row)\n continue\n\n if not has_data:\n error_handler.empty_data(input_row)\n continue\n for data in row.data:\n datasource_field_metadata[data].update_metadata_with_row(row)\n\n # Match the input dimensions to their canonical version.\n row_dimensions = row.key\n output_dimensions = metadata_collector.get_data_for_row(row_dimensions)\n\n if not output_dimensions:\n error_handler.missing_canonical_match(\n row_dimensions, input_row, track_failed_matches=track_failed_matches\n )\n continue\n\n # Copy unmapped key values into output dimension dict\n if has_unmapped_keys:\n # Need to clone the canonical dimensions since we don't want to\n # modify the version owned by the metadata_collector.\n output_dimensions = dict(output_dimensions)\n for key in row_dimensions:\n # NOTE: Only copy the value over from the original row if\n # a value has not been set yet. This *might* happen if the user has\n # supplied metadata for a canonical row while also allowing process\n # steps to fill it in directly. Prefer the canonical metadata value\n # instead.\n # TODO: Should we warn when this happens?\n if key not in unmapped_keys or key in output_dimensions:\n continue\n output_dimensions[key] = row_dimensions[key]\n\n row.key = output_dimensions\n rows_written = write_output_rows(row, output_file, parsed_extras)\n output_row_count += rows_written\n\n if (input_row_count % 20000) == 0:\n LOG.info('Rows processed: %s', input_row_count)\n if output_metadata_digest_writer:\n output_metadata_digest_writer.writeheader()\n for field in datasource_field_metadata:\n output_metadata_digest_writer.writerow(\n {\n 'indicator_id': field,\n 'count': datasource_field_metadata[field].count,\n 'start_date': datasource_field_metadata[field].start_date,\n 'end_date': datasource_field_metadata[field].end_date,\n }\n )\n\n LOG.info('Finished processing')\n LOG.info('Input rows processed: %s', input_row_count)\n LOG.info('Output rows written: %s', output_row_count)\n error_handler.print_stats()\n\n\nclass Parser:\n '''Class providing the various serialization/deserialization methods that\n are supported.\n\n Each method returns a tuple of (parse_row, write_output_rows). The signature\n of these functions is:\n parse_row(row_str) -> (BaseRow, has_data?, extras from parsing)\n write_output_rows(base_row, output_file, extras from parsing)\n -> output count\n '''\n\n @staticmethod\n def safe_parser(base_row_cls):\n deserialize_fn = base_row_cls.from_json\n\n def parse_row(row_str):\n base_row = deserialize_fn(row_str)\n return (base_row, bool(base_row.data), None)\n\n def write_output_rows(row, output_file, _):\n output_row_count = 0\n for output_row in row.to_druid_json_iterator(True):\n output_file.write(output_row)\n output_row_count += 1\n return output_row_count\n\n return (parse_row, write_output_rows)\n\n @staticmethod\n def optimized_parser(base_row_cls):\n deserialize_fn = base_row_cls.from_json\n\n def parse_row(row_str):\n return parse_row_optimized(row_str, deserialize_fn)\n\n def write_output_rows(row, output_file, raw_data):\n return write_output_rows_optimized(row, raw_data, output_file)\n\n return (parse_row, write_output_rows)\n\n\n## Methods for manually serializing/deserializing BaseRows into Druid format ##\n\nDATA_MARKER = '\"data\": {'\n\n# Build a minimal BaseRow for the given json string by extracting the raw data\n# and storing it separately. Return both the full row object and the raw data\n# string.\ndef parse_row_optimized(row_str, deserialize_fn):\n # Find the start and end index of the contents of the `data` object.\n start_idx = row_str.index(DATA_MARKER) + len(DATA_MARKER)\n end_idx = row_str.index('}', start_idx)\n raw_data = row_str[start_idx:end_idx]\n base_row = deserialize_fn(f'{row_str[:start_idx]}{row_str[end_idx:]}')\n return (base_row, bool(raw_data), raw_data)\n\n\ndef serialize_dimension_mapping(mapping):\n '''Build a \"key\": \"value\" JSON serialized mapping. The returned string can be used\n inside a JSON object.\n\n Optimization: We know that the dimension mapping should only be a Dict[str, str], so\n we can optimize how this string is built. To be safe, we will fallback when other\n values are encountered.\n\n NOTE: This is a super optimized version of PyPy's\n JSONEncoder.__encode_dict. It only is beneficial when PyPy is being used.\n '''\n # Safeguard check in case this method was run inside CPython.\n if not StringBuilder:\n return json.dumps(mapping)[1:-1]\n\n builder = StringBuilder()\n first = True\n for key, value in mapping.items():\n # Add the separator at the end of the last key/value pair.\n if not first:\n builder.append(', ')\n first = False\n\n # Add the key to the string.\n builder.append('\"')\n builder.append(raw_encode_basestring_ascii(key))\n builder.append('\": ')\n\n if isinstance(value, str):\n builder.append('\"')\n builder.append(raw_encode_basestring_ascii(value))\n builder.append('\"')\n elif isinstance(value, int):\n builder.append(int.__str__(key))\n elif isinstance(value, float):\n # Disallow NaN, Infinity, and -Infinity since those indicate the pipeline\n # is not producing valid data and should be reviewed.\n assert value not in (\n NAN,\n INFINITY,\n -INFINITY,\n ), f'Bad float value passed: {value}'\n builder.append(float.__repr__(value))\n else:\n # Multi value dimensions are type lists so avoid printing error logs\n if not isinstance(value, list):\n LOG.error(\n 'Unexpected dimension value found. Key: %s, Value: %s', key, value\n )\n builder.append(json.dumps(value))\n return builder.build()\n\n\n# Take a row that is ready for output and add the raw data object back in. Write\n# the serialized version to the output file.\ndef write_output_rows_optimized(row, raw_data, output_file):\n # Build a JSON row that does not have a closing brace. It will look like:\n # { ...dimensions, \"Real_Date\": \"2021-01-01\", \"source\": \"pipeline_source\"\n # NOTE: Only need to JSON serialize the dimensions and the row's source\n # value since we know that the date and source field key are JSON safe.\n open_row_str = '{%s, \"%s\": \"%s\", \"%s\": \"%s\"' % (\n serialize_dimension_mapping(row.key),\n row.DATE_FIELD,\n row.date,\n row.SOURCE_FIELD,\n raw_encode_basestring_ascii(row.source),\n )\n\n count = 0\n (zero_fields, nonzero_data) = extract_zero_fields(raw_data)\n if zero_fields:\n output_file.write(\n '%s, \"field\": [%s], \"val\": 0}\\n' % (open_row_str, zero_fields)\n )\n count += 1\n\n if nonzero_data:\n output_file.write('%s, \"data\": {%s}}\\n' % (open_row_str, nonzero_data))\n count += 1\n return count\n\n\n# Determine if there are enough zero value fields in the raw data to make it\n# worth it to split them out separately.\ndef _has_enough_zero_values(raw_data, min_count=3):\n count_zero_int = raw_data.count(': 0,') + int(raw_data.endswith(': 0'))\n if count_zero_int > min_count:\n return True\n\n count_zero_float = raw_data.count(': 0.0,') + int(raw_data.endswith(': 0.0'))\n return (count_zero_int + count_zero_float) > min_count\n\n\n# Remove zero fields from the raw_data so that the nested json that is sent\n# to druid is only non-zero values. Zero values will be passed as a list of\n# fields all in one row.\ndef extract_zero_fields(raw_data):\n if not _has_enough_zero_values(raw_data):\n return (None, raw_data)\n\n zero_fields = []\n idx = 0\n end_idx = len(raw_data)\n ends_with_zero = False\n nonzero_start_idx = 0\n nonzero_end_idx = 0\n nonzero_indices = []\n while idx < end_idx:\n # Get the start/end index of the field string key. Include the quotation\n # marks so we can avoid adding them back later.\n field_start_idx = raw_data.index('\"', idx)\n field_end_idx = raw_data.index('\": ', field_start_idx) + 1\n\n # Get the start/end index of the field's value.\n value_start_idx = field_end_idx + 2\n value_end_idx = raw_data.find(', ', value_start_idx)\n\n # Ensure we don't overflow the data section. This happens when parsing\n # the final value of the data object.\n if value_end_idx == -1 or value_end_idx > end_idx:\n value_end_idx = end_idx\n\n raw_value = raw_data[value_start_idx:value_end_idx]\n if raw_value == '0' or raw_value == '0.0':\n zero_fields.append(raw_data[field_start_idx:field_end_idx])\n ends_with_zero = value_end_idx == end_idx\n\n if nonzero_end_idx > nonzero_start_idx:\n nonzero_indices.append((nonzero_start_idx, nonzero_end_idx))\n\n # Set the start of the next potential nonzero segment to begin\n # right after this nonzero value ends.\n nonzero_start_idx = value_end_idx\n\n # If the first value encountered is a zero, and no non-zero values\n # have been found yet, then we want to increment the start index\n # to drop the leading ', '.\n if not nonzero_indices:\n nonzero_start_idx += 2\n else:\n nonzero_end_idx = value_end_idx\n\n # Move on to the next field/value to parse.\n idx = value_end_idx + 1\n\n if not ends_with_zero:\n nonzero_indices.append((nonzero_start_idx, end_idx))\n\n nonzero_data = ''.join(\n raw_data[start_idx:end_idx] for start_idx, end_idx in nonzero_indices\n )\n\n return (', '.join(zero_fields), nonzero_data)\n","repo_name":"Zenysis/Harmony","sub_path":"data/pipeline/io/druid_writer.py","file_name":"druid_writer.py","file_ext":"py","file_size_in_byte":18618,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"70212635045","text":"def main():\r\n A, B = map(int, input().split())\r\n partial = partial_sum(B)\r\n print(partial[B - 1] - partial[A - 2]) if A != 1 else print(partial[B - 1])\r\n\r\n\r\ndef partial_sum(B: int) -> list[int]:\r\n partial = [1]\r\n\r\n N_max = 45\r\n for n in range(2, N_max + 1):\r\n for _ in range(n):\r\n if len(partial) == B:\r\n break\r\n partial.append(n + partial[-1])\r\n return partial\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"SeungWoo-You/PS","sub_path":"백준/Bronze/1292. 쉽게 푸는 문제/쉽게 푸는 문제.py","file_name":"쉽게 푸는 문제.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37285787228","text":"#\n# @lc app=leetcode id=56 lang=python3\n#\n# [56] Merge Intervals\n#\n# https://leetcode.com/problems/merge-intervals/description/\n#\n# algorithms\n# Medium (36.32%)\n# Likes: 2647\n# Dislikes: 210\n# Total Accepted: 425.9K\n# Total Submissions: 1.2M\n# Testcase Example: '[[1,3],[2,6],[8,10],[15,18]]'\n#\n# Given a collection of intervals, merge all overlapping intervals.\n# \n# Example 1:\n# \n# \n# Input: [[1,3],[2,6],[8,10],[15,18]]\n# Output: [[1,6],[8,10],[15,18]]\n# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into\n# [1,6].\n# \n# \n# Example 2:\n# \n# \n# Input: [[1,4],[4,5]]\n# Output: [[1,5]]\n# Explanation: Intervals [1,4] and [4,5] are considered overlapping.\n# \n# NOTE: input types have been changed on April 15, 2019. Please reset to\n# default code definition to get new method signature.\n# \n#\n\n# @lc code=start\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals.sort(key=lambda x: x[0])\n merged = []\n for interval in intervals:\n if not merged or merged[-1][1] < interval[0]:\n merged.append(interval)\n else:\n merged[-1][1] = max(merged[-1][1], interval[1])\n\n return merged\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"56.merge-intervals.py","file_name":"56.merge-intervals.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"41589424254","text":"import RPi.GPIO as GPIO\nimport time\n\na_pin = 18\nb_pin = 23\n\ndef setup():\n GPIO.setmode(GPIO.BCM)\n\ndef discharge():\n GPIO.setup(a_pin, GPIO.IN)\n GPIO.setup(b_pin, GPIO.OUT)\n GPIO.output(b_pin, GPIO.LOW)\n time.sleep(0.05)\n\ndef charge_time():\n GPIO.setup(b_pin, GPIO.IN)\n GPIO.setup(a_pin, GPIO.OUT)\n count = 0\n GPIO.output(a_pin, GPIO.HIGH)\n while not GPIO.input(b_pin):\n count = count + 1\n return count\n\ndef analog_read():\n discharge()\n return charge_time()\n\ndef loop():\n while True:\n print(analog_read())\n time.sleep(1)\n\nif __name__ == '__main__': # Program start from here\n setup()\n try:\n loop()\n except KeyboardInterrupt: \n print('Quitting')\n finally:\n GPIO.cleanup()\n","repo_name":"yaliyao/0718","sub_path":"code/potentiometer.py","file_name":"potentiometer.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28159860009","text":"# -*- coding: utf-8 -*-\ndef permute(nums):\n \"\"\"\n 全排列\n O(N*N!) time | O(N*N!) space\n \"\"\"\n res = []\n \n def helper(combination, nums):\n if not nums:\n res.append(combination)\n return \n else:\n for i in range(len(nums)):\n helper(combination + [nums[i]], nums[0:i] + nums[i+1:])\n \n helper([], nums)\n return res\n\n\nfrom itertools import permutations\n\ndef permute(nums):\n res = []\n\n for tpl in permutations(nums):\n lst = list(tpl)\n res.append(lst)\n \n return res\n\n\nif __name__ == \"__main__\":\n nums = [1, 2, 3, 4, 5]\n permute(nums)\n","repo_name":"Lukaschen1986/LeetCodeProgress","sub_path":"AlgoExpert/medium/Permutations.py","file_name":"Permutations.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38243516180","text":"import re\nimport sys\nimport inflect\nfrom datetime import date\n\n\ndef main():\n\n # Input in YYYY-MM-DD Format\n dat = input(\"Date of Birth: \")\n \n # Calling minute(), passing DOB and getting minutes between respected dates\n total_min = minute(dat)\n\n # Calling in_words function\n print(in_words(total_min))\n\n\n# Checking User Input in YYYY-MM-DD format\ndef minute(dob):\n\n # Getting todays date\n today = date.today()\n\n try:\n\n # Verifying date format\n if re.search(r\"^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$\", dob):\n year, mm, dd = dob.split(\"-\")\n dob = date(int(year), int(mm), int(dd))\n num_days = abs(dob - today)\n\n min = num_days.days * 24 * 60\n\n return min\n\n else:\n raise ValueError\n\n except ValueError:\n sys.exit(\"Invalid date\")\n\n\n# Printing minutes in number to words\ndef in_words(minutes):\n\n word = inflect.engine()\n words = word.number_to_words(minutes, andword=\"\")\n result = words.capitalize() + \" minutes\"\n return result\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"divyanshu-github2295/Python","sub_path":"seasons/seasons.py","file_name":"seasons.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12642772729","text":"from unidecode import unidecode\n\nwith open(\"palavrasnovas.txt\", \"r\", encoding=\"UTF-8\") as a_file:\n final_file = []\n for line in a_file:\n stripped_line = line.strip().replace('.', '').replace(\"'\", '').replace(\"-\", '')\n if(len(stripped_line) == 5):\n final_file.append(unidecode(stripped_line.upper()))\n\n with open('palavras_filtradas.txt', 'w') as f:\n for item in final_file:\n f.write(\"%s\\n\" % item)\n","repo_name":"felps-dev/termoo_bot","sub_path":"filtrar.py","file_name":"filtrar.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4574940689","text":"import sys\n\nsys.stdin = open('whereami.in', 'r')\nsys.stdout = open('whereami.out', 'w')\n\ninput = sys.stdin.readline\n\nn = int(input())\nroad = input().strip()\n\nans = n\nfor k in range(1, n+1):\n val = True\n for i in range(n-k+1):\n for j in range(i):\n if road[i:i+k] == road[j:j+k]:\n val = False\n break\n if val:\n ans = k\n break\nprint(ans)\n","repo_name":"C0derTang/mixed-cp-solutions","sub_path":"USACO/Bronze/Python/USACO 2019 Dec Bronze Where Am I_.py","file_name":"USACO 2019 Dec Bronze Where Am I_.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"70800711524","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # **Data-SIFTS**\n# This is the data-preprocessing script that screens through [RCSB PDB](https://www.rcsb.org/) [search API](https://search.rcsb.org/) and [PDBe](https://www.ebi.ac.uk/pdbe/) [SIFTS API](https://www.ebi.ac.uk/pdbe/api/doc/sifts.html) to retrieve targeted PDB ids and associated gene ontology (GO) codes.\n# \n# ## **0. Prerequisites**\n# ### Required packages\n\n# In[1]:\n\n\nimport math\nimport time\nfrom datetime import datetime\nimport numpy as np\nimport requests\nimport json\nfrom tqdm.auto import tqdm\n\nfrom argparse import Namespace\n\n\n# ### Configurations\n\n# In[2]:\n\n\nconfig = Namespace(\n sifts_timeout=10,\n sifts_savedir='./sifts',\n go_thres=50\n)\n\n\n# ## **1. First screening**\n# \n# ### Filter PDB ids and chains from [RCSB PDB](https://www.rcsb.org/) [search API](https://search.rcsb.org/)\n\n# In[3]:\n\n\nrequest = \"\"\"{\n \"query\": {\n \"type\": \"group\",\n \"logical_operator\": \"and\",\n \"nodes\": [\n {\n \"type\": \"terminal\",\n \"service\": \"text\",\n \"parameters\": {\n \"operator\": \"exact_match\",\n \"negation\": false,\n \"value\": \"Protein\",\n \"attribute\": \"entity_poly.rcsb_entity_polymer_type\"\n }\n },\n {\n \"type\": \"terminal\",\n \"service\": \"text\",\n \"parameters\": {\n \"operator\": \"range\",\n \"negation\": false,\n \"attribute\": \"rcsb_polymer_entity.formula_weight\",\n \"value\": {\n \"from\": 10,\n \"include_lower\": true,\n \"to\": 300,\n \"include_upper\": true\n }\n }\n }\n ]\n },\n \"request_options\": {\n \"results_verbosity\": \"minimal\",\n \"return_all_hits\": true,\n \"group_by\": {\n \"aggregation_method\": \"sequence_identity\",\n \"similarity_cutoff\": 95,\n \"ranking_criteria_type\": {\n \"sort_by\": \"entity_poly.rcsb_sample_sequence_length\",\n \"direction\": \"desc\"\n }\n },\n \"group_by_return_type\": \"representatives\",\n \"scoring_strategy\": \"combined\",\n \"sort\": [\n {\n \"sort_by\": \"rcsb_entry_info.resolution_combined\",\n \"direction\": \"asc\"\n }\n ]\n },\n \"return_type\": \"polymer_entity\"\n}\"\"\"\n\nurl = \"https://search.rcsb.org/rcsbsearch/v1/query?json={:s}\".format(request)\nprint(\"Fetching data from {:s}...\".format(url))\ndata = requests.get(url)\n\nif data.status_code != 200:\n raise AssertionError(\"cannot fetch data from databse\")\n\ndecoded = data.json()\n\nnow = datetime.now()\ndt_string = now.strftime(\"%m/%d/%Y %H:%M:%S\")\n\nprint(\"\\t{:d} out of total {:d} proteins received on {:s}\".format(\n decoded['group_by_count'], \n decoded['total_count'], \n dt_string))\n\npolymers = []\nfor entry in decoded['result_set']:\n polymers.append(entry['identifier'])\n\ndel data, decoded\n\n\n# ## **2. Second screening**\n# ### Fetch GO codes from [PDBe](https://www.ebi.ac.uk/pdbe/) [SIFTS API](https://www.ebi.ac.uk/pdbe/api/doc/sifts.html)\n\n# In[4]:\n\n\nprint(\"Fetching GO codes...\")\n\n# t_str = time.time()\n\nwith open(f'{config.sifts_savedir}/sifts-err-1.log', \"w\") as err:\n mf_go_codes_all = []\n pdb_chains_all = []\n for i, polymer in enumerate(tqdm(polymers)):\n pdb_id, entity_id = polymer.lower().split('_')\n \n url = \"https://www.ebi.ac.uk/pdbe/api/mappings/go/\"+pdb_id\n\n try:\n data = requests.get(url, timeout=config.sifts_timeout)\n except requests.Timeout:\n err.write(\"\\tpdb_id: {:4s} -> Timeout\\n\".format(pdb_id))\n err.flush()\n continue\n\n if data.status_code != 200:\n err.write(\"\\tpdb_id: {:4s} -> Failure (status = {:d})\\n\".format(pdb_id, data.status_code))\n err.flush()\n continue\n\n decoded = data.json()\n\n for go_code in decoded[pdb_id]['GO'].keys():\n if decoded[pdb_id]['GO'][go_code]['category'] == \"Molecular_function\":\n for mapping in decoded[pdb_id]['GO'][go_code]['mappings']:\n if int(mapping['entity_id']) == int(entity_id):\n mf_go_codes_all.append(go_code)\n pdb_chains_all.append('{:s}_{:s}'.format(pdb_id, mapping['chain_id']))\n\n err.close()\n\n\n# ### Save all and filtered pdb-chain ids and GO codes\n\n# In[5]:\n\n\npdb_chains = np.unique(pdb_chains_all)\n\nnp.savetxt(f'{config.sifts_savedir}/pdb_chains.dat', pdb_chains, fmt='%s')\n\nuniques, counts = np.unique(mf_go_codes_all, return_counts=True)\n\nnp.savetxt(f'{config.sifts_savedir}/mf_go_codes-allcnt.dat', \n np.concatenate((uniques.reshape(-1,1), \n counts.reshape(-1,1)),\n axis=1),\n fmt='%s\\t%s')\n\nmask = counts >= config.go_thres\n\nnp.savetxt(f'{config.sifts_savedir}/mf_go_codes-thres-{config.go_thres:d}.dat', \n np.concatenate((uniques[mask].reshape(-1,1), \n counts[mask].reshape(-1,1)),\n axis=1),\n fmt='%s\\t%s')\n\nnp.save(f'{config.sifts_savedir}/mf_go_codes-thres-{config.go_thres:d}.npy', \n uniques[counts >= config.go_thres])\n\n\n# ## **3. Export PDB-GO pairs**\n# ### Generate PDB-GO pairs based on filtered entries\n\n# In[7]:\n\n\nprint(\"Generating pdb mf-go vectors...\")\n\nmf_go_codes = np.load(f'{config.sifts_savedir}/mf_go_codes-thres-{config.go_thres:d}.npy')\n\npdbmfgos = {}\n\nwith open(f'{config.sifts_savedir}/sifts-err-2.log', \"w\") as err:\n for i, pdb_chain in enumerate(tqdm(pdb_chains)):\n pdb_id, chain_id = pdb_chain.split('_')\n\n url = \"https://www.ebi.ac.uk/pdbe/api/mappings/go/\"+pdb_id\n\n try:\n data = requests.get(url, timeout=config.sifts_timeout)\n except requests.Timeout:\n err.write(\"\\tpdb_id: {:4s} -> Timeout\\n\".format(pdb_chain))\n err.flush()\n continue\n\n if data.status_code != 200:\n err.write(\"\\tpdb_id: {:4s} -> Failure (status = {:d})\\n\".format(pdb_id, data.status_code))\n err.flush()\n continue\n\n decoded = data.json()\n\n pdbmfgo = np.zeros(mf_go_codes.shape, dtype=int)\n for go_code in decoded[pdb_id]['GO'].keys():\n if decoded[pdb_id]['GO'][go_code]['category'] == \"Molecular_function\":\n for mapping in decoded[pdb_id]['GO'][go_code]['mappings']:\n if mapping['chain_id'] == chain_id:\n pdbmfgo += np.where(mf_go_codes == go_code, 1, 0).astype(int)\n \n pdbmfgos[pdb_chain] = np.argwhere(np.where(pdbmfgo > 0, 1, 0)).reshape(-1).tolist()\n\n err.close()\n \n\n\n# ### Save as JSON file\n\n# In[8]:\n\n\nwith open(f'{config.sifts_savedir}/pdbmfgos-thres-{config.go_thres:d}.json', \"w\") as out_file:\n json.dump(pdbmfgos, out_file, \n skipkeys=False, \n ensure_ascii=True, \n indent=None, separators=(', ', ': '),\n sort_keys=True)\n\n\n# ### Dataset summary\n\n# In[9]:\n\n\nwith open(f'{config.sifts_savedir}/pdbmfgos-thres-{config.go_thres:d}.json', \"r\") as in_file:\n pdbmfgos = json.load(in_file)\n\nprint(\"protein entries: {:6d}\\nmf-go entries: {:6d}\".format(\n len(pdbmfgos.keys()), \n max(list(map(lambda x: [max(x)] if x else [], list(pdbmfgos.values()))))[0]+1)\n)\n\n","repo_name":"chiang-yuan/ProDAR","sub_path":"data/data-sifts.py","file_name":"data-sifts.py","file_ext":"py","file_size_in_byte":7173,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"37547037431","text":"from flask import Flask, request, render_template\nfrom search import request_base\nimport re\n\n\napp = Flask(__name__)\n\n\n@app.route(\n \"/\", methods=[\"GET\", \"POST\"],\n)\ndef search():\n phone_number = request.form.get(\n 'phone',\n type=str,\n default=''\n )\n name = request.form.get(\n 'name',\n type=str,\n default=''\n )\n action = request.form.get(\n 'action',\n default=False,\n type=bool\n )\n if re.search(r'[9]{1}\\d{5,}', phone_number):\n phone_number = re.findall(r'[9]{1}\\d{5,}', phone_number)[0]\n else:\n phone_number = ''\n print(phone_number)\n match, get_records = request_base(phone=phone_number, name=name)\n\n return render_template(\n 'index.html',\n match=match,\n action=action,\n get_records=get_records\n )\n\n\nif __name__ == '__main__':\n app.run()","repo_name":"PlanSK/search_in_base","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1931830255","text":"import json\nimport argparse\nimport hashlib\n\ndef PrintItems(items):\n for item in items:\n PrintItem(item)\n\ndef PrintItem(item):\n print(str(item[\"year\"])+\"-\"+item[\"month\"]+\"-\"+item[\"day\"],item[\"transactionType\"],item[\"accountName\"],item[\"account\"],item[\"vs\"],item[\"value\"],item.get(\"place\",\"\"),sep=\"|\")\n\ndef PrintRule(rule):\n print(rule[\"ruleType\"],rule[\"ruleValue\"],rule[\"who\"],rule[\"type\"],rule[\"subType\"])\n\ndef PrintIdentifiedItems(items):\n print(\"Identified items: \")\n for item in items:\n if item[\"identified\"]:\n PrintItem(item)\n\ndef PrintUnidentifiedItems(items):\n print(\"Unidentified items: \")\n for item in items:\n if not item[\"identified\"]:\n PrintItem(item)\n\ndef PrintRules(rules):\n for rule in rules:\n print(rule[\"ruleType\"],rule[\"ruleValue\"],rule[\"who\"],rule[\"type\"],rule[\"subType\"])\n\ndef ReadItems(items):\n try:\n fileName = \"\"\n if args.air:\n fileName = 'data/extractedPayments/items_' + str(args.Year) + \"_\" + str(args.Month) + \"_AirBank.json\"\n else:\n fileName = 'data/extractedPayments/items_' + str(args.Year) + \"_\" + str(args.Month) + \".json\"\n\n with open(fileName, 'r') as filehandle:\n items[:] = json.load(filehandle)\n items.sort(key = lambda i: i['value'])\n except:\n print(\"No file: \" + fileName + \" found!\")\n exit(1)\n # PrintItems(items)\n\ndef ReadRules(rules):\n try:\n with open('configs/rules.json', 'r') as filehandle:\n rules[:] = json.load(filehandle)\n except:\n with open('configs/rules.json', 'w') as filehandle:\n rules[:] = []\n\ndef ReadFinancialBook():\n fileName = \"\"\n if args.air:\n fileName = 'data/financialBook/finBook_AirBank.json'\n else:\n fileName = 'data/financialBook/finBook.json'\n try:\n with open(fileName, 'r') as filehandle:\n # book{:} = json.load(filehandle)\n data = json.load(filehandle)\n except:\n data = {}\n with open(fileName, 'w') as filehandle:\n json.dump(book, filehandle)\n return data\n\ndef SaveFinancialBook(book):\n fileName = \"\"\n if args.air:\n fileName = 'data/financialBook/finBook_AirBank.json'\n else:\n fileName = 'data/financialBook/finBook.json'\n with open(fileName, 'w') as filehandle:\n json.dump(book, filehandle)\n\ndef CheckItem(item,rule):\n if item.get(rule[\"ruleType\"]) == None or type(item.get(rule[\"ruleType\"])) != type(\"\"):\n return False\n # PrintItem(item)\n # PrintRule(rule)\n if rule[\"ruleValue\"].lower() in item.get(rule[\"ruleType\"]).lower():\n # print(\"Item identified\")\n # print(item)\n item[\"identified\"] = True\n item[\"who\"] = rule[\"who\"]\n item[\"type\"] = rule[\"type\"]\n item[\"subType\"] = rule[\"subType\"]\n return True\n\ndef IdentifyItems(items,rules):\n for item in items:\n item[\"type\"] = \"unidentified\"\n for rule in rules:\n if CheckItem(item,rule):\n break\n\ndef GenerateHash(item):\n # PrintItem(item)\n print(str(item[\"year\"]),str(item[\"month\"]),str(item[\"day\"]),str(item[\"transactionType\"]),str(item[\"transactionID\"]),str(item[\"accountName\"]),str(item[\"account\"]),str(item[\"vs\"]),str(item[\"value\"]),item.get(\"place\",\"\"))\n hashInput = str(item[\"year\"]) + str(item[\"month\"]) + str(item[\"day\"]) + str(item[\"transactionType\"]) + str(item[\"transactionID\"]) + str(item[\"accountName\"]) + str(item[\"account\"]) + str(item[\"vs\"]) + str(item[\"value\"]) + item.get(\"place\",\"\")\n m = hashlib.md5()\n m.update(hashInput.encode('utf-8'))\n return str(int(m.hexdigest(), 16))[0:12]\n\ndef AddToBook(items,book):\n for item in items:\n hash = GenerateHash(item)\n if hash in book:\n if book[hash][\"identified\"] == False and item[\"identified\"] == True:\n book[hash][\"type\"] = item[\"type\"]\n book[hash][\"who\"] = item[\"who\"]\n book[hash][\"subType\"] = item[\"subType\"]\n book[hash][\"identified\"] = True\n continue\n else:\n book[hash] = item\n\n# Create the parser\nmy_parser = argparse.ArgumentParser(description='Tries to identify extracted payments based on the identification rules')\n\n# Add the arguments\nmy_parser.add_argument('Year',\n metavar='year',\n type=int,\n help='year of the statement')\n\n# Add the arguments\nmy_parser.add_argument('Month',\n metavar='month',\n type=int,\n help='month of the statement')\n\nmy_parser.add_argument('-a',\n '--air',\n action='store_true',\n help='read AirBank statement format')\n\n# Execute the parse_args() method\nargs = my_parser.parse_args()\n\nif __name__ == \"__main__\":\n items = []\n rules = []\n book = {}\n ReadItems(items)\n # PrintItems(items)\n ReadRules(rules)\n # PrintRules(rules)\n book = ReadFinancialBook()\n IdentifyItems(items,rules)\n AddToBook(items,book)\n SaveFinancialBook(book)\n PrintIdentifiedItems(items)\n PrintUnidentifiedItems(items)\n","repo_name":"fajtak/fun-monthlyBudget","sub_path":"identifyItems.py","file_name":"identifyItems.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43544569963","text":"import math\nimport time\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom progress.bar import Bar\nfrom torch.nn import MSELoss\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom torchsummary import summary\n\n\nfrom model import DnCnn\nfrom dataloader import ZurichDataset, ToTensor\n\nBATCH_SIZE = 8\nDATASET_DIR = \"/storage/zurich-dataset\"\nINPUT_DIR = \"/storage/dncnn_2021_6_22_21\"\n\nif __name__ == '__main__':\n # Output folder creation\n output_dir = os.path.join(INPUT_DIR, \"apply\")\n os.makedirs(output_dir, exist_ok=True)\n\n # Initiate log file\n # log_file = open(f\"{output_dir}/log.txt\", \"w\")\n\n # Device definition\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n text = f\"Using device: {device}\\n\"\n print(text)\n # log_file.write(f\"{text}\\n\")\n\n\n # Datasets definition\n test_dataset = ZurichDataset(\n DATASET_DIR,\n transform=transforms.Compose([\n ToTensor()\n ]),\n train=False\n )\n\n # Dataloader definition\n test_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=True)\n\n # Model initialization\n model_path = os.path.join(INPUT_DIR, \"dncnn.pth\")\n model = torch.load(model_path)\n model.eval()\n\n # Applying model\n text = f\"Applying model...\"\n print(text)\n # log_file.write(f\"{text}\\n\")\n\n with torch.no_grad():\n (test_x, test_y) = next(iter(test_dataloader))\n print(\"Processing\", test_x.shape, \"elements\")\n predict_y = model(test_x.float().to(device)).detach()\n print(predict_y.shape)\n out = predict_y.cpu().numpy().transpose([0, 2, 3, 1]) * 255\n print(out.shape)\n for idx, image in enumerate(out):\n print(idx, image.shape)\n cv2.imwrite(os.path.join(output_dir, f\"output{idx}.png\"), image)\n ground = test_y[idx].cpu().numpy().transpose([1, 2, 0]) * 255\n print(ground.shape)\n cv2.imwrite(os.path.join(output_dir, f\"groundtruth{idx}.png\"), ground)\n\n # log_file.close()\n","repo_name":"rrarrais/Deep-Learning-solutions-for-the-ISP-pipeline","sub_path":"DnCNN/apply.py","file_name":"apply.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"35468950471","text":"# pylint: disable=W0614\nfrom helper import *\n\n# Attempts to overflow the number of lines of input passed into the binary\n\n\ndef checkBufferOverflowLines(sampleInputFile, binary, lock):\n print(\"Looking for buffer overflow in number of lines...\\n\", end=\"\")\n # First we read the first line of the file and store it in a string\n sampleInputFile.seek(0)\n sampleInput = sampleInputFile.readline()\n\n # We then attempt to overflow the number of lines in the input 100 times\n for i in range(1, 100):\n # We simply duplicate the first line of the file i * 10 times in our sample\n # input\n mutatedInput = (sampleInput * i * 10)\n if sendInputAndCheck(binary, mutatedInput, lock):\n return True, \"Found vulnerability from buffer overflow of lines!\"\n return False\n\n\ndef checkBufferOverflowColumns(sampleInputFile, binary, lock):\n print(\"Looking for buffer overflow in the columns...\\n\", end=\"\")\n # First we read the first line of the file and store it in a string\n sampleInputFile.seek(0)\n sampleInput = sampleInputFile.readline()\n columnValues = sampleInput.strip().split(\",\")\n modifiedValues = []\n for _ in range(0, len(columnValues)):\n modifiedValues.append(\"z\")\n # fuzz using the original values\n print(\"Fuzzing Columns with original input\\n\", end=\"\")\n description = \"Found vulnerability from buffer overflow in columns!\"\n if fuzzColumns(binary,columnValues,lock):\n return True , description\n # fuzz using modified columnValues\n print(\"Fuzzing Columns with modified input values\\n\", end=\"\")\n if fuzzColumns(binary,modifiedValues,lock):\n return True , description\n \n# For example: aaa........,bbbb.........,cccc.....,ddd...................\n\n\ndef fuzzColumns(binary, columnValues, lock):\n columnValues = list(columnValues)\n for _ in range(1, 100):\n # increase length of each element by 10 per iteration\n columnValues = [e + \"x\" * 10 for e in columnValues]\n mutatedInput = \",\".join(columnValues)\n if sendInputAndCheck(binary, mutatedInput, lock):\n return True\n return False\n","repo_name":"Multifactored/6447-Binary-Fuzzer","sub_path":"csvHelpers.py","file_name":"csvHelpers.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"30502860772","text":"import io\nfrom collections import Counter\n\nfrom PIL import Image\nfrom torchvision.transforms import ToPILImage\nimport torch\nimport numpy as np\n\n\nAI_APP_PATH = \"app/services/ai_model/\"\n\nmodel = torch.hub.load(\n AI_APP_PATH + \"yolov5/\",\n \"custom\",\n source=\"local\",\n path=AI_APP_PATH + \"weights/weights.pt\",\n force_reload=True,\n)\n\n\ndef detect(image: bytes) -> tuple[dict[str, int], Image]:\n image = Image.open(io.BytesIO(image))\n results = model(np.asarray(image))\n\n out_img = np.asarray(results.render())\n out_img = out_img.reshape(tuple(out_img.shape[1:]))\n return dict(Counter(results.pandas().xyxy[0][\"name\"])), np.squeeze(\n ToPILImage()(out_img)\n )\n","repo_name":"EldarKhayarov/recipe-recommendation-backend","sub_path":"app/services/ai_model/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12537873485","text":"from __future__ import print_function\n\nimport sys\n\nfrom chromite.cbuildbot import chromeos_config\nfrom chromite.lib import constants\nfrom chromite.lib import commandline\n\ndef GetParser():\n \"\"\"Creates the argparse parser.\"\"\"\n parser = commandline.ArgumentParser(description=__doc__)\n\n parser.add_argument('-f', '--full', action='store_true', default=False,\n help='Dump fully expanded configs.')\n parser.add_argument('-u', '--update_config', action='store_true',\n default=False, help='Update the site config json dump.')\n\n return parser\n\ndef main(argv):\n parser = GetParser()\n options = parser.parse_args(argv)\n\n site_config = chromeos_config.GetConfig()\n\n with (open(constants.CHROMEOS_CONFIG_FILE,\n 'w') if options.update_config else sys.stdout) as filehandle:\n if options.full:\n filehandle.write(site_config.DumpExpandedConfigToString())\n else:\n filehandle.write(site_config.SaveConfigToString())\n","repo_name":"kiwibrowser/src","sub_path":"third_party/chromite/scripts/cbuildbot_view_config.py","file_name":"cbuildbot_view_config.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"23589464021","text":"numbers = int(input())\n\nnumbers_list = list()\nresult = list()\nflag = False\n\nwhile True:\n if flag:\n print(result)\n break\n command = input()\n\n if command == \"even\":\n for num in numbers_list:\n if num % 2 == 0:\n result.append(num)\n flag = True\n\n elif command == \"odd\":\n for num in numbers_list:\n if num % 2 != 0:\n result.append(num)\n flag = True\n\n elif command == \"negative\":\n for num in numbers_list:\n if num < 0:\n result.append(num)\n flag = True\n\n elif command == \"positive\":\n for num in numbers_list:\n if num >= 0:\n result.append(num)\n flag = True\n else:\n numbers_list.append(int(command))","repo_name":"niki9011/python-fundamentals","sub_path":"lists_basics-lab/numbers_filter.py","file_name":"numbers_filter.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9170098217","text":"#!/usr/bin/python\n\n__doc__ = \"\"\"\nScript to convert FASTA files with (possibly) more than one line per record in\nto a file with all bases/amino acids on one line.\n\nThis format is needed for, e.g., BioProspector.\n\nInput can be file or stdin; output is stdout.\n\nRequires BioPython.\n\"\"\"\n\nimport sys\nimport optparse\nfrom Bio import SeqIO\n\nop = optparse.OptionParser()\nop.add_option('-i', dest='infn', help='Input FASTA file. Can be \"stdin\".')\n__doc__ += op.format_help()\n\ndef main(options):\n if options.infn == 'stdin':\n handle = sys.stdin\n else:\n handle = open(options.infn)\n fout = sys.stdout\n for record in SeqIO.parse(handle, 'fasta'):\n seq = record.seq.tostring()\n description = record.description\n fout.write('>%s\\n' % description)\n fout.write(seq+'\\n')\n\nif __name__ == \"__main__\":\n options,args = op.parse_args()\n main(options)\n","repo_name":"daler/rdbio-scripts","sub_path":"sequenceFiles/fastaToOneline.py","file_name":"fastaToOneline.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"7976007220","text":"import xlrd\nimport xlwt\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nimport string\n\n\ndef parse_excel(_file):\n wb = xlrd.open_workbook(filename=None, file_contents=_file.read())\n ws = wb.sheets()[0]\n data = list()\n for row in range(ws.nrows):\n title = ws.cell(row, 3).value\n abstract = ws.cell(row, 5).value\n data.append([title, abstract,])\n return data[1:]\n\n\ndef parse_spreadsheet(filename, title_index, abstract_index, sheet_index=0):\n wb = xlrd.open_workbook(filename=filename)\n ws = wb.sheets()[sheet_index]\n data = list()\n for row in range(ws.nrows):\n title = ws.cell(row, title_index).value\n abstract = ws.cell(row, abstract_index).value\n level_1_screening = ws.cell(row, 0).value\n final_selection = ws.cell(row, 1).value\n data.append([title, abstract, level_1_screening, final_selection])\n return data[1:]\n\n\ndef read_criteria_from_file(filename):\n with open(filename, 'r') as f:\n lines = f.readlines()\n return lines\n\n\ndef write_output(results, criteria_list):\n criteria_headers = list()\n\n for criteria in criteria_list:\n criteria_headers.append('CRITERIA_%s_SUM' % criteria['id'])\n criteria_headers.append('CRITERIA_%s_SIMILARITY' % criteria['id'])\n\n header = ['ARTICLE_ID', 'TITLE',] + criteria_headers + ['TOTAL_SIMILARITY',]\n\n results.insert(0, header)\n\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet('Screening')\n\n for i, row in enumerate(results):\n for j, col in enumerate(row):\n sheet.write(i, j, col)\n\n workbook.save('output.xls')\n\n\ndef normalize(text):\n translator = str.maketrans('', '', string.punctuation)\n text = text.translate(translator)\n text = text.lower()\n text = ' '.join(text.split())\n return text\n\n\ndef remove_stopwords(word_list):\n stops = set(stopwords.words('english'))\n filtered = [word for word in word_list if word not in stops]\n return filtered\n\n\ndef stemming(word_list):\n stemmer = SnowballStemmer('english')\n stemmed = map(lambda word: stemmer.stem(word), word_list)\n return list(stemmed)\n","repo_name":"vitorfs/elektra","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"7101913333","text":"#!/usr/bin/env python3\nimport os\nimport redis\nfrom flask import Flask, render_template, redirect, request, url_for, make_response\n\nif 'VCAP_SERVICES' in os.environ:\n VCAP_SERVICES = json.loads(os.environ['VCAP_SERVICES'])\n CREDENTIALS = VCAP_SERVICES[\"rediscloud\"][0][\"credentials\"]\n r = redis.Redis(host=CREDENTIALS[\"hostname\"], port=CREDENTIALS[\"port\"], password=CREDENTIALS[\"password\"])\nelse:\n r = redis.Redis(host='127.0.0.1', port='6379')\n\napp = Flask(__name__)\n\n@app.route('/')\ndef survey():\n resp = make_response(render_template('survey.html'))\n return resp\n\n@app.route('/suthankyou.html', methods=['POST'])\ndef suthankyou():\n\n d = request.form['division']\n s = request.form['state']\n f = request.form['feedback']\n\n print (\"Division is \" + d)\n print (\"State is \" + s)\n print (\"Feedback: \" + f)\n\n Counter = r.incr('new_counter')\n print (\"the counter is now: \", Counter)\n ## Create a new key that includes the counter\n newsurvey = 'review' + str(Counter)\n print (\"the name of the new key is: \" + newsurvey)\n\n print (\"Storing the survey now\")\n print (\"----------------------\")\n ## Now the key name is the content of the variable newsurvey\n r.hmset(newsurvey,{'division':d,'state':s,'feedback':f})\n\n print (\"Reading it back from Redis\")\n ####Need to use str(bytes_string, 'utf-8') to display properly without b''\n print (\"Division : \", str(r.hget('newsurvey','division'),'utf-8'))\n print (\"State : \", str(r.hget('newsurvey','state'),'utf-8'))\n print (\"Feedback : \", str(r.hget('newsurvey','feedback'),'utf-8'))\n\t\n resp = \"\"\"\n <h3> - THANKS FOR TAKING THE SURVEY - </h3>\n \"\"\"\n return resp\n\t\nif __name__ == \"__main__\":\n\tapp.run(debug=False, host='0.0.0.0', \\\n port=int(os.getenv('PORT', '5000')), threaded=True)\n","repo_name":"cermegno/Redis-test","sub_path":"_V3/step4.py","file_name":"step4.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70856569764","text":"class BaseBin:\n\n items = []\n\n def search(self, target):\n\n raise NotImplementedError('Method `search` must be implemented')\n\n\n def _search(self, items, target):\n\n self.items = items\n self.target = target\n \n min_ = 0\n max_ = len(items) - 1\n\n\n while min_ <= max_:\n mid = (max_ + min_) // 2\n\n if items[mid] == target:\n\n while items[mid - 1] == target:\n mid -= 1\n\n return mid\n\n if target > items[mid]:\n min_ = mid + 1\n else:\n max_ = mid - 1\n\n return - 1\n\n\n\n\nclass IntBin(BaseBin):\n\n def __init__(self, *args):\n\n if len(args) > 0 and isinstance(args[0], (set, tuple, list)):\n\n for element in args[0]:\n\n if isinstance(element, int):\n self.items.append(element)\n\n else:\n raise TypeError(\"Not all elements are integer\")\n\n elif len(args) > 0:\n\n for element in args:\n\n if isinstance(element, int):\n self.items.append(element)\n\n else:\n raise TypeError(\"Not all elements are integer\")\n\n else:\n raise TypeError(\"Not suported type or empty input\")\n\n self.items.sort()\n\n\n def __contains__(self, target):\n\n return self._search(self.items, target) != -1\n\n\n def search(self, target):\n\n return self._search(self.items, target)\n\n\n\n\nclass StringBin(BaseBin):\n\n items = []\n\n def __init__(self, *args):\n\n if len(args) > 0 and isinstance(args[0], (set, tuple, list)):\n\n for element in args[0]:\n\n if isinstance(element, str):\n self.items.append(element)\n\n else:\n raise TypeError(\"Not all elements are string\")\n\n elif len(args) > 0:\n\n for element in args:\n\n if isinstance(element, str):\n self.items.append(element)\n\n else:\n raise TypeError(\"Not all elements are string\")\n\n else:\n raise TypeError(\"Not suported type or empty input\")\n\n self.items.sort()\n\n\n def search(self, target):\n\n self.target = target\n\n return self._search(self.items, target)\n\n\n def __contains__(self, target):\n\n return self._search(self.items, target) != -1\n\n\n\nintegers = IntBin(1, 5, 2, 7, 9, 9, 4)\nprint(integers.search(5) == 3)\nprint(integers.search(1) == 0)\nprint(integers.search(9) == 5)\nprint((4 in integers) == True)\nprint((10 in integers) == False)\n\nstrings = StringBin(['a', 'mama', 'papa', 'papa', 'vasa', 'kola'])\nprint(strings.search('mama') == 2)\nprint(strings.search('a') == 0)\nprint(strings.search('papa') == 3)\nprint(('vasa' in strings) == True)\nprint(('olala' in strings) == False)\n","repo_name":"LeOneMoe/binsearch-struct","sub_path":"implementation.py","file_name":"implementation.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42050673003","text":"# -*- coding: utf-8 -*-\nimport pickle\n\nimport numpy as np\nfrom matplotlib import cm\nimport cv2\nfrom numba import jit\n\n@jit\ndef CalMandelbrotSet_dat(row, col, N, nmg, colorlist):\n img = np.zeros((row,col,3),dtype=np.uint8)\n \n for i in range(row):\n for j in range(col):\n if nmg[i,j] < N:\n img[i,j,:] = colorlist[nmg[i,j]]\n return img\n\ndef main():\n fname = \"MandelbrotSet_Save.dat\"\n with open(fname,\"rb\") as frb:\n [row, col, x, y, r, N, R, nmg] = pickle.load(frb)\n \n colorlist = np.zeros((N,3),dtype=np.uint8)\n for i in range(N):\n color = cm.hsv(i/64 % 1)\n for j in range(3):\n colorlist[i,j] = int(color[j]*255)\n \n img = CalMandelbrotSet_dat(row, col, N, nmg, colorlist)\n img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR)\n cv2.imwrite(\"MandelbrotSet_Load.png\",img)\n print(\"min n = %d\" % np.min(nmg), \"max n = %d\" % np.max(nmg))\n \nif __name__ == \"__main__\":\n main()","repo_name":"Shiki-mc2/MandelbrotSetZoomVideo_for_techbookfest11","sub_path":"MandelbrotSet_Load.py","file_name":"MandelbrotSet_Load.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"44026566860","text":"# ---- YOUR APP STARTS HERE ----\n# -- Import section --\nfrom flask import Flask, render_template, request\nfrom datetime import datetime\nfrom model import getImageUrlFrom\nimport os\n\n# -- Initialization section --\napp = Flask(__name__)\n\n\n# -- Routes section --\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template(\"index.html\", time = datetime.now())\n\n# add route for your gif results\n@app.route('/yourgif', methods = [\"GET\", \"POST\"])\ndef yourgif():\n user_response = \"dog\"\n gifLink = getImageUrlFrom(user_response)\n print(gifLink)\n \n #pass URL to render template and have that URL appear as an image in yourgif.html\n\n # get the gif for giphy and puts the link on the webpage\n return render_template(\"yourgif.html\", time = datetime.now(), gifLink = gifLink)\n # add datetime.now() to trick our browser into updating the css if we make any changes\n\n ","repo_name":"katherine-chao/giphy","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74787949605","text":"from django.contrib.auth import get_user_model\nfrom django.contrib.auth.forms import UserCreationForm, UsernameField\n\nUser = get_user_model()\n\n\nclass CreationForm(UserCreationForm):\n \"\"\"Cобственный класс для формы регистрации.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(CreationForm, self).__init__(*args, **kwargs)\n self.fields[\"email\"].required = True\n\n class Meta(UserCreationForm.Meta):\n model = User\n fields = (\"username\", \"first_name\", \"last_name\", \"email\")\n field_classes = {\"username\": UsernameField}\n","repo_name":"Bazulenkov/foodgram-project","sub_path":"users/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72877401765","text":"TICKET_COST = 150\ncollection_of_items = input().split(\"|\")\nbudget = float(input())\nbasket = budget\nprofit = .0\nprice_list = []\nfor item in collection_of_items:\n items = item.split(\"->\")\n type = items[0]\n price = float(items[1])\n filter_items = (\n basket >= price and (\n (type == \"Clothes\" and price <= 50) or\n (type == \"Shoes\" and price <= 35) or\n (type == \"Accessories\" and price <= 20.50)\n )\n )\n if filter_items:\n basket -= price\n profit += price * 0.4\n price *= 1.4 \n price_list.append(f\"{price:.2f}\")\n \nprint(\" \".join(price_list))\nprint(f\"Profit: {profit:.2f}\")\nif budget + profit >= TICKET_COST:\n print(f\"Hello, France!\")\nelse:\n print(f\"Not enough money.\")","repo_name":"Gibinski/SoftUni-training","sub_path":"Programming Fundamentals with Python/3. Lists Basics/Exercise/09_hello_france.py","file_name":"09_hello_france.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1897860846","text":"from typing import Iterator\n\n\nclass Node:\n def __init__(self, value: str, left=None, right=None):\n self.right: Node = right\n self.left: Node = left\n self.value: str = value\n\n self.parent = None\n\n if left:\n self.left.parent = self\n if right:\n self.right.parent = self\n\n def traverse_preorder_initial(self):\n res = [] # THIS IS BAD\n\n def traverse(current: Node):\n if current is None:\n return\n\n print(f\"Current: {current.value}\")\n res.append(current.value)\n\n if current.left:\n print(f\"Current: {current}; Left to go: {current.left.value}\")\n traverse(current.left)\n if current.right:\n print(f\"Current: {current}; Left to go: {current.right.value}\")\n traverse(current.right)\n\n traverse(self)\n\n for n in res:\n yield n\n\n def traverse_preorder_middle(self):\n\n def traverse(current: Node) -> Iterator[int]:\n if current is None:\n return # this is how we exit generator if needed\n\n print(f\"Current: {current.value}\")\n yield current.value\n\n # if current.left:\n # print(f\"Current: {current}; Left to go: {current.left.value}\")\n for n in traverse(current.left):\n yield n # Work with the left-hand node\n\n # if current.right:\n # print(f\"Current: {current}; Left to go: {current.right.value}\")\n for n in traverse(current.right):\n yield n\n\n for n in traverse(self):\n yield n\n\n def traverse_preorder(self): # Ideal\n\n def traverse(current: Node) -> Iterator[str]:\n if current is None:\n return # this is how we exit generator if needed\n\n print(f\"Current: {current.value}\")\n yield current.value # This actually returns a node\n\n # for left_node in traverse(current.left): # Work with the left-hand node\n # yield left_node # this returns the result that is returned by the iterator\n yield from traverse(current.left)\n\n # for right_node in traverse(current.right): # Work with the right-hand node\n # yield right_node\n yield from traverse(current.right)\n\n # for n in traverse(self):\n # yield n.value\n yield from traverse(self)\n\n def traverse_preorder_reduced(self) -> Iterator[str]:\n print(f\"Current: {self.value}\")\n yield self.value # This actually returns a node\n\n if self.left:\n yield from self.left.traverse_preorder_reduced()\n if self.right:\n yield from self.right.traverse_preorder_reduced()\n\n\nif __name__ == '__main__':\n # F B A D C E G I H\n\n n_b = Node(\n \"B\",\n Node(\"A\"),\n Node(\"D\",\n Node(\"C\"),\n Node(\"E\"))\n )\n n_g = Node(\"G\",\n None,\n Node(\"I\", Node(\"H\"), None)\n )\n\n root = Node(\"F\", n_b, n_g)\n # print([x for x in root.traverse_preorder()])\n # for x in root.traverse_preorder():\n # print(x)\n res = list(root.traverse_preorder())\n print(f\"\\nFinal result My Implementation: {res}\\n\")\n\n res = list(root.traverse_preorder_reduced())\n print(f\"\\nFinal result Exemplar Implementation: {res}\")\n","repo_name":"fif911/desing_patterns","sub_path":"16. Iterator/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73668748005","text":"# ############################################################################# #\n# Naive Bayes Classifier #\n# Glenn Dawson #\n# 2017-10-08 (updated 2019) #\n# ############################################################################# #\n\nimport numpy as np\nimport scipy.stats as spstats\nfrom numpy.random import multivariate_normal as mvnrand\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets as ds\nfrom sklearn.model_selection import KFold\n\n\ndef main():\n tests = ['iris', 'wine', 'cancer', False]\n for test in tests:\n print('------')\n if test:\n uci_test(test)\n else:\n synthetic_test()\n\n\n# ######################## #\n# Naive Bayes Classifier #\n# ######################## #\n\nclass NaiveBayes:\n \"\"\"\n Naive Bayes object. Assumes Gaussian prior.\n\n Parameters\n ----------\n train : array-like, shape = (n_samples, n_features)\n Training data on which to fit the classifier.\n\n labels : array-like, shape = (n_samples)\n Target values.\n\n Attributes\n ----------\n n_classes_ : int\n Number of classes.\n\n n_features_ : int\n Number of features.\n\n mu_ : array, shape = (n_classes_, n_features_)\n Mean of each feature per class.\n\n sigma_ : array, shape = (n_classes_, n_features_)\n Standard deviation of each feature per class.\n\n prior_ : array, shape = (n_classes_)\n Prior probability of each class.\n \"\"\"\n def __init__(self, train, labels):\n train = np.array(train)\n labels = np.array(labels)\n\n # Extract number of classes, instances, and features in training data\n self.n_classes_ = len(np.unique(labels))\n self.n_features_ = train.shape[1]\n\n # Compute mu, sigma, and prior probabilities for each class\n self.mu_ = np.zeros((self.n_classes_, self.n_features_))\n self.sigma_ = np.zeros((self.n_classes_, self.n_features_))\n self.prior_ = np.zeros(self.n_classes_)\n\n for i in range(self.n_classes_):\n train_class = train[np.nonzero(labels == i)[0]]\n self.mu_[i, :] = np.mean(train_class, axis=0)\n self.sigma_[i, :] = np.std(train_class, axis=0)\n self.prior_[i] = len(train_class) / train.shape[0]\n\n def predict(self, data):\n \"\"\"Make classification predictions on testing data.\n\n Parameters\n ----------\n data : array-like, shape = (n_samples, n_features)\n Array of data to classify.\n\n Returns\n -------\n classifications : array, shape = (n_samples)\n Classification predictions for testing data.\n \"\"\"\n data = np.array(data)\n classifications = []\n\n # For each instance...\n for i in range(len(data)):\n # ...compute class-conditional likelihoods...\n cc_likelihood = spstats.norm.pdf(data[i, :], self.mu_, self.sigma_)\n\n # ...and posterior probabilities...\n posterior = self.prior_ * np.prod(cc_likelihood, axis=1)\n\n # ...and make classification decision.\n classifications.append(np.argmax(posterior))\n\n return np.array(classifications)\n\n\n##################\n# Test scripts #\n##################\n\ndef run_naive_bayes(x_train, x_test, y_train, y_test):\n \"\"\"Train a Naive Bayes classifier and evaluate on test data.\n\n Parameters\n ----------\n x_train : array-like, shape = (n_samples, n_features)\n Training data.\n\n x_test : array-like, shape = (n_samples, n_features)\n Testing data.\n\n y_train : array-like, shape = (n_samples)\n Training targets.\n\n y_test : arraylike, shape = (n_samples)\n Testing targets.\n\n Returns\n -------\n correct : int\n Number of correctly classified test samples.\n\n n_test : int\n Number of samples in the testing dataset.\n \"\"\"\n # Train Naive Bayes classifier\n nb = NaiveBayes(x_train, y_train)\n\n # Classification of test data\n pred = nb.predict(x_test)\n\n # Evaluation of results\n evaluation = np.logical_and(y_test.T, pred)\n correct = np.count_nonzero(evaluation)\n\n return correct, len(x_test)\n\n\ndef synthetic_test():\n n_samples = 1000\n mu1 = [2, 1]\n mu2 = [3, 3]\n mu3 = [1, 3]\n sigma1 = [[0.1, 0],[0, 0.1]]\n sigma2 = [[0.1, 0],[0, 0.1]]\n sigma3 = [[0.1, 0],[0, 0.1]]\n q1 = mvnrand(mu1, sigma1, n_samples)\n q2 = mvnrand(mu2, sigma2, n_samples)\n q3 = mvnrand(mu3, sigma3, n_samples)\n data = np.vstack((q1, q2, q3))\n labels = np.vstack((np.zeros((n_samples, 1)),\n np.ones((n_samples, 1)),\n np.full((n_samples, 1), 2)))\n\n nb = NaiveBayes(data, labels)\n\n plt.subplot(121)\n plt.plot(q1[:, 0], q1[:, 1], 'b.')\n plt.plot(q2[:, 0], q2[:, 1], 'r.')\n plt.plot(q3[:, 0], q3[:, 1], 'g.')\n plt.title('Plot of randomly generated training data')\n plt.grid()\n plt.xlim(-.25, 4.25)\n plt.ylim(-.25, 4.25)\n\n # Classification test\n mu_test = [2, 2]\n sigma_test = [[1, 0], [0, 1]]\n q_test = mvnrand(mu_test, sigma_test, n_samples)\n pred = nb.predict(q_test)\n\n # Plotting data\n plt.subplot(122)\n plt.plot(q_test[pred == 0, 0], q_test[pred == 0, 1], 'b.')\n plt.plot(q_test[pred == 1, 0], q_test[pred == 1, 1], 'r.')\n plt.plot(q_test[pred == 2, 0], q_test[pred == 2, 1], 'g.')\n plt.title('Naive Bayes classification of testing data')\n plt.grid()\n plt.xlim(-.25, 4.25)\n plt.ylim(-.25, 4.25)\n\n plt.show()\n\n\ndef uci_test(uci_data):\n data, target = load_data(uci_data)\n\n kf = KFold(n_splits=10, shuffle=True)\n results = []\n totals = []\n fold = 1\n for train_idx, test_idx in kf.split(data):\n x_train = data[train_idx]\n x_test = data[test_idx]\n y_train = target[train_idx]\n y_test = target[test_idx]\n\n result, total = run_naive_bayes(x_train, x_test, y_train, y_test)\n percentage = 100 * result / total\n\n # Print results\n print('Fold {0} accuracy is {1:.8f} percent.'.format(fold, percentage))\n\n results.append(result)\n totals.append(total)\n fold += 1\n\n result = sum(results)\n total = sum(totals)\n\n print('Overall 10-fold accuracy on', uci_data, 'dataset is {:.8f} '\n 'percent'.format(100 * result / total))\n\n\ndef load_data(data):\n if data == 'iris':\n # Load Fisher iris data\n print('Loading Fisher iris data...')\n data, targets = ds.load_iris(return_X_y=True)\n elif data == 'wine':\n # Load wine data\n print('Loading UCI wine dataset...')\n data, targets = ds.load_wine(return_X_y=True)\n elif data == 'cancer':\n # Load breast cancer Wisconsin (diagnostic) data\n print('Loading UCI breast cancer Wisconsin dataset...')\n data, targets = ds.load_breast_cancer(return_X_y=True)\n\n return data, targets\n\nif __name__ == '__main__':\n main()\n","repo_name":"trebledawson/Machine-Learning-Examples","sub_path":"Python/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17663614594","text":"import os\nfrom collections import Counter, defaultdict\nfrom copy import copy, deepcopy\nfrom numbers import Integral\nfrom itertools import chain\nfrom typing import Union, Optional, List, Tuple, Dict\nfrom warnings import warn\n\nimport nltk\nimport numpy as np\nfrom Orange.data import (\n Variable,\n ContinuousVariable,\n DiscreteVariable,\n Domain,\n RowInstance,\n Table,\n StringVariable,\n)\nfrom Orange.preprocess.transformation import Identity\nfrom Orange.data.util import get_unique_names\nfrom gensim import corpora\nfrom orangewidget.utils.signals import summarize, PartialSummary\nimport scipy.sparse as sp\n\nfrom orangecontrib.text.language import ISO2LANG\n\n\ndef get_sample_corpora_dir():\n path = os.path.dirname(__file__)\n directory = os.path.join(path, 'datasets')\n return os.path.abspath(directory)\n\n\ndef _check_arrays(*arrays):\n for a in arrays:\n if not (a is None or isinstance(a, np.ndarray) or sp.issparse(a)):\n raise TypeError('Argument {} should be of type np.array, sparse or None.'.format(a))\n\n lengths = set(a.shape[0] for a in arrays if a is not None)\n if len(lengths) > 1:\n raise ValueError('Leading dimension mismatch')\n\n return lengths.pop() if len(lengths) else 0\n\n\nclass Corpus(Table):\n \"\"\"Internal class for storing a corpus.\"\"\"\n NGRAMS_SEPARATOR = \" \"\n\n def __new__(cls, *args, **kwargs):\n if args and isinstance(args[0], Domain) or \"domain\" in kwargs:\n warn(\n \"Signature of Corpus constructor when called with numpy \"\n \"arrays will change in the future to be equal to Corpus.from_numpy. \"\n \"To avoid issues use Corpus.from_numpy instead.\",\n FutureWarning,\n )\n # __init__ had a different signature than from_numpy\n params = [\"domain\", \"X\", \"Y\", \"metas\", \"W\", \"text_features\", \"ids\"]\n kwargs.update({param: arg for param, arg in zip(params, args)})\n\n # in old signature it can happen that X is missing\n n_doc = _check_arrays(\n kwargs.get(\"X\", None), kwargs.get(\"Y\", None), kwargs.get(\"metas\", None)\n )\n if \"X\" not in kwargs:\n kwargs[\"X\"] = np.empty((n_doc, 0))\n\n return cls.from_numpy(**kwargs)\n return super().__new__(cls, *args, **kwargs)\n\n def _setup_corpus(self, text_features: List[Variable] = None) -> None:\n \"\"\"\n Parameters\n ----------\n text_features\n meta attributes that are used for text mining. Infer them if None.\n \"\"\"\n self.text_features = [] # list of text features for mining\n self._tokens = None\n self.ngram_range = (1, 1)\n self._pos_tags = None\n from orangecontrib.text.preprocess import PreprocessorList\n self.__used_preprocessor = PreprocessorList([]) # required for compute values\n self._titles: Optional[np.ndarray] = None\n self._pp_documents = None # preprocessed documents\n\n if text_features is None:\n self._infer_text_features()\n else:\n self.set_text_features(text_features)\n\n self._set_unique_titles()\n if \"language\" not in self.attributes:\n self.attributes[\"language\"] = None\n\n @property\n def used_preprocessor(self):\n return self.__used_preprocessor\n\n @used_preprocessor.setter\n def used_preprocessor(self, pp):\n from orangecontrib.text.preprocess import PreprocessorList, Preprocessor\n\n if isinstance(pp, PreprocessorList):\n self.__used_preprocessor = PreprocessorList(list(pp.preprocessors))\n elif isinstance(pp, Preprocessor):\n self.__used_preprocessor.preprocessors.append(pp)\n else:\n raise NotImplementedError\n\n def _find_identical_feature(self, feature: Variable) -> Optional[Variable]:\n \"\"\"\n Find a renamed feature in the domain which is identical to a feature.\n\n Parameters\n ----------\n feature\n A variable to find an identical variable in the domain.\n\n Returns\n -------\n Variable which is identical to a feature (have different name but has\n Identity(feature) in compute value.\n \"\"\"\n for var in chain(self.domain.variables, self.domain.metas):\n if (\n var == feature\n or isinstance(var.compute_value, Identity)\n and var.compute_value.variable == feature\n ):\n return var\n return None\n\n def set_text_features(self, feats: Optional[List[Variable]]) -> None:\n \"\"\"\n Select which meta-attributes to include when mining text.\n\n Parameters\n ----------\n feats\n List of text features to include. If None infer them.\n \"\"\"\n if feats is not None:\n feats = copy(feats) # copy to not edit passed array inplace\n for i, f in enumerate(feats):\n if f not in chain(self.domain.variables, self.domain.metas):\n # if not exact feature in the domain, it may be renamed\n # find identity - renamed feature\n id_feat = self._find_identical_feature(f)\n if id_feat is not None:\n feats[i] = id_feat\n else:\n raise ValueError('Feature \"{}\" not found.'.format(f))\n if len(set(feats)) != len(feats):\n raise ValueError('Text features must be unique.')\n if feats != self.text_features:\n # when new features are same than before it is not required\n # to invalidate tokens\n self.text_features = feats\n self._tokens = None # invalidate tokens\n else:\n self._infer_text_features()\n\n def set_title_variable(\n self, title_variable: Union[StringVariable, str, None]\n ) -> None:\n \"\"\"\n Set the title attribute. Only one column can be a title attribute.\n\n Parameters\n ----------\n title_variable\n Variable that need to be set as a title variable. If it is None,\n do not set a variable.\n \"\"\"\n for a in self.domain.variables + self.domain.metas:\n a.attributes.pop(\"title\", None)\n\n if title_variable and title_variable in self.domain:\n self.domain[title_variable].attributes[\"title\"] = True\n\n self._set_unique_titles()\n\n def _set_unique_titles(self):\n \"\"\"\n Define self._titles variable as a list of titles (a title for each\n document). It is used to have an unique title for each document. In\n case when the document have the same title as the other document we\n put a number beside.\n \"\"\"\n if self.domain is None:\n return\n attrs = [attr for attr in\n chain(self.domain.variables, self.domain.metas)\n if attr.attributes.get('title', False)]\n\n if attrs:\n self._titles = np.array(self._unique_titles(\n self.documents_from_features(attrs)))\n else:\n self._titles = np.array([\n 'Document {}'.format(i + 1) for i in range(len(self))])\n\n @staticmethod\n def _unique_titles(titles: List[str]) -> List[str]:\n \"\"\"\n Function adds numbers to the non-unique values fo the title.\n\n Parameters\n ----------\n titles\n List of titles - not necessary unique\n\n Returns\n -------\n List with unique titles.\n \"\"\"\n counts = Counter(titles)\n cur_appearances = defaultdict(int)\n new_titles = []\n for t in titles:\n if counts[t] > 1:\n cur_appearances[t] += 1\n t += f\" ({cur_appearances[t]})\"\n new_titles.append(t)\n return new_titles\n\n def _infer_text_features(self):\n \"\"\"\n Infer which text features to use. If nothing was provided\n in the file header, use the first text feature.\n \"\"\"\n include_feats = []\n first = None\n for attr in self.domain.metas:\n if attr.is_string:\n if first is None:\n first = attr\n incl = attr.attributes.get('include', False)\n # variable attributes can be boolean from Orange 3.29\n # they are string in older versions\n # incl == True, since without == string \"False\" would be True\n if incl == \"True\" or incl == True:\n include_feats.append(attr)\n if len(include_feats) == 0 and first:\n include_feats.append(first)\n self.set_text_features(include_feats)\n\n def extend_attributes(\n self, X, feature_names, feature_values=None, compute_values=None,\n var_attrs=None, sparse=False, rename_existing=False\n ):\n \"\"\"\n Append features to corpus. If `feature_values` argument is present,\n features will be Discrete else Continuous.\n\n Args:\n X (numpy.ndarray or scipy.sparse.csr_matrix): Features values to append\n feature_names (list): List of string containing feature names\n feature_values (list): A list of possible values for Discrete features.\n compute_values (list): Compute values for corresponding features.\n var_attrs (dict): Additional attributes appended to variable.attributes.\n sparse (bool): Whether the features should be marked as sparse.\n rename_existing (bool): When true and names are not unique rename\n exiting features; if false rename new features\n \"\"\"\n def _rename_features(additional_names: List) -> Tuple[List, List, List]:\n cur_attr = list(self.domain.attributes)\n cur_class = self.domain.class_var\n cur_meta = list(self.domain.metas)\n if rename_existing:\n current_vars = (\n cur_attr + (\n [cur_class] if cur_class else []) + cur_meta\n )\n current_names = [a.name for a in current_vars]\n new_names = get_unique_names(\n additional_names, current_names, equal_numbers=False\n )\n renamed_vars = [\n var.renamed(n) for var, n in zip(current_vars, new_names)\n ]\n cur_attr = renamed_vars[:len(cur_attr)]\n cur_class = renamed_vars[len(cur_attr)] if cur_class else None\n cur_meta = renamed_vars[-len(cur_meta):]\n return cur_attr, cur_class, cur_meta\n\n if sp.issparse(self.X) or sp.issparse(X):\n X = sp.hstack((self.X, X)).tocsr()\n else:\n X = np.hstack((self.X, X))\n\n if compute_values is None:\n compute_values = [None] * X.shape[1]\n if feature_values is None:\n feature_values = [None] * X.shape[1]\n\n # rename existing variables if required\n curr_attributes, curr_class_var, curr_metas = _rename_features(feature_names)\n if not rename_existing:\n # rename new feature names if required\n feature_names = get_unique_names(\n self.domain, feature_names, equal_numbers=False\n )\n\n additional_attributes = []\n for f, values, cv in zip(feature_names, feature_values, compute_values):\n if values is not None:\n var = DiscreteVariable(f, values=values, compute_value=cv)\n else:\n var = ContinuousVariable(f, compute_value=cv)\n var.sparse = sparse # don't pass this to constructor so this works with Orange < 3.8.0\n if isinstance(var_attrs, dict):\n var.attributes.update(var_attrs)\n additional_attributes.append(var)\n\n new_domain = Domain(\n attributes=curr_attributes + additional_attributes,\n class_vars=curr_class_var,\n metas=curr_metas\n )\n c = Corpus.from_numpy(\n new_domain,\n X,\n self.Y.copy(),\n self.metas.copy(),\n self.W.copy(),\n text_features=copy(self.text_features),\n )\n c.name = self.name # keep corpus's name\n Corpus.retain_preprocessing(self, c)\n return c\n\n @property\n def documents(self):\n \"\"\" Returns a list of strings representing documents — created\n by joining selected text features. \"\"\"\n return self.documents_from_features(self.text_features)\n\n @property\n def pp_documents(self):\n \"\"\" Preprocessed documents (transformed). \"\"\"\n return self._pp_documents or self.documents\n\n @pp_documents.setter\n def pp_documents(self, documents):\n self._pp_documents = documents\n\n @property\n def titles(self):\n \"\"\" Returns a list of titles. \"\"\"\n assert self._titles is not None\n return self._titles\n\n @property\n def language(self):\n return self.attributes[\"language\"]\n\n def __setstate__(self, state: Dict):\n super().__setstate__(state)\n if \"language\" not in self.attributes:\n self.attributes[\"language\"] = None\n\n def documents_from_features(self, feats):\n \"\"\"\n Args:\n feats (list): A list fo features to join.\n\n Returns: a list of strings constructed by joining feats.\n \"\"\"\n # create a Table where feats are in metas\n data = Table.from_table(Domain([], [], [i.name for i in feats],\n source=self.domain), self)\n\n # When we use only features coming from sparse X data.metas is sparse.\n # Transform it to dense.\n if sp.issparse(data.metas):\n data.metas = data.metas.toarray()\n\n return [' '.join(f.str_val(val) for f, val in zip(data.domain.metas, row))\n for row in data.metas]\n\n def store_tokens(self, tokens, dictionary=None):\n \"\"\"\n Args:\n tokens (list): List of lists containing tokens.\n \"\"\"\n if dictionary is not None:\n warn(\n \"dictionary argument is deprecated and doesn't have effect.\"\n \"It will be removed in future orange3-text 1.15.\",\n FutureWarning,\n )\n self._tokens = np.array(tokens, dtype=object)\n\n @property\n def tokens(self):\n \"\"\"\n np.ndarray: A list of lists containing tokens. If tokens are not yet\n present, run default preprocessor and return tokens.\n \"\"\"\n if self._tokens is None:\n return self._base_tokens()\n return self._tokens\n\n def has_tokens(self):\n \"\"\" Return whether corpus is preprocessed or not. \"\"\"\n return self._tokens is not None\n\n def _base_tokens(self):\n from orangecontrib.text.preprocess import BASE_TRANSFORMER, \\\n BASE_TOKENIZER, PreprocessorList\n\n # don't use anything that requires NLTK data to assure async download\n base_preprocessors = PreprocessorList([BASE_TRANSFORMER, BASE_TOKENIZER])\n corpus = base_preprocessors(self)\n return corpus.tokens\n\n @property\n def dictionary(self):\n warn(\n \"dictionary is deprecated and will be removed in Orange3-text 1.15\",\n FutureWarning,\n )\n return corpora.Dictionary(self.tokens)\n\n @property\n def pos_tags(self):\n \"\"\"\n np.ndarray: A list of lists containing POS tags. If there are no\n POS tags available, return None.\n \"\"\"\n if self._pos_tags is None:\n return None\n return np.array(self._pos_tags, dtype=object)\n\n @pos_tags.setter\n def pos_tags(self, pos_tags):\n self._pos_tags = pos_tags\n\n def ngrams_iterator(self, join_with=NGRAMS_SEPARATOR, include_postags=False):\n if self.pos_tags is None:\n include_postags = False\n\n if include_postags:\n data = zip(self.tokens, self.pos_tags)\n else:\n data = self.tokens\n\n if join_with is None:\n processor = lambda doc, n: nltk.ngrams(doc, n)\n elif include_postags:\n processor = lambda doc, n: (join_with.join(token + '_' + tag for token, tag in ngram)\n for ngram in nltk.ngrams(zip(*doc), n))\n else:\n processor = lambda doc, n: (join_with.join(ngram) for ngram in nltk.ngrams(doc, n))\n\n return (list(chain(*(processor(doc, n)\n for n in range(self.ngram_range[0], self.ngram_range[1]+1))))\n for doc in data)\n\n def count_tokens(self) -> int:\n \"\"\"Count number of all (non-unique) tokens in the corpus\"\"\"\n return sum(map(len, self.tokens))\n\n def count_unique_tokens(self) -> int:\n \"\"\"Count number of all (unique) tokens in the corpus\"\"\"\n # it seems to be fast enough even datasets very large dataset, so I\n # would avoid caching to prevetnt potential problems connected to that\n return len({tk for lst in self.tokens for tk in lst})\n\n @property\n def ngrams(self):\n \"\"\"generator: Ngram representations of documents.\"\"\"\n return self.ngrams_iterator(join_with=self.NGRAMS_SEPARATOR)\n\n def copy(self):\n \"\"\"Return a copy of the table.\"\"\"\n c = super().copy()\n c._setup_corpus(text_features=copy(self.text_features))\n # since tokens are considered immutable copies are not needed\n c._tokens = self._tokens\n c.ngram_range = self.ngram_range\n c.pos_tags = self.pos_tags\n c.name = self.name\n c.used_preprocessor = self.used_preprocessor\n c._titles = self._titles\n c._pp_documents = self._pp_documents\n return c\n\n @staticmethod\n def from_documents(documents, name, attributes=None, class_vars=None, metas=None,\n title_indices=None, language=None):\n \"\"\"\n Create corpus from documents.\n\n Args:\n documents (list): List of documents.\n name (str): Name of the corpus\n attributes (list): List of tuples (Variable, getter) for attributes.\n class_vars (list): List of tuples (Variable, getter) for class vars.\n metas (list): List of tuples (Variable, getter) for metas.\n title_indices (list): List of indices into domain corresponding to features which will\n be used as titles.\n language (str): Resulting corpus's language\n\n Returns:\n Corpus.\n \"\"\"\n attributes = attributes or []\n class_vars = class_vars or []\n metas = metas or []\n title_indices = title_indices or []\n\n domain = Domain(attributes=[attr for attr, _ in attributes],\n class_vars=[attr for attr, _ in class_vars],\n metas=[attr for attr, _ in metas])\n\n for ind in title_indices:\n domain[ind].attributes['title'] = True\n\n def to_val(attr, val):\n if isinstance(attr, DiscreteVariable):\n attr.val_from_str_add(val)\n return attr.to_val(val)\n\n if documents:\n X = np.array([[to_val(attr, func(doc)) for attr, func in attributes]\n for doc in documents], dtype=np.float64)\n Y = np.array([[to_val(attr, func(doc)) for attr, func in class_vars]\n for doc in documents], dtype=np.float64)\n metas = np.array([[to_val(attr, func(doc)) for attr, func in metas]\n for doc in documents], dtype=object)\n else: # assure shapes match the number of columns\n X = np.empty((0, len(attributes)))\n Y = np.empty((0, len(class_vars)))\n metas = np.empty((0, len(metas)))\n\n corpus = Corpus.from_numpy(\n domain=domain, X=X, Y=Y, metas=metas, text_features=[]\n )\n corpus.name = name\n corpus.attributes[\"language\"] = language\n return corpus\n\n def __getitem__(self, key):\n c = super().__getitem__(key)\n if isinstance(c, (Corpus, RowInstance)):\n Corpus.retain_preprocessing(self, c, key)\n return c\n\n @classmethod\n def from_table(cls, domain, source, row_indices=...):\n c = super().from_table(domain, source, row_indices)\n c._setup_corpus()\n Corpus.retain_preprocessing(source, c, row_indices)\n # temp fix: remove when oldest Orange >= 3.34\n c.attributes = deepcopy(c.attributes)\n return c\n\n @classmethod\n def from_numpy(\n cls,\n domain,\n X,\n Y=None,\n metas=None,\n W=None,\n attributes=None,\n ids=None,\n text_features=None,\n language=None\n ):\n t = super().from_numpy(\n domain, X, Y=Y, metas=metas, W=W, attributes=attributes, ids=ids\n )\n # t is corpus but corpus specific attributes were not set yet\n t._setup_corpus(text_features=text_features)\n # language can be already set in attributes if they provided\n if language is not None or \"language\" not in t.attributes:\n t.attributes[\"language\"] = language\n return t\n\n @classmethod\n def from_list(cls, domain, rows, weights=None, language=None):\n t = super().from_list(domain, rows, weights)\n # t is corpus but corpus specific attributes were not set yet\n t._setup_corpus()\n t.attributes[\"language\"] = language\n return t\n\n @classmethod\n def from_table_rows(cls, source, row_indices):\n c = super().from_table_rows(source, row_indices)\n # t is corpus but corpus specific attributes were not set yet\n c._setup_corpus()\n if hasattr(source, \"_titles\"):\n # covering case when from_table_rows called by from_table\n c._titles = source._titles[row_indices]\n # temp fix: remove when oldest Orange >= 3.34\n c.attributes = deepcopy(c.attributes)\n return c\n\n @classmethod\n def from_file(cls, filename, sheet=None):\n if not os.path.exists(filename): # check the default location\n abs_path = os.path.join(get_sample_corpora_dir(), filename)\n if not abs_path.endswith('.tab'):\n abs_path += '.tab'\n if os.path.exists(abs_path):\n filename = abs_path\n\n table = super().from_file(filename, sheet=sheet)\n if not isinstance(table, Corpus):\n # when loading regular file result of super().from_file is Table - need\n # to be transformed to Corpus, when loading pickle it is Corpus already\n name = table.name\n table = cls.from_numpy(table.domain, table.X, table.Y, table.metas, table.W, attributes=table.attributes)\n table.name = name\n return table\n\n @staticmethod\n def retain_preprocessing(orig, new, key=...):\n \"\"\" Set preprocessing of 'new' object to match the 'orig' object. \"\"\"\n if isinstance(orig, Corpus):\n if isinstance(key, tuple): # get row selection\n key = key[0]\n\n if orig._tokens is not None: # retain preprocessing\n if isinstance(key, Integral):\n new._tokens = np.array([orig._tokens[key]])\n new.pos_tags = None if orig.pos_tags is None else np.array(\n [orig.pos_tags[key]])\n elif isinstance(key, list) or isinstance(key, np.ndarray) \\\n or isinstance(key, slice) or isinstance(key, range):\n new._tokens = orig._tokens[key]\n new.pos_tags = None if orig.pos_tags is None else orig.pos_tags[key]\n elif key is Ellipsis:\n new._tokens = orig._tokens\n new.pos_tags = orig.pos_tags\n else:\n raise TypeError('Indexing by type {} not supported.'.format(type(key)))\n\n if isinstance(new, Corpus):\n # _find_identical_feature returns non when feature not found\n # filter this Nones from list\n new.text_features = list(filter(None, [\n new._find_identical_feature(tf)\n for tf in orig.text_features\n ]))\n else:\n new.text_features = [\n tf\n for tf in orig.text_features\n if tf in set(new.domain.metas)\n ]\n\n new._titles = orig._titles[key]\n new.ngram_range = orig.ngram_range\n new.attributes = orig.attributes\n new.used_preprocessor = orig.used_preprocessor\n else: # orig is not Corpus\n new._set_unique_titles()\n new._infer_text_features()\n\n\n@summarize.register(Corpus)\ndef summarize_corpus(corpus: Corpus) -> PartialSummary:\n \"\"\"\n Provides automated input and output summaries for Corpus\n \"\"\"\n table_summary = summarize.dispatch(Table)(corpus)\n extras = (\n (\n f\"<br/><nobr>Tokens: {corpus.count_tokens()}, \"\n f\"Types: {corpus.count_unique_tokens()}</nobr>\"\n )\n if corpus.has_tokens()\n else \"<br/><nobr>Corpus is not preprocessed</nobr>\"\n )\n language = ISO2LANG[corpus.language] if corpus.language else \"not set\"\n extras += f\"<br/><nobr>Language: {language}</nobr>\"\n return PartialSummary(table_summary.summary, table_summary.details + extras)\n","repo_name":"biolab/orange3-text","sub_path":"orangecontrib/text/corpus.py","file_name":"corpus.py","file_ext":"py","file_size_in_byte":25640,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"52"} +{"seq_id":"70306275685","text":"import sys\nimport os\nimport boto3\nimport mimetypes\n\nfrom .config import *\nfrom awyes import awyes\nfrom pathlib import Path\nfrom botocore.exceptions import ClientError\n\n\ndef init(bucket_name):\n \"\"\"\n Initialize your S3 bucket\n\n :param bucket_name: Name of your aws bucket\n :return: None\n \"\"\"\n write_config_to_file(bucket_name)\n\n awyes_template = (Path(__file__).parent / \"awyes_template.yml\").resolve()\n\n with open(awyes_template, 'r') as file:\n awyes_yaml = file.read().replace('${BUCKET_NAME}', bucket_name)\n\n awyes.Deployment(config=awyes_yaml).deploy()\n\n\ndef upload_file(file_name, object_name):\n \"\"\"\n Upload a file to an S3 bucket\n\n :param file_name: File to upload\n :param bucket: Bucket to upload to\n :param object_name: S3 object name. If not specified then file_name is used\n :return: url, or error\n \"\"\"\n bucket_name = read_config_from_file().strip()\n\n # If S3 object_name was not specified, use file_name\n if not object_name:\n object_name = os.path.basename(file_name)\n\n # Upload the file\n s3_client = boto3.client('s3')\n try:\n content_type, _ = mimetypes.guess_type(file_name)\n\n s3_client.upload_file(file_name, bucket_name, object_name, ExtraArgs={\n 'ContentType': content_type})\n\n location = s3_client.get_bucket_location(Bucket=bucket_name)[\n 'LocationConstraint']\n\n return f\"https://s3-{location}.amazonaws.com/{bucket_name}/{object_name}\"\n except ClientError as e:\n return e\n\n\ndef main():\n _, command, resource_name, *secondary_name = sys.argv\n\n if command.lower() == 'init':\n init(bucket_name=resource_name)\n elif command.lower() == 'upload':\n secondary_name = secondary_name[0] if secondary_name else \"\"\n url = upload_file(file_name=resource_name, object_name=secondary_name)\n print(url)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"bb-labs/pastewin","sub_path":"pastewin/pastewin.py","file_name":"pastewin.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30367879344","text":"from django.core.mail import send_mail\nfrom django.shortcuts import render\nfrom .models import Contact\nfrom .forms import ContactForm\nfrom django.http import HttpResponse\n\n# Create your views here.\ndef sendMail(request):\n context = {}\n if request.method == 'POST':\n form = ContactForm(data=request.POST)\n if form.is_valid():\n email = form.save()\n\n send_mail(\n subject=email.subject,\n message=email.message,\n from_email=email.sender_email,\n recipient_list=['jumashafara0@gmail.com'],\n )\n # return success http response\n return HttpResponse('success')\n else:\n context['form': form]\n else:\n context['form'] = ContactForm()\n return render(request=request,\n template_name='mailer/form.html',\n context=context)\n\n\n","repo_name":"jumashafara/django-mailer","sub_path":"mailer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36338581825","text":"from io import BytesIO\n\nimport pytest\nimport requests\n\nfrom megfile.errors import HttpFileNotFoundError, HttpPermissionError, UnknownError\nfrom megfile.http import http_open, is_http\n\n\ndef test_is_http():\n assert is_http(\"http://www.baidu.com\")\n assert is_http(\"https://www.baidu.com\")\n assert not is_http(\"no-http://www.baidu.com\")\n\n\ndef test_http_open(mocker):\n\n with pytest.raises(ValueError) as error:\n http_open('http://test', 'w')\n\n requests_get_func = mocker.patch('megfile.http.requests.get')\n\n class FakeResponse:\n status_code = 0\n\n @property\n def raw(self):\n return BytesIO(b'test')\n\n def raise_for_status(self):\n if self.status_code // 100 == 2:\n return\n error = requests.exceptions.HTTPError()\n error.response = self\n raise error\n\n class FakeResponse200(FakeResponse):\n status_code = 200\n\n requests_get_func.return_value = FakeResponse200()\n assert http_open('http://test', 'rb').read() == b'test'\n\n class FakeResponse404(FakeResponse):\n status_code = 404\n\n requests_get_func.return_value = FakeResponse404()\n with pytest.raises(HttpFileNotFoundError) as error:\n http_open('http://test', 'rb')\n\n class FakeResponse401(FakeResponse):\n status_code = 401\n\n requests_get_func.return_value = FakeResponse401()\n with pytest.raises(HttpPermissionError) as error:\n http_open('http://test', 'rb')\n\n class FakeResponse502(FakeResponse):\n status_code = 502\n\n requests_get_func.return_value = FakeResponse502()\n with pytest.raises(UnknownError) as error:\n http_open('http://test', 'rb')\n\n def fake_get(*args, **kwargs):\n raise requests.exceptions.ReadTimeout('test')\n\n requests_get_func.side_effect = fake_get\n with pytest.raises(UnknownError) as error:\n http_open('http://test', 'rb')\n\n assert str(\n error.value\n ) == 'Unknown error encountered: \\'http://test\\', error: requests.exceptions.ReadTimeout(\\'test\\')'\n","repo_name":"leavers/megfile","sub_path":"tests/test_http.py","file_name":"test_http.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"27332512852","text":"import cv2 as cv\nfrom segment_anything import SamAutomaticMaskGenerator, sam_model_registry\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n\n\ndef show_anns(anns):\n if len(anns) == 0:\n return\n sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)\n ax = plt.gca()\n ax.set_autoscale_on(False)\n\n img = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4))\n img[:,:,3] = 0\n for ann in sorted_anns:\n m = ann['segmentation']\n color_mask = np.concatenate([np.random.random(3), [0.35]])\n img[m] = color_mask\n ax.imshow(img)\n\n\n# # 10 x image - it works with this\n# image_dir = '/home/franz/Downloads/10x.jpg'\n# img = cv.imread(image_dir)\n# img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n\n# Real organoid image\nimage_dir = '/home/franz/Documents/mep/data/for-creating-OrganoTrack/training-dataset/preliminary-gt-dataset/2.images-with-edited-names-finished-annotating/images/d0r1t3.tiff'\nimg = cv.imread(image_dir, cv.IMREAD_GRAYSCALE) # uint8\nimg = cv.cvtColor(img,cv.COLOR_GRAY2RGB) # makes grayscale image RGB - same values\n\n\n\n# # Very small organoid image\n# image_dir = '/home/franz/Documents/mep/data/for-creating-OrganoTrack/training-dataset/preliminary-gt-dataset/2.images-with-edited-names-finished-annotating/images/small1.png'\n# img = cv.imread(image_dir)\n\n\n# Show original image\ntic = time.process_time()\nplt.figure(figsize=(20,20))\nplt.imshow(img)\nplt.axis('off')\nplt.show()\ntoc = time.process_time() - tic\nprint(toc)\nprint('Original image shown')\n\n\n# '''\n# Generating masks with Model H\n# '''\n#\n# sam_checkpoint_h = \"sam_vit_h_4b8939.pth\"\n# model_type_h = \"vit_h\"\n#\n# print('generating mask - model H')\n# tic_H = time.process_time()\n# sam = sam_model_registry[model_type_h](checkpoint=sam_checkpoint_h)\n# mask_generator = SamAutomaticMaskGenerator(sam)\n# masks_H = mask_generator.generate(img)\n# toc_H = time.process_time() - tic_H\n# print('Time elapsed with model H (s): ', toc_H)\n#\n# # Show segmented image\n# plt.figure(figsize=(20,20))\n# plt.imshow(img)\n# show_anns(masks_H)\n# plt.axis('off')\n# plt.show()\n# print('Model H figure shown')\n\n\n\n\n'''\n Generating masks with Model B\n'''\nsam_checkpoint_b = \"sam_vit_b_01ec64.pth\"\nmodel_type_b = \"vit_b\"\n\nprint('generating mask - model B')\ntic_B = time.process_time()\nsam = sam_model_registry[model_type_b](checkpoint=sam_checkpoint_b)\nmask_generator = SamAutomaticMaskGenerator(sam)\nmasks_B = mask_generator.generate(img)\ntoc_B = time.process_time() - tic_B\nprint('Time elapsed with model B (s): ', toc_B)\n\n# Show segmented image\nplt.figure(figsize=(20,20))\nplt.imshow(img)\nshow_anns(masks_B)\nplt.axis('off')\nplt.show()\nprint('Model B figure shown')\n\nsam_output = [masks_B[x]['segmentation'] for x in range(len(masks_B))]\nsum_sam_output = sum(sam_output)\nm2 = np.zeros(np.max(sum_sam_output) + 1)\nm2[2:] = 1\nbinary_sam_output = m2[sum_sam_output]\ncv.imshow('sam output', binary_sam_output)\ncv.waitKey(0)\n\n\n\n# '''\n# Generating masks with Model L\n# '''\n# sam_checkpoint_l = \"sam_vit_l_0b3195.pth\"\n# model_type_l = \"vit_l\"\n#\n# print('generating mask - model L')\n# tic_L = time.process_time()\n# sam = sam_model_registry[model_type_l](checkpoint=sam_checkpoint_l)\n# mask_generator = SamAutomaticMaskGenerator(sam)\n# masks_L = mask_generator.generate(img)\n# toc_L = time.process_time() - tic_L\n# print('Time elapsed with model L (s): ', toc_L)\n#\n# # Show segmented image\n# plt.figure(figsize=(20,20))\n# plt.imshow(img)\n# show_anns(masks_L)\n# plt.axis('off')\n# plt.show()\n# print('Model L figure shown')\n\n\nprint('debug here')","repo_name":"ErasmusMC-Bioinformatics/OrganoTrack","sub_path":"Building-OrganoTrack-functionalities/Experimenting-with-SAM/generate-masks-for-img.py","file_name":"generate-masks-for-img.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22689726272","text":"import os\r\nimport argparse\r\nimport json\r\nimport re\r\nfrom moviepy.editor import ColorClip, ImageClip, VideoFileClip, TextClip, CompositeVideoClip, clips_array, concatenate_videoclips\r\nfrom moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip\r\nfrom datetime import datetime\r\n\r\nImageMagick_dir = os.getcwd() + \"\\\\portablePython\\\\python310\\\\Tools\\\\ImageMagick\\\\bin\"\r\nprint(\"Image Magick Directory:\", ImageMagick_dir)\r\n\r\n#On windows for some reason it cannot find ImageMagic binary, so we need to tell MoviePy where it is\r\nfrom moviepy.config import change_settings\r\nchange_settings({\"IMAGEMAGICK_BINARY\": ImageMagick_dir + r\"\\\\magick.exe\"})\r\n#change_settings({\"IMAGEMAGICK_BINARY\": r\"C:\\\\Program Files\\\\ImageMagick-7.0.8-Q16\\\\magick.exe\"})\r\n\r\ndef remove_comments(text):\r\n # Remove single-line comments (// ...) from the text\r\n text = re.sub(r'\\/\\/[^\\n]*', '', text)\r\n return text\r\n\t\r\ndef parse_time(time_str):\r\n # Parse time in HH:MM:SS.MMM format and return it in seconds\r\n time_obj = datetime.strptime(time_str, \"%H:%M:%S.%f\")\r\n return time_obj.hour * 3600 + time_obj.minute * 60 + time_obj.second + time_obj.microsecond / 1000000\r\n\r\ndef add_text_to_video(video_path, text_elements, output_path):\r\n txt_clips = []\r\n # Load the video clip\r\n video_clip = VideoFileClip(video_path)\r\n \r\n for element in text_elements:\r\n start_time = parse_time(element[\"start_time\"])\r\n end_time = parse_time(element[\"end_time\"])\r\n text = TextClip(element[\"text\"], fontsize=element[\"font_size\"], color=element[\"color\"])\r\n text = text.set_start(start_time)\r\n text = text.set_duration(end_time - start_time)\r\n text = text.set_position((int(element[\"position_x\"]),int(element[\"position_y\"])))\r\n txt_clips.append(text)\r\n \t\r\n #Save video\r\n final_video = CompositeVideoClip([video_clip] + txt_clips)\r\n final_video.write_videofile(output_path, codec=None)\r\n #final_video.write_videofile(output_path, codec='libx264')\r\n\r\ndef format_duration(duration):\r\n duration = int(duration) # Convert to seconds\r\n hours, mins, secs = duration // 3600, (duration % 3600) // 60, duration % 60\r\n return f\"{hours:02d}:{mins:02d}:{secs:02d}\"\r\n\r\ndef add_title_and_end_screen(video_path, title_of_video, title_of_next_video, subtitle, output_path):\r\n title_duration = parse_time(\"00:00:05.000\")\r\n # Load the video clip\r\n video_clip = VideoFileClip(video_path)\r\n\r\n # Create/get all the text needed to be added to the clips\r\n theme=\"Naslov: \"+title_of_video\r\n duration_txt = \"Trajanje:\"\r\n duration_str = format_duration(video_clip.duration + title_duration * 2)\r\n subtitle=\"Podnaslov: \" + subtitle\r\n lea=\"LAPSy Embedded Academy\"\r\n next_video=\"Naslednji posnetek: \"+title_of_next_video\r\n end_title = \"Hvala za ogled!\"\r\n\r\n #get the custom font (Right now is the font that the university uses)\r\n custom_font=\"fonts/garamond.ttf\"\r\n\r\n # Create a text clip with the title for the beginning of the video\r\n theme_clip=TextClip(theme, fontsize=70, color='black', font=custom_font).set_duration(title_duration).set_position(('center')).set_start(0)\r\n subtitle_clip=TextClip(subtitle, fontsize=35, color='black', font=custom_font).set_duration(title_duration).set_position(('center', video_clip.h/2+50)).set_start(0)\r\n professor_clip=TextClip(duration_txt, fontsize=35, color='black', font=custom_font).set_duration(title_duration).set_position((5, video_clip.size[1]-85)).set_start(0)\r\n duration_clip=TextClip(duration_str, fontsize=35, color='black', font=custom_font).set_duration(title_duration).set_position((10, video_clip.size[1]-50)).set_start(0)\r\n lea_clip=TextClip(lea, fontsize=50, color='white', font=custom_font).set_duration(title_duration).set_position(('center', 30)).set_start(0)\r\n next_video_clip=TextClip(next_video, fontsize=35, color='black', font=custom_font).set_duration(title_duration).set_position(('center', 420)).set_start(0)\r\n\r\n # Create a text clip with the title for the end of the video\r\n end_text_clip = TextClip(end_title, fontsize=70, color='black', font=custom_font).set_duration(title_duration).set_position('center')\r\n\r\n # Create a color clip with black background and white text, with a duration of 5 seconds\r\n color_clip = ColorClip(video_clip.size, color=(255, 255, 255), duration=title_duration)\r\n red_lane = ColorClip((video_clip.size[0], 100), color=(180, 22, 44), duration=title_duration).set_position(('center', 0)).set_start(0)\r\n\r\n # Create an image clip from the provided image file\r\n fri_logo_clip = ImageClip(\"photos/fri_logo.png\", duration=title_duration)\r\n lea_logo_clip= ImageClip(\"photos/lea.png\", duration=title_duration)\r\n # Resize the image to a smaller width, maintaining the original aspect ratio\r\n new_width = 300 # Set the desired width (adjust as needed)\r\n fri_logo_clip = fri_logo_clip.resize(width=new_width)\r\n lea_logo_clip= lea_logo_clip.resize(height=100)\r\n lea_logo_clip = lea_logo_clip.set_position((0,0))\r\n\r\n # Calculate the new height to maintain the aspect ratio\r\n aspect_ratio = fri_logo_clip.size[0] / fri_logo_clip.size[1]\r\n new_height = int(new_width / aspect_ratio)\r\n\r\n # Calculate the x-position for the right bottom corner\r\n image_x = video_clip.size[0] - new_width\r\n image_y = video_clip.size[1] - new_height\r\n fri_logo_clip = fri_logo_clip.set_position((image_x, image_y))\r\n\r\n # Overlay the text clip on the color clip\r\n start_text_overlay_clip = CompositeVideoClip([color_clip, red_lane, professor_clip, duration_clip, theme_clip, subtitle_clip, lea_clip, lea_logo_clip, fri_logo_clip])\r\n end_text_overlay_clip = CompositeVideoClip([color_clip, red_lane, end_text_clip, fri_logo_clip, lea_logo_clip, next_video_clip, lea_clip])\r\n\r\n # Concatenate the video clip with the text clip\r\n final_clip = concatenate_videoclips([start_text_overlay_clip, video_clip, end_text_overlay_clip])\r\n # Save the video\r\n final_clip.write_videofile(output_path, codec='libx264')\r\n\r\n\r\ndef edit_all_videos(folder_path, output_path, config_path):\r\n # Read the JSON configuration file and remove comments\r\n with open(config_path, 'r') as config_file:\r\n config_text = remove_comments(config_file.read())\r\n config = json.loads(config_text)\r\n text_elements = config.get(\"spica\", [])\r\n\r\n #Go through all elements in the config file and edit the videos\r\n for element in text_elements:\r\n #Get the video name and the text elements\r\n video_name = element.get(\"video_name\", \"\")\r\n title_of_video = element.get(\"title_of_video\", \"\")\r\n title_of_next_video = element.get(\"title_of_next_video\", \"\")\r\n subtitle= element.get(\"subtitle\", \"\")\r\n place=element.get(\"place\", \"\")\r\n cut=element.get(\"cut\", \"\")\r\n\r\n #Create the paths to the input and output videos and temp video\r\n video_path = os.path.join(folder_path, f\"{video_name}.mp4\")\r\n output_video_path = os.path.join(output_path, f\"{video_name}_edited.mp4\")\r\n temp_video_path = os.path.join(output_path, f\"{video_name}_temp.mp4\")\r\n\r\n #Check if the video exists and edit it\r\n if os.path.exists(video_path):\r\n print(f\"Editing video: {video_name}\")\r\n if(place==\"None\"):\r\n #add title and end screen\r\n add_title_and_end_screen(video_path, title_of_video, title_of_next_video, subtitle, output_video_path)\r\n else:\r\n # hide all the people in the video\r\n hide_people(video_path, temp_video_path, place, cut)\r\n # make temporaty video with the title screen and end screen\r\n add_title_and_end_screen(temp_video_path, title_of_video, title_of_next_video, subtitle, output_video_path)\r\n\r\n # remove the temporary video\r\n os.remove(temp_video_path)\r\n print(f\"Done editing video: {video_name}\")\r\n else:\r\n print(f\"Video not found: {video_name}\")\r\n\r\n\r\n\r\n\r\ndef hide_people(video_path, output_path, position, start_time):\r\n\r\n video = VideoFileClip(video_path)\r\n k = video.duration\r\n\r\n if start_time != 0:\r\n cut_video = CompositeVideoClip([video.subclip(start_time, k)])\r\n k=cut_video.duration\r\n banner = ImageClip(\"photos/\"+ position + \".jpg\").set_position(position, position).set_duration(k).set_start(0)\r\n final = CompositeVideoClip([cut_video, banner])\r\n final.write_videofile(output_path, codec=\"libx264\")\r\n else:\r\n banner = ImageClip(\"photos/\" + position + \".jpg\").set_position(position, position).set_duration(k).set_start(0)\r\n final = CompositeVideoClip([video, banner])\r\n final.write_videofile(output_path, codec=\"libx264\")\r\n\r\n VideoFileClip(video_path).close()\r\n\r\n\r\ndef main():\r\n\r\n\r\n # edit_all_videos(\"input\", \"output\", \"spica.json\")\r\n\r\n\r\n parser = argparse.ArgumentParser(description='Add text to a video using MoviePy')\r\n parser.add_argument('-c', '--config', required=True, help='Path to the JSON configuration file')\r\n parser.add_argument('-i', '--input', required=True, help='Path to the input video file')\r\n parser.add_argument('-o', '--output', required=True, help='Path to the output video file')\r\n args = parser.parse_args()\r\n\r\n edit_all_videos(args.input, args.output, args.config)\r\n\r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"BodanT/MoviePy-2.0","sub_path":"posnetek.py","file_name":"posnetek.py","file_ext":"py","file_size_in_byte":9418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7927762069","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\ndriver = webdriver.Chrome()\nbase_url = 'https://www.saucedemo.com/'\n\ndef authorization():\n driver.get(base_url)\n driver.maximize_window()\n login_standard_user = \"standard_user\"\n password = \"secret_sauce\"\n user_name = driver.find_element(By.CSS_SELECTOR, \"#user-name\").send_keys(login_standard_user)\n print('Input login')\n password = driver.find_element(By.CSS_SELECTOR, \"#password\").send_keys(password)\n print('Input password')\n button_login = driver.find_element(By.CSS_SELECTOR, \"#login-button\").click()\n print('Click login button')\n\n\"\"\"INFO products\"\"\"\n\ndef get_product_1():\n product_1 = driver.find_element(By.XPATH, \"//a[@id='item_4_title_link']\")\n value_product_1 = product_1.text\n\n price_product_1 = driver.find_element(By.XPATH, \"//div[@class='inventory_item_price']\")\n value_price_product_1 = price_product_1.text.replace('$', '')\n\n select_product_1 = driver.find_element(By.XPATH, \"//button[@id='add-to-cart-sauce-labs-backpack']\")\n select_product_1.click()\n print(f'First product \"{value_product_1}\", price: {value_price_product_1}, was added to basket')\n\ndef get_product_2():\n product_2 = driver.find_element(By.XPATH, \"//*[@id='item_1_title_link']/div\")\n value_product_2 = product_2.text\n\n price_product_2 = driver.find_element(By.XPATH, \"//div[@class='inventory_list']//div[3]//div[@class='inventory_item_description']//div[@class='pricebar']//div[@class='inventory_item_price']\")\n value_price_product_2 = price_product_2.text.replace('$', '')\n\n select_product_2 = driver.find_element(By.XPATH, \"//button[@id='add-to-cart-sauce-labs-bolt-t-shirt']\")\n select_product_2.click()\n print(f'Second product \"{value_product_2}\", price: {value_price_product_2}, was added to basket')\n\ndef get_product_3():\n product_3 = driver.find_element(By.XPATH, \"//*[@id='item_2_title_link']/div\")\n value_product_3 = product_3.text\n\n price_product_3 = driver.find_element(By.XPATH, \"//div[@class='inventory_list']//div[5]//div[@class='inventory_item_description']//div[@class='pricebar']//div[@class='inventory_item_price']\")\n value_price_product_3 = price_product_3.text.replace('$', '')\n\n select_product_3 = driver.find_element(By.XPATH, \"//button[@id='add-to-cart-sauce-labs-onesie']\")\n select_product_3.click()\n print(f'Third product \"{value_product_3}\", price: {value_price_product_3}, was added to basket')\n\n\"\"\"CHECKOUT\"\"\"\ndef checkout():\n cart = driver.find_element(By.XPATH, \"//a[@class='shopping_cart_link']\").click()\n print(\"Enter to basket\")\n checkout = driver.find_element(By.XPATH, \"//button[@id='checkout']\")\n checkout.click()\n print(\"Click checkout\")\n\n\"\"\"User info\"\"\"\n\ndef input_user_info():\n first_name = driver.find_element(By.XPATH, \"//input[@id='first-name']\").send_keys('Ivan')\n print(\"Input first name\")\n last_name = driver.find_element(By.XPATH, \"//input[@id='last-name']\").send_keys('Ivanov')\n print(\"Input last name\")\n zip_code = driver.find_element(By.XPATH, \"//input[@id='postal-code']\").send_keys(197197)\n print(\"Input Zip Code\")\n button_continue = driver.find_element(By.XPATH, \"//input[@id='continue']\").click()\n print(\"Press the button 'continue'\")\n \n\"\"\"check price\"\"\"\n\ndef check_total_price():\n total_price = driver.find_element(By.XPATH, \"//div[@class='summary_info_label summary_total_label']\")\n value_total_price = total_price.text.replace('Total: $', '')\n value_total_price_num = float(value_total_price)\n assert 58.29 == value_total_price_num, \"Wrong total price!\"\n print('Total summary price is good!')\n\n\"\"\"finish process\"\"\"\n\ndef finish_process():\n finish = driver.find_element(By.XPATH, \"//button[@id='finish']\").click()\n back_home = driver.find_element(By.XPATH, \"//button[@id='back-to-products']\").click()\n\n\ndef test_buy_products():\n authorization()\n get_product_1()\n get_product_2()\n get_product_3()\n checkout()\n input_user_info()\n check_total_price()\n finish_process()\n \n \n","repo_name":"MDN78/Skypro_auto_course","sub_path":"check_work/test_saucedemo.py","file_name":"test_saucedemo.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70365102565","text":"from multiprocessing import Process\nfrom subprocess import *\n\nimport time\nimport random\nimport logging\nimport os\n\n\n# -------------------- PROCESS --------------------\nclass Worker(Process):\n def __init__(self, file_path, software_path, task_id, log_path, lock, pipe):\n self.file_paths = file_path if type(file_path) is list else [file_path]\n self.software_path = software_path\n self.task_id = task_id\n self.log_path = log_path\n self.lock = lock\n self.pipe = pipe\n super().__init__()\n\n def run(self):\n # Initiate logger\n logger = logging.getLogger(self.log_path[-8:]) # arbitrary name\n handler = logging.FileHandler(self.log_path)\n formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s ')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.DEBUG)\n logger.info('Logging initialized on:\\n' + '\\n\\t'.join(self.file_paths))\n\n # Prepare for run\n logger.info('Running software: ' + self.software_path)\n self.pipe.send(2)\n time.sleep(random.randint(3, 4))\n\n # Acquire a lock\n while not self.lock.acquire(timeout=20):\n logger.info('Acquiring lock...')\n self.pipe.send(1)\n\n # Run software on logs\n for file in self.file_paths:\n self.pipe.send(3)\n logger.info('Starting run on: %s.' % file)\n time.sleep(random.randint(5, 10))\n logger.info('Log finished.')\n\n # Validate log\n if random.randint(0, 5):\n logger.info('Run successful.')\n self.pipe.send(4)\n else:\n logger.error('Run failed.')\n self.pipe.send(5)\n\n try:\n self.lock.release()\n except ValueError:\n pass\n\n self.pipe.close()\n logger.info('Process finished.')\n return\n","repo_name":"JerryLui/hil","sub_path":"hil/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73185628964","text":"import unittest\n\n\nclass TestParsingdates(unittest.TestCase):\n \"\"\"\n Class containing the test suite for parse_non_english_date_string1()\n\n Tests are programmed as prescribed the pythons unittest's package\n\n \"\"\"\n\n def test_parse_non_english_date_string1(self):\n result = \"2015-05-03\"\n expected = \"2015-05-03\"\n self.assertEqual(expected, result)\n","repo_name":"qcri/DiplomaticPulse","sub_path":"diplomaticpulse/tests/test_parse_non_english_date_string.py","file_name":"test_parse_non_english_date_string.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"27508543936","text":"from odoo import models, fields, _, api\nfrom odoo.exceptions import UserError\n\n\nclass Admission(models.Model):\n _name = \"college.admission\"\n _description = \"College Admission\"\n _rec_name = \"first_name\"\n _inherit = 'mail.thread'\n\n first_name = fields.Char(string=\"First Name\")\n last_name = fields.Char(string=\"Last Name\")\n father = fields.Char(string=\"Father\")\n mother = fields.Char(string=\"Mother\")\n communication_address = fields.Text(string=\"Communication Address\")\n permanent_address = fields.Text(string=\"Permanent Address\")\n same_as_communication = fields.Boolean(string=\"Same as Communication\")\n phone = fields.Integer(string=\"Phone\")\n email = fields.Char(string=\"Email\")\n course_id = fields.Many2one(\"college.courses\", string=\"Course\")\n date_of_application = fields.Date(string=\"Date of Application\")\n academic_year_id = fields.Many2one(\"college.academic\",\n string=\"Academic Year\")\n previous_educational_qualification = fields.Selection(\n string=\"Previous Educational Qualification\",\n selection=[('higher_secondary', 'Higher Secondary'),\n ('ug', 'UG'),\n ('pg', 'PG')]\n )\n education_institute = fields.Char(string=\"Educational Institute\")\n transfer_certificate = fields.Binary(string=\"Transfer Certificate\")\n state = fields.Selection(\n string=\"State\",\n selection=[('draft', 'Draft'),\n ('application', 'Application'),\n ('approved', 'Approved'),\n ('done', 'Done'),\n ('rejected', 'Rejected')\n ],\n default=\"draft\"\n )\n\n admission_no = fields.Char(string='Admission No', required=True,\n readonly=True, default=lambda self: _('New'))\n admission_date = fields.Date(default=lambda self: fields.Date.today())\n student_count = fields.Integer(compute='_compute_count')\n\n @api.constrains(\"transfer_certificate\")\n def validate_tc(self):\n if not self.transfer_certificate:\n raise UserError(\"please upload Tc\")\n\n def button_application(self):\n self.write({'state': \"application\"})\n\n def button_done(self):\n self.write(({'state': 'done',\n 'admission_no': self.env['ir.sequence'].next_by_code(\n 'college.admission') or _('New')}))\n mail_template = self.env.ref('college_erp.done_email_template')\n mail_template.send_mail(self.id, force_send=True)\n self.env['college.students'].create({\n 'admission_no': self.admission_no,\n 'first_name': self.first_name,\n 'last_name': self.last_name,\n 'father': self.father,\n 'mother': self.mother,\n 'communication_address': self.communication_address,\n 'permanent_address': self.permanent_address,\n 'phone': self.phone,\n 'email': self.email,\n 'academic_year_id': self.academic_year_id.id,\n 'course_id': self.course_id.id\n\n })\n\n def button_rejected(self):\n self.state = 'rejected'\n self.write(({'state': 'rejected'}))\n mail_template = self.env.ref('college_erp.reject_template')\n mail_template.send_mail(self.id, force_send=True)\n\n def get_students(self):\n self.ensure_one()\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'Students',\n 'view_mode': 'tree,form',\n 'res_model': 'college.students',\n 'domain': [('admission_no', '=', self.admission_no)],\n 'context': \"{'create': False}\"\n }\n\n def _compute_count(self):\n for record in self:\n record.student_count = self.env['college.students'].search_count(\n [('admission_no', '=', self.admission_no)])\n","repo_name":"Hafeesulali/odoo_college_erp","sub_path":"models/college_admission.py","file_name":"college_admission.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19876855054","text":"print('정수를 입력해 주세요: ', end='')\nn=int(input())\ncount = 1\nsum=0\n\nwhile count <= n:\n if count%2 == 0:\n sum = sum + count\n count = count + 1\n\nprint('1~'+str(n)+'까지 2의 배수의 합: '+str(sum))\n","repo_name":"hamin7/ITE3035_Python","sub_path":"Python/Assignment/assingment4_1.py","file_name":"assingment4_1.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31675402354","text":"from peewee import *\n\nDATABASE = SqliteDatabase('todos.db')\n\n\nclass Todo(Model):\n name = CharField()\n completed = BooleanField(default=False)\n\n class Meta:\n database = DATABASE\n\n\ndef initialize(): # pragma: no cover\n DATABASE.connect(reuse_if_open=True)\n DATABASE.create_tables([Todo], safe=True)\n DATABASE.close()\n","repo_name":"AndrewHawes/techdegree-project-10","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22249513235","text":"# PROGRESS BAR by Alex Tomsovic\n# linktr.ee/alextomsovic\n\n# Libraries \nimport math\nfrom colorama import Fore\n\n# Progress bar function\ndef progressbar(progress, total):\n percentage = 50 * (progress / float(total))\n bar = Fore.LIGHTGREEN_EX + '█' * int(percentage) + Fore.WHITE + '-' * (50 - int(percentage))\n print(f\"\\r |{bar}| {percentage * 2:.2f}%\", end = \"\\r\")\n\n# Getting the list to iterate length\nnums = [x * 2 for x in range(2000, 3000)]\nresults = []\n\n# for loop to enumerate / increase \nprogressbar(0, len(nums))\nfor i, x in enumerate(nums):\n results.append(math.factorial(x))\n progressbar(i + 1, len(nums))\n","repo_name":"alexandertomsovic/progressbar","sub_path":"progressbar.py","file_name":"progressbar.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11869357199","text":"from PIL import ImageDraw\n\nfrom pitop import Camera\n\ncam = Camera()\n\n\ndef draw_red_cross_over_image(im):\n # Use Pillow to draw a red cross over the image\n draw = ImageDraw.Draw(im)\n draw.line((0, 0) + im.size, fill=128, width=5)\n draw.line((0, im.size[1], im.size[0], 0), fill=128, width=5)\n return im\n\n\nim = draw_red_cross_over_image(cam.get_frame())\nim.show()\n","repo_name":"thymjan/pi-top-Python-SDK","sub_path":"examples/camera/camera_image_processing.py","file_name":"camera_image_processing.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"15725370160","text":"def Collatz(n): \n while n != 1: \n print(n, end = ', ') \n\n n = 3 * n + 1 if n & 1 else n // 2\n print(n) \n\n \nnumber = int(input(\"Bitte die Start Zahl angeben: \\n\"))\nCollatz(number) \n","repo_name":"CEOXeon/School-Cheater","sub_path":"Info/Collatz_Problem.py","file_name":"Collatz_Problem.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"14976500969","text":"import gtk, pygtk\nimport gobject\nimport pynotify\n\nfrom Pymodoro import *\n\nclass Gui:\n\n def on_window_destroy(self, widget):\n gtk.main_quit()\n\n def status_clicked(self, widget):\n \"\"\"docstring for status_clicked\"\"\"\n self.window.show_all()\n\n def delete_event(self, window, event):\n \"\"\"docstring for delete_event\"\"\"\n self.window.hide_on_delete()\n\n def show_about_dialog(self):\n \"\"\"docstring for show_about_dialog\"\"\"\n dialog = gtk.MessageDialog(\n parent = None,\n flags = gtk.DIALOG_DESTROY_WITH_PARENT,\n type = gtk.MESSAGE_INFO,\n buttons = gtk.BUTTONS_CLOSE,\n message_format = \"Do you want to close this Status Icon program?\")\n dialog.set_title('Popup Window')\n dialog.connect('response', self.destroyer)\n dialog.show() \n\n def popup(self, button, widget, data=None):\n self.menu = gtk.Menu()\n\n about = gtk.MenuItem()\n about.set_label(\"About\")\n quit = gtk.MenuItem()\n quit.set_label(\"Quit\")\n\n about.connect(\"activate\", self.show_about_dialog)\n quit.connect(\"activate\", gtk.main_quit)\n\n self.menu.append(about)\n self.menu.append(quit)\n\n self.menu.show_all()\n\n def update_labels(self):\n \"\"\"Update labels on the gui\"\"\"\n self.num_pomodoros_label.set_text(str(self.pymodoro.num_pomodoros) + \" pomodoros completed\")\n self.num_big_breaks_label.set_text(str(self.pymodoro.num_big_breaks) + \" extended breaks taken\")\n remaining_time = self.pymodoro.current_clock.time\n minutes = remaining_time / 60\n seconds = remaining_time % 60\n self.time_left_label.set_text(\"%d:%s remaining\" % (minutes, str(seconds).rjust(2,'0'))) \n return True\n\n def notify_expiry(self,message,title):\n \"\"\"docstring for notify_expiry\"\"\"\n n = pynotify.Notification(title, message)\n n.show()\n\n def __init__(self):\n \"\"\"docstring for __init__\"\"\"\n self.pymodoro = Pymodoro(self)\n\n self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n self.window.set_size_request(400,300)\n self.window.set_title(\"Pymodoro\")\n\n self.main_box = gtk.VBox(False, 5)\n self.button_box = gtk.HBox(False, 5)\n self.bottom_box = gtk.HBox(False, 5)\n self.info_box = gtk.VBox(False, 5)\n\n self.start_pomodoro_button = gtk.Button(\"Start a pomodoro...\")\n self.start_pomodoro_button.connect('clicked', self.pymodoro.start_pomodoro)\n\n self.stop_button = gtk.Button(\"Stop and Reset\")\n self.stop_button.connect('clicked', self.pymodoro.stop)\n\n self.time_left_label = gtk.Label(\"0:00 remaining\")\n self.num_pomodoros_label = gtk.Label(\"0 pomodoros completed\")\n self.num_big_breaks_label = gtk.Label(\"0 extended breaks taken\")\n\n self.window.add(self.main_box)\n self.main_box.pack_start(self.button_box)\n self.button_box.pack_start(self.start_pomodoro_button)\n self.button_box.pack_start(self.stop_button)\n self.main_box.pack_start(self.bottom_box)\n self.bottom_box.pack_start(self.time_left_label)\n self.bottom_box.pack_start(self.info_box)\n self.info_box.pack_start(self.num_pomodoros_label)\n self.info_box.pack_start(self.num_big_breaks_label)\n\n self.clock_timer = gobject.timeout_add(1000, self.pymodoro.update_clocks)\n self.gui_timer = gobject.timeout_add(1000, self.update_labels)\n\n pynotify.init(\"Pymodoro\")\n self.status_icon = gtk.status_icon_new_from_stock(gtk.STOCK_GOTO_TOP)\n self.status_icon.connect('activate', self.status_clicked)\n self.status_icon.connect('popup-menu', self.popup)\n self.window.connect('delete-event', self.delete_event)\n # self.window.connect(\"destroy\", self.on_window_destroy)\n self.window.show_all()\n\ndef start():\n \"\"\"Start pymodoro\"\"\"\n gui = Gui()\n gtk.main()\n\nif __name__ == \"__main__\":\n start()\n","repo_name":"davidbeckingsale/pymodoro","sub_path":"pymodoro/Gui.py","file_name":"Gui.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"18289416111","text":"#!/usr/bin/env python3\n\nimport os\nfrom tqdm.auto import tqdm \n\n\ndef getResults(dataset, h, w, noRef = False):\n assert dataset is not None, \"Please provide dataset name\"\n\n if noRef:\n os.system(f\"./run_test.py --gpu_1 1 --gpu_2 1 --calcMetrics \\\n --dataset {dataset} \\\n --filenames_file_eval ./FT_train-test_files/{dataset}/test_files.txt \\\n --genDP_path /data2/aryan/{dataset}/test/ \\\n --filenames_file_folder /data2/aryan/mono-eccv/FT_train-test_files/{dataset}/ \\\n --no_refinement \\\n -th {h} -tw {w} -vh {h} -vw {w}\")\n else:\n os.system(f\"./run_test.py --gpu_1 1 --gpu_2 1 --calcMetrics \\\n --dataset {dataset} \\\n --filenames_file_eval ./FT_train-test_files/{dataset}/test_files.txt \\\n --genDP_path /data2/aryan/{dataset}/test/ \\\n --filenames_file_folder /data2/aryan/mono-eccv/FT_train-test_files/{dataset}/ \\\n -th {h} -tw {w} -vh {h} -vw {w}\")\n\n\ndef dispMethodComparison(dataset, rH = 352, rW = 528, ref=False): \n assert dataset is not None, \"Please provide dataset name\"\n\n rh, rw = rH, rW \n print(f\"Resolution: {rh} x {rw}\")\n\n disp_paths = ['/data2/aryan/unimatch/dp_otherDS/', '/media/data/prasan/datasets/LF_datasets/DPT-depth/']\n\n for dips_path in disp_paths:\n if \"unimatch\" in dips_path:\n print(f\"Using Unimatch Disparities\")\n else:\n print(f\"Using DPT Disparities\")\n\n if ref:\n os.system(f\"./run_test.py --calcMetrics \\\n --gpu_1 1 --gpu_2 1 \\\n --dataset {dataset} \\\n --genDP_path /data2/aryan/{dataset}/test_dp \\\n --filenames_file_eval ./FT_train-test_files/{dataset}/test_files.txt \\\n --filenames_file_folder /data2/aryan/mono-eccv/FT_train-test_files/{dataset}/ \\\n -th {rh} -vh {rh} \\\n -tw {rw} -vw {rw} \\\n --otherDS_disp_path {dips_path}\")\n else:\n os.system(f\"./run_test.py --calcMetrics --no_refinement \\\n --gpu_1 1 --gpu_2 1 \\\n --dataset {dataset} \\\n --genDP_path /data2/aryan/{dataset}/test_dp \\\n --filenames_file_eval ./FT_train-test_files/{dataset}/test_files.txt \\\n --filenames_file_folder /data2/aryan/mono-eccv/FT_train-test_files/{dataset}/ \\\n -th {rh} -vh {rh} \\\n -tw {rw} -vw {rw} \\\n --otherDS_disp_path {dips_path}\")\n\n\ndef calc_DPT_Time(dataset, h, w):\n assert dataset is not None, \"Please provide dataset name\"\n assert h is not None, \"Please provide height\"\n assert w is not None, \"Please provide width\"\n\n os.system(f\"./midas_dummy.py --dataset {dataset} -th {h} -tw {w}\")\n\n\ndef calcTime(dataset, h, w, no_ref=None):\n assert dataset is not None, \"Provide DS\"\n assert no_ref is not None, \"Provide an inference mode\"\n\n if no_ref:\n os.system(f\"./run_test.py --calcMetrics --calcTime --no_refinement \\\n --results net_timing \\\n --gpu_1 3 --gpu_2 3 \\\n --dataset {dataset} \\\n --genDP_path /data2/aryan/{dataset}/test_dp \\\n --filenames_file_eval ./FT_train-test_files/{dataset}/test_files.txt \\\n --filenames_file_folder /data2/aryan/mono-eccv/FT_train-test_files/{dataset}/ \\\n -th {h} -vh {h} \\\n -tw {w} -vw {w} \\\n --otherDS_disp_path /media/data/prasan/datasets/LF_datasets/DPT-depth/\")\n else:\n os.system(f\"./run_test.py --calcMetrics --calcTime \\\n --results net_timing \\\n --gpu_1 3 --gpu_2 3 \\\n --dataset {dataset} \\\n --genDP_path /data2/aryan/{dataset}/test_dp \\\n --filenames_file_eval ./FT_train-test_files/{dataset}/test_files.txt \\\n --filenames_file_folder /data2/aryan/mono-eccv/FT_train-test_files/{dataset}/ \\\n -th {h} -vh {h} \\\n -tw {w} -vw {w} \\\n --otherDS_disp_path /media/data/prasan/datasets/LF_datasets/DPT-depth/\")\n\n\nif __name__ == '__main__':\n datasets = ['Hybrid', 'Stanford', 'Kalantari', 'TAMULF']\n # our: 256x192 | Govindrajan: 176x264 | Li: 192x192 | Srinivasan: 188x270 |\n # Random: 384x528 (to introduce another baseline) | 480p-SD: 480x640\n resH = [256, 176, 192, 384, 480]\n resW = [192, 264, 192, 528, 640]\n noRef = [True, False]\n\n # for noRef_bool in noRef:\n # for dataset in (pbar:=tqdm(datasets)):\n # pbar.set_description(f\"Processing {dataset}\")\n # dispMethodComparison(dataset)\n # # for i in range(len(resH)):\n # # getResults(dataset, resH[i], resW[i], noRef=noRef_bool)\n\n resH2 = [352]\n resW2 = [528]\n\n for dataset in datasets:\n for i in range(len(resH)):\n dispMethodComparison(dataset, resH[i], resW[i], ref=False)\n dispMethodComparison(dataset, resH[i], resW[i], ref=True)\n # print(f\"DPT Timing on {dataset}\")\n # calc_DPT_Time(dataset, resH2[i], resW2[i])\n # print(f\"Network Timing on no_ref {dataset}\")\n # calcTime(dataset, resH2[i], resW2[i], no_ref=True)\n # print(f\"Network Timing (+ Ref) {dataset}\")\n # calcTime(dataset, resH2[i], resW2[i], no_ref=False)","repo_name":"Aryan-Garg/Baseline_Mono-LFVR","sub_path":"resTester.py","file_name":"resTester.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73668387045","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 19 02:00:58 2020\n\"\"\"\n#pip install msvc-runtime\nimport selectivesearch\nimport numpy as np\nimport tensorflow as tf\nfrom PIL import Image\nimport argparse\nfrom xml.etree.ElementTree import ElementTree\n\nimport slidingWindow as sw\nimport augmentation\nimport dataSet as ds\nimport utils\nimport model\nimport solver\nimport blackPercent as bp\nimport os\n\nimport streamlit as st\n\n#################################STREAMLIT APPLICATION\nst.write(\"\"\"\n # 전동킥보드 안전 주차 확인 시스템\n \"\"\")\n\nst.write(\"보행자들의 안전을 위해 갓길에 주차 후 사진을 찍어 올려주시기 바랍니다.\")\n\nfile = st.file_uploader(\"이미지 파일 업로드\", type=[\"jpg\", \"png\"])\n\nif file is None:\n st.write(\"주차된 전동킥보드의 사진을 올려주세요\")\nelse: \n image = Image.open(file)\n img_dir = os.getcwd() + '\\\\' + 'test_image' + '\\\\'+file.name\n # st.write(img_dir)\n image.save(img_dir)\n st.image(image, caption = '주차된 전동킥보드', use_column_width=True)\n # prediction = import_and_predict(image, model)\n\n \t\t\t\t\t\t\t\n\n#################################################\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-training\", \"--training\", type=bool, default=False)\nparser.add_argument(\"-epochs\", \"--epochs\", type=int, default=100)\nargs = parser.parse_args()\n\nprint(\"Phase 0 : Load data\")\ndata = ds.dataSet()\nj = ds.jsonObject('para.json')\nparam = j.para\nprint(param)\n\ntarget_index = []\nfor cl in param['label_dic']:\n if cl in param['target_list']:\n target_index.append(param['label_dic'][cl])\n\ntraining = args.training\n\nif training:\n data_dir = 'image'\nelse:\n data_dir = None\n \ndata.load_data(dir=data_dir, test_dir='test_image')\n\n#data.grayscale()\ndata.augmentation()\n#data.edge()\n\nif training:\n data.sep_train_test()\n_, *model_input_size = data.img_set.shape\n\nsess = tf.Session()\nmodel = model.four_layer_CNN(sess=sess, input_shape=data.img_set.shape, n_class=len(param['label_dic']))\nsv = solver.Solver(sess=sess, name='op', model=model, dataset=data, optimizer=tf.train.AdamOptimizer)\n\nepochs = args.epochs\nbatch_size = param['batch_size']\nlearning_rate = param['lr']\npath = '/home/paperspace/Dropbox/krlee/easy-yolo/devkit/2017/Images'\n\nsess.run(tf.global_variables_initializer())\n\nif not training:\n print(\"Phase 1 : Load model\")\n sv.model_load('braille_segment.h5')\n\nelse:\n print(\"Phase 1 : Train model\")\n sv.train(epoch=epochs, batch_size=batch_size, lr=learning_rate, print_frequency=100)\n sv.model_save('braille_segment.h5')\n\ndef cf(x):\n return sv.predict(x)[0] in target_index\n\ndef score_cf(imag):\n scores = np.array(sv.predict_softmax_score(imag))\n return (np.argmax(scores) in target_index) and (np.max(scores) > param['score_bottom_line'])\n\n\nfor i, img in enumerate(data.test_img):\n print(\"{}th image in progress\".format(i))\n temp_img, matrix = sw.sliding_window(img, score_cf, window_size=param['ss_dic']['window_size'], stride=16, boundary=param['sw_dic']['boundary'])\n check = bp.bpercent(temp_img)\n if check : \n print(i+1,\"번째 사진: \",\"점자블록이 없는 곳으로 이동해주세요\")\n st.markdown('<style>h1{color: red;}</style>', unsafe_allow_html=True)\n st.markdown(\"\"\"\n <style>\n body {\n color:white;\n background-color:red;\n font-size:30;\n }\n </style>\n 점자블록이 없는 곳에 킥보드를 주차해 주세요\n \"\"\", unsafe_allow_html=True)\n os.remove(img_dir)\n else: \n st.write(\"전동 킥보드가 반납되었습니다\")\n os.remove(img_dir)\n temp_img.save('./test_result/sw'+str(i)+'.jpg', 'jpeg')\n img.save('./Images/sw'+str(i)+'.jpg', 'jpeg')\n print()","repo_name":"treblenalto/safe-rider","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37623199488","text":"import urllib.parse\nimport networkx\n\ndef event_url(event):\n '''\n '''\n scheme = event.get('headers', {}).get('X-Forwarded-Proto') or 'http'\n host = event.get('headers', {}).get('Host')\n query = urllib.parse.urlencode(event.get('queryStringParameters') or {})\n \n # only seems true running at *.execute-api.us-east-1.amazonaws.com\n is_raw_gateway = (event['requestContext'].get('path') != event.get('path'))\n \n if is_raw_gateway:\n path = event['requestContext']['path']\n else:\n path = urllib.parse.urlparse(event.get('resource')).path\n \n return urllib.parse.urlunparse((scheme, host, path, None, query, None))\n\ndef combine_digraphs(graph1, graph2):\n '''\n '''\n graph3 = networkx.DiGraph()\n \n for (node_id, _) in graph1.edges.keys():\n graph3.add_node(node_id, **graph1.nodes[node_id])\n \n for (node_id, _) in graph2.edges.keys():\n graph3.add_node(node_id, **graph2.nodes[node_id])\n \n for ((node1_id, node2_id), edge) in graph1.edges.items():\n graph3.add_edge(node1_id, node2_id, **edge)\n \n for ((node1_id, node2_id), edge) in graph2.edges.items():\n graph3.add_edge(node1_id, node2_id, **edge)\n \n return graph3\n","repo_name":"PlanScore/DistrictGraphs","sub_path":"DistrictGraphs/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"24736272886","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: kipp\n@contact: kaidma.kipp@gmail.com\n@site: \n@software: PyCharm\n@file: model_tools.py\n@time: 19-5-31 上午10:48\n# Shallow men believe in luck.\nStrong men believe in cause and effect.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport torch\nimport torchvision\nimport pandas as pd\nfrom collections import OrderedDict\nfrom matplotlib import pyplot as plt\nfrom graphviz import Digraph\nfrom tool.flops import count_ops\n\nclass ModelTools(object):\n def __init__(self, input, model):\n self.model = model\n self.input = input\n\n @staticmethod\n def parameters_total(model):\n total = sum(param.numel() for param in model.parameters())\n return total / 1e6\n\n def print_parameters_total(self):\n total = self.parameters_total(self.model)\n print('Number of params: %.2f M' % (total))\n\n\n @staticmethod\n def model_flops(input_tensor, model):\n estimated = count_ops(model, input_tensor, print_readable=False)\n return estimated / 1e9\n\n def print_model_flops(self):\n flops = self.model_flops(self.input,self.model)\n print('Number of flops: %.2fG' % (flops))\n\n\n #TODO: what fuck\n @staticmethod\n def model_forward(input_tensor, model):\n select_layer = model.layer1[0].conv1\n grads = {}\n\n def save_grad(name):\n def hook(self, input, output):\n grads[name] = input\n return hook\n\n select_layer.register_forward_hook(save_grad('select_layer'))\n input = input_tensor.requires_grad_(True)\n model(input)\n return grads\n\n def print_model_forward(self):\n grads = self.model_forward(self.input, self.model)\n print('model forward: \\n',grads)\n\n\n @classmethod\n def summarize(cls, model, params_switch=True, weights_switch=True):\n \"\"\"\n Summarizes torch model by showing trainable parameters and weights.\n \"\"\"\n from torch.nn.modules.module import _addindent\n tmpstr = model.__class__.__name__ + '(\\n'\n for key, module in model._modules.items():\n if type(module) in [\n torch.nn.modules.container.Container,\n torch.nn.modules.container.Sequential\n ]:\n modstr = cls.summarize(module)\n else:\n modstr = module.__repr__()\n modstr = _addindent(modstr, 2)\n\n tmpstr += ' ('+key + '): ' + modstr\n if params_switch:\n params = sum([np.prod(p.size()) for p in module.parameters()])\n tmpstr += ', parameters={}'.format(params)\n if weights_switch:\n weights = tuple([tuple(p.size()) for p in module.parameters()])\n tmpstr += ', weights={}'.format(weights)\n tmpstr += '\\n'\n\n tmpstr = tmpstr + ')'\n return tmpstr\n\n def print_summarize(self, params_switch=True, weights_switch=True):\n tmpstr = self.summarize(self.model, params_switch, weights_switch)\n print(tmpstr)\n\n @staticmethod\n def __get_names_dict(model):\n \"\"\"Recursive walk to get names including path\"\"\"\n names = {}\n def _get_names(module, parent_name=''):\n for key, module in module.named_children():\n name = parent_name + '.' + key if parent_name else key\n names[name] = module\n if isinstance(module, torch.nn.Module):\n _get_names(module, parent_name=name)\n _get_names(model)\n return names\n\n\n @classmethod\n def keras_summarize_like(cls,input_tensor, model, weights=False, input_shape=True, trainable=False):\n \"\"\"\n Summarizes torch model by showing trainable parameters and weights.\n\n author: wassname\n url: https://gist.github.com/wassname/0fb8f95e4272e6bdd27bd7df386716b7\n license: MIT\n\n Modified from:\n - https://github.com/pytorch/pytorch/issues/2001#issuecomment-313735757\n - https://gist.github.com/wassname/0fb8f95e4272e6bdd27bd7df386716b7/\n\n Usage:\n import torchvision.models as models\n model = models.alexnet()\n df = torch_summarize_df(input_size=(3, 224,224), model=model)\n print(df)\n\n # name class_name input_shape output_shape nb_params\n # 1 features=>0 Conv2d (-1, 3, 224, 224) (-1, 64, 55, 55) 23296#(3*11*11+1)*64\n # 2 features=>1 ReLU (-1, 64, 55, 55) (-1, 64, 55, 55) 0\n # ...\n \"\"\"\n names = cls.__get_names_dict(model)\n summary = OrderedDict()\n hooks = []\n\n def register_hook(module):\n def hook(module, input, output):\n name = ''\n for key, item in names.items():\n if item == module:\n name = key\n class_name = str(module.__class__).split('.')[-1].split(\"'\")[0]\n module_idx = len(summary)\n\n m_key = module_idx +1\n summary[m_key] = OrderedDict()\n summary[m_key]['name'] = name\n summary[m_key]['class_name'] = class_name\n\n if input_shape:\n summary[m_key]['input_shape']=(-1, )+tuple(input[0].size())[1:]\n summary[m_key]['output_shape']=(-1,)+tuple(output.size())[1:]\n if weights:\n summary[m_key]['weights']=list(\n [tuple(p.size()) for p in module.parameters()])\n\n if trainable:\n params_trainable = sum(\n [torch.LongTensor(list(p.size())).prod()\n for p in module.parameters() if p.requires_grad])\n summary[m_key]['nb_trainable'] = params_trainable\n\n params = sum([torch.LongTensor(list(p.size())).prod()\n for p in module.parameters()])\n summary[m_key]['nb_params'] = params\n\n if not isinstance(module, torch.nn.Sequential) and \\\n not isinstance(module, torch.nn.ModuleList) and \\\n not (module == model):\n hooks.append(module.register_forward_hook(hook))\n\n input_tensor.requires_grad_(True)\n\n if next(model.parameters()).is_cuda:\n input_tensor.to('cuda')\n\n model.apply(register_hook)\n model(input_tensor)\n\n for h in hooks:\n h.remove()\n\n df_summary = pd.DataFrame.from_dict(summary, orient='index')\n\n return df_summary\n\n def print_keras_summary_like(self,\n weights=True, input_shape=True, trainable=True):\n dataFrame = self.keras_summarize_like(self.input,self.model,weights, input_shape, trainable)\n pd.set_option('display.max_columns', None)\n pd.set_option('display.width', 800)\n pd.set_option('display.max_rows', None)\n print(dataFrame)\n\n @staticmethod\n def visualization_weights(weights, ch=0, file_name=None, all_kernels=False, nrow=8, padding=2):\n \"\"\"\n :param weight:\n :param ch: channel for visualization\n :param file_name: if it is None, don't save the weight\n :param all_kernels: all kernels for visualization\n :param nrow:\n :param padding:\n :return:\n \"\"\"\n from torchvision import utils\n\n n,c,h,w = weights.shape\n if all_kernels:\n weights = weights.view(n*c, -1, w, h)\n elif c!=3:\n weights = weights[:, ch, :, :].unsqueeze(dim=1)\n\n grad = utils.make_grid(weights, nrow=nrow,padding=padding,normalize=True)\n if file_name:\n utils.save_image(weights,file_name, nrow=nrow, normalize=True, padding=padding)\n plt.imshow(grad.numpy().transpose((1,2,0)))#CHW to HWC\n\n @classmethod\n def run_visualization_weights(cls):\n model = torchvision.models.resnet18(pretrained=True)\n mm = model.double()\n body_model = [i for i in mm.children()]\n layer1 = body_model[0]\n tensor = layer1.weight.data.clone()\n cls.visualization_weights(tensor, file_name='weight.png')\n\n\n @staticmethod\n def make_dot(var, params=None):\n \"\"\" Produces Graphviz representation of PyTorch autograd graph.\n\n Blue nodes are the Variables that require grad, orange are Tensors\n saved for backward in torch.autograd.Function\n\n Args:\n var: output Variable\n params: dict of (name, Variable) to add names to node that\n require grad (TODO: make optional)\n \"\"\"\n if params is not None:\n assert all(torch.is_tensor(p) for p in params.values())\n param_map = {id(v): k for k, v in params.items()}\n node_attr = dict(style='filled',\n shape='box',\n align='left',\n fontsize='12',\n ranksep='0.1',\n height='0.2')\n dot = Digraph(node_attr=node_attr, graph_attr=dict(size=\"12,12\"))\n seen = set()\n\n def size_to_str(size):\n return '(' + (', ').join(['%d' % v for v in size]) + ')'\n\n output_nodes = (var.grad_fn,) if not isinstance(var, tuple) else tuple(v.grad_fn for v in var)\n\n def add_nodes(var):\n if var not in seen:\n if torch.is_tensor(var):\n # note: this used to show .saved_tensors in pytorch0.2, but stopped\n # working as it was moved to ATen and Variable-Tensor merged\n dot.node(str(id(var)), size_to_str(var.size()), fillcolor='orange')\n elif hasattr(var, 'variable'):\n u = var.variable\n node_name = '%s\\n %s' % (param_map.get(id(u.data)), size_to_str(u.size()))\n dot.node(str(id(var)), node_name, fillcolor='lightblue')\n elif var in output_nodes:\n dot.node(str(id(var)), str(type(var).__name__), fillcolor='darkolivegreen1')\n else:\n dot.node(str(id(var)), str(type(var).__name__))\n seen.add(var)\n if hasattr(var, 'next_functions'):\n for u in var.next_functions:\n if u[0] is not None:\n dot.edge(str(id(u[0])), str(id(var)))\n add_nodes(u[0])\n if hasattr(var, 'saved_tensors'):\n for t in var.saved_tensors:\n dot.edge(str(id(t)), str(id(var)))\n add_nodes(t)\n\n # handle multiple outputs\n if isinstance(var, tuple):\n for v in var:\n add_nodes(v.grad_fn)\n else:\n add_nodes(var.grad_fn)\n\n def resize_graph(dot, size_per_element=0.15, min_size=12):\n \"\"\"Resize the graph according to how much content it contains.\n\n Modify the graph in place.\n \"\"\"\n # Get the approximate number of nodes and edges\n num_rows = len(dot.body)\n content_size = num_rows * size_per_element\n size = max(min_size, content_size)\n size_str = str(size) + \",\" + str(size)\n dot.graph_attr.update(size=size_str)\n\n resize_graph(dot)\n\n return dot\n\n @classmethod\n def visualization_compute_graph_deprecated(cls):\n torch.manual_seed(1)\n input = torch.randn(1,3,224,224,requires_grad=True)\n model = torchvision.models.resnet18(pretrained=False)\n y = model(input)\n g = cls.make_dot(y, params=model.state_dict())\n g.render('resnet18_compute_graph/resnet18', format='png')\n\n @staticmethod\n def visualization_compute_graph():\n import hiddenlayer as hl\n # VGG16 with BatchNorm\n model = torchvision.models.resnet18()\n\n # Build HiddenLayer graph\n # Jupyter Notebook renders it automatically\n g = hl.build_graph(model, torch.zeros([1, 3, 224, 224]))\n g.save(\"resnet18_compute_graph/resnet18\",format='png')\n\n\n def print_info(self):\n self.print_parameters_total()\n self.print_model_flops()\n self.print_model_forward()\n # self.print_summarize()\n self.print_keras_summary_like()\n\ndef main():\n net = torchvision.models.resnet18()\n input = torch.rand(1, 3, 224,224)\n tools = ModelTools(input, net)\n tools.print_parameters_total()\n tools.print_model_flops()\n #tools.print_model_forward()\n # tools.print_summarize()\n tools.print_keras_summary_like()\n # tools.run_visualization_weights()\n # plt.pause(1)\n #tools.visualization_compute_graph()\n\nif __name__ == \"__main__\":\n import fire\n fire.Fire(main)","repo_name":"kadimakipp/GAN","sub_path":"tool/model_tools.py","file_name":"model_tools.py","file_ext":"py","file_size_in_byte":12926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43375430841","text":"# class to handle the robot motion planner k-PRM\nfrom collections import deque\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom robot import Robot\n# import the shapely class\nfrom shapely.geometry import Point, Polygon, LineString\nfrom sklearn.neighbors import NearestNeighbors\n\n\nclass PRM:\n def __init__(self, samples_per_dimension, num_neighbors, num_dimensions, link_lengths, obstacles):\n self.samples_per_dimension = samples_per_dimension # resolution of the PRM\n self.num_neighbors = num_neighbors # connectivity of the PRM (k)\n self.obstacles = obstacles # array of obstacles in the environment (shapely polygons)\n self.num_dimensions = num_dimensions # number of arm links\n self.link_lengths = link_lengths # length of each arm link\n self.samples = [] # list of samples\n self.adjacency_list = {} # graph represented as an adjacency list\n self.visited_from = {} # dictionary to keep track of which node a node was visited from\n self.step_size = 0.05 # step size for collision checking along the path\n\n self.uniform_dense_sample() # initialize the list of samples\n\n # collect the uniform dense samples\n def uniform_dense_sample(self):\n print(\"Generating samples...\")\n # Get the number of samples to take per dimension\n current_sample = []\n self.uniform_dense_sample_recursive(current_sample)\n\n # recursive helper for uniform_dense_sample\n def uniform_dense_sample_recursive(self, current_sample):\n # base case: if the index is num_dimensions, then we have assigned the last dimension\n if len(current_sample) == self.num_dimensions:\n # append the sample to the list of samples\n self.samples.append(tuple(current_sample))\n return\n # otherwise, we need to recurse and assign the next dimension\n # for each value in the number of samples per dimension\n for i in range(self.samples_per_dimension):\n # make a copy of the current sample\n current_sample_copy = current_sample.copy()\n # add the next value\n current_sample_copy.append((i / self.samples_per_dimension) * 2 * np.pi)\n # pass it to the next recursive call\n self.uniform_dense_sample_recursive(current_sample_copy)\n \n # build the graph using the adjacency list\n def build_graph(self):\n # for each sample in the list of samples\n progress = 0\n for sample in self.samples:\n print(str(int(progress/len(self.samples)*100)) + \"% Complete\", end=\"\\r\")\n progress += 1\n robot = Robot(sample, self.link_lengths)\n # check if the sample is in collision\n if not robot.check_collision(self.obstacles):\n # add the sample to the adjacency list\n self.adjacency_list[sample] = []\n k = 0\n # for each other sample in the list of samples\n for other_sample in self.get_sample_distances(sample):\n # if the sample is not the other sample\n if sample != other_sample:\n # check if the edge is valid\n if self.validate_path(sample, other_sample):\n # if it is, add it to the adjacency list\n self.adjacency_list[sample].append(other_sample)\n k += 1\n if k == self.num_neighbors:\n break\n \n # sort samples by distance\n def get_sample_distances(self, sample):\n # Initialize an empty dict of distances\n distances = {}\n # For each other sample in the list of samples\n for other_sample in self.samples:\n # If the sample is not the other sample\n if sample != other_sample:\n # Calculate and store the distance in the distances dictionary\n distances[other_sample] = get_distance(sample, other_sample)\n # Sort the dictionary items by the distance value and get the keys\n sorted_keys = [k for k, _ in sorted(distances.items(), key=lambda item: item[1])]\n # Return the list of keys sorted by distance\n return sorted_keys\n\n def get_nearest_neighbors(self, sample):\n samples_array = np.array(self.samples)\n\n # Create a NearestNeighbors object\n nn = NearestNeighbors(n_neighbors=len(self.samples), algorithm='auto', metric='euclidean')\n nn.fit(samples_array)\n\n # Find the indices of the nearest neighbors and their distances\n indices = nn.kneighbors(samples_array)\n\n # Convert the indices and distances to lists\n sorted_keys = indices[0].tolist()\n\n # Remove the index of the sample itself (if it's in the list)\n if sample in self.samples:\n sample_index = self.samples.index(sample)\n if sample_index in sorted_keys:\n sorted_keys.remove(sample_index)\n\n return sorted_keys\n \n \n # check that the path between two samples is valid\n def validate_path(self, sample1, sample2): \n # initialize the path to be valid\n valid = True\n # initialize the robot\n robot = Robot(sample1, self.link_lengths)\n # get the distance between the samples\n distance = get_distance(sample1, sample2)\n # get the number of steps to take\n num_steps = int(distance / self.step_size)\n # reset num steps if it is just 1\n if num_steps == 0:\n num_steps = 1\n # for each step\n for i in range(num_steps+1):\n # get the interpolated sample\n interpolated_sample = []\n for j in range(self.num_dimensions):\n interpolated_sample.append(sample1[j] + (sample2[j] - sample1[j]) * i / num_steps)\n # set the robot to the interpolated sample \n robot = Robot(interpolated_sample, self.link_lengths)\n # check if the interpolated sample is in collision\n if robot.check_collision(self.obstacles):\n # if it is, set the path to be invalid\n valid = False\n break\n # return whether or not the path is valid\n return valid\n\n # graph the adjacency list\n def graph(self, path=None):\n # graph the adjacency list, assuming 2D samples\n if self.num_dimensions == 2:\n # initialize the figure\n fig, ax = plt.subplots()\n # for each sample in the list of samples\n for sample in self.samples:\n # for each other sample in the list of samples\n if sample in self.adjacency_list:\n ax.plot(sample[0], sample[1], 'o', color='k')\n for other_sample in self.adjacency_list[sample]:\n # plot a line between the samples\n ax.plot([sample[0], other_sample[0]], [sample[1], other_sample[1]], color='k')\n # if a path is provided\n if path: \n # plot that path in a different color\n for i in range(len(path)-1):\n ax.plot([path[i][0], path[i+1][0]], [path[i][1], path[i+1][1]], color='r')\n # show the plot\n plt.show()\n else: \n print(\"cannot graph: incorrect dimensionality\")\n\n # handle a query from the user for the planner\n def query(self, start, goal):\n # ensure valid start and goal states\n start_robot = Robot(start, self.link_lengths)\n goal_robot = Robot(goal, self.link_lengths)\n if start_robot.check_collision(self.obstacles) or goal_robot.check_collision(self.obstacles):\n print(\"start or goal is in collision\")\n return None\n # if the start or goal node isn't in the graph, connect it to its nearest neighbor\n if start not in self.adjacency_list:\n self.connect_node_to_graph(start)\n if goal not in self.adjacency_list: \n self.connect_node_to_graph(goal)\n # run the search algorithm\n return self.find_path(start, goal)\n \n # connect the start or goal node to the graph if it isn't already in it\n def connect_node_to_graph(self, node):\n # add the sample to self.samples\n self.samples.append(node)\n # start the new adjacency list\n self.adjacency_list[node] = []\n # for each other sample\n for other_sample in self.get_sample_distances(node):\n # if the sample is not the node of interest\n if node != other_sample:\n # if the there is a valid path\n if self.validate_path(node, other_sample):\n self.adjacency_list[node].append(other_sample)\n self.adjacency_list[other_sample].append(node)\n break \n\n # takes a start robot and an end robot, returning a path of robot configurations to connect them (adapted from Foxes and Chickens/uninformed_search.py)\n def find_path(self, start_state, goal_state):\n # initialize queue, add the start node\n queue = deque()\n queue.append(start_state)\n\n # visted satates set to avoid revisits\n visited_states = set() \n visited_states.add(start_state)\n\n # track how many nodes have been visited and initialize the solution\n path = []\n\n # begin the search\n while queue: \n # get the next node in queue and increment num_nodes_visited\n current = queue.popleft()\n\n # if this is the goal node, backchain \n if current == goal_state: \n path = self.backchain(current)\n return path\n\n # otherwise, get its unvisited successors and add them to the queue\n else: \n for state in self.adjacency_list[current]:\n # check if already visited\n if state not in visited_states:\n self.visited_from[state] = current\n visited_states.add(state)\n queue.append(state)\n print(\"no path found with given resolution and goal points. change the resolution, neighbors, or start and goal points and try gain.\")\n return False\n\n\n # Backchain function for BFS to reconstruct the path\n def backchain(self, goal):\n path = []\n current = goal\n\n # Start from the goal node and follow parent references\n while current in self.visited_from:\n path.append(current)\n current = self.visited_from[current]\n path.append(current)\n\n # Reverse the path to get it in the correct order and return it\n path.reverse()\n return path\n \n def animate_robot_movement(self, path):\n fig, ax = plt.subplots()\n smoothed_path = []\n\n # get each robot's points and save them \n xmax, ymax = 0, 0\n xmin, ymin = 0, 0\n \n # save axis limits\n for i in range(len(path)):\n robot = Robot(path[i], self.link_lengths)\n points = robot.get_points()\n for point in points:\n if point[0] > xmax:\n xmax = point[0]\n if point[1] > ymax:\n ymax = point[1]\n if point[0] < xmin:\n xmin = point[0]\n if point[1] < ymin:\n ymin = point[1]\n \n smoothed_path.append(path[0]) # add the initial point\n\n # for each point in the path\n for i in range(len(path) - 1):\n dif = []\n # get the absolute differences between the current and the next point\n for j in range(self.num_dimensions):\n difference = (path[i+1][j] - path[i][j])\n if abs(difference) > np.pi: \n if difference > 0:\n difference = -(2 * np.pi - abs(difference))\n else:\n difference = (2 * np.pi - abs(difference))\n dif.append(difference)\n print(dif) \n\n # get the number of steps to take\n num_steps = 10\n \n # for each step\n for j in range(int(num_steps)): # start from 1 to avoid adding duplicate points\n # get the interpolated sample\n interpolated_sample = []\n for k in range(self.num_dimensions):\n # interpolate each dimension using a consistent step size\n interpolated_sample.append(path[i][k] + (dif[k] / num_steps * j))\n smoothed_path.append(interpolated_sample)\n\n # add the final point\n smoothed_path.append(path[-1])\n\n\n def update(frame):\n ax.clear()\n # Set initial axis limits based on obstacle positions\n ax.set_xlim(xmin - 1, xmax + 1) # Adjust as needed\n ax.set_ylim(ymin - 1, ymax + 1) # Adjust as needed\n\n\n\n # Draw obstacles (if applicable)\n for obstacle in self.obstacles:\n plt.plot(*obstacle.exterior.xy, color='black', linewidth=2, linestyle='-', alpha=0.5)\n\n # draw the start and goal locations in red and green, respectively \n startbot = Robot(path[0], self.link_lengths)\n endbot = Robot(path[-1], self.link_lengths)\n start_and_end = [startbot, endbot]\n colors = ['red', 'green']\n for j in range(2):\n # for each robot arm link\n points = start_and_end[j].get_points()\n for i in range(len(points)-1):\n # get the length and base angle of that link\n start_point = points[i]\n end_point = points[i+1]\n\n # plot a line from start_point to end_point\n plt.plot([start_point[0], end_point[0]], [start_point[1], end_point[1]], linewidth=2, marker='o', color=colors[j], alpha=0.5)\n\n # Draw robot arm\n robot = Robot(smoothed_path[frame], self.link_lengths)\n points = robot.get_points()\n\n # for each robot arm link\n for i in range(len(points)-1):\n # get the length and base angle of that link\n start_point = points[i]\n end_point = points[i+1]\n\n # plot a line from start_point to end_point\n plt.plot([start_point[0], end_point[0]], [start_point[1], end_point[1]], linewidth=2, marker='o')\n\n\n plt.title('Robot Arm Movement')\n plt.xlabel('X-axis')\n plt.ylabel('Y-axis')\n plt.grid(True)\n # Return the iterable of Artists (in this case, an empty list)\n return []\n\n ani = FuncAnimation(fig, update, frames=len(smoothed_path), interval=20, repeat=True)\n plt.show()\n\n\n\n# retrieve the distance between two samples\ndef get_distance(sample1, sample2): \n # initialize the distance to 0\n distance = 0\n # for each dimension\n for i in range(len(sample1)):\n # if the difference is less than pi\n if abs(sample1[i] - sample2[i]) < np.pi:\n # add the squared difference in the dimension\n distance += (sample1[i] - sample2[i]) ** 2\n # if the difference is greater than pi\n else:\n # add the squared difference in the dimension\n distance += (2 * np.pi - abs(sample1[i] - sample2[i])) ** 2\n # return the square root of the distance\n return np.sqrt(distance)\n\n# main\nif __name__ == \"__main__\":\n # make some obstacles\n obstacles = []\n # Create a smaller square with side length 0.3 at position (1, 1)\n small_square = Polygon([\n (0.85, 0.85), (1.15, 0.85), (1.15, 1.15), (0.85, 1.15)\n ])\n\n # Create a smaller triangle with vertices (0.85, 1), (1.15, 1), and (1, 1.15)\n small_triangle = Polygon([\n (0.85, -0.6), (1.15, -0.6), (1, -1.15)\n ])\n\n # Create a smaller circle with radius 0.3 at position (2, 2)\n small_circle = Point(-0.5, 1).buffer(0.3)\n\n # Create a smaller hexagon with side length 0.2 at position (-1, -1)\n small_hexagon = Polygon([\n (-1.1, -1.2), (-0.9, -1.2), (-0.8, -1), (-0.9, -0.8), (-1.1, -0.8), (-1.2, -1)\n ])\n square1 = Polygon([(0.5, 1.2), (0.5, 1.7), (0.3, 1.7), (0.3, 1.2)])\n square2 = Polygon([(-0.2, -1), (-0.2, -0.5), (-0.5, -0.5), (-0.5, -1)])\n\n\n # # TODO: CHOOSE YOUR ARRAY OF POLYGONS HERE\n # obstacles = [small_square, small_triangle, small_circle, small_hexagon]\n\n # # TODO: Adjust the other parameters as needed: Keep dimensions to 2 if you want to be able to graph and view the animation. \n # # Remember, if you change the dimensionality, link lenghts need to be adjusted accordingly. \n obstacles = [small_circle, small_triangle, small_hexagon, small_square, square1]\n motion_planner = PRM(samples_per_dimension=45, num_neighbors=10, num_dimensions=2,link_lengths=[1, 0.5], obstacles=obstacles)\n motion_planner.build_graph()\n motion_planner.graph()\n path = motion_planner.query((0, 0), (3, 5))\n print(\"Path: \" + str(path))\n motion_planner.graph(path=path)\n if path: motion_planner.animate_robot_movement(path)\n\n\n # This is code that I preprogrammed so that i know the start and goal configurations are unobstructed, and that there is a path. Comment this out if you dont' want it. \n # obstacles = [square1, square2]\n # motion_planner = PRM(samples_per_dimension=40, num_neighbors=10, num_dimensions=2,link_lengths=[1, 0.5], obstacles=obstacles)\n # motion_planner.build_graph()\n # path = motion_planner.query((0.5, 0.5), (3, 5))\n # print(\"Path: \" + str(path))\n # # motion_planner.graph(path=path)\n # if path: motion_planner.animate_robot_movement(path)\n\n","repo_name":"brendanshaw14/CS-76-Projects","sub_path":"Robot Motion Planning/PRM.py","file_name":"PRM.py","file_ext":"py","file_size_in_byte":17925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4557746387","text":"# libraries import\nimport os\nimport matplotlib.pyplot as plt\nimport sklearn.datasets\nimport numpy as np\n\n# load function, iris dataset from sklearn library\ndef load():\n return sklearn.datasets.load_iris()['data'].T, sklearn.datasets.load_iris()['target']\n\n# reshape to column vector function\ndef mcol(m):\n return m.reshape((m.size, 1))\n \n# reshape to row vector function\ndef mrow(m):\n return m.reshape((1, m.size))\n\n# function to compute the mean of each column of a numpy array\ndef compute_mean(X):\n return mcol(X.mean(1))\n\n# function to compute the covariance matrix\ndef compute_cov(X):\n mu = compute_mean(X)\n return np.dot((X-mu), (X-mu).T)/X.shape[1]\n\ndef pca(iris_data):\n \n\n # mean computation for data centering, note that it will be a 1-D row array\n mu = compute_mean(iris_data)\n mu = mcol(mu)\n\n covar = compute_cov(iris_data)\n\n # computation of the eigenvalues/eigenvectors: \n # s contains the eigenvalues from smallest to largest\n # U contains the eigenvectors as columns\n s, U = np.linalg.eigh(covar)\n\n # choose the number of eigenvectors you are going to use\n m = 2\n # take the principal components\n pc = U[:, [-m+1,-m]]\n \n\n\n # projecting the original datasets along these principal components\n DProjList = [] \n\n for i in range(iris_data.shape[1]):\n xi = mcol(iris_data[:, i])\n yi = np.dot(pc.T, xi)\n DProjList.append(yi)\n\n # transformation into the new transform data matrix\n DY = np.hstack(DProjList)\n\n return DY\n\ndef pcaPlot(D, L):\n\n D0 = D[:, L==0]\n D1 = D[:, L==1]\n D2 = D[:, L==2]\n\n plt.figure()\n plt.xlabel(\"First principal component\")\n plt.ylabel(\"Second principal component\")\n\n plt.scatter(D0[0, :], D0[1, :], label = 'Setosa')\n plt.scatter(D1[0, :], D1[1, :], label = 'Versicolor')\n plt.scatter(D2[0, :], D2[1, :], label = 'Virginica')\n \n plt.tight_layout() # Use with non-default font size to keep axis label inside the figure\n plt.savefig('labs/pcaScatter.pdf')\n plt.show()\n\ndef lda(iris_data, targets):\n\n # computation of the within class covariance matrix\n SW = []\n for i in [0, 1, 2]:\n SW += (targets==i).sum() * compute_cov(iris_data[:, targets==i])\n\n SB = []\n muG = compute_mean(iris_data)\n for i in [0, 1, 2]:\n D = iris_data[:, targets==i]\n mu = compute_mean(D)\n\n SB += D.shape[1] * np.dot((mu - muG), (mu - muG).T)\n return SB / iris_data.shape[1]\n\n # missing parts - lesson about lab 3 around from min 40\n\ndef ldaPlot(D, L):\n\n plt.figure()\n plt.xlabel(\"First direction\")\n plt.ylabel(\"Second direction\")\n\n plt.scatter(D0[0, :], D0[1, :], label = 'Setosa')\n plt.scatter(D1[0, :], D1[1, :], label = 'Versicolor')\n plt.scatter(D2[0, :], D2[1, :], label = 'Virginica')\n \n plt.tight_layout() # Use with non-default font size to keep axis label inside the figure\n plt.savefig('labs/pcaScatter.pdf')\n plt.show()\n\n\n# executing all the functions\nif __name__ == '__main__':\n \n # load the dataset and the targets\n iris_data, targets = load()\n \n # pca analysis\n DY, targets = pca(iris_data, targets) \n pcaPlot(DY, targets)\n\n # lda analysis\n ldaMatrix = lda(iris_data, targets)\n ldaPlot(ldaMatrix, targets)","repo_name":"moDal7/machine-learning-labs-and-projects","sub_path":"labs/lab3_sol.py","file_name":"lab3_sol.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10947289846","text":"#!/usr/bin/env python3\n\"\"\"A wrapper script for calling data processing functions.\"\"\"\n\nimport argparse\nimport sys\nimport os\nimport utils\nimport warnings\n\nimport process_mwrpy\n\nwarnings.simplefilter(\"ignore\", UserWarning)\nwarnings.simplefilter(\"ignore\", RuntimeWarning)\n\n\"\"\"All modules MUST have an add_arguments function which adds the subcommand to the subparser.\"\"\"\nmodules = {\n \"process\": process_mwrpy,\n}\n\n\ndef main(args):\n os.chdir(\"/home/tmarke/Dokumente/GitHub/actris_mwr_pro/mwrpy/\")\n args = _parse_args(args)\n cmd = args.cmd\n modules[cmd].main(args)\n\n\ndef _parse_args(args):\n parser = argparse.ArgumentParser(\n description=\"MWRpy processing main wrapper.\", epilog=\"Have fun!\"\n )\n subparsers = parser.add_subparsers(\n title=\"Command\", help=\"Command to execute.\", required=True, dest=\"cmd\"\n )\n for module in modules.values():\n subparsers = module.add_arguments(subparsers)\n group = parser.add_argument_group(title=\"General options\")\n group.add_argument(\n \"-s\", \"--site\", required=True, help=\"Site to process data from, e.g. juelich\", type=str\n )\n group.add_argument(\n \"-p\",\n \"--products\",\n help=\"Products to be processed, e.g., 1C01, 2I02, 2P03, stats.\\\n Default is all regular products.\",\n type=lambda s: s.split(\",\"),\n default=[\n \"1C01\",\n \"2I01\",\n \"2I02\",\n \"2P01\",\n \"2P02\",\n \"2P03\",\n \"2P04\",\n \"2P07\",\n \"2P08\",\n \"2S02\",\n \"stats\",\n ],\n )\n group.add_argument(\n \"--start\",\n type=str,\n metavar=\"YYYY-MM-DD\",\n help=\"Starting date. Default is current day - 1 (included).\",\n default=utils.get_date_from_past(1),\n )\n group.add_argument(\n \"--stop\",\n type=str,\n metavar=\"YYYY-MM-DD\",\n help=\"Stopping date. Default is current day + 1 (excluded).\",\n default=utils.get_date_from_past(-1),\n )\n group.add_argument(\n \"-d\", \"--date\", type=str, metavar=\"YYYY-MM-DD\", help=\"Single date to be processed.\"\n )\n return parser.parse_args(args)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"igmk/actris_mwr_pro","sub_path":"mwrpy/mwrpy.py","file_name":"mwrpy.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"44553185468","text":"import numpy as np\nimport random\n\n\nclass Game:\n def __init__(void):\n\n void.reset()\n\n def reset(void):\n void.mass = [[\" \", \"|\", \" \", \"|\", \" \"],\n [\"-\", \"+\", \"-\", \"+\", \"-\"],\n [\" \", \"|\", \" \", \"|\", \" \"],\n [\"-\", \"+\", \"-\", \"+\", \"-\"],\n [\" \", \"|\", \" \", \"|\", \" \"]]\n void.count = 0\n void.draw = False\n void.massO = np.zeros([9], dtype=np.uint8)\n void.massX = np.zeros([9], dtype=np.uint8)\n\n def get(void, s):\n\n if s == \"O\":\n return void.massO\n elif s == \"X\":\n return void.massX\n\n def show(void):\n print()\n q = \"\"\n for i in void.mass:\n for j in i:\n q += j\n\n print(q)\n q = \"\"\n print()\n\n def make(void, data, s):\n\n void.count += 1\n\n if s != \"O\" and s != \"X\":\n void.count -= 1\n return False\n\n void.__getCoordinate__(data)\n\n if void.y != None and void.x != None:\n if void.mass[void.y][void.x] == \" \":\n void.mass[void.y][void.x] = s\n\n if s == \"O\":\n void.massO[data - 1] = 1\n if s == \"X\":\n void.massX[data - 1] = 1\n\n return True\n\n else:\n void.count -= 1\n return False\n\n else:\n void.count -= 1\n return False\n\n def __getCoordinate__(void, data):\n\n if data > 0 and data < 10:\n if data < 4:\n void.x = data\n void.y = 1\n elif data > 3 and data < 7:\n void.x = data - 3\n void.y = 2\n else:\n void.x = data - 6\n void.y = 3\n\n if void.x == 1:\n void.x = 0\n\n if void.y == 1:\n void.y = 0\n\n if void.x == 2:\n void.x = 2\n\n if void.y == 2:\n void.y = 2\n\n if void.x == 3:\n void.x = 4\n\n if void.y == 3:\n void.y = 4\n\n else:\n void.x = None\n void.y = None\n\n def isWin(void, s):\n if void.draw:\n return \"D\"\n return void.__Win__(s)\n\n def isfinish(void):\n\n if void.count == 9:\n void.draw = True\n return True\n\n elif void.__Win__(\"X\"):\n return True\n elif void.__Win__(\"O\"):\n return True\n\n else:\n return False\n\n def __Win__(void, s):\n\n if s == \"O\":\n void.win = void.massO.reshape([3, 3])\n else:\n void.win = void.massX.reshape([3, 3])\n\n for i in void.win:\n if i.all() == 1:\n return True\n\n void.some = 0\n for i in void.win:\n if i[0] == 1:\n void.some += 1\n if void.some == 3:\n return True\n\n void.some = 0\n for i in void.win:\n if i[1] == 1:\n void.some += 1\n if void.some == 3:\n return True\n\n void.some = 0\n for i in void.win:\n if i[2] == 1:\n void.some += 1\n if void.some == 3:\n return True\n\n void.some = 0\n for i in range(3):\n if void.win[i][i] == 1:\n void.some += 1\n\n if void.some == 3:\n return True\n\n if void.win[0][2] == 1 and void.win[1][1] == 1 and void.win[2][0]:\n return True\n\n return False\n\n\nclass AI:\n def __init__(void, sign):\n void.sign = sign\n\n # void.q_table = np.zeros([512, 512, 9])\n void.q_table = np.random.rand(512, 512, 9)\n\n def get_hex(void, hex):\n\n void.n = hex.shape[0]\n void.res = 0\n for i in reversed(hex):\n void.n -= 1\n void.res += i * (2 ** void.n)\n\n return int(void.res)\n\n def action(void, my, enemy):\n\n # void.my = void.get_hex(my)\n # void.enemy = void.get_hex(enemy)\n\n # void.action = np.argmax(void.q_table[void.my][void.enemy])\n void.action = np.argmax(void.q_table[my][enemy])\n return void.action\n\n def train(void, episodes, a, y, e):\n void.a = a\n void.y = y\n void.e = e\n\n for i in range(episodes):\n\n void.done = False\n\n while not void.done:\n\n if random.uniform(0, 1) < void.e:\n void.actions = void.action()\n else:\n void.actions = random.radint(0, 9)\n\n\n","repo_name":"nazarshevchenko/TicTacToe_DobotMagician","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70503402725","text":"from abc import abstractmethod\nfrom typing import Any, List\n\n\nclass BaseSpell:\n \"\"\"Classe modélisant la base du comportement d'un sort.\"\"\"\n\n def __init__(\n self,\n damages: List[int],\n damage_type: List[str],\n *,\n stun: bool,\n blind: bool,\n bump: bool,\n ) -> None:\n \"\"\"Instanciation de la classe parent représentant un sort.\n\n :param damages: Les dégats de base du sort.\n :type damages: List[int]\n :param damage_type: Les éléments des dégâts appliqués de de chacun du sort\n :type damage_type: List[str]\n :param stun: Indique si le sort a un effet paralysant\n :type stun: bool\n :param blind: indique si le sort aveugle le champion\n :type blind: bool\n :param bump: indique si le sort propulse un champion dans les airs\n :type bump: bool\n \"\"\"\n self.damages = damages\n self.damage_type = damage_type\n self.stun = stun\n self.blind = blind\n self.bump = bump\n\n def __call__(self, hitted: List[Any]) -> None:\n \"\"\"Voir la méthode apply().\n\n :param champion: listes d'instances d'objets atteints par le sort\n :type champion: List[Any]\n \"\"\"\n self.apply(hitted)\n\n @abstractmethod\n def apply(self, hitted: List[Any]) -> None:\n \"\"\"Applique les effets aux objets atteints par le sort.\n\n :param champion: listes d'instances d'objets atteints par le sort\n :type champion: List[Any]\n :raises NotImplementedError: Méthode abstraite qui doit être implémentée par une classe enfant\n \"\"\"\n raise NotImplementedError(\"This method must be implemented by a child class\")\n\n def apply_damages(self, hitted: List[Any]) -> None:\n \"\"\"Applique les dégâts aux objets atteints par le sort.\n\n :param champion: listes d'instances d'objets atteints par le sort\n :type champion: List[Any]\n :raises NotImplementedError: Méthode abstraite qui doit être implémentée par une classe enfant\n \"\"\"\n raise NotImplementedError(\"This method must be implemented by a child class\")\n\n def apply_state(self, hitted: List[Any]) -> None:\n \"\"\"Applique les effets de contrôle aux objets atteints par le sort.\n\n :param champion: listes d'instances d'objets atteints par le sort\n :type champion: List[BaseChampion]\n :raises NotImplementedError: Méthode abstraite qui doit être implémentée par une classe enfant\n \"\"\"\n raise NotImplementedError(\"This method must be implemented by a child class\")\n","repo_name":"lbaret/CIA_MLOps_tools","sub_path":"exemples/sphinx/spells/base_spell.py","file_name":"base_spell.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}