diff --git "a/1562.jsonl" "b/1562.jsonl" new file mode 100644--- /dev/null +++ "b/1562.jsonl" @@ -0,0 +1,963 @@ +{"seq_id":"18132718192","text":"from keras.models import Sequential\nfrom keras.layers.core import Dense, Flatten, Activation, Dropout\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.datasets import cifar10\n\nfrom matplotlib import pyplot as plt\n\nIMG_CHANNELS = 3\nIMG_ROWS = 32\nIMG_COLS = 32\n\nBATCH_SIZE = 128\nEPOCHS = 20\nVALIDATION_SPLIT = 0.2\nVERBOSE = 1\nNB_CLASSES = 10\nOPTIM = RMSprop()\n\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255\n\ny_train = np_utils.to_categorical(y_train, NB_CLASSES)\ny_test = np_utils.to_categorical(y_test, NB_CLASSES)\n\ndatagen = ImageDataGenerator(rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, zoom_range=0.2, horizontal_flip=True)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=3, input_shape=(IMG_ROWS, IMG_COLS, IMG_CHANNELS), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, kernel_size=3, padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, kernel_size=3, padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(NB_CLASSES))\nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer=OPTIM, metrics=['accuracy'])\n\ndatagen.fit(X_train)\nhistory = model.fit_generator(datagen.flow(X_train, y_train, batch_size=BATCH_SIZE),\n samples_per_epoch=X_train.shape[0],\n epochs=EPOCHS,\n validation_steps=VALIDATION_SPLIT,\n verbose=VERBOSE)\n\n\nprint('Testing...')\nscore = model.evaluate(X_test, y_test, batch_size=BATCH_SIZE, verbose=VERBOSE)\nprint(\"\\nTest score:\", score[0])\nprint('Test accuracy:', score[1])\n\n#save model\nmodel_json = model.to_json()\nopen('../../../cache/cifar10_architecture.json', 'w').write(model_json)\nmodel.save_weights('../../../cache/cifar10_weights.h5', overwrite=True)\n\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n\n\n","repo_name":"chen0040/pydl-hands-on","sub_path":"pydl/keras/dcnn/cifar10/convnet_cifar10_data_aug.py","file_name":"convnet_cifar10_data_aug.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9707638125","text":"# Desenvolva um programa que recebe do usuário nome completo e ano de nascimento que seja entre 1922 e 2021.\n# A partir dessas informações, o sistema mostrará o nome do usuário e a idade que completou, ou completará, no ano atual (2022).\n# Caso o usuário não digite um número ou apareça um inválido no campo do ano, o sistema informará o erro e continuará perguntando até que um valor correto seja preenchido.\n# Resposta:\nwhile True:\n nome = str(input(\"digite seu nome\"))\n nasceu = int(input(\"digite o ano que voce nasceu\"))\n if nasceu >= 1922 and nasceu <= 2021:\n idade = 2022 - nasceu\n print(nome, idade)\n break\n\n else:\n print(\n \"ano de nascimento deve ser maior que 1922 e menor que 2021, tente de novo\")\n","repo_name":"Vitor-Mateus-Dev/Proz","sub_path":"Atividades/nome_idade.py","file_name":"nome_idade.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2764780477","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport sonnet as snt\nimport tensorflow as tf\n\nimport addressing\nimport util\n\nAccessState = collections.namedtuple('AccessState', (\n 'memory', 'read_weights', 'write_weights', 'linkage', 'usage'))\n\n\ndef _erase_and_write(memory, address, reset_weights, values):\n \"\"\"Module to erase and write in the external memory.\n\n Erase operation:\n M_t'(i) = M_{t-1}(i) * (1 - w_t(i) * e_t)\n\n Add operation:\n M_t(i) = M_t'(i) + w_t(i) * a_t\n\n where e are the reset_weights, w the write weights and a the values.\n\n Args:\n memory: 3-D tensor of shape `[batch_size, memory_size, word_size]`.\n address: 3-D tensor `[batch_size, num_writes, memory_size]`.\n reset_weights: 3-D tensor `[batch_size, num_writes, word_size]`.\n values: 3-D tensor `[batch_size, num_writes, word_size]`.\n\n Returns:\n 3-D tensor of shape `[batch_size, num_writes, word_size]`.\n \"\"\"\n with tf.name_scope('erase_memory', values=[memory, address, reset_weights]):\n expand_address = tf.expand_dims(address, 3)\n reset_weights = tf.expand_dims(reset_weights, 2)\n weighted_resets = expand_address * reset_weights\n reset_gate = tf.reduce_prod(1 - weighted_resets, [1])\n memory *= reset_gate\n\n with tf.name_scope('additive_write', values=[memory, address, values]):\n add_matrix = tf.matmul(address, values, adjoint_a=True)\n memory += add_matrix\n\n return memory\n\n\nclass MemoryAccess(snt.RNNCore):\n \"\"\"Access module of the Differentiable Neural Computer.\n\n This memory module supports multiple read and write heads. It makes use of:\n\n * `addressing.TemporalLinkage` to track the temporal ordering of writes in\n memory for each write head.\n * `addressing.FreenessAllocator` for keeping track of memory usage, where\n usage increase when a memory location is written to, and decreases when\n memory is read from that the controller says can be freed.\n\n Write-address selection is done by an interpolation between content-based\n lookup and using unused memory.\n\n Read-address selection is done by an interpolation of content-based lookup\n and following the link graph in the forward or backwards read direction.\n \"\"\"\n\n def __init__(self,\n memory_size=128,\n word_size=20,\n num_reads=1,\n num_writes=1,\n name='memory_access'):\n \"\"\"Creates a MemoryAccess module.\n\n Args:\n memory_size: The number of memory slots (N in the DNC paper).\n word_size: The width of each memory slot (W in the DNC paper)\n num_reads: The number of read heads (R in the DNC paper).\n num_writes: The number of write heads (fixed at 1 in the paper).\n name: The name of the module.\n \"\"\"\n super(MemoryAccess, self).__init__(name=name)\n self._memory_size = memory_size\n self._word_size = word_size\n self._num_reads = num_reads\n self._num_writes = num_writes\n\n self._write_content_weights_mod = addressing.CosineWeights(\n num_writes, word_size, name='write_content_weights')\n self._read_content_weights_mod = addressing.CosineWeights(\n num_reads, word_size, name='read_content_weights')\n\n self._linkage = addressing.TemporalLinkage(memory_size, num_writes)\n self._freeness = addressing.Freeness(memory_size)\n\n def _build(self, inputs, prev_state):\n \"\"\"Connects the MemoryAccess module into the graph.\n\n Args:\n inputs: tensor of shape `[batch_size, input_size]`. This is used to\n control this access module.\n prev_state: Instance of `AccessState` containing the previous state.\n\n Returns:\n A tuple `(output, next_state)`, where `output` is a tensor of shape\n `[batch_size, num_reads, word_size]`, and `next_state` is the new\n `AccessState` named tuple at the current time t.\n \"\"\"\n inputs = self._read_inputs(inputs)\n\n # Update usage using inputs['free_gate'] and previous read & write weights.\n usage = self._freeness(\n write_weights=prev_state.write_weights,\n free_gate=inputs['free_gate'],\n read_weights=prev_state.read_weights,\n prev_usage=prev_state.usage)\n\n # Write to memory.\n write_weights = self._write_weights(inputs, prev_state.memory, usage)\n memory = _erase_and_write(\n prev_state.memory,\n address=write_weights,\n reset_weights=inputs['erase_vectors'],\n values=inputs['write_vectors'])\n\n linkage_state = self._linkage(write_weights, prev_state.linkage)\n\n # Read from memory.\n read_weights = self._read_weights(\n inputs,\n memory=memory,\n prev_read_weights=prev_state.read_weights,\n link=linkage_state.link)\n read_words = tf.matmul(read_weights, memory)\n\n return (read_words, AccessState(\n memory=memory,\n read_weights=read_weights,\n write_weights=write_weights,\n linkage=linkage_state,\n usage=usage))\n\n def _read_inputs(self, inputs):\n \"\"\"Applies transformations to `inputs` to get control for this module.\"\"\"\n\n def _linear(first_dim, second_dim, name, activation=None):\n \"\"\"Returns a linear transformation of `inputs`, followed by a reshape.\"\"\"\n linear = snt.Linear(first_dim * second_dim, name=name)(inputs)\n if activation is not None:\n linear = activation(linear, name=name + '_activation')\n return tf.reshape(linear, [-1, first_dim, second_dim])\n\n # v_t^i - The vectors to write to memory, for each write head `i`.\n write_vectors = _linear(self._num_writes, self._word_size, 'write_vectors')\n\n # e_t^i - Amount to erase the memory by before writing, for each write head.\n erase_vectors = _linear(self._num_writes, self._word_size, 'erase_vectors',\n tf.sigmoid)\n\n # f_t^j - Amount that the memory at the locations read from at the previous\n # time step can be declared unused, for each read head `j`.\n free_gate = tf.sigmoid(\n snt.Linear(self._num_reads, name='free_gate')(inputs))\n\n # g_t^{a, i} - Interpolation between writing to unallocated memory and\n # content-based lookup, for each write head `i`. Note: `a` is simply used to\n # identify this gate with allocation vs writing (as defined below).\n allocation_gate = tf.sigmoid(\n snt.Linear(self._num_writes, name='allocation_gate')(inputs))\n\n # g_t^{w, i} - Overall gating of write amount for each write head.\n write_gate = tf.sigmoid(\n snt.Linear(self._num_writes, name='write_gate')(inputs))\n\n # \\pi_t^j - Mixing between \"backwards\" and \"forwards\" positions (for\n # each write head), and content-based lookup, for each read head.\n num_read_modes = 1 + 2 * self._num_writes\n read_mode = snt.BatchApply(tf.nn.softmax)(\n _linear(self._num_reads, num_read_modes, name='read_mode'))\n\n # Parameters for the (read / write) \"weights by content matching\" modules.\n write_keys = _linear(self._num_writes, self._word_size, 'write_keys')\n write_strengths = snt.Linear(self._num_writes, name='write_strengths')(\n inputs)\n\n read_keys = _linear(self._num_reads, self._word_size, 'read_keys')\n read_strengths = snt.Linear(self._num_reads, name='read_strengths')(inputs)\n\n result = {\n 'read_content_keys': read_keys,\n 'read_content_strengths': read_strengths,\n 'write_content_keys': write_keys,\n 'write_content_strengths': write_strengths,\n 'write_vectors': write_vectors,\n 'erase_vectors': erase_vectors,\n 'free_gate': free_gate,\n 'allocation_gate': allocation_gate,\n 'write_gate': write_gate,\n 'read_mode': read_mode,\n }\n return result\n\n def _write_weights(self, inputs, memory, usage):\n \"\"\"Calculates the memory locations to write to.\n\n This uses a combination of content-based lookup and finding an unused\n location in memory, for each write head.\n\n Args:\n inputs: Collection of inputs to the access module, including controls for\n how to chose memory writing, such as the content to look-up and the\n weighting between content-based and allocation-based addressing.\n memory: A tensor of shape `[batch_size, memory_size, word_size]`\n containing the current memory contents.\n usage: Current memory usage, which is a tensor of shape `[batch_size,\n memory_size]`, used for allocation-based addressing.\n\n Returns:\n tensor of shape `[batch_size, num_writes, memory_size]` indicating where\n to write to (if anywhere) for each write head.\n \"\"\"\n with tf.name_scope('write_weights', values=[inputs, memory, usage]):\n # c_t^{w, i} - The content-based weights for each write head.\n write_content_weights = self._write_content_weights_mod(\n memory, inputs['write_content_keys'],\n inputs['write_content_strengths'])\n\n # a_t^i - The allocation weights for each write head.\n write_allocation_weights = self._freeness.write_allocation_weights(\n usage=usage,\n write_gates=(inputs['allocation_gate'] * inputs['write_gate']),\n num_writes=self._num_writes)\n\n # Expands gates over memory locations.\n allocation_gate = tf.expand_dims(inputs['allocation_gate'], -1)\n write_gate = tf.expand_dims(inputs['write_gate'], -1)\n\n # w_t^{w, i} - The write weightings for each write head.\n return write_gate * (allocation_gate * write_allocation_weights +\n (1 - allocation_gate) * write_content_weights)\n\n def _read_weights(self, inputs, memory, prev_read_weights, link):\n \"\"\"Calculates read weights for each read head.\n\n The read weights are a combination of following the link graphs in the\n forward or backward directions from the previous read position, and doing\n content-based lookup. The interpolation between these different modes is\n done by `inputs['read_mode']`.\n\n Args:\n inputs: Controls for this access module. This contains the content-based\n keys to lookup, and the weightings for the different read modes.\n memory: A tensor of shape `[batch_size, memory_size, word_size]`\n containing the current memory contents to do content-based lookup.\n prev_read_weights: A tensor of shape `[batch_size, num_reads,\n memory_size]` containing the previous read locations.\n link: A tensor of shape `[batch_size, num_writes, memory_size,\n memory_size]` containing the temporal write transition graphs.\n\n Returns:\n A tensor of shape `[batch_size, num_reads, memory_size]` containing the\n read weights for each read head.\n \"\"\"\n with tf.name_scope(\n 'read_weights', values=[inputs, memory, prev_read_weights, link]):\n # c_t^{r, i} - The content weightings for each read head.\n content_weights = self._read_content_weights_mod(\n memory, inputs['read_content_keys'], inputs['read_content_strengths'])\n\n # Calculates f_t^i and b_t^i.\n forward_weights = self._linkage.directional_read_weights(\n link, prev_read_weights, forward=True)\n backward_weights = self._linkage.directional_read_weights(\n link, prev_read_weights, forward=False)\n\n backward_mode = inputs['read_mode'][:, :, :self._num_writes]\n forward_mode = (\n inputs['read_mode'][:, :, self._num_writes:2 * self._num_writes])\n content_mode = inputs['read_mode'][:, :, 2 * self._num_writes]\n\n read_weights = (\n tf.expand_dims(content_mode, 2) * content_weights + tf.reduce_sum(\n tf.expand_dims(forward_mode, 3) * forward_weights, 2) +\n tf.reduce_sum(tf.expand_dims(backward_mode, 3) * backward_weights, 2))\n\n return read_weights\n\n @property\n def state_size(self):\n \"\"\"Returns a tuple of the shape of the state tensors.\"\"\"\n return AccessState(\n memory=tf.TensorShape([self._memory_size, self._word_size]),\n read_weights=tf.TensorShape([self._num_reads, self._memory_size]),\n write_weights=tf.TensorShape([self._num_writes, self._memory_size]),\n linkage=self._linkage.state_size,\n usage=self._freeness.state_size)\n\n @property\n def output_size(self):\n \"\"\"Returns the output shape.\"\"\"\n return tf.TensorShape([self._num_reads, self._word_size])\n","repo_name":"huseinzol05/Stock-Prediction-Models","sub_path":"deep-learning/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":12286,"program_lang":"python","lang":"en","doc_type":"code","stars":6916,"dataset":"github-code","pt":"48"} +{"seq_id":"11679074571","text":"alfabeto = \"abcdefghijklmnopqrstuvwxyz\"\ndef cesarecifra(lettera,chiave):\n indice = alfabeto.index(lettera)\n indice = (indice + chiave) % len(alfabeto)\n return alfabeto[indice]\ndef scambiatore(lettera):\n indice = alfabeto.index(lettera)\n indice = len(alfabeto) - indice % len(alfabeto)\n return alfabeto[indice]\n\n#chiavi\nprint(\"inserisci le chiavi dei tre rotori\")\nchiave1 = int(input());\nchiave2 = int(input());\nchiave3 = int(input());\n\n#stecker\nquadro = list(\"abcdefghijklmnopqrstuvwxyz\")\nprint(\"inserisci 6 coppie di lettere\")\nfor i in range(0,6):\n coppia = input()\n lettera1 = coppia[0]\n lettera2 = coppia[1]\n indice1 = quadro.index(lettera1)\n indice2 = quadro.index(lettera2)\n tmp = quadro[indice1] \n quadro[indice1] = quadro[indice2]\n quadro[indice2] = tmp\n\n#cifra la parola\nprint(\"inserisci la frase\")\nfrase = input()\ncifrata = \"\"\nfor i in range(0,len(frase)):\n #stecker\n indice = alfabeto.index(frase[i])\n uscita = quadro[indice]\n\n #rotori\n uscita_r1 = cesarecifra(uscita,chiave1)\n uscita_r2 = cesarecifra(uscita_r1,chiave2)\n uscita_r3 = cesarecifra(uscita_r2,chiave3)\n\n #riflettore\n uscita_rif = scambiatore(uscita_r3)\n\n #rotori (indietro)\n uscita_r4 = cesarecifra(uscita_rif,-chiave1)\n uscita_r5 = cesarecifra(uscita_r4,-chiave2)\n uscita_r6 = cesarecifra(uscita_r5,-chiave3)\n\n #stecker (indietro)\n indice = alfabeto.index(uscita_r6)\n uscita = quadro[indice]\n\n cifrata = cifrata + uscita\n \n #movimento rotori dopo ogni lettera\n chaive1 = chiave1 +1\n if chiave1 > len(alfabeto):\n chiave1 = 0\n chiave2 = chiave2 + 1\n if chiave2 > len(alfabeto):\n chiave2 = 0\n chiave3 = chiave3 + 1\n if chiave3 > len(alfabeto):\n chiave3 = 0\nprint(cifrata)\n","repo_name":"DiniSauri/dinicode","sub_path":"crittografia/enigma.py","file_name":"enigma.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12739752325","text":"from typing import List\r\n\r\n\r\nclass Solution:\r\n\r\n MAX_WEIGHT = 500\r\n\r\n def shipWithinDays(self, weights: List[int], D: int) -> int:\r\n low, high = 0, len(weights) * Solution.MAX_WEIGHT\r\n possible = self.possible\r\n while low < high:\r\n mid = low + (high - low) // 2\r\n if possible(weights, D, mid):\r\n high = mid\r\n else:\r\n low = mid + 1\r\n return high\r\n\r\n def possible(self, weights: List[int], D: int, capacity: int) -> bool:\r\n ship = 0\r\n current = 0\r\n for weight in weights:\r\n if current + weight > capacity:\r\n ship += 1\r\n if ship > D:\r\n return False\r\n current = weight\r\n if current > capacity:\r\n return False\r\n else:\r\n current += weight\r\n if current > 0:\r\n ship += 1\r\n return ship <= D\r\n","repo_name":"sandychn/LeetCode-Solutions","sub_path":"Algorithms/BinarySearch/1011-capacity-to-ship-packages-within-d-days.py","file_name":"1011-capacity-to-ship-packages-within-d-days.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21404489871","text":"import asyncio\nimport aio_pika\n\n\nasync def main(loop):\n connection = await aio_pika.connect_robust(\n \"amqp://guest:guest@127.0.0.1/\", loop=loop\n )\n\n async with connection:\n routing_key = \"test_queue\"","repo_name":"Skylar-Kerzner/when-the","sub_path":"when_the/lib/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6686383459","text":"from langchain.document_loaders import UnstructuredURLLoader\nimport session_info\n\nfrom chatbot_settings import ChatBotSettings\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.schema import (\n SystemMessage,\n HumanMessage,\n AIMessage\n)\n\nchatbotSettings = ChatBotSettings()\n\nsession_info.show()\n\nurls = [\n \"https://www.understandingwar.org/backgrounder/russian-offensive-campaign-assessment-february-8-2023\",\n \"https://www.understandingwar.org/backgrounder/russian-offensive-campaign-assessment-february-9-2023\",\n]\n\nprint(urls)\n\nloader = UnstructuredURLLoader(urls=urls)\n\nprint(loader)\n\ndata = loader.load()\n\nprint(data)\n\n","repo_name":"ggrow3/ExtensibleChatBot","sub_path":"misc_url_loader.py","file_name":"misc_url_loader.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"18027130245","text":"# import package\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import PCA\n\n# import datasets\nfrom sklearn.datasets import load_breast_cancer\ncancer=load_breast_cancer()\nprint(cancer.keys())\n\ndf=pd.DataFrame(cancer['data'],columns=cancer['feature_names'])\nprint(df.head(5))\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler()\nscaler.fit(df)\nStandardScaler(copy=True, with_mean=True, with_std=True)\nscaled_data=scaler.transform(df)\nprint(scaled_data)\n\npca=PCA(n_components=2)\npca.fit(scaled_data)\n\nx_pca=pca.transform(scaled_data)\nprint(scaled_data.shape)\n\nprint(x_pca.shape)\n\nscaled_data\n\nprint(x_pca)\n\nplt.figure(figsize=(8,6))\nplt.scatter(x_pca[:,0],x_pca[:,1],c=cancer['target'])\nplt.xlabel('First principle component')\nplt.ylabel('Second principle component')\nplt.show()\n\n","repo_name":"kecoaktempur/Machine-Learning-Prak-Smt4","sub_path":"TM 5 - Extraction and Selection Feature/week 5.py","file_name":"week 5.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44194000486","text":"from models.event import EventModel\nfrom db import db\n\n\nclass OrdersModel(db.Model):\n __tablename__ = 'orders'\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(30), db.ForeignKey('accounts.username'), nullable=False)\n id_event = db.Column(db.Integer, nullable=False)\n tickets_bought = db.Column(db.Integer, nullable=False)\n\n def json(self):\n event = EventModel.find_by_id(self.id_event)\n return {\n \"Id\": self.id_event,\n \"Username\": self.username,\n \"Event_name\": event.name,\n \"Event_date\": event.date,\n \"Event_city\": event.city,\n \"Tickets_bought\": self.tickets_bought\n }\n\n def save_to_db(self):\n if self.id and OrdersModel.query.get(self.id):\n db.session.commit()\n else:\n db.session.add(self)\n db.session.commit()\n\n\n def delete_from_db(self):\n if self.id and OrdersModel.query.get(self.id):\n db.session.delete(self)\n db.session.commit()\n else:\n raise Exception(\"Warning not in DB\")\n\n @classmethod\n def find_by_username(cls, username):\n if username:\n return OrdersModel.query.filter_by(username=username).all()\n else:\n return None\n\n @classmethod\n def find_all(cls):\n return OrdersModel.query.all()\n\n def __init__(self, id_event, tickets_bought):\n self.id_event = id_event\n self.tickets_bought = tickets_bought\n","repo_name":"aldakata/SD_p2","sub_path":"backend/models/orders.py","file_name":"orders.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42113390315","text":"# Write a function called list_manipulator which receives a list of numbers as first parameter and different amount of\r\n# other parameters. The second parameter might be \"add\" or \"remove\". The third parameter might be \"beginning\" or \"end\".\r\n# There might or might not be any other parameters (numbers):\r\n# •\tIn case of \"add\" and \"beginning\", add the given numbers to the beginning of the given list of numbers and\r\n# return the new list\r\n# •\tIn case of \"add\" and \"end\", add the given numbers to the end of the given list of numbers and return the new list\r\n# •\tIn case of \"remove\" and \"beginning\"\r\n# o\tIf there is another parameter (number), remove that amount of numbers from the beginning of the list of numbers.\r\n# o\tIf there are no other parameters, remove only the first element of the list.\r\n# o\tFinaly, return the new list\r\n# •\tIn case of \"remove\" and \"end\"\r\n# o\tIf there is another parameter (number), remove that amount of numbers from the end of the list of numbers.\r\n# o\tOtherwise if there are no other parameters, remove only the last element of the list.\r\n# o\tFinaly, return the new list\r\n# For more clarifications, see the examples below.\r\n\r\n\r\nfrom collections import deque\r\n\r\n\r\ndef list_manipulator(current_lst, operation, position, *args):\r\n new_list = deque(current_lst)\r\n\r\n if operation == 'add':\r\n if position == 'beginning':\r\n if len(args) > 0:\r\n new_list = deque(args) + new_list\r\n\r\n elif position == 'end':\r\n if len(args) > 0:\r\n new_list += deque(args)\r\n\r\n elif operation == 'remove':\r\n if position == 'beginning':\r\n if 0 <= len(args) <= 1:\r\n n = args[0] if len(args) == 1 else 1\r\n fn = new_list.popleft if position == 'beginning' else new_list.pop\r\n for _ in range(n):\r\n fn()\r\n\r\n elif position == 'end':\r\n if 0 <= len(args) <= 1:\r\n n = args[0] if len(args) == 1 else 1\r\n fn = new_list.popleft if position == 'beginning' else new_list.pop\r\n for _ in range(n):\r\n fn()\r\n\r\n return list(new_list)\r\n\r\n\r\nprint(list_manipulator([1, 2, 3], \"remove\", \"end\"))\r\nprint(list_manipulator([1, 2, 3], \"remove\", \"beginning\"))\r\nprint(list_manipulator([1, 2, 3], \"add\", \"beginning\", 20))\r\nprint(list_manipulator([1, 2, 3], \"add\", \"end\", 30))\r\nprint(list_manipulator([1, 2, 3], \"remove\", \"end\", 2))\r\nprint(list_manipulator([1, 2, 3], \"remove\", \"beginning\", 2))\r\nprint(list_manipulator([1, 2, 3], \"add\", \"beginning\", 20, 30, 40))\r\nprint(list_manipulator([1, 2, 3], \"add\", \"end\", 30, 40, 50))\r\n","repo_name":"AlexanderIvanofff/Python-OOP","sub_path":"Multidimensional Lists/list_manipulator.py","file_name":"list_manipulator.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41494184528","text":"from pynput import mouse\n\ndef on_click(x, y,button,pressed):\n if pressed:\n print(str(button)+\" pressed(\"+str(x)+\", \"+str(y)+\")\")\n else:\n print(str(button)+\" released at (\"+str(x)+\", \"+str(y)+\")\")\n\nwith mouse.Listener(\n on_click=on_click) as listener:\n\n listener.join()\n\n\nlistener = mouse.Listener(\n #on_press=on_press,\n #on_release=on_release\n on_click=on_click)\nlistener.start()","repo_name":"erdebankadas/Automated_mouse_monitor","sub_path":"mouse.py","file_name":"mouse.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35123766875","text":"import requests\nimport re\nimport html\nfrom pipe_fn import e\nimport json\nimport os.path\nimport bs4\n\nimg_url = \"https://i.pximg.net/img-original/img/{date}/{pid}_p{page}.{ext}\"\nartworks_url = \"https://www.pixiv.net/artworks/{pid}\"\n\n\ndef get_info(illust_id):\n url = artworks_url.format(pid=illust_id)\n response = requests.get(url)\n soup = bs4.BeautifulSoup(response.content)\n content = json.loads(soup.find(\"meta\", id=\"meta-preload-data\")[\"content\"])\n return {\n \"id\": content[\"illust\"][illust_id][\"id\"],\n \"title\": content[\"illust\"][illust_id][\"title\"],\n \"description\": content[\"illust\"][illust_id][\"description\"],\n \"illustType\": content[\"illust\"][illust_id][\"illustType\"],\n \"xRestrict\": content[\"illust\"][illust_id][\"xRestrict\"],\n \"tags\": content[\"illust\"][illust_id][\"tags\"][\"tags\"]\n | e / map @ (lambda t: t[\"tag\"])\n | e / list,\n \"pageCount\": content[\"illust\"][illust_id][\"pageCount\"],\n \"bookmarkCount\": content[\"illust\"][illust_id][\"bookmarkCount\"],\n \"likeCount\": content[\"illust\"][illust_id][\"likeCount\"],\n \"viewCount\": content[\"illust\"][illust_id][\"viewCount\"],\n }\n\n\ndef dict2cookie(cookie):\n return (\n list(cookie.items())\n | e / map @ (lambda x: str(x[0]) + \"=\" + str(x[1]))\n | e / \";\".join\n )\n\n\ndef get_image_ext(date, pid):\n url = img_url.format(date=date, pid=pid, page=0, ext=\"jpg\")\n x = requests.head(url, headers={\"referer\": url})\n if x.status_code == 200:\n return \"jpg\"\n else:\n # normally there are only two formats\n return \"png\"\n\n\ndef get_newest_followed_illusts(cookie, page_id):\n def extract_date(illust):\n url = illust[\"url\"]\n date = re.compile(\n r\"img-master/img/(\\d{4}/\\d{2}/\\d{2}/\\d{2}/\\d{2}/\\d{2})/\"\n ).findall(url)[0]\n return date\n\n patt = re.compile(\n '
'\n )\n url = f\"https://www.pixiv.net/bookmark_new_illust.php?p={page_id}\"\n response = requests.get(\n url, params={\"p\": page_id}, headers={\"cookie\": dict2cookie(cookie)}\n )\n result = patt.findall(response.content.decode())\n return (\n result[0]\n | e / html.unescape\n | e / json.loads\n | e / filter @ (lambda x: x[\"illustType\"] != \"2\") # ignore animate\n | e / map @ (lambda x: (x[\"illustId\"], extract_date(x), x[\"pageCount\"]))\n | e / map @ (lambda x: (x[0], x[1], x[2], get_image_ext(x[1], x[0])))\n | e / list\n )\n\n\ndef download_newest_followed_illusts(cookie, latest_pid, dest):\n lst = []\n k = 1\n p = get_newest_followed_illusts(cookie, k)\n ret = p | e / map @ (lambda x: int(x[0])) | e / max\n p = p | e / filter @ (lambda x: int(x[0]) > latest_pid) | e / list\n while p:\n download_list(p, dest)\n k += 1\n p = (\n get_newest_followed_illusts(cookie, k)\n | e / filter @ (lambda x: int(x[0]) > latest_pid)\n | e / list\n )\n return (ret, lst)\n\n\ndef download_list(lst, dest, filtering=lambda x: True):\n for illust in lst:\n if not filtering(illust):\n continue\n # illust :: (pid, date, page count, ext)\n for page in range(0, int(illust[2])):\n name = \"{}_p{}.{}\".format(illust[0], page, illust[3])\n with open(os.path.join(dest, name), \"wb\") as f:\n url = img_url.format(\n pid=illust[0], date=illust[1], ext=illust[3], page=page\n )\n print(\"Downloading {}\".format(url))\n response = requests.get(url, headers={\"referer\": url})\n print(\"Response: {}\".format(response.status_code))\n if response.status_code != 200:\n continue\n f.write(response.content)\n return True\n\n\ndef main(\n cookie={\n \"device_token\": \"\",\n \"PHPSESSID\": \"\",\n },\n latest_pid=\"81515705\",\n dest=\"D:\\\\palette\\\\Sync\\\\Devices\",\n):\n if os.path.isfile(\"prop/latest_pid\"):\n with open(\"prop/latest_pid\", \"r\") as f:\n latest_pid = f.readline()\n latest_pid, _ = download_newest_followed_illusts(\n cookie, int(latest_pid), \"D:\\\\palette\\\\Sync\\\\Devices\"\n )\n with open(\"prop/latest_pid\", \"w\") as f:\n f.write(str(latest_pid))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"paletteOvO/CodeColle","sub_path":"Python/waifu/pixiv.py","file_name":"pixiv.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34273977045","text":"import unittest\nfrom house_scrapping.remax_url_scrapper import RemaxURLScraper\n\nclass TestRemaxWebScraper(unittest.TestCase):\n def test_set_search_param(self):\n \"\"\"Test if the set_search_param method correctly updates search parameters.\"\"\"\n scraper = RemaxURLScraper()\n scraper.set_search_param(\"rooms\", 3)\n self.assertEqual(scraper.search_params[\"rooms\"], 3)\n\n def test_scrape_listing_urls(self):\n \"\"\"Test if the scrape_listing_urls method returns valid listing URLs.\"\"\"\n scraper = RemaxWebScraper()\n urls = scraper.scrape_listing_urls()\n \n # Check if the returned URLs are valid by verifying their format\n self.assertIsInstance(urls, list)\n self.assertTrue(all(url.startswith(\"https://remax.pt/\") for url in urls))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"pedrotmatias/house_scrapping","sub_path":"house_scrapping/tests/test_remax_url_scapper.py","file_name":"test_remax_url_scapper.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8254817612","text":"import pandas as pd\r\nimport numpy as np\r\nimport movie_list as ml\r\n\r\n\r\ntitles = pd.read_csv('recom_title.csv')\r\ntitleids = pd.read_csv('recom_titleid.csv')\r\nsim_records = pd.read_csv('sim_record.csv')\r\n\r\nif __name__ == '__main__':\r\n user_movie_list,idss = ml.getMovieList()\r\n result = {}\r\n for ids in idss:\r\n recom_ids = titleids[titleids['title_id'] == ids].to_numpy().tolist()[0][1:]\r\n #print(recom_ids)\r\n sim_scores = sim_records[titleids['title_id'] == ids].to_numpy().tolist()[0][1:]\r\n #print(recom_ids)\r\n for i in range(15):\r\n if recom_ids[i] in result:\r\n result[recom_ids[i]] += sim_scores[i]\r\n else:\r\n result[recom_ids[i]] = sim_scores[i]\r\n recom_list = sorted(list(result.keys()), key = lambda x: result[x], reverse = True)\r\n recom_movies = [titles.loc[titleids['title_id'] == recom_id, 'title'].tolist()[0] for recom_id in recom_list]\r\n for movie in recom_movies[:15]:\r\n print(movie)\r\n","repo_name":"What-s-Our-Team-Name/CSE5914FinalProject","sub_path":"haidong/name_recommendations.py","file_name":"name_recommendations.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41007555458","text":"# -*- coding: utf-8 -*-\n# -----------------------------------\n# @CreateTime : 2020/3/19 23:07\n# @Author : Mark Shawn\n# @Email : shawninjuly@gmail.com\n# ------------------------------------\nimport os\nimport logging\nimport random\nimport numpy as np\nfrom functools import partial\n\nfrom .common import lazy\n\n\nclass DataLoader:\n\tdef __init__(self, use_mp=True, shuffle=False, batch_size=256, split_ratio=0.9, seed=None):\n\t\tself.use_mp = use_mp\n\t\tself.shuffle = shuffle\n\t\tself.batch_size = batch_size\n\n\t\tself.split_ratio = split_ratio\n\t\tassert 0 <= split_ratio <= 1, \"训练集与验证集之间的切割比率要在0-1之间!\"\n\n\t\tself.seed = seed\n\t\tnp.random.seed(self.seed)\n\n\tdef _load_from_file(self, file_path, dtype=float):\n\t\tassert os.path.exists(file_path), \"目标文件不存在: {}\".format(os.path.abspath(file_path))\n\t\twith open(file_path, \"r\") as fp:\n\t\t\tlines = fp.readlines()\n\t\t\tif self.use_mp:\n\t\t\t\timport multiprocessing as mp\n\t\t\t\twith mp.Pool() as p:\n\t\t\t\t\tdata = np.array(p.map(partial(self._load_line, dtype=dtype), lines))\n\t\t\telse:\n\t\t\t\tdata = np.array(list(map(partial(self._load_line, dtype=dtype), lines)))\n\t\tlogging.info(\"Loaded data with shape {} from {}\".format(data.shape, os.path.abspath(file_path)))\n\t\treturn data\n\n\tdef load_X(self, file_path):\n\t\tself.X = self._load_from_file(file_path, dtype=float)\n\t\tself.N_items, self.N_features = self.X.shape\n\n\tdef load_Y(self, file_path):\n\t\tself.Y = self._load_from_file(file_path, dtype=int).flatten()\n\n\tdef load_XY(self, file_path):\n\t\tdata = self._load_from_file(file_path, dtype=float)\n\t\tself.X = data[:, :-1]\n\t\tself.N_items, self.N_features = self.X.shape\n\t\tself.Y = data[:, -1].astype(int)\n\n\t@lazy\n\tdef data(self):\n\t\t_data = np.hstack([self.X, self.Y.reshape(-1, 1)])\n\t\treturn _data\n\n\t@lazy\n\tdef X_to_valid(self):\n\t\treturn self.X[int(self.N_items * self.split_ratio):]\n\n\t@lazy\n\tdef Y_to_valid(self):\n\t\treturn self.Y[int(self.N_items * self.split_ratio):]\n\n\t@lazy\n\tdef N_to_train(self):\n\t\treturn int(self.N_items * self.split_ratio)\n\n\t@lazy\n\tdef _train_slice(self) -> list:\n\t\t\"\"\"\n\t\t使用数组的索引以操控shuffle\n\t\t预期可以比直接shuffle训练数据效率更高\n\n\t\t:return: 返回一个索引列表,该列表不包含验证集部分\n\t\t\"\"\"\n\t\tidx = list(range(self.N_items))\n\t\tif self.shuffle:\n\t\t\trandom.shuffle(idx)\n\t\treturn idx[: self.N_to_train]\n\n\t@staticmethod\n\tdef _load_line(line, delimiter=\",\", dtype=float):\n\t\treturn np.array(line.split(delimiter), dtype=dtype)\n\n\tdef __iter__(self):\n\t\tfor i in range(0, self.N_to_train, self.batch_size):\n\t\t\tyield self.X[self._train_slice[i: i + self.batch_size]], \\\n\t\t\t self.Y[self._train_slice[i: i + self.batch_size]]\n\n\tdef __len__(self):\n\t\treturn np.ceil(self.N_to_train / self.batch_size).astype(int).item()\n","repo_name":"winterf97/MachineLarning_Numpy_CodeCraft2020","sub_path":"core/dataloaders.py","file_name":"dataloaders.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"35659214064","text":"# import socket programming library \nimport socket \nimport struct \nfrom _thread import *\nimport threading \n\nprint_lock = threading.Lock() \n\n# thread fuction \ndef threaded_receive(c): \n\twhile True: \n\n\t\t# data received from client \n\t\tdata = c.recv(1024) \n\t\tif not data: \n\t\t\tprint('Bye') \n\t # lock released on exit \n\t\t\tprint_lock.release() \n\t\t\tbreak\n\t\tdata = data[2:]\n\t\tprint(\"\\nUser: \" + data.decode()) \n\n\t# connection closed \n\tc.close() \n\n\ndef threaded_send(c):\n\twhile True:\n\t\tmsg = input(\"\\n\")\n\t\tif msg is \"\\n\" :\n\t\t\tprint(\"ERROR\")\n\t\t\tbreak\n\t\t# msg = msg + \"\\n\"\n\t\tmsg = msg.encode(\"utf-8\", 'ignore')\n\t\tc.send(struct.pack(\"!H\", len(msg)))\n\t\tc.send(msg)\n\tc.close()\n\n\ndef Main(): \n\thost = \"10.147.148.105\" \n\n\t# reverse a port on your computer \n\t# in our case it is 12345 but it \n\t# can be anything \n\tport = int(input(\"Port ?\"))\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\ts.bind((host, port)) \n\tprint(\"socket binded to post\", port) \n\n\t# put the socket into listening mode \n\ts.listen(5) \n\tprint(\"socket is listening\") \n\n\t# a forever loop until client wants to exit \n\twhile True: \n\n\t\t# establish connection with client \n\t\tc, addr = s.accept() \n\n\t\t# lock acquired by client \n\t\tprint('Connected to :', addr[0], ':', addr[1]) \n\n\t\tprint_lock.acquire() \n\n\t\t# Start a new thread and return its identifier\n\t\tstart_new_thread(threaded_send,(c,))\n\t\tstart_new_thread(threaded_receive, (c,))\n\ts.close()\n\nif __name__ == '__main__': \n\tMain() \n","repo_name":"RKJenamani/J.A.R.V.I.C.","sub_path":"Front_end/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70818345106","text":"from datasets import Dataset\nfrom loguru import logger\n\n\ndef preprocess_squad_format(dataset: Dataset) -> Dataset:\n \"\"\"Preprocesses a dataset in SQuAD format (nested answers) to a dataset in SQuAD format that has flat answers.\n {\"answer\": {\"text\": \"answer\", \"start\": 0}} -> {\"text\": \"answer\"}\n\n Args:\n dataset (Dataset): A huggingface dataset in SQuAD format.\n\n Returns:\n Dataset: A huggingface dataset in SQuAD format with flat answers.\n \"\"\"\n\n def preprocess(example):\n if example[\"answers\"]:\n example[\"answers\"] = example[\"answers\"].pop()\n else:\n example[\"answers\"] = \"\"\n return example\n\n dataset = dataset.flatten().rename_column(\"answers.text\", \"answers\").map(preprocess)\n return dataset\n\n\ndef postprocess_squad_format(dataset: Dataset, add_answer_start: bool = True) -> Dataset:\n \"\"\"Postprocesses a dataset in SQuAD format (flat answers) to a dataset in SQuAD format that has nested answers.\n {\"text\": \"answer\"} -> {\"answer\": {\"text\": \"answer\", \"start\": 0}}\n\n Args:\n dataset (Dataset): A huggingface dataset in SQuAD format.\n add_answer_start (bool, optional): Whether to add the answer start index to the dataset. Defaults to True.\n\n Returns:\n Dataset: A huggingface dataset in SQuAD format with nested answers.\n \"\"\"\n # remove punctuation and whitespace from the start and end of the answer\n def remove_punctuation(example):\n example[\"answers\"] = example[\"answers\"].strip(\".,;!? \")\n return example\n\n dataset = dataset.map(remove_punctuation)\n\n if add_answer_start:\n dataset = dataset.map(calculate_answer_start)\n\n def unify_answers(example):\n is_answerable = \"answer_start\" in example\n if is_answerable:\n example[\"answers\"] = {\"text\": [example[\"answers\"]], \"answer_start\": [example[\"answer_start\"]]}\n else:\n example[\"answers\"] = {\"text\": [], \"answer_start\": []}\n return example\n\n dataset = dataset.map(unify_answers)\n if \"answer_start\" in dataset.column_names:\n dataset = dataset.remove_columns(\"answer_start\")\n return dataset\n\n\ndef calculate_answer_start(example):\n \"\"\"Calculates the answer start index for a SQuAD example.\n\n Args:\n example (Dict): A SQuAD example.\n\n Returns:\n Dict: The SQuAD example with the answer start index added.\n \"\"\"\n answer_start = example[\"context\"].lower().find(example[\"answers\"].lower())\n if answer_start < 0:\n logger.info(\n 'Could not calculate the answer start because the context \"{}\" ' 'does not contain the answer \"{}\".',\n example[\"context\"],\n example[\"answers\"],\n )\n answer_start = -1\n else:\n # check that the answer doesn't occur more than once in the context\n second_answer_start = example[\"context\"].lower().find(example[\"answers\"].lower(), answer_start + 1)\n if second_answer_start >= 0:\n logger.info(\"Could not calculate the answer start because the context contains the answer more than once.\")\n answer_start = -1\n else:\n # correct potential wrong capitalization of the answer compared to the context\n example[\"answers\"] = example[\"context\"][answer_start : answer_start + len(example[\"answers\"])]\n example[\"answer_start\"] = answer_start\n return example\n","repo_name":"flairNLP/fabricator","sub_path":"src/fabricator/dataset_transformations/question_answering.py","file_name":"question_answering.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"48"} +{"seq_id":"2444003286","text":"__author__ = \"Andrew Seitz\"\n\"\"\"\nMain iirc event loop. Hosts the relay and is responsible for launching irc modules.\n\"\"\"\n\nimport sys\n\nfrom twisted.internet import protocol, reactor\nfrom twisted.internet.endpoints import TCP4ServerEndpoint\nfrom twisted.internet.protocol import Factory\nfrom twisted.protocols import amp\nfrom twisted.protocols.basic import LineReceiver\nfrom twisted.python import log\n\nimport commands\nimport ircclient\n\n\nclass SupCommand(amp.Command):\n pass\n\n\nclass AMPProtocol(amp.AMP):\n \"\"\"Needs reference to own factory\"\"\"\n\n def __init__(self):\n self.ampFactory = None\n\n @commands.SupCommand.responder\n def sup(self):\n log.msg('got sup')\n return {}\n\n @commands.IRCSendRelayMSGLine.responder\n def cmdIRCSendRelayMSGLine(self, server, channel, user, message):\n user = user.split('!', 1)[0]\n\n line = 'msg {0} {1} {2} {3}'.format(server, channel, user, message)\n self.ampFactory.getRelay().sendLine(line)\n return {}\n\n @commands.IRCSendRelayInfoLine.responder\n def cmdIRCSendRelayInfoLine(self, message):\n self.ampFactory.getRelay().sendLine(message)\n return {}\n\n def connectionMade(self):\n self.ampFactory.setAMP(self)\n log.msg('Connection with amp server made, proto: ', self.ampFactory.getAMP())\n\n def connectionLost(self, reason):\n log.msg('AMP client disconnected')\n # tear everything down\n\n\nclass AMPFactory(protocol.ServerFactory):\n protocol = AMPProtocol\n\n \"\"\"Needs a reference to its current AMP and the Relay factory\"\"\"\n\n def __init__(self):\n self.amp = None\n self.relayFactory = None\n\n def buildProtocol(self, addr):\n self.amp = AMPProtocol()\n self.amp.ampFactory = self\n log.msg('AMP client spawned')\n return self.amp\n\n def getAMP(self):\n return self.amp\n\n def setAMP(self, ap):\n self.amp = ap\n\n def getRelay(self):\n return self.relayFactory.getRelay()\n\n def setRelayFactory(self, rf):\n self.relayFactory = rf\n\n def getRelayFactory(self):\n return self.relayFactory\n\n\nclass RelayProtocol(LineReceiver):\n def __init__(self):\n # self.relayFactory = rf\n # self.relayFactory.setRelay(self)\n self.relayFactory = None\n\n \"\"\"Wants a reference to its factory\"\"\"\n\n def connectionMade(self):\n self.relayFactory.setRelay(self)\n self.sendLine('Welcome to iirc')\n self.sendLine('Type \\'connectRate limit exceeded - you must wait at least 1798 seconds before we'll service this request.
Rate limit exceeded - please wait 1 minute before accessing more shortened URLs
Rate limit exceeded - ' in response.text:\n raise PleaseRetry()\n\n if \"
The full original link is shown below. Click the link if you'd like to proceed to the destination shown:\" in response.text:\n return self.parse_preview(response)\n if '
For reference and to help those fighting spam the original destination of this URL is given below \\(we strongly recommend you don't visit it since it may damage your PC\\): -
(.*)
is\\.gd is a free service used to shorten long URLs\\.\", response.text)\n if not match:\n raise errors.UnexpectedNoResult(\"Could not find target URL in 'Link Disabled' page\")\n\n url = match.group(1)\n url = html_parser.HTMLParser().unescape(url)\n if url == \"\":\n return (URLStatus.unavailable, None, None)\n return (URLStatus.ok, url, response.encoding)\n\n def parse_preview(self, response):\n response.encoding = 'utf-8'\n\n match = re.search(\"Click the link if you'd like to proceed to the destination shown: -
\", response.text)\n if not match:\n raise errors.UnexpectedNoResult(\"Could not find target URL in 'Preview' page\")\n\n url = match.group(1)\n return (URLStatus.ok, html_parser.HTMLParser().unescape(url), response.encoding)\n \n def process_phishing(self, response):\n if self._processing_phishing_page:\n raise errors.UnexpectedNoResult(\"Alreadying processing phishing page for %s\" % self.current_shortcode)\n \n self._processing_phishing_page = True\n time.sleep(1)\n \n match = re.search(r'', response.text)\n \n url = 'https://is.gd/cdn-cgi/phish-bypass?u=/{0}&atok={1}'.format(\n self.current_shortcode, match.group(1))\n \n response = self.fetch_url(url)\n return self.process_response(response)\n\n\nclass Isgd6Service(HashRandMixin, IsgdService):\n def get_shortcode_width(self):\n return 6\n","repo_name":"ArchiveTeam/terroroftinytown","sub_path":"terroroftinytown/services/isgd.py","file_name":"isgd.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"48"}
+{"seq_id":"6467611141","text":"from pyglfw.glfw import *\nimport vectormath\nfrom OpenGL.GLU import gluLookAt\nfrom math import atan2, pi\nfrom sound import sounds\n\nclass Camera: \n def __init__(self, x0, y0, z0, angleA0, angleB0): \n self.setCameraView(x0, y0, z0, angleA0, angleB0)\n self.target = None\n self.oldTargetPos = None\n self.delta = 10\n \n def setTarget(self, target):\n self.target = target\n def setCameraView(self, x, y, z, angleX, angleY): \n self.x = x \n self.y = y \n self.z = z \n self.angleX = angleX \n self.angleY = angleY \n\n def applyInputs(self, performance): \n moveSpeed = 5\n turnSpeed = 100\n mouseSPEEDmultiplier = 0.4\n deltaY = 0\n deltaX = 0\n\n if glfwGetKey(GLFW_KEY_UP):\n deltaX = +moveSpeed * performance \n if glfwGetKey(GLFW_KEY_DOWN): \n deltaX = -moveSpeed * performance \n if glfwGetKey(GLFW_KEY_LEFT): \n deltaY = -moveSpeed * performance \n if glfwGetKey(GLFW_KEY_RIGHT): \n deltaY = +moveSpeed * performance\n self.x += deltaX\n self.z += deltaY\n def draw(self):\n #set listener position at camera\n sounds.setListenerPosition((self.x, self.y, self.z))\n\n #target coord\n tx, ty, tz = self.target.body.getPosition()\n\n if self.oldTargetPos==None:\n self.oldTargetPos = tx, ty, tz\n \n gluLookAt(self.x, self.y, self.z, (tx+self.oldTargetPos[0])/2, (self.y+self.oldTargetPos[1])/2/3, (tz+self.oldTargetPos[2])/2, 0, 1, 0)\n self.oldTargetPos = tx, ty, tz\n\n v = vectormath.getVector((self.x, 0.0, self.z), (tx, 0.0, tz))\n self.angleY = -(atan2(v[2], v[0]) + pi/2)*180.0/pi","repo_name":"mmozeiko/Squares3D-prototype","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"30480108647","text":"\"\"\"\nAdopted from https://github.com/ziatdinovmax/atomai by Maxim Ziatdinov (maxim.ziatdinov@ai4microscopy.com)\n\"\"\"\n\nfrom typing import List, Union, Type\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom blocks import ConvBlock, ResModule, UpsampleBlock\n\n\nclass SegResNet(nn.Module):\n '''\n Builds a fully convolutional neural network based on residual blocks\n for semantic segmentation\n Args:\n nb_classes:\n Number of classes in the ground truth\n nb_filters:\n Number of filters in 1st residual block\n (gets multiplied by 2 in each next block)\n batch_norm:\n Use batch normalization after each convolutional layer\n (Default: True)\n upsampling_mode:\n Select between \"bilinear\" or \"nearest\" upsampling method.\n Bilinear is usually more accurate,but adds additional (small)\n randomness. For full reproducibility, consider using 'nearest'\n (this assumes that all other sources of randomness are fixed)\n **layers (list):\n 3-element list with a number of residual blocks\n in each residual segment (Default: [2, 2])\n '''\n def __init__(self,\n nb_classes: int = 1,\n nb_filters: int = 32,\n batch_norm: bool = True,\n upsampling_mode: str = \"bilinear\",\n **kwargs: List[int]\n ) -> None:\n '''\n Initializes module parameters\n '''\n super(SegResNet, self).__init__()\n nbl = kwargs.get(\"layers\", [2, 2, 2])\n self.c1 = ConvBlock(\n 2, 1, 1, nb_filters, batch_norm=batch_norm\n )\n self.c2 = ResModule(\n 2, nbl[0], nb_filters, nb_filters*2, batch_norm=batch_norm\n )\n self.bn = ResModule(\n 2, nbl[1], nb_filters*2, nb_filters*4, batch_norm=batch_norm\n )\n self.upsample_block1 = UpsampleBlock(\n 2, nb_filters*4, nb_filters*2, 2, upsampling_mode\n )\n self.c3 = ResModule(\n 2, nbl[2], nb_filters*4, nb_filters*2, batch_norm=batch_norm\n )\n self.upsample_block2 = UpsampleBlock(\n 2, nb_filters*2, nb_filters, 2, upsampling_mode\n )\n self.c4 = ConvBlock(\n 2, 1, nb_filters*2, nb_filters, batch_norm=batch_norm\n )\n self.px = nn.Conv2d(nb_filters, nb_classes, 1, 1, 0)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n '''Defines a forward pass'''\n # Contracting path\n c1 = self.c1(x)\n d1 = F.max_pool2d(c1, kernel_size=2, stride=2)\n c2 = self.c2(d1)\n d2 = F.max_pool2d(c2, kernel_size=2, stride=2)\n # Bottleneck\n bn = self.bn(d2)\n # Expanding path\n u2 = self.upsample_block1(bn)\n u2 = torch.cat([c2, u2], dim=1)\n u2 = self.c3(u2)\n u1 = self.upsample_block2(u2)\n u1 = torch.cat([c1, u1], dim=1)\n u1 = self.c4(u1)\n # pixel-wise classification\n px = self.px(u1)\n return px","repo_name":"navn1/atomfinder_skunkworks","sub_path":"model/fcn.py","file_name":"fcn.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"39545675100","text":"class MazeEnvironment:\n def __init__(self, maze: list):\n '''\n Initialization of the Maze Environment\n -------------\n maze : list\n List of list of c (clear) or w (wall) that represent the maze\n '''\n self.maze = maze\n self.num_rows = len(maze)\n self.num_columns = len(maze[0])\n\n # Available actions\n self.actions = ['up', 'down', 'left', 'right']\n\n # Status\n self.current = None\n self.previous = None\n\n self.terminal_state = (self.num_rows - 1, self.maze[-1].index('c'))\n\n def reset(self):\n '''\n Set state in the initial position.\n '''\n self.current = (0, 1) # Row 0, Column 1\n self.previous = None\n\n def step(self, action: str):\n \"\"\"\n Performs a movement in the environment and gets the new State and Reward\n ------------\n action : str\n One of the following actions: up, down, left, right\n \"\"\"\n self.current = self.move(action)\n\n return self.current, self.get_reward(), self.is_terminal_state()\n\n def move(self, action: str):\n \"\"\"\n Calculates the new State given a current State and an Action\n -----------\n action: str\n One of the following actions: up, down, left, right\n \"\"\"\n self.previous = self.current\n\n if action not in self.actions:\n raise Exception(f\"'{action}' is not a valid action!\")\n\n row = self.current[0]\n column = self.current[1]\n\n if action == 'up':\n return self.current if self.is_wall(row - 1, column) else (row - 1, column)\n elif action == 'down':\n return self.current if self.is_wall(row + 1, column) else (row + 1, column)\n elif action == 'left':\n return self.current if self.is_wall(row, column - 1) else (row, column - 1)\n elif action == 'right':\n return self.current if self.is_wall(row, column + 1) else (row, column + 1)\n\n def is_wall(self, row: int, column: int):\n '''\n Returns if the specific row, column is a wall of the Maze\n '''\n return self.maze[row][column] == 'w'\n\n def get_reward(self):\n \"\"\"\n Gets Reward of the last movement\n \"\"\"\n if self.is_terminal_state():\n return 500\n\n # Returns -2 if the movement was over a Wall, -1 in all other cases\n return -2 if self.previous == self.current else -1\n\n def is_terminal_state(self):\n '''\n If the State is in the last row, that means that is is in the exit\n '''\n return self.current[0] == self.num_rows - 1\n\n def set_state(self, row: int, column: int):\n \"\"\"\n Forces change to a specific state\n \"\"\"\n if not self.is_wall(row, column):\n self.current = (row, column)\n","repo_name":"juanmadlg/Generalized-Policy-Iteration","sub_path":"generalized_pollicy_iteration/maze_environment.py","file_name":"maze_environment.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"44814491946","text":"import glob as gb\nimport pandas as pd \n\n#Collect the Comments files in a list to parse\ncommentsFile = \"posts*\" #the string that all comments.pk files contain\nfileList = [] #the list where we will store the comments.pk files\n\nfor file in gb.glob(commentsFile): #compile a list of all the comments.pk files\n\tfileList.append(file)\n\ndf = pd.concat([pd.read_pickle(file) for file in fileList], axis=0) #concatenate all comments files into one comment file\ndf.to_pickle('./allposts.pk') ","repo_name":"kennymuli/Reddit","sub_path":"concatenate.py","file_name":"concatenate.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"31308539880","text":"import pytest\n\nimport numpy as np\n\nfrom mlagents.trainers.ghost.trainer import GhostTrainer\nfrom mlagents.trainers.ghost.controller import GhostController\nfrom mlagents.trainers.behavior_id_utils import BehaviorIdentifiers\nfrom mlagents.trainers.ppo.trainer import PPOTrainer\nfrom mlagents.trainers.agent_processor import AgentManagerQueue\nfrom mlagents.trainers.buffer import BufferKey, RewardSignalUtil\nfrom mlagents.trainers.tests import mock_brain as mb\nfrom mlagents.trainers.tests.mock_brain import copy_buffer_fields\nfrom mlagents.trainers.tests.test_trajectory import make_fake_trajectory\nfrom mlagents.trainers.settings import TrainerSettings, SelfPlaySettings\nfrom mlagents.trainers.tests.dummy_config import create_observation_specs_with_shapes\n\n\n@pytest.fixture\ndef dummy_config():\n return TrainerSettings(self_play=SelfPlaySettings())\n\n\nVECTOR_ACTION_SPACE = 1\nVECTOR_OBS_SPACE = 8\nDISCRETE_ACTION_SPACE = [3, 3, 3, 2]\nBUFFER_INIT_SAMPLES = 10241\nNUM_AGENTS = 12\n\n\n@pytest.mark.parametrize(\"use_discrete\", [True, False])\ndef test_load_and_set(dummy_config, use_discrete):\n mock_specs = mb.setup_test_behavior_specs(\n use_discrete,\n False,\n vector_action_space=DISCRETE_ACTION_SPACE\n if use_discrete\n else VECTOR_ACTION_SPACE,\n vector_obs_space=VECTOR_OBS_SPACE,\n )\n\n trainer_params = dummy_config\n trainer = PPOTrainer(\"test\", 0, trainer_params, True, False, 0, \"0\")\n trainer.seed = 1\n policy = trainer.create_policy(\"test\", mock_specs)\n trainer.seed = 20 # otherwise graphs are the same\n to_load_policy = trainer.create_policy(\"test\", mock_specs)\n\n weights = policy.get_weights()\n load_weights = to_load_policy.get_weights()\n try:\n for w, lw in zip(weights, load_weights):\n np.testing.assert_array_equal(w, lw)\n except AssertionError:\n pass\n\n to_load_policy.load_weights(weights)\n load_weights = to_load_policy.get_weights()\n\n for w, lw in zip(weights, load_weights):\n np.testing.assert_array_equal(w, lw)\n\n\ndef test_resume(dummy_config, tmp_path):\n mock_specs = mb.setup_test_behavior_specs(\n True, False, vector_action_space=[2], vector_obs_space=1\n )\n behavior_id_team0 = \"test_brain?team=0\"\n behavior_id_team1 = \"test_brain?team=1\"\n brain_name = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0).brain_name\n tmp_path = tmp_path.as_posix()\n ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, tmp_path)\n controller = GhostController(100)\n trainer = GhostTrainer(\n ppo_trainer, brain_name, controller, 0, dummy_config, True, tmp_path\n )\n\n parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0)\n policy = trainer.create_policy(parsed_behavior_id0, mock_specs)\n trainer.add_policy(parsed_behavior_id0, policy)\n\n parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team1)\n policy = trainer.create_policy(parsed_behavior_id1, mock_specs)\n trainer.add_policy(parsed_behavior_id1, policy)\n\n trainer.save_model()\n\n # Make a new trainer, check that the policies are the same\n ppo_trainer2 = PPOTrainer(brain_name, 0, dummy_config, True, True, 0, tmp_path)\n trainer2 = GhostTrainer(\n ppo_trainer2, brain_name, controller, 0, dummy_config, True, tmp_path\n )\n policy = trainer2.create_policy(parsed_behavior_id0, mock_specs)\n trainer2.add_policy(parsed_behavior_id0, policy)\n\n policy = trainer2.create_policy(parsed_behavior_id1, mock_specs)\n trainer2.add_policy(parsed_behavior_id1, policy)\n\n trainer1_policy = trainer.get_policy(parsed_behavior_id1.behavior_id)\n trainer2_policy = trainer2.get_policy(parsed_behavior_id1.behavior_id)\n weights = trainer1_policy.get_weights()\n weights2 = trainer2_policy.get_weights()\n\n for w, lw in zip(weights, weights2):\n np.testing.assert_array_equal(w, lw)\n\n\ndef test_process_trajectory(dummy_config):\n mock_specs = mb.setup_test_behavior_specs(\n True, False, vector_action_space=[2], vector_obs_space=1\n )\n behavior_id_team0 = \"test_brain?team=0\"\n behavior_id_team1 = \"test_brain?team=1\"\n brain_name = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0).brain_name\n\n ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, \"0\")\n controller = GhostController(100)\n trainer = GhostTrainer(\n ppo_trainer, brain_name, controller, 0, dummy_config, True, \"0\"\n )\n\n # first policy encountered becomes policy trained by wrapped PPO\n parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0)\n policy = trainer.create_policy(parsed_behavior_id0, mock_specs)\n trainer.add_policy(parsed_behavior_id0, policy)\n trajectory_queue0 = AgentManagerQueue(behavior_id_team0)\n trainer.subscribe_trajectory_queue(trajectory_queue0)\n\n # Ghost trainer should ignore this queue because off policy\n parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team1)\n policy = trainer.create_policy(parsed_behavior_id1, mock_specs)\n trainer.add_policy(parsed_behavior_id1, policy)\n trajectory_queue1 = AgentManagerQueue(behavior_id_team1)\n trainer.subscribe_trajectory_queue(trajectory_queue1)\n\n time_horizon = 15\n trajectory = make_fake_trajectory(\n length=time_horizon,\n max_step_complete=True,\n observation_specs=create_observation_specs_with_shapes([(1,)]),\n action_spec=mock_specs.action_spec,\n )\n trajectory_queue0.put(trajectory)\n trainer.advance()\n\n # Check that trainer put trajectory in update buffer\n assert trainer.trainer.update_buffer.num_experiences == 15\n\n trajectory_queue1.put(trajectory)\n trainer.advance()\n\n # Check that ghost trainer ignored off policy queue\n assert trainer.trainer.update_buffer.num_experiences == 15\n # Check that it emptied the queue\n assert trajectory_queue1.empty()\n\n\ndef test_publish_queue(dummy_config):\n mock_specs = mb.setup_test_behavior_specs(\n True, False, vector_action_space=[1], vector_obs_space=8\n )\n\n behavior_id_team0 = \"test_brain?team=0\"\n behavior_id_team1 = \"test_brain?team=1\"\n\n parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0)\n\n brain_name = parsed_behavior_id0.brain_name\n\n ppo_trainer = PPOTrainer(brain_name, 0, dummy_config, True, False, 0, \"0\")\n controller = GhostController(100)\n trainer = GhostTrainer(\n ppo_trainer, brain_name, controller, 0, dummy_config, True, \"0\"\n )\n\n # First policy encountered becomes policy trained by wrapped PPO\n # This queue should remain empty after swap snapshot\n policy = trainer.create_policy(parsed_behavior_id0, mock_specs)\n trainer.add_policy(parsed_behavior_id0, policy)\n policy_queue0 = AgentManagerQueue(behavior_id_team0)\n trainer.publish_policy_queue(policy_queue0)\n\n # Ghost trainer should use this queue for ghost policy swap\n parsed_behavior_id1 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team1)\n policy = trainer.create_policy(parsed_behavior_id1, mock_specs)\n trainer.add_policy(parsed_behavior_id1, policy)\n policy_queue1 = AgentManagerQueue(behavior_id_team1)\n trainer.publish_policy_queue(policy_queue1)\n\n # check ghost trainer swap pushes to ghost queue and not trainer\n assert policy_queue0.empty() and policy_queue1.empty()\n trainer._swap_snapshots()\n assert policy_queue0.empty() and not policy_queue1.empty()\n # clear\n policy_queue1.get_nowait()\n\n buffer = mb.simulate_rollout(BUFFER_INIT_SAMPLES, mock_specs)\n # Mock out reward signal eval\n copy_buffer_fields(\n buffer,\n src_key=BufferKey.ENVIRONMENT_REWARDS,\n dst_keys=[\n BufferKey.ADVANTAGES,\n RewardSignalUtil.rewards_key(\"extrinsic\"),\n RewardSignalUtil.returns_key(\"extrinsic\"),\n RewardSignalUtil.value_estimates_key(\"extrinsic\"),\n RewardSignalUtil.rewards_key(\"curiosity\"),\n RewardSignalUtil.returns_key(\"curiosity\"),\n RewardSignalUtil.value_estimates_key(\"curiosity\"),\n ],\n )\n\n trainer.trainer.update_buffer = buffer\n\n # when ghost trainer advance and wrapped trainer buffers full\n # the wrapped trainer pushes updated policy to correct queue\n assert policy_queue0.empty() and policy_queue1.empty()\n trainer.advance()\n assert not policy_queue0.empty() and policy_queue1.empty()\n\n\nif __name__ == \"__main__\":\n pytest.main()\n","repo_name":"Unity-Technologies/ml-agents","sub_path":"ml-agents/mlagents/trainers/tests/torch_entities/test_ghost.py","file_name":"test_ghost.py","file_ext":"py","file_size_in_byte":8529,"program_lang":"python","lang":"en","doc_type":"code","stars":15647,"dataset":"github-code","pt":"48"}
+{"seq_id":"5002174459","text":"# USAGE\n# python reading_from_memory.py\n\n# import the necessary packages\nfrom pyimagesearch.helpers import benchmark\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.datasets import cifar100\nfrom tensorflow.data import AUTOTUNE\nimport tensorflow as tf\n\n# initialize the batch size and number of steps\nBS = 64\nNUM_STEPS = 5000\n\n# load the CIFAR-10 dataset from\nprint(\"[INFO] loading the cifar100 dataset...\")\n((trainX, trainY), (testX, testY)) = cifar100.load_data()\n\n# create a standard image generator object\nprint(\"[INFO] creating a ImageDataGenerator object...\")\nimageGen = ImageDataGenerator()\ndataGen = imageGen.flow(\n\tx=trainX, y=trainY,\n\tbatch_size=BS, shuffle=True)\n\n# build a TensorFlow dataset from the training data\ndataset = tf.data.Dataset.from_tensor_slices((trainX, trainY))\n\n# build the data input pipeline\nprint(\"[INFO] creating a tf.data input pipeline..\")\ndataset = (dataset\n\t.shuffle(1024)\n\t.cache()\n\t.repeat()\n\t.batch(BS)\n\t.prefetch(AUTOTUNE)\n)\n\n# benchmark the image data generator and display the number of data\n# points generated, along with the time taken to perform the\n# operation\ntotalTime = benchmark(dataGen, NUM_STEPS)\nprint(\"[INFO] ImageDataGenerator generated {} images in \" \\\n\t \" {:.2f} seconds...\".format(\n\tBS * NUM_STEPS, totalTime))\n\n# create a dataset iterator, benchmark the tf.data pipeline, and\n# display the number of data points generator along with the time taken\ndatasetGen = iter(dataset)\ntotalTime = benchmark(datasetGen, NUM_STEPS)\nprint(\"[INFO] tf.data generated {} images in {:.2f} seconds...\".format(\n\tBS * NUM_STEPS, totalTime))","repo_name":"marb61a/Course-Notes","sub_path":"Artificial Intellingence/Python/Notebooks/PyImageSearch University/Deep Learning 125/tfdata-intro/reading_from_memory.py","file_name":"reading_from_memory.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"6351397824","text":"import pytest\nfrom django.conf import settings\n\nfrom kubeportal.models.portalgroup import PortalGroup\n\n\n@pytest.mark.django_db\ndef test_single_group_denied(api_client_anon, admin_group):\n url = f'/api/{settings.API_VERSION}/groups/{admin_group.pk}/'\n response = api_client_anon.get(url)\n assert response.status_code == 401\n\n\n@pytest.mark.django_db\ndef test_groups_denied(api_client_anon):\n group1 = PortalGroup(name=\"group1\")\n group1.save()\n response = api_client_anon.get(f'/api/{settings.API_VERSION}/groups/{group1.pk}/')\n assert response.status_code == 401\n\n\ndef test_group(api_client, admin_group):\n response = api_client.get(f'/api/{settings.API_VERSION}/groups/{admin_group.pk}/')\n assert response.status_code == 200\n\n data = response.json()\n assert data['name'] == admin_group.name\n\n\ndef test_group_invalid_id(api_client):\n response = api_client.get(f'/api/{settings.API_VERSION}/groups/777/')\n assert response.status_code == 404\n\n\ndef test_group_non_member(api_client):\n group1 = PortalGroup(name=\"group1\")\n group1.save()\n response = api_client.get(f'/api/{settings.API_VERSION}/groups/{group1.pk}/')\n assert response.status_code == 404","repo_name":"kubeportal/kubeportal","sub_path":"kubeportal/tests/test_api_groups.py","file_name":"test_api_groups.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"}
+{"seq_id":"9938531735","text":"from flask import Flask, render_template, request\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport joblib\nfrom sklearn.ensemble import VotingRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\n\n\n\n# One hot encode the 'coin_name' feature\n# data = pd.get_dummies(data, columns=['coin_name'])\n\n\n# Create a Flask instance\napp = Flask(__name__)\n\n# Define the index page\n@app.route('/')\ndef index():\n return render_template('./index.html')\n\n# Define the predict page\n@app.route('/predict', methods=['POST'])\ndef predict():\n try:\n open = float(request.form['open']) if request.form['open'] else 0.0\n high = float(request.form['high']) if request.form['high'] else 0.0\n low = float(request.form['low']) if request.form['low'] else 0.0\n date = request.form['date'] if request.form['date'] else 0.0\n volume = float(request.form['volume']) if request.form['volume'] else 0.0\n coin_name = str(request.form['coin_name'])\n\n # rest of the code for prediction\n \n except Exception as e:\n x = (\"Error: {}\".format(str(e)))\n return render_template('index.html', data=x)\n\n\n\n # output validation\n if not coin_name or not open or not high or not low or not date or not volume:\n return render_template('index.html', data = \"Please fill out all fields.\")\n else:\n\n\n\n #Creating a data dictionary\n data_dict = {'Date': [date],'Open': [open], 'High': [high], 'Low': [low], 'Volume': [volume],\n 'ADA_GBP': [0], 'ATOM_GBP': [1], 'AVAX_GBP': [0], 'BNB_GBP': [0], 'BTC_GBP': [0], 'DAI_GBP': [0],\n 'DOGE_GBP': [0], 'DOT_GBP': [0], 'ETH_GBP': [0], 'FIL_GBP': [0], 'FTM_GBP': [0], 'GRC_GBP': [0],\n 'LINK_GBP': [0], 'LTC_GBP': [0], 'MATIC_GBP': [0], 'SOL_GBP': [0], 'TRX_GBP': [0], 'USDC_GBP': [0],\n 'USDT_GBP': [0], 'XRP_GBP': [0]}\n\n data_dict[coin_name] = [1]\n # create a new DataFrame with the same columns as the training data\n new_data = pd.DataFrame(data_dict)\n # convert the date column to a datetime data type\n new_data['Date'] = pd.to_datetime(new_data['Date'])\n # convert the date column to a float data type using Unix time (seconds since 1970-01-01)\n new_data['Date'] = (new_data['Date'] - pd.Timestamp(\"1970-01-01\")) // pd.Timedelta('1s')\n new_data['Date'] = new_data['Date'].astype(float)\n\n # make a prediction using the ensemble model\n model = joblib.load('ensemble.sav')\n close_price = (f\"CLOSE: {model.predict(new_data)[0]}\")\n \n\n # Return the prediction to the user\n return render_template('index.html', data=close_price)\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"C4LEB-ai/stock_prediction","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"25334765483","text":"from random import randint\n\ndef solve(lock: str) -> str:\n num_list = sorted(lock, reverse=True)\n final_mod = int(lock) % 3\n\n if final_mod != 0:\n mod1_index = None\n mod2_indices = []\n\n for i in reversed(range(len(num_list))):\n num = int(num_list[i])\n current_mod = num % 3\n\n if current_mod == final_mod:\n mod1_index = i\n break\n elif current_mod != 0 and len(mod2_indices) < 2:\n mod2_indices.append(i)\n \n if mod1_index:\n num_list.pop(mod1_index)\n elif mod2_indices:\n num_list.pop(mod2_indices[0])\n num_list.pop(mod2_indices[1])\n\n return ''.join(num_list)\n\nstart = 11\nfor i in range(start, start + 20):\n inp = open('inp/' + str(i), 'w')\n out = open('out/' + str(i), 'w')\n\n inp_text = []\n for i in range(randint(3, 10**5)):\n inp_text.append(str(randint(0, 9)))\n\n inp_text = ''.join(inp_text)\n inp.write(inp_text)\n out_text = solve(inp_text) + '\\n'\n out.write(out_text)","repo_name":"thinhntr/CS112.L12.KHCL","sub_path":"bt5/khoa_so/test_generator.py","file_name":"test_generator.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"42141016614","text":"#\r\r\n# Home Automation Hub\r\r\n# Helper Script to process different Actuator Types\r\r\n#\r\r\n# Catching too general exception\r\r\n# pylint: disable=W0703\r\r\n#\r\r\n\"\"\"Actuator helpers\"\"\"\r\r\n\r\r\nimport sys\r\r\nimport logging\r\r\nimport RPi.GPIO as GPIO\r\r\n\r\r\n\r\r\n# --- Global Variables ---\r\r\nHUB_LOGGER = logging.getLogger('HubLogger')\r\r\n\r\r\n# BCM Pin References\r\r\nGPIO.setmode(GPIO.BCM)\r\r\nGPIO.setwarnings(False)\r\r\n\r\r\n\r\r\ndef simple_on_off(cur_val, method_params):\r\r\n\r\r\n \"\"\"Simple On/Off\"\"\"\r\r\n\r\r\n try:\r\r\n\r\r\n bcm_pin = int(method_params[0])\r\r\n HUB_LOGGER.debug(\"In simple_on_off %s %s \", cur_val, bcm_pin)\r\r\n status = -1\r\r\n if bcm_pin is not None:\r\r\n func = GPIO.gpio_function(bcm_pin)\r\r\n is_output = (func == GPIO.OUT)\r\r\n HUB_LOGGER.debug(\"Pin Mode %s %s %s\", func, GPIO.OUT, is_output)\r\r\n\r\r\n HUB_LOGGER.debug(\"Making Output always\")\r\r\n GPIO.setup(bcm_pin, GPIO.OUT)\r\r\n\r\r\n result = (cur_val > 0)\r\r\n cur_state = GPIO.input(bcm_pin)\r\r\n requires_changing = (GPIO.input(bcm_pin) != cur_val)\r\r\n HUB_LOGGER.debug(\r\r\n \"Reading Output %d = %s requires_changing? %s\",\r\r\n bcm_pin,\r\r\n cur_state,\r\r\n requires_changing)\r\r\n\r\r\n # turn on/off?\r\r\n if requires_changing:\r\r\n HUB_LOGGER.debug(\r\r\n \"Setting Output %d to %s ...\",\r\r\n bcm_pin,\r\r\n result)\r\r\n GPIO.output(bcm_pin, result)\r\r\n status = result\r\r\n\r\r\n return status\r\r\n\r\r\n except Exception:\r\r\n HUB_LOGGER.error(\"Error in simple_on_off\")\r\r\n etype = sys.exc_info()[0]\r\r\n value = sys.exc_info()[1]\r\r\n trace = sys.exc_info()[2]\r\r\n line = trace.tb_lineno\r\r\n HUB_LOGGER.error(\"%s %s %s\", etype, value, line)\r\r\n","repo_name":"paul-warren-hub/home-hub","sub_path":"code/controller/actuator_helpers/simple_on_off.py","file_name":"simple_on_off.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"22859107309","text":"def overlaps(a, b):\n if a[1] >= b[0] and a[0] <= b[1]:\n return True\n if b[1] >= a[0] and b[0] <= a[1]:\n return True\n return False\n\n\ndef parse_range(range):\n range = range.split(\"-\")\n return [int(range[0]), int(range[1])]\n\n\ncontained_count = 0\n\nwith open(\"input.txt\") as file:\n for line in file:\n ranges = line.strip().split(\",\")\n\n a = parse_range(ranges[0])\n b = parse_range(ranges[1])\n\n if overlaps(a, b):\n contained_count += 1\n\nprint(contained_count)\n","repo_name":"Pysselbit/advent-of-code-2022","sub_path":"Calendar/Day 4 - Camp Cleanup/4-B.py","file_name":"4-B.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"25255859646","text":"#!/usr/bin/python3\n\n# dlicv\n\nimport argparse as _argparse\nimport os as _os\nimport urllib.request\nfrom urllib.parse import urlparse\nimport zipfile\nimport sys as _sys\n\n##############################################################\n## This is a dictionary that keeps the saved models for now\nmdlurl = 'https://github.com/CBICA/DeepMRSeg-Models/raw/main/models'\n\nmodelDict = {}\nmodelDict['dlicv'] = mdlurl + '/DLICV/DeepMRSeg_DLICV_v1.0.zip'\n\n##############################################################\n\n## Path to saved models\nDEEPMRSEG = _os.path.expanduser(_os.path.join('~', '.dlicv'))\nMDL_DIR = _os.path.join(DEEPMRSEG, 'trained_models')\n\ndef _main():\n \"\"\"Main program for the script to download pre-trained models.\"\"\"\n \n argv = _sys.argv\n\n exeName = _os.path.basename(argv[0])\n\n descTxt = '{prog} downloads pre-trained DLICV model'.format(prog=exeName)\n\n ## Download model\n mdl_type = 'dlicv'\n\n mdlurl = modelDict[mdl_type]\n mdlfname = _os.path.basename(urlparse(mdlurl).path)\n outFile = _os.path.join(MDL_DIR , mdl_type, mdlfname)\n\n if _os.path.isdir(outFile.replace('.zip', '')):\n print(\"Model already downloaded: \" + outFile.replace('.zip', ''))\n\n else:\n print(\"Loading model: \" + mdl_type)\n\n outPath = _os.path.join(MDL_DIR , mdl_type)\n if not _os.path.exists(outPath):\n _os.makedirs(outPath)\n print('Created dir : ' + outPath)\n\n urllib.request.urlretrieve(mdlurl, outFile)\n print('Downloaded model : ' + outFile)\n\n with zipfile.ZipFile(outFile, 'r') as fzip:\n fzip.extractall(outPath)\n print('Unzipped model : ' + outFile.replace('.zip', ''))\n\n _os.remove(outFile)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gurayerus/DLICV","sub_path":"DLICV/dlicv_downloadmodel.py","file_name":"dlicv_downloadmodel.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"11963326872","text":"import csv\nimport sys\nimport random\nimport cv2\nfrom gaskLibs.utils.segaug import ImgAugTransform\nfrom torch.utils.data.dataset import Dataset\n\nsys.path.insert(0, '..')\n\n\nclass ImageDataset(Dataset):\n def __init__(self, csv_path, img_size, is_aug):\n super().__init__()\n self.img_path = []\n self.labels = []\n self.transform = ImgAugTransform()\n self.isaug = is_aug\n self.img_w = img_size[0]\n self.img_h = img_size[1]\n\n with open(csv_path, newline='') as csvfile:\n rows = csv.reader(csvfile)\n _ = next(rows)\n for row in rows:\n self.img_path.append(row[0])\n self.labels.append(row[1])\n\n def __getitem__(self, index):\n\n img = cv2.imread(self.img_path[index])\n img = cv2.resize(img, (self.img_w, self.img_h))\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n img_map = cv2.imread(self.labels[index])\n img_map = cv2.resize(img_map, (self.img_w, self.img_h))\n\n # pixel label to class label\n img_map = img_map / 255\n img_map = img_map.astype(int)\n\n if self.isaug:\n j = random.randint(0, 4)\n img_tensor, map_tensor = self.transform(img, img_map, j)\n\n else:\n img_tensor, map_tensor = self.transform(img, img_map, 3)\n\n return img_tensor, map_tensor\n\n def __len__(self):\n return len(self.labels)\n","repo_name":"GuffreyKu/image-segmentation","sub_path":"train_python/PTdata/Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"73747475344","text":"import tweepy\nimport re\nimport csv\nimport os\nimport sys\nfrom pandas import DataFrame\n\nclass CreateTweetsCsv():\n\n def __init__(self,tweets_csv_file_path,logger,tweet_cursor,last_id_logged=None) -> None:\n self.tweets_csv_file_path = tweets_csv_file_path\n self.logger = logger\n self.last_id_logged = last_id_logged\n self.tweet_cursor = tweet_cursor\n\n def MakeCsvFile(self) -> bool:\n write_to_file = False\n if os.path.exists(self.tweets_csv_file_path):\n self.logger.info(\"Writing to file(s) ....\")\n write_to_file=True\n else:\n with open(self.tweets_csv_file_path,\"a+\") as tweets_csv_file:\n writer = csv.DictWriter(tweets_csv_file,fieldnames=[\"Tweet\",\"Reply\"])\n writer.writeheader()\n self.logger.info(\"File created ...\\nWriting to file(s) ....\")\n write_to_file = True\n\n print(\"Writing to file(s) ....\")\n\n return write_to_file\n\n def GetTweetsAndReplies(self, api, use_keywords=None):\n regex_str = \"@\\S*[^\\s]|RT |\\S*https?:\\S*|(\\n+)(?=.*)\"\n pattern = re.compile(regex_str) \n\n if self.MakeCsvFile():\n # Search for a tweet on the timeline\n # Find the replies\n try:\n self.records_added = 0\n self.current_since_id,tweet_text,reply_text= None,None,None\n # Alter the number of items to be returned\n for tweet in self.tweet_cursor.items():\n\n if use_keywords:\n replies = tweepy.Cursor(api.search,\n q='to:{} -filter:retweets'.format(tweet.user.screen_name),\n tweet_mode='extended').items(10)\n\n else:\n replies = tweepy.Cursor(api.search,\n tweet_mode='extended',\n q='to:{} -filter:retweets'.format(tweet.user.screen_name),\n include_entities=False).items(100)\n\n\n tweet_data = {\"Tweet\":[], \"Reply\":[]}\n\n try:\n for reply in replies:\n if reply.in_reply_to_status_id==tweet.id:\n # use full_text instead of text because of tweet mode extend\n tweet_text = pattern.sub('', tweet.full_text)\n else:\n if reply.in_reply_to_status_id != None:\n # Find the original tweets for the replies without\n tweetFetched = api.get_status(reply.in_reply_to_status_id,\n include_entities=False)\n tweet_text = tweetFetched.text\n tweet_text = pattern.sub('', tweet_text)\n \n reply_text = pattern.sub('', reply.full_text)\n if (tweet_text != None) & (reply_text != None):\n tweet_data[\"Tweet\"].append(tweet_text)\n tweet_data[\"Reply\"].append(reply_text)\n # Combine them all into one df\n data = DataFrame(tweet_data).drop_duplicates()\n data.to_csv(self.tweets_csv_file_path,\n mode = 'a',\n header = None,\n index = False)\n \n # Get the amount of data recieved\n self.records_added += len(data)\n # Save the last tweet id retreived\n self.current_since_id = tweet.id\n\n\n except tweepy.error.TweepError as er:\n # Log the specific errors if need be\n self.logger.error(\"TWEEPY ERROR: \",er)\n continue\n \n except Exception as e:\n self.logger.exception(e)\n self.logger.info(\"Number of entries added : \"+str(self.records_added))\n if self.current_since_id:\n self.logger.info(\"ID of last retrieved tweet before the error above: \"+str(self.current_since_id ))\n else:\n # If it hasn't completed the loop successfully even once\n self.logger.info(\"ID of last retrieved tweet before the error above: \"+str(self.last_id_logged ))\n\n\n self.logger.info(\"Number of entries added : \"+str(self.records_added))\n # Make these the last entry for easy retreival \n self.logger.info(\"ID of last retrieved tweet: \"+str(self.current_since_id ))\n\n except KeyboardInterrupt:\n # These will log the last values assigned before the interrupt\n self.logger.info(\"Number of entries added before KeybordInterrupt: \"+str(self.records_added))\n \n # if it had run through a complete cycle for tweet replies at least once\n if self.current_since_id:\n self.logger.info(\"ID of last retrieved tweet before KeybordInterrupt: \"+str(self.current_since_id ))\n else:\n # If it hasn't completed the loop successfully even once\n self.logger.info(\"ID of last retrieved tweet before KeybordInterrupt: \"+str(self.last_id_logged ))\n \n \n sys.exit(0)\n\n\n else:\n self.logger.critical(\" Could Not find/create csv file to write to\")\n \n ","repo_name":"AsetaShadrach/KenyaNLP","sub_path":"TweetCollection/GetTweets.py","file_name":"GetTweets.py","file_ext":"py","file_size_in_byte":5918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"33070288276","text":"import unittest\nfrom q1python import period_generator\n\n# CRITERIA:\n# All periods and data points must be whole numbers\n# There can only ever be a maximum of 10 periods\n# Each point represents one second - a period may be no longer than 10 seconds\n# Each period must contain between one and 10 data points\n# Points must be stored in time order, with the earliest listed first\n\nlist1 = [1, 5, 6, 10, 11, 20, 21, 25, 26, 40, 41, 50]\n\nlist2 = [14, 9, 24, 2, 44, 8, 41, 4, 46, 26,\n 11, 31, 18, 24, 21, 4, 22, 50, 6, 36]\n\n\nclass TestPeriodGenerator(unittest.TestCase):\n\n # the result of this test depends on the values of list1 and list2\n def test_all_periods_and_data_points_whole_numbers(self):\n periods = period_generator(list1, list2)\n\n # all periods integers\n self.assertTrue(all(isinstance(period.start, int) and isinstance(\n period.end, int) for period in periods))\n\n # all points integers\n self.assertTrue(all(all(isinstance(point, int)\n for point in period.points) for period in periods))\n\n # similarly, the result of this test depends on the amount of values in list1\n def test_max_of_ten_periods(self):\n periods = period_generator(list1, list2)\n\n self.assertTrue(len(periods) <= 10)\n\n # similarly, the result of this test depends on the values of list1\n def test_period_no_longer_than_ten_secs(self):\n periods = period_generator(list1, list2)\n\n for period in periods:\n print((period.end - period.start))\n\n self.assertTrue(all((period.end - period.start) <=\n 10 for period in periods))\n\n def test_each_period_contains_between_one_and_ten_data_points(self):\n periods = period_generator(list1, list2)\n\n self.assertTrue(all(1 <= len(period.points)\n <= 10 for period in periods))\n\n def test_points_ordered_by_ascending(self):\n periods = period_generator(list1, list2)\n\n def list_is_ascending(list):\n output = True\n for i in range(len(list) - 1):\n if list[i+1] < list[i]:\n output = False\n return output\n\n self.assertTrue(all(list_is_ascending(period.points)\n for period in periods))\n\n# the program will NOT pass with the data set provided, due to the 3rd criteria (that a period can be no longer than 10 seconds),\n# as the penultimate period has a gap of 14 seconds (between 26 and 40)\n","repo_name":"Harrison-Hughes/anthesis-code-task","sub_path":"q2testing.py","file_name":"q2testing.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"71054722067","text":"\r\n# Aluna Diana Faustino de Siqueira\r\n# Exercícios aula 17\r\n\r\nconta = 0\r\nfrutas = []\r\nn = int(input())\r\nm = int(input())\r\n\r\nfor i in range(m):\r\n nome,preco = input().split()\r\n feira = {'nome':nome,'preco':float(preco)}\r\n frutas.append(feira)\r\n\r\np = int(input())\r\n\r\nfor j in range(p):\r\n nome,quantidade = input().split()\r\n quantidade = int(quantidade)\r\n\r\n for k in frutas:\r\n if k['nome'] == nome:\r\n conta += k['preco']*quantidade\r\nprint(f'R$ {conta:.2f}')","repo_name":"dexeme/uri-solutions","sub_path":"URI_1281.py","file_name":"URI_1281.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"34693609124","text":"\"\"\"empty message\n\nRevision ID: 263dec48ea7f\nRevises: \nCreate Date: 2022-08-23 12:23:44.461815\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '263dec48ea7f'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('users',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('name', sa.String(length=20), nullable=False),\n sa.Column('user_id', sa.String(length=20), nullable=False),\n sa.Column('email', sa.String(length=120), nullable=False),\n sa.Column('password', sa.String(length=255), nullable=False),\n sa.Column('birth', sa.DateTime(), nullable=False),\n sa.Column('alergy_dai', sa.Integer(), nullable=True),\n sa.Column('alergy_cru', sa.Integer(), nullable=True),\n sa.Column('alergy_nut', sa.Integer(), nullable=True),\n sa.Column('alergy_pch', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('name'),\n sa.UniqueConstraint('user_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('users')\n # ### end Alembic commands ###\n","repo_name":"Kogoon/fantastic-bassoon","sub_path":"migrations/versions/263dec48ea7f_.py","file_name":"263dec48ea7f_.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"5578539383","text":"import cv2\nimport os\nimport pandas as pd\nfrom tqdm import tqdm\n\n\ndef split_ldr(root, size):\n for file in tqdm(os.listdir(root)):\n\n imgroot = os.path.join(root, file)\n image = cv2.imread(imgroot)\n\n height = image.shape[0]\n width = image.shape[1]\n\n file = file.split('.')[0]\n for y in range(0, height, size):\n for x in range(0, width, size):\n tiles = image[y:y + size, x:x + size]\n if (tiles.shape[0] == size) and (tiles.shape[1] == size):\n cv2.imwrite('data/train/split_img' + '/' + file + str(x) + '2' + str(y) + \".jpg\", tiles)\n #os.remove(root + '/input_2_aligned.tif')\n\n\ndef split_hdr(root, size):\n for file in tqdm(os.listdir(root)):\n imgroot = os.path.join(root, file)\n image = cv2.imread(imgroot, cv2.IMREAD_ANYDEPTH)\n\n height = image.shape[0]\n width = image.shape[1]\n\n file = file.split('.')[0]\n for y in range(0, height, size):\n for x in range(0, width, size):\n tiles = image[y:y + size, x:x + size]\n if (tiles.shape[0] == size) and (tiles.shape[1] == size):\n cv2.imwrite('data/train/split_img' + '/' + file + str(x) + '2' + str(y) + \".hdr\", tiles)\n #os.remove(root + '/ref_hdr_aligned.hdr')\n\n\nif __name__ == '__main__':\n #for file in tqdm(os.listdir('data/train/LDR')):\n #split_ldr('data/train/LDR', size=256)\n #for file in tqdm(os.listdir('data/train/HDR')):\n #split_hdr('data/train/HDR', size=256)\n\n df = pd.DataFrame()\n f = open('data/test/annotations.txt', 'w+')\n path = 'data/test/image_split'\n\n name_list = list()\n for file in os.listdir(path):\n name = file.split('.')[0]\n #name = name.split('_')[1]\n if name not in name_list:\n f.write(path + '/' + name + '.png' + '%%' + path + '/' + name + '.hdr\\n')\n name_list.append(name)\n f.close()","repo_name":"godwantma/HDR_reconstruction","sub_path":"split_image.py","file_name":"split_image.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"42218273408","text":"#!/usr/local/bin/python\r\n\r\nfrom flask import Flask, render_template, jsonify, request, redirect, url_for, session, make_response\r\nimport secrets\r\n\r\nimport MySQLdb\r\n\r\n# My API functions\r\nfrom api import *\r\n\r\napp = Flask(__name__, static_url_path='')\r\n\r\napp.secret_key = secrets.token_urlsafe(16)\r\n\r\n#app.debug = True\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n \r\n@app.route(\"/searchTheWiki\", methods = [\"POST\"])\r\ndef searchTheWiki():\r\n queryTitle = request.form['title']\r\n numSentences = request.form['sentences']\r\n summary = \"\"\r\n image = \"\"\r\n status = \"\"\r\n try:\r\n title = searchForPage(queryTitle)\r\n title = title[0]\r\n \r\n if (isVideoGame(title)):\r\n summary = getPageSummary(title, numSentences)\r\n image = getPageImage(title)\r\n url = getURL(title)\r\n status=\"Success\"\r\n categories = getCategories(title)\r\n return jsonify(title=title, summary=summary, image=image, status=status, categories=categories, url=url)\r\n else:\r\n status = \"ERROR: That is not a video game! (If it is, please add `(video game)` to the end of the title\"\r\n except Exception as e:\r\n print(e)\r\n status = \"Page does not exist\"\r\n return jsonify(status=status)\r\n","repo_name":"Quantaxer/Game-Backlogger","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"36060879555","text":"\ndef combinationSum(candidates, target):\n result = []\n nums = sorted(candidates)\n if sum(nums) == target: return [nums]\n if sum(nums) < target: return []\n def tracking(temp, nums, target):\n if sum(temp) == target:\n if sorted(temp) not in result:\n result.append(sorted(temp))\n return\n if sum(temp) > target:\n return\n for i in nums:\n temp.append(i)\n nums.remove(i)\n Newnums = list(nums)\n tracking(temp, Newnums, target)\n nums.insert(0, i)\n temp.pop()\n tracking([], nums, target)\n return result\n\n\nif __name__ == \"__main__\":\n candidates = [1, 2]\n target = 2\n print(combinationSum(candidates, target))\n\n\n\n","repo_name":"ficherfisher/leetcode","sub_path":"39CombinationSum.py","file_name":"39CombinationSum.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"5683605258","text":"first_name = input('What is your first name? ').title()\nlast_name = input('What is your last name? ').title()\nyear_born = int(input('When were you born? '))\ncurrent_year = 2021\nage = current_year - year_born\ncity = input('Name of the city your are living in? ').title()\ncountry = input('Conuntry you are living in? ').title()\ngender = input('What is your gender F or M? ' ).lower()\npronoun = ''\n\nif gender == 'f' or 'Female':\n pronoun = 'She'\nelif gender == 'm' or 'male':\n pronoun = 'He' \n\n\nprint(f'{pronoun} is {first_name} {last_name}. {pronoun} is {age}. {pronoun} lives in {city} {country} ')","repo_name":"meronfan/Five-Days-of-Python","sub_path":"Day3/conditional.py","file_name":"conditional.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"33406220704","text":"from time import sleep\n\nfrom ulakbus.models import BAPProje\nfrom ulakbus.models import User\nfrom ulakbus.models import Okutman\nfrom ulakbus.models import Personel\n\nfrom zengine.lib.test_utils import BaseTestCase\n\n\nclass TestCase(BaseTestCase):\n\n def lane_change_massage_kontrol(self, resp):\n assert resp.json['msgbox']['title'] == 'Teşekkürler!'\n assert resp.json['msgbox']['msg'] == 'Bu iş akışında şuan için gerekli adımları ' \\\n 'tamamladınız. İlgili kişiler, iş akışına ' \\\n 'katılmaları için haberdar edildiler.'\n\n def test_bap_proje_basvuru(self):\n user = User.objects.get(username='ogretim_uyesi_1')\n personel = Personel.objects.get(user=user)\n okutman = Okutman.objects.get(personel=personel) # Hanife Şener\n\n proje = BAPProje()\n proje.ad = \"Bap Test proje iptal talebi projesi\"\n proje.yurutucu = okutman\n proje.durum = 5\n proje.save()\n\n for i in range(4):\n if i == 1:\n token, user = self.get_user_token(username='ogretim_uyesi_1')\n self.prepare_client('/bap_yurutucu_degisikligi_talebi', user=user, token=token)\n resp = self.client.post()\n\n assert resp.json['forms']['form'][0]['helpvalue'] == \"%s projeniz için \" \\\n \"bulunduğunuz iptal talebi \" \\\n \"reddedilmiştir. \" \\\n \"Red Açıklaması: Red edildi.\" \\\n % proje.ad\n self.client.post(form={'bitir': 1})\n sleep(1)\n continue\n elif i == 3:\n token, user = self.get_user_token(username='ogretim_uyesi_1')\n self.prepare_client('/bap_yurutucu_degisikligi_talebi', user=user, token=token)\n resp = self.client.post()\n\n assert resp.json['forms']['form'][0]['helpvalue'] == \"%s projeniz için \" \\\n \"bulunduğunuz iptal talebi \" \\\n \"koordinasyon birimi \" \\\n \"tarafından kabul edilip \" \\\n \"Komisyon Gündemine \" \\\n \"alınmıştır.\" % proje.ad\n\n self.client.post(form={'bitir': 1})\n sleep(1)\n continue\n else:\n self.prepare_client('/bap_proje_iptal_talep', user=user)\n\n self.client.post()\n\n resp = self.client.post(form={'proje': proje.key,\n 'ilerle': 1})\n\n assert resp.json['object'][u'Proje Adı'] == proje.ad\n\n resp = self.client.post(form={'aciklama': 'Kişisel sebeblerden dolayı '\n 'bap test projesinin iptalini istiyorum.',\n 'onay': 1})\n\n assert resp.json['forms']['form'][0]['helpvalue'] == \"%s projesini iptal için onaya \" \\\n \"yollayacaksınız. Yollamak \" \\\n \"istiyor musunuz ?\" % proje.ad\n\n resp = self.client.post(form={'gonder': 1})\n\n self.lane_change_massage_kontrol(resp)\n\n sleep(1)\n\n token, user = self.get_user_token(username='bap_koordinasyon_birimi_1')\n self.prepare_client('/bap_yurutucu_degisikligi_talebi', user=user, token=token)\n\n resp = self.client.post()\n\n assert resp.json['object']['İptal Talep Açıklama'] == \"Kişisel sebeblerden dolayı \" \\\n \"bap test projesinin \" \\\n \"iptalini istiyorum.\"\n\n if i == 0:\n self.client.post(form={'reddet': 1})\n\n resp = self.client.post(form={'red_aciklama': 'Red edildi.',\n 'red_gonder': 1})\n else:\n resp = self.client.post(cmd='onayla', form={'onayla': 1}, object_key=proje.key)\n assert resp.json['forms']['schema']['title'] == \"Proje İptal Talebi Talebini \" \\\n \"Komisyona Yolla\"\n resp = self.client.post(form={'komisyona_gonder': 1})\n\n self.lane_change_massage_kontrol(resp)\n","repo_name":"zetaops/ulakbus","sub_path":"tests/test_bap_proje_iptal_talep.py","file_name":"test_bap_proje_iptal_talep.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"tr","doc_type":"code","stars":101,"dataset":"github-code","pt":"48"}
+{"seq_id":"20240255185","text":"import os\nimport numpy as np\nimport random\nimport torch\nimport torch.utils.data as data\nfrom tqdm import tqdm \nfrom torchvision import transforms\nfrom utils.file_processing import image_file_to_array\nclass BongardDataset(data.Dataset):\n\t\"\"\"\n\t\thttps://github.com/NVlabs/Bongard-LOGO\n\t\"\"\"\n\n\tdef __init__(self, random_seed=123, batch_type='train', img_dim=(512,512), batch_size=None, one_hot_size=3, root='./ShapeBongard_V2'):\n\t\t'''\n\t\tArgs:\n\t\t- batch_type: training, testing or validation set\n\t\t- img_dim: (height, weight) of image in input layer\n\t\t- root: directory where dataset will be stored\n\t\t- one_hot_size: one_hot_vector size of a label (left, right, unlabeled)\n\t\tUsage: \n\t\t\ttr_dataset = BongardDataset(batch_type='train', one_hot_size=3, root='./ShapeBongard_V2')\n\t\t\t# returns tr_dataset.y, tr_dataset.x_paths\n\t\t'''\n\n\t\tsuper(BongardDataset, self).__init__()\n\t\tself.seed = random_seed\n\t\tself.root = root\n\t\tself.batch_type = batch_type\n\t\tself.batch_size = batch_size\n\t\tself.one_hot_size = one_hot_size\n\t\tself.img_h, self.img_w = img_dim\n\t\tself.img_dim = self.img_h*self.img_w\n\t\t\n\t\t# as stated in paper\n\t\tself.num_train = 9300\n\t\tself.num_val = 900\n\n\t\t# in dataset dir\n\t\tself.num_classes = 2\n\t\tself.num_samples_per_class = 7\n\t\t\n\n\t\t# resize original 512x512 image to 256x246\n\t\tself.transform = transforms.Compose([transforms.ToPILImage(mode=None),\n\t\t\t\t\t\t\t\t\t\t\t\ttransforms.Resize(img_dim)])\n\n\t\tif not os.path.exists(self.root):\n\t\t\traise RuntimeError('Dataset not found.')\n\n\t\t\n\t\t# basic, free-form, abstract --> images --> pos, neg --> img.png\n\t\t# problem_type/images/problem_class/img.png\n\t\tproblem_folders = [os.path.join(self.root, problem_type, 'images', problem_class) #img path\n\t\t\t\t\t\t for problem_type in os.listdir(self.root) # basic, free-form, abstract\n\t\t\t\t\t\t if os.path.isdir(os.path.join(self.root, problem_type))\n\t\t\t\t\t\t for problem_class in os.listdir(os.path.join(self.root, problem_type, 'images')) # neg, pos\n\t\t\t\t\t\t if os.path.isdir(os.path.join(self.root, problem_type, 'images', problem_class))]\n\n\t\trandom.seed(self.seed)\n\t\trandom.shuffle(problem_folders)\n\n\t\tif self.batch_type == 'train':\n\t\t\tself.folders = problem_folders[: self.num_train]\n\t\telif self.batch_type == 'val':\n\t\t\tself.folders = problem_folders[self.num_train : self.num_train + self.num_val]\n\t\telif self.batch_type == 'test':\n\t\t\tself.folders = problem_folders[self.num_train + self.num_val:]\n\t\telse:\n\t\t\traise ValueError('Batch must be of type Train, Validation or Test')\n\n\t\tget_label = lambda folder, class_name : [class_name for problem_img in \n\t\t\t\t\t\tos.listdir(os.path.join(folder, str(class_name)))]\n\t\tprint(\"Fetching Y\"+batch_type+\" labels\")\n\t\tself.y = np.array([list(zip(np.eye(one_hot_size)[get_label(problem, 0)], \n\t\t\t\t\tnp.eye(one_hot_size)[get_label(problem, 1)])) \n\t\t\t\t\tfor problem in tqdm(self.folders)])\n\t\tassert self.y.shape == (len(self.folders), self.num_samples_per_class, \n\t\t\t\t\t\t\t\tself.num_classes, self.one_hot_size)\n\n\t\tprint(\"Fetching X\"+batch_type+\" paths\")\t\t\n\t\tget_img_path = lambda folder, class_name: [os.path.join(folder, str(class_name), problem_img) \n\t\t\t\t\t\t\tfor problem_img in os.listdir(os.path.join(folder, str(class_name)))]\n\t\tself.x_paths = np.array([list(zip(get_img_path(problem, 0), get_img_path(problem, 1))) \n\t\t\t\t\t\t\tfor problem in tqdm(self.folders)])\n\t\tassert self.x_paths.shape == (len(self.folders), self.num_samples_per_class, self.num_classes)\n\n\tdef __getitem__(self, idx):\n\t\t'''\n\t\tArgs:\n\t\t- idx: problem at idx\n\t\t\n\t\tReturns:\n\t\t- problem_imgs: img data for each img in problem, shape: num_samples_per_class x img_dim\n\t\t- labels: labels for each img in problem, shape: num_samples_per_class x num_classes x one_hot_size\n\t\t- problem_path: str obj is path to problem\n\t\t'''\n\t\t\n\t\tget_imgs_at_idx = lambda x: torch.stack([torch.stack([image_file_to_array(class_1, self.transform), \n\t\t\t\t\t\t\t\t\t\timage_file_to_array(class_2, self.transform)])\n\t\t\t\t\t\t\t\t\t\tfor class_1, class_2 in x])\n\n\t\tbatch_imgs = torch.stack([get_imgs_at_idx(batch_i) for batch_i in self.x_paths[idx]])\n\n\t\t#assert batch_imgs.shape == (self.batch_size, self.num_samples_per_class, \n\t\t#\t\t\t\t\t\t\tself.num_classes, self.img_dim)\n\t\t\n\t\tbatch_y = torch.from_numpy(self.y[idx])\n\t\t\n\t\tbatch_path = [os.path.split(path)[0] for path in self.x_paths[idx][:, 1, 1]]\n\t\t\n\t\treturn batch_imgs, self.y[idx], batch_path\n\n\tdef __len__(self):\n\t\treturn len(self.x_paths)\n\n#class BongardLOGODataset(data.Dataset):\n\"\"\"\nLOGO vectors for program induction\n\"\"\"\n\n","repo_name":"aishniparab/myaiframework","sub_path":"datasets/bongard_dataset.py","file_name":"bongard_dataset.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"17410081905","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom hwt.interfaces.std import FifoReader, FifoWriter\nfrom hwt.interfaces.utils import addClkRstn\nfrom hwt.simulator.simTestCase import SimTestCase\nfrom hwt.synthesizer.unit import Unit\nfrom hwtLib.mem.fifo import Fifo\nfrom hwtSimApi.constants import CLK_PERIOD\nfrom hwtSimApi.triggers import Timer, WaitWriteOnly\n\n\nclass FifoReaderPassTrought(Unit):\n\n def _declr(self):\n addClkRstn(self)\n self.din = FifoReader()\n self.dout = FifoReader()._m()\n\n def _impl(self):\n self.dout(self.din)\n\n\nclass FifoWriterPassTrought(FifoReaderPassTrought):\n\n def _declr(self):\n addClkRstn(self)\n self.din = FifoWriter()\n self.dout = FifoWriter()._m()\n\n\nclass FifoReaderAgentTC(SimTestCase):\n CLK = CLK_PERIOD\n\n @classmethod\n def setUpClass(cls):\n cls.u = FifoReaderPassTrought()\n cls.compileSim(cls.u)\n\n def test_fifoReader(self):\n u = self.u\n self.randomize(u.din)\n self.randomize(u.dout)\n\n ref = [i for i in range(30)]\n u.din._ag.data.extend(ref)\n self.runSim(120 * self.CLK)\n\n self.assertValSequenceEqual(u.dout._ag.data, ref)\n\n\nclass FifoWriterAgentTC(SimTestCase):\n CLK = CLK_PERIOD\n\n @classmethod\n def setUpClass(cls):\n cls.u = FifoWriterPassTrought()\n cls.compileSim(cls.u)\n\n def test_fifoWriter(self):\n u = self.u\n\n self.randomize(u.din)\n self.randomize(u.dout)\n\n ref = [i for i in range(30)]\n u.din._ag.data.extend(ref)\n self.runSim(120 * self.CLK)\n\n self.assertValSequenceEqual(u.dout._ag.data, ref)\n\n\nclass FifoTC(SimTestCase):\n ITEMS = 4\n IN_CLK = CLK_PERIOD\n OUT_CLK = CLK_PERIOD\n CLK = max(IN_CLK, OUT_CLK) # clock used for resolving of sim duration\n\n @classmethod\n def setUpClass(cls):\n u = cls.u = Fifo()\n u.DATA_WIDTH = 8\n u.DEPTH = cls.ITEMS\n u.EXPORT_SIZE = True\n cls.compileSim(cls.u)\n\n def getFifoItems(self):\n m = self.rtl_simulator.io.memory\n return set([int(x.read()) for x in m])\n\n def getUnconsumedInput(self):\n return self.u.dataIn._ag.data\n\n def test_fifoSingleWord(self):\n u = self.u\n\n expected = [1]\n u.dataIn._ag.data.extend(expected)\n\n self.runSim(9 * self.CLK)\n\n collected = u.dataOut._ag.data\n self.assertValSequenceEqual(collected, expected)\n\n def test_fifoWriterDisable(self):\n u = self.u\n\n ref = [i + 1 for i in range(self.ITEMS)]\n u.dataIn._ag.data.extend(ref)\n\n def init():\n u.dataIn._ag.setEnable(False)\n return\n yield\n\n self.procs.append(init())\n\n self.runSim(8 * self.CLK)\n\n self.assertValSequenceEqual(u.dataOut._ag.data, [])\n self.assertValSequenceEqual(self.getUnconsumedInput(), ref)\n\n def test_normalOp(self):\n u = self.u\n\n expected = list(range(4))\n u.dataIn._ag.data.extend(expected)\n\n self.runSim(9 * self.CLK)\n\n self.assertValSequenceEqual(u.dataOut._ag.data, expected)\n\n def test_multiple(self, sizeValues=[\n 0, 1, 2, 3, 4, 4, 4, 4, 4,\n 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 2, 1, 0, 0]):\n u = self.u\n\n def openOutputAfterWile():\n u.dataOut._ag.setEnable(False)\n yield Timer(self.CLK * 9)\n u.dataOut._ag.setEnable(True)\n\n self.procs.append(openOutputAfterWile())\n\n expected = list(range(2 * 8))\n u.dataIn._ag.data.extend(expected)\n\n self.runSim(27 * self.CLK)\n\n collected = u.dataOut._ag.data\n if u.EXPORT_SIZE:\n self.assertValSequenceEqual(\n u.size._ag.data, sizeValues)\n\n self.assertValSequenceEqual(collected, expected)\n\n def test_tryMore(self):\n u = self.u\n\n ref = [i + 1 for i in range(self.ITEMS * 3)]\n u.dataIn._ag.data.extend(ref)\n\n def init():\n yield WaitWriteOnly()\n u.dataOut._ag.setEnable(False)\n\n self.procs.append(init())\n\n self.runSim(self.ITEMS * 4 * self.CLK)\n\n collected = u.dataOut._ag.data\n self.assertSetEqual(self.getFifoItems(), set(ref[:self.ITEMS]))\n self.assertValSequenceEqual(collected, [])\n self.assertValSequenceEqual(self.getUnconsumedInput(), ref[self.ITEMS:])\n\n def test_tryMore2(self, capturedOffset=2):\n u = self.u\n\n ref = [i + 1 for i in range(self.ITEMS * 2)]\n u.dataIn._ag.data.extend(ref)\n\n def closeOutput():\n yield Timer(self.OUT_CLK * 4)\n u.dataOut._ag.setEnable(False)\n\n self.procs.append(closeOutput())\n self.runSim(15 * self.CLK)\n\n collected = [int(x) for x in u.dataOut._ag.data]\n\n self.assertSetEqual(self.getFifoItems(),\n set(ref[capturedOffset:self.ITEMS + capturedOffset]))\n se = self.assertSequenceEqual\n se(collected, ref[:capturedOffset])\n se(self.getUnconsumedInput(), ref[self.ITEMS + capturedOffset:])\n\n def test_randomizedIn(self):\n self._test_randomized(True, False)\n\n def test_randomizedOut(self):\n self._test_randomized(False, True)\n\n def test_randomizedAll(self):\n self._test_randomized(True, True)\n\n def _test_randomized(self, randIn, randOut):\n u = self.u\n LEN = 80\n ref = [i + 1 for i in range(LEN)]\n u.dataIn._ag.data.extend(ref)\n if randIn:\n self.randomize(u.dataIn)\n if randOut:\n self.randomize(u.dataOut)\n\n self.runSim(int(2.5 * LEN * self.CLK))\n\n collected = u.dataOut._ag.data\n self.assertSequenceEqual(collected, ref)\n\n def test_doloop(self):\n u = self.u\n u.dataIn._ag.data.extend([1, 2, 3, 4, 5, 6])\n\n self.runSim(12 * self.CLK)\n\n collected = u.dataOut._ag.data\n self.assertSequenceEqual([1, 2, 3, 4, 5, 6], collected)\n self.assertSequenceEqual([], u.dataIn._ag.data)\n\n def test_nop(self):\n u = self.u\n self.runSim(12 * self.CLK)\n self.assertEqual(len(u.dataOut._ag.data), 0)\n\n def test_stuckedData(self):\n u = self.u\n u.dataIn._ag.data.append(1)\n\n def init():\n yield WaitWriteOnly()\n u.dataOut._ag.setEnable(False)\n\n self.procs.append(init())\n\n self.runSim(12 * self.CLK)\n self.assertEqual(len(u.dataOut._ag.data), 0)\n\n def test_withPause(self):\n u = self.u\n ref = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n u.dataIn._ag.data.extend(ref)\n\n def pause():\n yield Timer(3 * self.OUT_CLK)\n u.dataOut._ag.setEnable_asMonitor(False)\n\n yield Timer(3 * self.OUT_CLK)\n u.dataOut._ag.setEnable_asMonitor(True)\n\n yield Timer(3 * self.IN_CLK)\n u.dataIn._ag.setEnable_asDriver(False)\n\n yield Timer(3 * self.IN_CLK)\n u.dataIn._ag.setEnable_asDriver(True)\n\n self.procs.append(pause())\n\n self.runSim(20 * self.CLK)\n\n self.assertValSequenceEqual(u.dataOut._ag.data, ref)\n self.assertSequenceEqual(self.getUnconsumedInput(), [])\n\n def test_withPause2(self):\n u = self.u\n ref = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n u.dataIn._ag.data.extend(ref)\n\n def pause():\n yield Timer(4 * self.OUT_CLK)\n u.dataOut._ag.setEnable_asMonitor(False)\n yield Timer(3 * self.OUT_CLK)\n u.dataOut._ag.setEnable_asMonitor(True)\n yield Timer(3 * self.IN_CLK)\n u.dataIn._ag.setEnable_asDriver(False)\n yield Timer(3 * self.IN_CLK)\n u.dataIn._ag.setEnable_asDriver(True)\n\n self.procs.append(pause())\n\n self.runSim(20 * self.CLK)\n\n self.assertValSequenceEqual(u.dataOut._ag.data, ref)\n self.assertSequenceEqual(self.getUnconsumedInput(), [])\n\n def test_passdata(self):\n u = self.u\n ref = [1, 2, 3, 4, 5, 6]\n u.dataIn._ag.data.extend(ref)\n\n self.runSim(12 * self.CLK)\n\n self.assertValSequenceEqual(u.dataOut._ag.data, ref)\n self.assertValSequenceEqual(self.getUnconsumedInput(), [])\n\n\nif __name__ == \"__main__\":\n _ALL_TCs = [FifoWriterAgentTC, FifoReaderAgentTC, FifoTC]\n testLoader = unittest.TestLoader()\n loadedTcs = [testLoader.loadTestsFromTestCase(tc) for tc in _ALL_TCs]\n suite = unittest.TestSuite(loadedTcs)\n runner = unittest.TextTestRunner(verbosity=3)\n runner.run(suite)\n","repo_name":"Nic30/hwtLib","sub_path":"hwtLib/mem/fifo_test.py","file_name":"fifo_test.py","file_ext":"py","file_size_in_byte":8551,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"48"}
+{"seq_id":"17938755823","text":"import os\n\nfrom ament_index_python.packages import get_package_share_directory\n\nfrom launch import LaunchDescription\nfrom launch_ros.actions import Node\nfrom launch.actions import ExecuteProcess, IncludeLaunchDescription, RegisterEventHandler\nfrom launch.event_handlers import OnProcessExit\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\nfrom launch.substitutions import LaunchConfiguration\nfrom launch_ros.substitutions import FindPackageShare\n\n\nimport xacro\nimport yaml\n\n\ndef generate_launch_description():\n\n #Joy_sub to motor_control node\n motor_node = Node(package='rpi_robot', executable='rpi_motor')\n\n #Camera_pub node\n cam_node = Node(package=\"v4l2_camera\",\n executable=\"v4l2_camera_node\",\n name=\"v4l2_camera_node\",\n parameters=[{\"image_size\": \"[640,480]\", \"camera_frame_id\": \"camera_link_optical\"}],\n )\n\n #\n rpi_robot_description_path = os.path.join(\n get_package_share_directory('rpi_robot_description'))\n\n #Getting robot urdf\n xacro_file = os.path.join(rpi_robot_description_path,\n 'urdf',\n 'rpi_robot.urdf.xacro')\n\n doc = xacro.parse(open(xacro_file))\n xacro.process_doc(doc)\n robot_description_config = doc.toxml()\n robot_description = {'robot_description': robot_description_config}\n\n #Robot_state_publisher node\n node_robot_state_publisher = Node(\n package='robot_state_publisher',\n executable='robot_state_publisher',\n output='screen',\n parameters=[robot_description]\n )\n\n #Lidar_pub node\n lidar_driver_node = IncludeLaunchDescription(\n PythonLaunchDescriptionSource([\n FindPackageShare(\"ydlidar_ros2_driver\"), '/launch', '/ydlidar_launch.py'])\n )\n \n\n # Launch them all!\n return LaunchDescription([\n motor_node,\n cam_node,\n #node_robot_state_publisher,\n #lidar_driver_node\n ])\n","repo_name":"E12-CO/rpi_robot","sub_path":"launch/robot_launch.py","file_name":"robot_launch.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"38122401340","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\ndef lowestCommonAncestor(root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n if root in (None, p, q): \n return root\n left = lowestCommonAncestor(root.left, p, q)\n right = lowestCommonAncestor(root.right, p, q)\n if left and right:\n return root # if p and q are respectively in the left and right subtrees of root, then root is their LCA\n else:\n return left if left else right # either one of p,q is in the subtree of root, or none is. If none is, this will eventually return None\n#time O(n)\n#space O(n)\n","repo_name":"0xspringtime/leetcode","sub_path":"0236n.py","file_name":"0236n.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"39997952873","text":"'''\nConsecutive prime sum\nProblem 50\nThe prime 41, can be written as the sum of six consecutive primes:\n\n41 = 2 + 3 + 5 + 7 + 11 + 13\nThis is the longest sum of consecutive primes that adds to a prime below one-hundred.\n\nThe longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.\n\nWhich prime, below one-million, can be written as the sum of the most consecutive primes?\n'''\n\nfrom math import sqrt\nprimes = [2, 3]\n\n\ndef is_prime(a):\n result = True\n l = int(sqrt(a))\n for p in primes:\n if p > l:\n break\n elif a % p == 0:\n result = False\n break\n return result\n\n\ndef main():\n\n for i in range(5, 1000000, 2):\n if is_prime(i):\n primes.append(i)\n\n #primes_f = [ i for i in primes if i < 1000]\n print(\"step 1 done : \", len(primes))\n\n sub = []\n max_s = 0\n max_l = 0\n s = 0\n sl = 0\n\n for i in range(len(primes)):\n sub = primes[:i + 1]\n s = sum(sub)\n sl = len(sub)\n if s > 1000000:\n break\n if s in primes:\n max_l = sl\n sax_s = s\n else:\n while (sl > max_l):\n sub[:1] = []\n sl = len(sub)\n s = sum(sub)\n if (s in primes):\n if sl > max_l:\n max_l = sl\n max_s = s\n\n print(\" Done : \", max_s, \" len=\", max_l)\n\n\nif __name__ == '__main__':\n\n main()\n","repo_name":"murli777/Project-Euler-Solutions","sub_path":"src/001-050/P050.py","file_name":"P050.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15310238463","text":"# Adding two lists together using for loops\n\n#first way\n\nlist_1 = [\"Shirt\", \"Pants\", \"Sweater\", \"Socks\", \"Jacket\"] \nlist_2 = [\"Hat\", \"Watch\", \"Shoes\"]\nfor list_3 in list_1:\n list_3 = list_1 + list_2\nprint(list_3)\n#second way\nlist_1 = [\"Shirt\", \"Pants\", \"Sweater\", \"Socks\", \"Jacket\"]\nlist_2 = [\"Hat\", \"Watch\", \"Shoes\"]\nfor list_3 in list_2:\n list_1.append(list_3)\nprint(list_1)\n\n#sum = 5\n#numbers = [1,10,2]\n#for sum in numbers:\n#print(sum +1)\n\nlist_1 = [1, 2, 3, 4]\nlist_2 = [5, 6, 7, 8]\nlist_5 = []\n\nlength = len(list_1)\nfor i in range(length):\n result = list_1[i] + list_2[i]\n print(list_1[i], \"+\" ,list_2[i], \"=\", result)\n list_5.append(result)\nprint(list_5)","repo_name":"itsAimen/Python-Learning","sub_path":"Loops.py/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"70905419665","text":"from dotenv import load_dotenv\nimport os\n\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\nload_dotenv()\n\n\nclass Config(object):\n DEBUG = False\n TESTING = False\n CSRF_ENABLED = True\n\n\nclass Prod(Config):\n DEBUG = False\n\n\nclass Dev(Config):\n DEVELOPMENT = True\n DEBUG = True\n","repo_name":"DResthal/ConfigManageUtils","sub_path":"configApi/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"14075512181","text":"def menu():\r\n print(\"Menu: \")\r\n print(\"[1] - Importar palabras clave.\")\r\n print(\"[2] - Mostrar palabras clave.\")\r\n print(\"[0] - Salir\")\r\n\r\n\r\ndef elegirOpcion():\r\n opcion = 0\r\n while True:\r\n try:\r\n opcion = int(input(\"Opcion: \"))\r\n if opcion in [0, 1, 2]:\r\n break\r\n except ValueError:\r\n print('ERROR: Introduzca un numero')\r\n return opcion\r\n\r\n\r\ndef carga_keywords():\r\n claves = []\r\n with open('keywords.txt') as f:\r\n for linea in f:\r\n claves += linea.split()\r\n return claves\r\n\r\n\r\ndef muestraKeywords(claves):\r\n vuelta = 1\r\n for contador, clave in enumerate(claves):\r\n if contador < 20 * vuelta:\r\n print(clave)\r\n else:\r\n input('Mostrar mas...')\r\n print(clave)\r\n vuelta += 1\r\n\r\n\r\ndef flujo():\r\n while True:\r\n menu()\r\n opcion = elegirOpcion()\r\n\r\n if opcion == 0:\r\n break\r\n elif opcion == 1:\r\n keywords = carga_keywords()\r\n elif opcion == 2:\r\n muestraKeywords(keywords)\r\n\r\n\r\nif __name__ == '__main__':\r\n flujo()\r\n","repo_name":"aperonac/j2logo-ejericios","sub_path":"Ejercicio 1/Ejercicio1.py","file_name":"Ejercicio1.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"24202202932","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[12]:\n\n\nimport datetime\nclass Temperature:\n \n temp=0;\n \n def __init__(self,temp):\n self.temp=temp;\n \n def ToFahrenheit(self):\n InFahrenheit = float((9 * self.temp) / 5 + 32)\n return InFahrenheit\n \n def ToCelcius(self):\n InCelcius = float((self.temp - 32) * 5 / 9)\n return InCelcius\n \nclass Time(Temperature):\n \n \n def time():\n cur_tim=datetime.datetime.now()\n return cur_tim\n \n \n pass\n\n \n \ninp_temp1 = float(input(\"\"\"Enter the input in Celcius:\"\"\"))\ntemp_fah=Temperature(inp_temp1)\nprint(temp_fah.ToFahrenheit())\n\ninp_temp2 = float(input(\"\"\"Enter the input in Fahrenheit\"\"\"))\ntemp_cel=Temperature(inp_temp2)\nprint(temp_cel.ToCelcius())\n\nx=Time(23)\nprint(x.ToFahrenheit())\n\n\ny=Time.time()\nprint(y)\n\n\n\n\n \n \n \n \n \n\n\n# In[ ]:\n\n\n\n\n","repo_name":"akhileshgowda7/Python-2","sub_path":"FahToCel.py","file_name":"FahToCel.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"73839674707","text":"#---- foo52ru ---------\r\n# генерация дерева без листьев\r\n# https://youtu.be/mAz46Z5curo\r\nimport turtle\r\nfrom random import randint\r\nturtle.hideturtle()\r\nturtle.tracer(0)\r\nturtle.penup()\r\nturtle.setposition(0,-300)\r\nturtle.left(90)\r\nturtle.pendown()\r\nthick = 16\r\nturtle.pensize(thick)\r\n\r\naxiom = \"22220\"\r\naxmTemp = \"\"\r\nitr = 11\r\nangl = 20\r\ndl = 10\r\nstc = []\r\n\r\ntranslate={\"1\":\"21\",\r\n \"0\":\"1[-20]+20\"}\r\n\r\nfor k in range(itr):\r\n for ch in axiom:\r\n if ch in translate:\r\n axmTemp+=translate[ch]\r\n else:\r\n axmTemp+=ch\r\n axiom = axmTemp\r\n axmTemp = \"\"\r\n\r\nfor ch in axiom:\r\n if ch == \"+\":\r\n turtle.right(angl - randint(-13,13))\r\n elif ch == \"-\":\r\n turtle.left(angl - randint(-13,13))\r\n elif ch == \"2\":\r\n if randint(0,10)>5:\r\n turtle.forward(dl) \r\n elif ch == \"1\":\r\n turtle.forward(dl)\r\n elif ch == \"0\":\r\n turtle.forward(dl) \r\n elif ch == \"[\":\r\n thick = thick*0.75\r\n turtle.pensize(thick)\r\n stc.append(thick)\r\n stc.append(turtle.xcor())\r\n stc.append(turtle.ycor())\r\n stc.append(turtle.heading())\r\n elif ch == \"]\":\r\n turtle.penup()\r\n turtle.setheading(stc.pop())\r\n turtle.sety(stc.pop())\r\n turtle.setx(stc.pop())\r\n thick = stc.pop()\r\n turtle.pensize(thick)\r\n turtle.pendown()\r\nturtle.update() \r\nturtle.mainloop()\r\n","repo_name":"foo52ru/L-systems-Trees","sub_path":"notLeafs.py","file_name":"notLeafs.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"6824310582","text":"import os\nimport re\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom setuptools import find_packages\nfrom setuptools import Extension, setup\nfrom setuptools.command.build_ext import build_ext\n\n# Convert distutils Windows platform specifiers to CMake -A arguments\nPLAT_TO_CMAKE = {\n \"win32\": \"Win32\",\n \"win-amd64\": \"x64\",\n \"win-arm32\": \"ARM\",\n \"win-arm64\": \"ARM64\",\n}\n\n# A CMakeExtension needs a sourcedir instead of a file list.\n# The name must be the _single_ output extension from the CMake build.\n# If you need multiple extensions, see scikit-build.\nclass CMakeExtension(Extension):\n def __init__(self, name: str, sourcedir: str = \"\") -> None:\n super().__init__(name, sources=[])\n self.sourcedir = os.fspath(Path(sourcedir).resolve())\n\n\n\nclass CMakeBuild(build_ext):\n def build_extension(self, ext):\n extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))\n\n # required for auto-detection & inclusion of auxiliary \"native\" libs\n if not extdir.endswith(os.path.sep):\n extdir += os.path.sep\n\n debug = int(os.environ.get(\"DEBUG\", 0)) if self.debug is None else self.debug\n cfg = \"Debug\" if debug else \"Release\"\n\n # CMake lets you override the generator - we need to check this.\n # Can be set with Conda-Build, for example.\n cmake_generator = os.environ.get(\"CMAKE_GENERATOR\", \"\")\n\n # Set Python_EXECUTABLE instead if you use PYBIND11_FINDPYTHON\n # EXAMPLE_VERSION_INFO shows you how to pass a value into the C++ code\n # from Python.\n cmake_args = [\n f\"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}\",\n f\"-DPYTHON_EXECUTABLE={sys.executable}\",\n f\"-DCMAKE_BUILD_TYPE={cfg}\", # not used on MSVC, but no harm\n ]\n build_args = []\n # Adding CMake arguments set as environment variable\n # (needed e.g. to build for ARM OSx on conda-forge)\n if \"CMAKE_ARGS\" in os.environ:\n cmake_args += [item for item in os.environ[\"CMAKE_ARGS\"].split(\" \") if item]\n\n # In this example, we pass in the version to C++. You might not need to.\n cmake_args += [f\"-DEXAMPLE_VERSION_INFO={self.distribution.get_version()}\"]\n\n if self.compiler.compiler_type != \"msvc\":\n # Using Ninja-build since it a) is available as a wheel and b)\n # multithreads automatically. MSVC would require all variables be\n # exported for Ninja to pick it up, which is a little tricky to do.\n # Users can override the generator with CMAKE_GENERATOR in CMake\n # 3.15+.\n if not cmake_generator or cmake_generator == \"Ninja\":\n try:\n import ninja # noqa: F401\n\n ninja_executable_path = os.path.join(ninja.BIN_DIR, \"ninja\")\n cmake_args += [\n \"-GNinja\",\n f\"-DCMAKE_MAKE_PROGRAM:FILEPATH={ninja_executable_path}\",\n ]\n except ImportError:\n pass\n\n else:\n\n # Single config generators are handled \"normally\"\n single_config = any(x in cmake_generator for x in {\"NMake\", \"Ninja\"})\n\n # CMake allows an arch-in-generator style for backward compatibility\n contains_arch = any(x in cmake_generator for x in {\"ARM\", \"Win64\"})\n\n # Specify the arch if using MSVC generator, but only if it doesn't\n # contain a backward-compatibility arch spec already in the\n # generator name.\n if not single_config and not contains_arch:\n cmake_args += [\"-A\", PLAT_TO_CMAKE[self.plat_name]]\n\n # Multi-config generators have a different way to specify configs\n if not single_config:\n cmake_args += [\n f\"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{cfg.upper()}={extdir}\"\n ]\n build_args += [\"--config\", cfg]\n\n if sys.platform.startswith(\"darwin\"):\n # Cross-compile support for macOS - respect ARCHFLAGS if set\n archs = re.findall(r\"-arch (\\S+)\", os.environ.get(\"ARCHFLAGS\", \"\"))\n if archs:\n cmake_args += [\"-DCMAKE_OSX_ARCHITECTURES={}\".format(\";\".join(archs))]\n\n # Set CMAKE_BUILD_PARALLEL_LEVEL to control the parallel build level\n # across all generators.\n if \"CMAKE_BUILD_PARALLEL_LEVEL\" not in os.environ:\n # self.parallel is a Python 3 only way to set parallel jobs by hand\n # using -j in the build_ext call, not supported by pip or PyPA-build.\n if hasattr(self, \"parallel\") and self.parallel:\n # CMake 3.12+ only.\n build_args += [f\"-j{self.parallel}\"]\n\n build_temp = os.path.join(self.build_temp, ext.name)\n if not os.path.exists(build_temp):\n os.makedirs(build_temp)\n\n subprocess.check_call([\"cmake\", ext.sourcedir] + cmake_args, cwd=build_temp)\n subprocess.check_call([\"cmake\", \"--build\", \".\"] + build_args, cwd=build_temp)\n\n\nsetup(\n name=\"pyElemSymPoly\",\n packages=find_packages(),\n version=\"0.1.14\",\n license=\"MIT\",\n #home_page=\"https://github.com/IshanHegde/ElemSymPoly\",\n install_requires=[\n \"numpy >= 1.19.2\"\n ],\n url= \"https://github.com/IshanHegde/ElemSymPoly\",\n description=\"Fast, arbitrary precision computation of Elementary Symmetric Polynomials.\",\n long_description = \"\"\"\n \n ElemSymPoly is a high-performance C library with Python bindings that utilizes the GNU MPFR Library for \n precise computation of Elementary Symmetric Polynomials and a custom FFT implimentation. \\n\n \n The Library is currently in development stage and not production ready. \\n\n \n The library is based on applying a divide and conquer approach to compute the elementary symmetric polynomials. \\n\n \n First, the elementary symmetric polynomials of order N is expressed as a product of N order 1 polynomials. \\n\n \n Next, using a divide and conquer approach, the product of N order 1 polynomials is computed by recursively. \\n\n \n After a certain arbitrary threshold (currently set to 8), the polynomials of order 8 or above are computed using FFT. \\n\n \n The FFT algorithm is a custom implementation of the classic recursive Cooley-Tukey FFT algorithm. \\n\n \n This algorithim has a time complexity of O( N log^2 N ) compared to the naive approach of O( N^2 ) and also has\n arbitrary precision support (currently up to 512 decimal places due to stack overflow concerns). \\n\n \n The library also has a Python wrapper for ease of use, and only relies on NumPy, GNU MPFR which in turn relies on\n GNU GMP, Python C headers, CMake, glibc and a C compiler (only tested with GCC). \\n\n \"\"\",\n ext_modules=[CMakeExtension('pyElemSymPoly')],\n cmdclass=dict(build_ext=CMakeBuild),\n zip_safe=False,\n python_requires=\">=3.8\",\n classifiers=[\n \"Intended Audience :: Science/Research\",\n \"Development Status :: 3 - Alpha\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: C\",\n \"Programming Language :: Python\",\n \"Topic :: Scientific/Engineering :: Mathematics\",\n \"Operating System :: POSIX\",\n \"Operating System :: Unix\",\n \"Operating System :: MacOS\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n \"Programming Language :: Python :: 3.12\",\n ]\n\n)\n","repo_name":"IshanHegde/ElemSymPoly","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":7765,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"6507549636","text":"from django.core.management.base import BaseCommand\nfrom django.db import transaction\nfrom people.models import Person\nfrom twitterbot.helpers import TwitterBot\n\nfrom ..twitter import TwitterAPIData\n\nVERBOSE = False\n\n\ndef verbose(*args, **kwargs):\n if VERBOSE:\n print(*args, **kwargs)\n\n\nclass Command(BaseCommand):\n help = (\n \"Use the Twitter API to check / fix Twitter screen names and user IDs\"\n )\n\n def handle_person(self, person):\n twitter_identifiers = person.get_identifiers_of_type(\"twitter_username\")\n\n # If they have any Twitter user IDs, then check to see if we\n # need to update the screen name from that; if so, update\n # the screen name. Skip to the next person. This catches\n # people who have changed their Twitter screen name, or\n # anyone who had a user ID set but not a screen name\n # (which should be rare). If the user ID is not a valid\n # Twitter user ID, it is deleted.\n\n # TODO can forloop be removed? As twitter_identifiers should only be 1\n # due to unique_together constraint on PersonIdentifier model?\n for identifier in twitter_identifiers:\n screen_name = identifier.value or None\n user_id = identifier.internal_identifier\n if user_id:\n verbose(\n \"{person} has a Twitter user ID: {user_id}\".format(\n person=person, user_id=user_id\n )\n )\n\n if user_id not in self.twitter_data.user_id_to_screen_name:\n # user ID not in our list our prefertched twitter_data but\n # before we delete them do a check to see if they were\n # suspended\n if self.twitterbot.is_user_suspended(\n screen_name=screen_name\n ):\n # log the suspension but keep the identifier and move on\n verbose(\n f\"{person}'s Twitter account ({user_id}) is currently suspended.\"\n )\n self.twitterbot.handle_suspended(identifier=identifier)\n continue\n\n # otherwise we know to remove them\n print(\n \"Removing user ID {user_id} for {person_name} as it is not a valid Twitter user ID. {person_url}\".format(\n user_id=user_id,\n person_name=person.name,\n person_url=person.get_absolute_url(),\n )\n )\n self.twitterbot.save(\n person,\n msg=\"This Twitter user ID no longer exists; removing it \",\n )\n identifier.delete()\n continue\n\n correct_screen_name = self.twitter_data.user_id_to_screen_name[\n user_id\n ]\n if not screen_name or screen_name != correct_screen_name:\n msg = \"Correcting the screen name from {old_screen_name} to {correct_screen_name}\".format(\n old_screen_name=screen_name,\n correct_screen_name=correct_screen_name,\n )\n print(msg)\n identifier.value = correct_screen_name\n identifier.extra_data[\"status\"] = \"active\"\n identifier.save()\n self.twitterbot.save(person, msg)\n else:\n if identifier.extra_data.get(\"status\") != \"active\":\n identifier.extra_data[\"status\"] = \"active\"\n identifier.save()\n verbose(\n \"The screen name ({screen_name}) was already correct\".format(\n screen_name=screen_name\n )\n )\n\n # Otherwise, if they have a Twitter screen name (but no\n # user ID, since we already dealt with that case) then\n # find their Twitter user ID and set that as an identifier.\n # If the screen name is not a valid Twitter screen name, it\n # is deleted.\n elif screen_name:\n verbose(\n \"{person} has Twitter screen name ({screen_name}) but no user ID\".format(\n person=person, screen_name=screen_name\n )\n )\n\n if (\n screen_name.lower()\n not in self.twitter_data.screen_name_to_user_id\n ):\n # at this point we have a screen name stored but it is not\n # in the `twitter_data` with valid names and ID's so we do a\n # final check to see if the user is currently suspended\n # before removing\n if self.twitterbot.is_user_suspended(\n screen_name=screen_name\n ):\n # log the suspension and move on to the next one\n verbose(\n f\"{person}'s Twitter account ({screen_name}) is currently suspended.\"\n )\n self.twitterbot.handle_suspended(identifier=identifier)\n continue\n\n # otherwise we know the name is not valid so remove it\n print(\n \"Removing screen name {screen_name} for {person_name} as it is not a valid Twitter screen name. {person_url}\".format(\n screen_name=screen_name,\n person_name=person.name,\n person_url=person.get_absolute_url(),\n )\n )\n # TODO check should the object be deleted here?\n identifier.value = \"\"\n identifier.save()\n return\n\n print(\n \"Adding the user ID {user_id}\".format(\n user_id=self.twitter_data.screen_name_to_user_id[\n screen_name.lower()\n ]\n )\n )\n\n person.tmp_person_identifiers.update_or_create(\n person=person,\n value_type=\"twitter_username\",\n value=screen_name,\n defaults={\n \"internal_identifier\": self.twitter_data.screen_name_to_user_id[\n screen_name.lower()\n ],\n \"extra_data\": {\"status\": \"active\"},\n },\n )\n self.twitterbot.save(person)\n else:\n verbose(\n \"{person} had no Twitter account information\".format(\n person=person\n )\n )\n\n def handle(self, *args, **options):\n global VERBOSE\n VERBOSE = int(options[\"verbosity\"]) > 1\n self.twitterbot = TwitterBot()\n self.twitter_data = TwitterAPIData()\n self.twitter_data.update_from_api()\n # Now go through every person in the database and check their\n # Twitter details. This can take a long time, so use one\n # transaction per person.\n for person_id in Person.objects.order_by(\"name\").values_list(\n \"pk\", flat=True\n ):\n with transaction.atomic():\n # n.b. even though it's inefficient query-wise, we get\n # each person from the database based on their ID\n # within the transaction because the loop we're in\n # takes a long time, other otherwise we might end up\n # with out of date information (e.g. this has happened\n # with the person.versions field, with confusing\n # results...)\n person = Person.objects.get(pk=person_id)\n self.handle_person(person)\n","repo_name":"DemocracyClub/yournextrepresentative","sub_path":"ynr/apps/twitterbot/management/commands/twitterbot_update_usernames.py","file_name":"twitterbot_update_usernames.py","file_ext":"py","file_size_in_byte":8208,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"}
+{"seq_id":"25217295805","text":"from rspecs.commons import DEFAULT_XMLNS, DEFAULT_XS, DEFAULT_SCHEMA_LOCATION,\\\n DSL_PREFIX\nfrom rspecs.commons_of import DEFAULT_OPENFLOW\nfrom rspecs.formatter_base import FormatterBase\nfrom lxml import etree\n\nDEFAULT_AD_SCHEMA_LOCATION = DEFAULT_SCHEMA_LOCATION\nDEFAULT_AD_SCHEMA_LOCATION += DSL_PREFIX + \"3/ad.xsd \"\nDEFAULT_AD_SCHEMA_LOCATION += DSL_PREFIX + \"ext/openflow/3/of-ad.xsd\"\n\n\nclass OFv3AdvertisementFormatter(FormatterBase):\n def __init__(self, xmlns=DEFAULT_XMLNS, xs=DEFAULT_XS,\n openflow=DEFAULT_OPENFLOW,\n schema_location=DEFAULT_AD_SCHEMA_LOCATION):\n super(OFv3AdvertisementFormatter, self).__init__(\n \"advertisement\", schema_location, {\"openflow\": \"%s\" % (openflow)},\n xmlns, xs)\n self.__of = openflow\n\n def add_datapath(self, rspec, dpath):\n d = etree.SubElement(rspec, \"{%s}datapath\" % (self.__of))\n d.attrib[\"component_id\"] = dpath.get(\"component_id\")\n d.attrib[\"component_manager_id\"] = dpath.get(\"component_manager_id\")\n d.attrib[\"dpid\"] = dpath.get(\"dpid\")\n\n for p in dpath.get('ports'):\n port = etree.SubElement(d, \"{%s}port\" % (self.__of))\n port.attrib[\"num\"] = p.get(\"num\")\n if p.get(\"name\") is not None:\n port.attrib[\"name\"] = p.get(\"name\")\n\n def datapath(self, dpath):\n self.add_datapath(self.rspec, dpath)\n\n def add_of_link(self, rspec, link):\n l = etree.SubElement(rspec, \"{%s}link\" % (self.__of))\n l.attrib[\"component_id\"] = link.get(\"component_id\")\n\n dpids_ = link.get(\"dpids\")\n ports_ = link.get(\"ports\")\n for i in range(len(dpids_)):\n dp = etree.SubElement(l, \"{%s}datapath\" % (self.__of))\n dp.attrib[\"component_id\"] = dpids_[i].get(\"component_id\")\n dp.attrib[\"component_manager_id\"] =\\\n dpids_[i].get(\"component_manager_id\")\n dp.attrib[\"dpid\"] = dpids_[i].get(\"dpid\")\n\n port = etree.SubElement(l, \"{%s}port\" % (self.__of))\n port.attrib[\"port_num\"] = ports_[i].get(\"port_num\")\n\n def of_link(self, link):\n self.add_of_link(self.rspec, link)\n\n def add_fed_link(self, rspec, link):\n l = etree.SubElement(rspec, \"{%s}link\" % (self.__of))\n l.attrib[\"component_id\"] = link.get(\"component_id\")\n\n ltype = etree.SubElement(l, \"{%s}link_type\" % (self.__of))\n ltype.attrib[\"name\"] = link.get(\"link_type_name\")\n\n cm = etree.SubElement(l, \"{%s}component_manager\" % (self.__of))\n cm.attrib[\"name\"] = link.get(\"component_manager_name\")\n\n for ifref in link.get(\"interface_ref_id\"):\n ref = etree.SubElement(l, \"{%s}interface_ref\" % (self.__of))\n ref.attrib[\"component_id\"] = ifref\n\n def fed_link(self, link):\n self.add_fed_link(self.rspec, link)\n","repo_name":"dana-i2cat/felix","sub_path":"modules/resource/utilities/rspecs/openflow/advertisement_formatter.py","file_name":"advertisement_formatter.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"}
+{"seq_id":"24763476811","text":"import discord\nimport datetime\nfrom discord.ext import tasks\nimport sqlite3\nfrom sqlite3 import Error\nfrom datetime import datetime\nfrom os import getenv\n\nclient = discord.Client()\n\n\ndef create_database_connection(database_name):\n \"\"\" create a database connection to the SQLite database\n specified by db_file\n :param database_name: database file\n :return: Connection object or None\n \"\"\"\n conn = None\n try:\n conn = sqlite3.connect(database_name)\n except Error as e:\n print(e)\n return conn\n\n\ndef query_database_for_reminders(current_time):\n \"\"\"\n Query reminders by datetime\n :param current_time:\n :return:\n \"\"\"\n conn = create_database_connection('reminders.db')\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM reminders WHERE datetime=?\", (current_time,))\n result = cur.fetchone()\n cur.execute(\"DELETE FROM reminders WHERE datetime=?\", (current_time,))\n conn.commit()\n return result\n\n\n@tasks.loop(seconds=20)\nasync def check_for_reminders():\n now = datetime.utcnow()\n current_time = f'{now.year},{now.month},{now.day},{now.hour},{now.minute}'\n reminders = query_database_for_reminders(current_time)\n if reminders:\n embed = discord.Embed(title=\"Link to submit forecast\", url=\"https://www.wxchallenge.com/submit_forecast.php\",\n description=\"Don't forget to submit your forecast! You have 30 more minutes.\",\n color=0xff2600)\n embed.set_author(name=\"WxChallenge Reminder\", url=\"https://www.wxchallenge.com/submit_forecast.php\",\n icon_url=\"https://www.wxchallenge.com/img/wxc_logo.png\")\n channel = client.get_channel(841145714726010920)\n await channel.send(embed=embed)\n\n\n@client.event\nasync def on_ready():\n check_for_reminders.start()\n\n\nclient.run(getenv('DISCORD_TOKEN'))\n","repo_name":"arian-nasr/WxChallengeDiscordReminderBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"18234927429","text":"#coding:utf-8\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.webdriver.support.select import Select\r\nfrom selenium.common.exceptions import *\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom case.happy_public.wang_logging import Log\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\n\r\nlog = Log()\r\nsuccess = \"SUCCESS \"\r\nfail = \"FAIL \"\r\nscreen_file = \"D:\\\\test\\\\happyHiiso3\\\\file\\\\\"\r\n\r\ndef Browser(browser='ff', remoteAddress=None):\r\n t1 = time.time()\r\n dc = {'platform': 'ANY', 'browserName': 'chrome', 'version': '', 'javascriptEnabled': True}\r\n dr = None\r\n if remoteAddress is None:\r\n if browser == \"firefox\" or browser == \"ff\":\r\n dr = webdriver.Firefox()\r\n elif browser == \"chrome\" or browser == \"Chrome\":\r\n dr = webdriver.Chrome()\r\n elif browser == \"internet explorer\" or browser == \"ie\":\r\n dr = webdriver.Ie()\r\n elif browser == \"opera\":\r\n dr = webdriver.Opera()\r\n elif browser == \"phantomjs\":\r\n dr = webdriver.PhantomJS()\r\n elif browser == \"edge\":\r\n dr = webdriver.Edge()\r\n else:\r\n if browser == \"RChrome\":\r\n dr = webdriver.Remote(command_executor='http://' + remoteAddress + '/wd/hub',\r\n desired_capabilities=dc)\r\n elif browser == \"RIE\":\r\n dc['browserName'] = 'internet explorer'\r\n dr = webdriver.Remote(command_executor='http://' + remoteAddress + '/wd/hub',\r\n desired_capabilities=dc)\r\n elif browser == \"RFirefox\":\r\n dc['browserName'] = 'firefox'\r\n dc['marionette'] = False\r\n dr = webdriver.Remote(command_executor='http://' + remoteAddress + '/wd/hub',\r\n desired_capabilities=dc)\r\n try:\r\n driver = dr\r\n log.info(\"{0} Start a new browser: {1}, Spend {2} seconds\".format(success, browser, time.time() - t1))\r\n return driver\r\n except Exception:\r\n raise NameError(\"Not found {0} browser,You can enter 'ie','ff',\"\r\n \"'chrome','RChrome','RIe' or 'RFirefox'.\".format(browser))\r\n\r\n\r\nclass Wang(object):\r\n #基于原生的selenium 框架做了二次封装\r\n # def __init__(self, browser='ff', remoteAddress=None):\r\n # \"\"\"\r\n # remote consle:\r\n # dr = PySelenium('RChrome','127.0.0.1:8080')\r\n # \"\"\"\r\n # t1 = time.time()\r\n # dc = {'platform': 'ANY', 'browserName': 'chrome', 'version': '', 'javascriptEnabled': True}\r\n # dr = None\r\n # if remoteAddress is None:\r\n # if browser == \"firefox\" or browser == \"ff\":\r\n # dr = webdriver.Firefox()\r\n # elif browser == \"chrome\" or browser == \"Chrome\":\r\n # dr = webdriver.Chrome()\r\n # elif browser == \"internet explorer\" or browser == \"ie\":\r\n # dr = webdriver.Ie()\r\n # elif browser == \"opera\":\r\n # dr = webdriver.Opera()\r\n # elif browser == \"phantomjs\":\r\n # dr = webdriver.PhantomJS()\r\n # elif browser == \"edge\":\r\n # dr = webdriver.Edge()\r\n # else:\r\n # if browser == \"RChrome\":\r\n # dr = webdriver.Remote(command_executor='http://' + remoteAddress + '/wd/hub',\r\n # desired_capabilities=dc)\r\n # elif browser == \"RIE\":\r\n # dc['browserName'] = 'internet explorer'\r\n # dr = webdriver.Remote(command_executor='http://' + remoteAddress + '/wd/hub',\r\n # desired_capabilities=dc)\r\n # elif browser == \"RFirefox\":\r\n # dc['browserName'] = 'firefox'\r\n # dc['marionette'] = False\r\n # dr = webdriver.Remote(command_executor='http://' + remoteAddress + '/wd/hub',\r\n # desired_capabilities=dc)\r\n # try:\r\n # self.driver = dr\r\n # self.my_print(\"{0} Start a new browser: {1}, Spend {2} seconds\".format(success,browser,time.time()-t1))\r\n # except Exception:\r\n # raise NameError(\"Not found {0} browser,You can enter 'ie','ff',\"\r\n # \"'chrome','RChrome','RIe' or 'RFirefox'.\".format( browser))\r\n def __init__(self, driver):\r\n self.driver = driver\r\n\r\n def my_print(self,msg):\r\n log.info(msg)\r\n\r\n def open(self,url,t='',timeout=10):\r\n '''\r\n 使用get打开url后,最大化窗口,判断title是否符合预期\r\n Usage:\r\n driver = Wang()\r\n driver.open(url,t='')\r\n\r\n '''\r\n t1 = time.time()\r\n try:\r\n self.driver.get(url)\r\n self.driver.maximize_window()\r\n self.my_print(\"{0} Navigated to {1}, Spend {2} seconds\".format(success, url, time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to load {1}, Spend {2} seconds\".format(fail, url, time.time() - t1))\r\n raise\r\n\r\n def max_window(self):\r\n '''\r\n Set browser window maximized.\r\n\r\n Usage:\r\n driver.max_window()\r\n '''\r\n t1 = time.time()\r\n self.driver.maximize_window()\r\n self.my_print(\"{0} Set browser window maximized, Spend {1} seconds\".format(success, time.time() - t1))\r\n\r\n def set_window(self, wide, high):\r\n '''\r\n Set browser window wide and high.\r\n\r\n Usage:\r\n driver.set_window(wide,high)\r\n '''\r\n t1 = time.time()\r\n self.driver.set_window_size(wide, high)\r\n self.my_print(\"{0} Set browser window wide: {1},high: {2}, Spend {3} seconds\".format(\r\n success,wide, high,time.time() - t1))\r\n\r\n def find_element(self,locator,timeout=10):\r\n '''\r\n 定位元素,参数locator是元祖类型\r\n Usage:\r\n locator = (\"id\",\"xxx\")\r\n driver.find_element(locator)\r\n\r\n by_id= \"id\"\r\n by_xpath = \"xpath\"\r\n by_link_text = \"link text\"\r\n by_partial_text = \"partial link text\"\r\n by_name = \"name\"\r\n by_tag_name = \"tag name\"\r\n by_class_name = \"class name\"\r\n by_css_selector = \"css selector\"\r\n\r\n '''\r\n try:\r\n element = WebDriverWait(self.driver,timeout,1).until(EC.presence_of_element_located(locator))\r\n return element\r\n except Exception:\r\n nowTime = time.strftime(\"%Y_%m_%d_%H_%M_%S\")\r\n self.driver.get_screenshot_as_file(screen_file+\"%s.jpg\"%nowTime)\r\n\r\n def find_elements(self,locator,timeout=10):\r\n #定位一组元素\r\n try:\r\n elements = WebDriverWait(self.driver,timeout,1).until(EC.presence_of_all_elements_located(locator))\r\n return elements\r\n except Exception:\r\n nowTime = time.strftime(\"%Y_%m_%d_%H_%M_%S\")\r\n self.driver.get_screenshot_as_file(screen_file+\"%s.jpg\"%nowTime)\r\n\r\n def send_keys(self,locator,text):\r\n '''\r\n Operation input box.\r\n Usage:\r\n locator = (\"id\", \"xxx\")\r\n driver.send_keys(locator,text)\r\n '''\r\n # el = self.find_element(locator)\r\n # el.send_keys(text)\r\n t1 = time.time()\r\n try:\r\n el = self.find_element(locator)\r\n el.send_keys(text)\r\n self.my_print(\"{0} Typed element: <{1}> content: {2}, Spend {3} seconds\".format(success,\r\n locator, text,\r\n time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to type element: <{1}> content: {2}, Spend {3} seconds\".format(fail,\r\n locator, text,\r\n time.time() - t1))\r\n raise\r\n\r\n def clear_send_keys(self, locator, text):\r\n \"\"\"\r\n Clear and input element.\r\n\r\n Usage:\r\n driver.clear_type((\"id\", \"kw\"),\"selenium\")\r\n \"\"\"\r\n t1 = time.time()\r\n try:\r\n el = self.find_element(locator)\r\n el.clear()\r\n el.send_keys(text)\r\n self.my_print(\"{0} Clear and type element: <{1}> content: {2}, Spend {3} seconds\".format(success,\r\n locator, text,time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to clear and type element: <{1}> content: {2}, Spend {3} seconds\".format(fail,\r\n locator, text,time.time() - t1))\r\n raise\r\n\r\n def send_keys_and_enter(self, locator, text, secs=0.5):\r\n \"\"\"\r\n Operation input box. 1、input message,sleep 0.5s;2、input ENTER.\r\n\r\n Usage:\r\n driver.type_css_keys(('id','kw'),'beck')\r\n \"\"\"\r\n t1 = time.time()\r\n try:\r\n ele = self.find_element(locator)\r\n ele.send_keys(text)\r\n time.sleep(secs)\r\n ele.send_keys(Keys.ENTER)\r\n self.my_print(\"{0} Element <{1}> type content: {2},and sleep {3} seconds,input ENTER key, Spend {4} seconds\".format(\r\n success,locator,text,secs,time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable element <{1}> type content: {2},and sleep {3} seconds,input ENTER key, Spend {4} seconds\".\r\n format(fail, locator, text, secs, time.time() - t1))\r\n raise\r\n\r\n def click(self,locator):\r\n '''\r\n 点击操作\r\n Usage:\r\n locator(\"id\",\"xxx\")\r\n driver.click(locator)\r\n '''\r\n t1 = time.time()\r\n try:\r\n el = self.find_element(locator)\r\n el.click()\r\n self.my_print(\"{0} Clicked element: <{1}>, Spend {2} seconds\".format(success, locator, time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to click element: <{1}>, Spend {2} seconds\".format(fail, locator, time.time() - t1))\r\n raise\r\n\r\n def right_click(self,locator):\r\n '''\r\n Right click element.\r\n 鼠标右击\r\n Usage:\r\n driver.right_click((\"id\",\"kw\"))\r\n '''\r\n t1 = time.time()\r\n try:\r\n el = self.find_element(locator)\r\n ActionChains(self.driver).context_click(el).perform()\r\n self.my_print(\"{0} Right click element: <{1}>, Spend {2} seconds\".format(success, locator, time.time() - t1))\r\n except Exception:\r\n self.my_print(\r\n \"{0} Unable to right click element: <{1}>, Spend {2} seconds\".format(fail, locator, time.time() - t1))\r\n raise\r\n\r\n def double_click(self, locator):\r\n '''\r\n Double click element.\r\n\r\n Usage:\r\n driver.double_click((\"id\",\"kw\"))\r\n '''\r\n t1 = time.time()\r\n try:\r\n el = self.find_element(locator)\r\n ActionChains(self.driver).double_click(el).perform()\r\n self.my_print(\"{0} Double click element: <{1}>, Spend {2} seconds\".format(success, locator, time.time() - t1))\r\n except Exception:\r\n self.my_print(\r\n \"{0} Unable to double click element: <{1}>, Spend {2} seconds\".format(fail, locator, time.time() - t1))\r\n raise\r\n\r\n def drag_and_drop(self, locator, target_locator):\r\n '''\r\n Drags an element a certain distance and then drops it.\r\n 鼠标拖动\r\n Usage:\r\n driver.drag_and_drop((\"id\",\"kw\"),(\"id2\",\"kw2\"))\r\n '''\r\n t1 = time.time()\r\n try:\r\n element = self.find_element(locator)\r\n target = self.find_element(target_locator)\r\n ActionChains(self.driver).drag_and_drop(element, target).perform()\r\n self.my_print(\"{0} Drag and drop element: <{1}> to element: <{2}>, Spend {3} seconds\".format(success,\r\n locator, target_locator,\r\n time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to drag and drop element: <{1}> to element: <{2}>, Spend {3} seconds\".format(fail,\r\n locator,\r\n target_locator,\r\n time.time() - t1))\r\n raise\r\n\r\n def submit(self, locator):\r\n '''\r\n Submit the specified form.\r\n\r\n Usage:\r\n driver.submit((\"id\",\"kw\"))\r\n '''\r\n t1 = time.time()\r\n try:\r\n el = self.find_element(locator)\r\n el.submit()\r\n self.my_print(\r\n \"{0} Submit form args element: <{1}>, Spend {2} seconds\".format(success, locator, time.time() - t1))\r\n except Exception:\r\n self.my_print(\r\n \"{0} Unable to submit form args element: <{1}>, Spend {2} seconds\".format(fail, locator, time.time() - t1))\r\n raise\r\n\r\n def F5(self):\r\n '''\r\n Refresh the current page.\r\n\r\n Usage:\r\n driver.F5()\r\n '''\r\n t1 = time\r\n self.driver.refresh()\r\n self.my_print(\"{0} Refresh the current page, Spend {1} seconds\".format(success, time.time() - t1))\r\n\r\n def is_element_exist(self, locator):\r\n \"\"\"\r\n judge element is exist,The return result is true or false.\r\n\r\n Usage:\r\n driver.element_exist((\"id\",\"kw\"))\r\n \"\"\"\r\n t1 = time.time()\r\n try:\r\n self.driver.find_element(locator)\r\n self.my_print(\"{0} Element: <{1}> is exist, Spend {2} seconds\".format(success,locator, time.time() - t1))\r\n return True\r\n except TimeoutException:\r\n self.my_print(\"{0} Element: <{1}> is not exist, Spend {2} seconds\".format(fail, locator, time.time() - t1))\r\n return False\r\n\r\n def is_text_in_element(self,locator,text,timeout=10):\r\n '''\r\n 判断文本是否在元素里,返回判断结果布尔值\r\n usage:\r\n locator=(id\", \"xxx\")\r\n text = \"\"\r\n result = driver.is_text_in_element(locator,text)\r\n '''\r\n try:\r\n result = WebDriverWait(self.driver,timeout,1).until(EC.text_to_be_present_in_element(locator,text))\r\n except TimeoutException:\r\n print(\"元素没定位到:\"+str(locator))\r\n nowTime = time.strftime(\"%Y_%m_%d_%H_%M_%S\")\r\n self.driver.get_screenshot_as_file(screen_file + \"%s.jpg\" % nowTime)\r\n return False\r\n else:\r\n return result\r\n\r\n def is_value_in_element(self,locator,value,timeout=10):\r\n '''\r\n 判断value值是否在元素里,返回判断结果布尔值\r\n usage:\r\n locator=(id\", \"xxx\")\r\n value =\r\n result = driver.is_value_in_element(locator,text)\r\n '''\r\n try:\r\n result = WebDriverWait(self.driver,timeout,1).until(EC.text_to_be_present_in_element_value(locator,value))\r\n except TimeoutException:\r\n print(\"元素没定位到:\"+str(locator))\r\n nowTime = time.strftime(\"%Y_%m_%d_%H_%M_%S\")\r\n self.driver.get_screenshot_as_file(screen_file + \"%s.jpg\" % nowTime)\r\n return False\r\n else:\r\n return result\r\n\r\n def is_title(self,title,timeout=10):\r\n # 判断title是否等于driver.title\r\n result = WebDriverWait(self.driver,timeout,1).until(EC.title_is(title))\r\n return result\r\n\r\n def is_title_contains(self,str,timeout=10):\r\n # 判断title包含于driver.title\r\n result = WebDriverWait(self.driver,timeout,1).until(EC.title_contains(str))\r\n return result\r\n\r\n def is_selected(self,locator,timeout=10):\r\n #判断元素是否被选中,返回布尔值\r\n result = WebDriverWait(self.driver,timeout,1).until(EC.element_located_to_be_selected(locator))\r\n return result\r\n\r\n def is_selected_be(self,locator,selected=True,timeout=10):\r\n #判断元素的状态,selected的期望值:True/False, 返回布尔值\r\n result = WebDriverWait(self.driver,timeout,1).until(EC.element_located_selection_state_to_be(locator,selected))\r\n return result\r\n\r\n def is_alert_present(self,timeout=10):\r\n #判断页面是否有alert, 有就返回alert, 没有就返回False\r\n result = WebDriverWait(self.driver,timeout,1).until(EC.alert_is_present())\r\n return result\r\n\r\n def is_visibility(self, locator, timeout=10):\r\n '''元素可见返回本身,不可见返回Fasle'''\r\n result = WebDriverWait(self.driver, timeout,1).until(EC.visibility_of_element_located(locator))\r\n return result\r\n\r\n def is_invisibility(self, locator, timeout=10):\r\n '''元素可见返回本身,不可见返回True,没找到元素也返回True'''\r\n result = WebDriverWait(self.driver, timeout, 1).until(EC.invisibility_of_element_located(locator))\r\n return result\r\n\r\n def is_clickable(self, locator, timeout=10):\r\n '''元素可以点击is_enabled返回本身,不可点击返回Fasle'''\r\n result = WebDriverWait(self.driver, timeout, 1).until(EC.element_to_be_clickable(locator))\r\n return result\r\n\r\n def is_located(self, locator, timeout=10):\r\n '''判断元素有没被定位到(并不意味着可见),定位到返回element,没定位到返回False'''\r\n result = WebDriverWait(self.driver, timeout, 1).until(EC.presence_of_element_located(locator))\r\n return result\r\n\r\n def move_to_element(self,locator):\r\n #鼠标悬停操作\r\n element = self.find_element(locator)\r\n ActionChains(self.driver).move_to_element(element).perform()\r\n\r\n def back(self):\r\n #浏览器页面回退\r\n self.driver.back()\r\n\r\n def forward(self):\r\n #浏览器前进\r\n self.driver.forward()\r\n\r\n def close(self):\r\n \"\"\"\r\n Simulates the user clicking the \"close\" button in the titlebar of a popup\r\n window or tab.\r\n\r\n Usage:\r\n driver.close()\r\n \"\"\"\r\n t1 = time.time()\r\n self.driver.close()\r\n self.my_print(\"{0} Closed current window, Spend {1} seconds\".format(success, time.time() - t1))\r\n\r\n def quit(self):\r\n \"\"\"\r\n Quit the driver and close all the windows.\r\n\r\n Usage:\r\n driver.quit()\r\n \"\"\"\r\n t1 = time.time()\r\n self.driver.quit()\r\n self.my_print(\"{0} Closed all window and quit the driver, Spend {1} seconds\".format(success, time.time() - t1))\r\n\r\n def get_title(self):\r\n #获取driver.title\r\n t1 = time.time()\r\n title = self.driver.title\r\n self.my_print(\"{0} Get current window title, Spend {1} seconds\".format(success, time.time() - t1))\r\n return title\r\n\r\n def get_text(self,locator):\r\n \"\"\"\r\n Get element text information.\r\n\r\n Usage:\r\n driver.get_text((\"id\",\"kw\"))\r\n \"\"\"\r\n t1 = time.time()\r\n try:\r\n element = self.find_element(locator)\r\n text = element.text\r\n self.my_print(\r\n \"{0} Get element text element: <{1}>, Spend {2} seconds\".format(success, locator, time.time() - t1))\r\n return text\r\n except Exception:\r\n self.my_print(\r\n \"{0} Unable to get element text element: <{1}>, Spend {2} seconds\".format(fail, locator, time.time() - t1))\r\n raise\r\n\r\n def get_url(self):\r\n '''\r\n Get the URL address of the current page.\r\n\r\n Usage:\r\n driver.get_url()\r\n '''\r\n t1 = time.time()\r\n url = self.driver.current_url\r\n self.my_print(\"{0} Get current window url, Spend {1} seconds\".format(success, time.time() - t1))\r\n return url\r\n\r\n def wait(self, secs):\r\n \"\"\"\r\n Implicitly wait.All elements on the page.\r\n\r\n Usage:\r\n driver.wait(10)\r\n \"\"\"\r\n t1 = time.time()\r\n self.driver.implicitly_wait(secs)\r\n self.my_print(\"{0} Set wait all element display in {1} seconds, Spend {2} seconds\".format(success,\r\n secs,time.time() - t1))\r\n\r\n def get_screenshot(self, file_path):\r\n '''\r\n Get the current window screenshot.\r\n\r\n Usage:\r\n driver.get_screenshot('/Screenshots/foo.jpg')\r\n driver.get_screenshot('/Screenshots/foo.png')\r\n '''\r\n t1 = time.time()\r\n try:\r\n self.driver.get_screenshot_as_file(file_path)\r\n self.my_print(\"{0} Get the current window screenshot,path: {1}, Spend {2} seconds\".format(success,\r\n file_path,\r\n time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to get the current window screenshot,path: {1}, Spend {2} seconds\".format(fail,\r\n file_path,\r\n time.time() - t1))\r\n raise\r\n\r\n # def get_screenshot_as_base64(self):\r\n # self.driver.get_screenshot_as_base64()\r\n\r\n def get_attribute(self, locator, name):\r\n '''获取属性'''\r\n t1 = time.time()\r\n try:\r\n el = self.find_element(locator)\r\n attribute = el.get_attribute(name)\r\n self.my_print(\"{0} Get attribute element: <{1}>,attribute: {2}, Spend {3} seconds\".format(success,\r\n locator, attribute,\r\n time.time() - t1))\r\n return attribute\r\n except Exception:\r\n self.my_print(\"{0} Unable to get attribute element: <{1}>,attribute: {2}, Spend {3} seconds\".format(fail,\r\n locator,\r\n attribute,\r\n time.time() - t1))\r\n raise\r\n\r\n def accept_alert(self):\r\n '''\r\n Accept warning box.\r\n\r\n Usage:\r\n driver.accept_alert()\r\n '''\r\n t1 = time.time()\r\n self.driver.switch_to.alert.accept()\r\n self.my_print(\"{0} Accept warning box, Spend {1} seconds\".format(success, time.time() - t1))\r\n\r\n def dismiss_alert(self):\r\n '''\r\n Dismisses the alert available.\r\n\r\n Usage:\r\n driver.dismiss_alert()\r\n '''\r\n t1 = time.time()\r\n self.driver.switch_to.alert.dismiss()\r\n self.my_print(\"{0} Dismisses the alert available, Spend {1} seconds\".format(success, time.time() - t1))\r\n\r\n def switch_to_frame(self, locator):\r\n '''\r\n Switch to the specified frame.\r\n\r\n Usage:\r\n driver.switch_to_frame((\"id\",\"kw\"))\r\n '''\r\n t1 = time.time()\r\n try:\r\n iframe_el = self.find_element(locator)\r\n self.driver.switch_to.frame(iframe_el)\r\n self.my_print(\r\n \"{0} Switch to frame element: <{1}>, Spend {2} seconds\".format(success, locator, time.time() - t1))\r\n except Exception:\r\n self.my_print(\r\n \"{0} Unable switch to frame element: <{1}>, Spend {2} seconds\".format(fail, locator, time.time() - t1))\r\n raise\r\n\r\n def switch_to_frame_out(self):\r\n '''\r\n Returns the current form machine form at the next higher level.\r\n Corresponding relationship with switch_to_frame () method.\r\n\r\n Usage:\r\n driver.switch_to_frame_out()\r\n '''\r\n t1 = time.time()\r\n self.driver.switch_to.default_content()\r\n self.my_print(\"{0} Switch to frame out, Spend {1} seconds\".format(success, time.time() - t1))\r\n\r\n\r\n def open_new_window(self, locator):\r\n '''\r\n Open the new window and switch the handle to the newly opened window.\r\n\r\n Usage:\r\n driver.open_new_window()\r\n '''\r\n t1 = time.time()\r\n try:\r\n original_windows = self.driver.current_window_handle\r\n el = self.find_element(locator)\r\n el.click()\r\n all_handles = self.driver.window_handles\r\n for handle in all_handles:\r\n if handle != original_windows:\r\n self.driver.switch_to.window(handle)\r\n self.my_print(\"{0} Click element: <{1}> open a new window and swich into, Spend {2} seconds\".format(success,\r\n locator,\r\n time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Click element: <{1}> open a new window and swich into, Spend {2} seconds\".format(fail,\r\n locator,\r\n time.time() - t1))\r\n raise\r\n\r\n def into_new_window(self):\r\n \"\"\"\r\n Into the new window.\r\n\r\n Usage:\r\n dirver.into_new_window()\r\n \"\"\"\r\n t1 = time.time()\r\n try:\r\n all_handle = self.driver.window_handles\r\n flag = 0\r\n while len(all_handle) < 2:\r\n time.sleep(1)\r\n all_handle = self.driver.window_handles\r\n flag += 1\r\n if flag == 5:\r\n break\r\n self.driver.switch_to.window(all_handle[-1])\r\n self.my_print(\"{0} Switch to the new window,new window's url: {1}, Spend {2} seconds\".format(success,\r\n self.driver.current_url,time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable switch to the new window, Spend {1} seconds\".format(fail, time.time() - t1))\r\n raise\r\n\r\n def js_execute(self, js):\r\n '''执行js'''\r\n t1 = time.time()\r\n try:\r\n self.driver.execute_script(js)\r\n self.my_print(\r\n \"{0} Execute javascript scripts: {1}, Spend {2} seconds\".format(success, js, time.time() - t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to execute javascript scripts: {1}, Spend {2} seconds\".format(fail,\r\n js,\r\n time.time() - t1))\r\n raise\r\n\r\n def js_focus_element(self, locator):\r\n '''聚焦元素'''\r\n target = self.find_element(locator)\r\n self.driver.execute_script(\"arguments[0].scrollIntoView();\", target)\r\n\r\n def js_scroll_top(self):\r\n '''滚动到顶部'''\r\n js = \"window.scrollTo(0,0)\"\r\n self.driver.execute_script(js)\r\n\r\n def js_scroll_end(self):\r\n '''滚动到底部'''\r\n js = \"window.scrollTo(0,document.body.scrollHeight)\"\r\n self.driver.execute_script(js)\r\n\r\n def js_click(self, css):\r\n \"\"\"\r\n Input a css selecter,use javascript click element.\r\n Usage:\r\n driver.js_click('#buttonid')\r\n \"\"\"\r\n t1 = time.time()\r\n js_str = \"$('{0}').click()\".format(css)\r\n try:\r\n self.driver.execute_script(js_str)\r\n self.my_print(\"{0} Use javascript click element: {1}, Spend {2} seconds\".format(success,js_str,time.time()-t1))\r\n except Exception:\r\n self.my_print(\"{0} Unable to use javascript click element: {1}, Spend {2} seconds\".format(fail,\r\n js_str, time.time() - t1))\r\n raise\r\n\r\n # def js_input_value(self, css, str):\r\n # \"\"\"\r\n # Input a css selecter,str,use javascript to set input.value.\r\n #\r\n # Usage:\r\n # driver.js_input_value('#buttonid',str)\r\n # \"\"\"\r\n # t1 = time.time()\r\n # js_str = \"document.getElementById('{0}').value='{2}')\".format(css,str)\r\n # try:\r\n # self.driver.execute_script(js_str)\r\n # self.my_print(\"{0} Use javascript set input.value : {1}, Spend {2} seconds\".format(success,js_str,time.time()-t1))\r\n # except Exception:\r\n # self.my_print(\"{0} Unable to use javascript set input.value: {1}, Spend {2} seconds\".format(fail,\r\n # js_str, time.time() - t1))\r\n # raise\r\n\r\n def select_by_index(self, locator, index):\r\n '''通过索引,index是索引第几个,从0开始'''\r\n element = self.find_element(locator)\r\n Select(element).select_by_index(index)\r\n\r\n def select_by_value(self, locator, value):\r\n '''通过value属性'''\r\n element = self.find_element(locator)\r\n Select(element).select_by_value(value)\r\n\r\n def select_by_text(self, locator, text):\r\n '''通过文本值定位'''\r\n element = self.find_element(locator)\r\n Select(element).select_by_value(text)\r\n\r\nif __name__ == '__main__':\r\n # if下面的代码都是测试调试的代码,自测内容\r\n # driver = browser()\r\n # 返回类的实例:打开浏览器\r\n driver_n = Wang(Browser())\r\n # 返回类的实例:打开浏览器\r\n driver_n.open(\"http://www.baidu.com\") # 打开url,顺便判断打开的页面对不对\r\n #获取页面title\r\n input_loc = (\"id\", \"kw\")\r\n print(driver_n.get_title())\r\n #输入yoyo\r\n el = driver_n.find_element(input_loc)\r\n driver_n.send_keys(input_loc, \"yoyo\")\r\n time.sleep(2)\r\n #清空搜索栏,重新输入“美女图片”,点击搜索\r\n driver_n.clear_send_keys(input_loc,\"美女图片\")\r\n driver_n.click((\"id\",\"su\"))\r\n # print (driver_n.is_text_in_element((\"name\", \"tj_trmap\"), \"地图\"))\r\n #鼠标悬停在设置按钮上\r\n set_loc = (\"link text\",\"设置\")\r\n driver_n.move_to_element(set_loc)\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"wanghaihong200/Wang-selenium","sub_path":"Wang-selenium/case/happy_public/wang_selenium.py","file_name":"wang_selenium.py","file_ext":"py","file_size_in_byte":31186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"7806940679","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nimport SE_VAF, SE_select_language\nfrom decimal import Decimal\n\n\nclass Ui_Form(object):\n counter = 0\n\n def __init__(self, saved_dict):\n self.displaylang_result = 0\n self.lang = \"None\"\n self.totalcount = 0\n self.vaf_value = 0\n self.fp = 0\n self.new_dict = saved_dict\n # print(\"Printing saved dict: {}\".format(saved_dict))\n Ui_Form.counter += 1\n\n def setupUi(self, Form, fpname):\n Form.setObjectName(\"Form\")\n Form.resize(717, 603)\n self.label_12 = QtWidgets.QLabel(Form)\n self.label_12.setGeometry(QtCore.QRect(450, 60, 51, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_12.setFont(font)\n self.label_12.setObjectName(\"label_12\")\n self.ILF_Label_2 = QtWidgets.QLabel(Form)\n self.ILF_Label_2.setGeometry(QtCore.QRect(580, 250, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.ILF_Label_2.setFont(font)\n self.ILF_Label_2.setObjectName(\"ILF_Label_2\")\n self.label_13 = QtWidgets.QLabel(Form)\n self.label_13.setGeometry(QtCore.QRect(350, 60, 51, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_13.setFont(font)\n self.label_13.setObjectName(\"label_13\")\n self.horizontalLayoutWidget_6 = QtWidgets.QWidget(Form)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(10, 140, 521, 31))\n self.horizontalLayoutWidget_6.setObjectName(\"horizontalLayoutWidget_6\")\n self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_6)\n self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_6.setObjectName(\"horizontalLayout_6\")\n self.label_14 = QtWidgets.QLabel(self.horizontalLayoutWidget_6)\n self.label_14.setObjectName(\"label_14\")\n self.horizontalLayout_6.addWidget(self.label_14)\n self.EO_lineedit_2 = QtWidgets.QLineEdit(self.horizontalLayoutWidget_6)\n self.EO_lineedit_2.setMinimumSize(QtCore.QSize(100, 0))\n self.EO_lineedit_2.setMaximumSize(QtCore.QSize(50, 16777215))\n self.EO_lineedit_2.setObjectName(\"EO_lineedit_2\")\n self.horizontalLayout_6.addWidget(self.EO_lineedit_2)\n self.radioButton_16 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_6)\n self.radioButton_16.setObjectName(\"radioButton_16\")\n self.horizontalLayout_6.addWidget(self.radioButton_16)\n self.radioButton_17 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_6)\n self.radioButton_17.setObjectName(\"radioButton_17\")\n self.horizontalLayout_6.addWidget(self.radioButton_17)\n self.radioButton_18 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_6)\n self.radioButton_18.setObjectName(\"radioButton_18\")\n self.horizontalLayout_6.addWidget(self.radioButton_18)\n self.FP_Label_2 = QtWidgets.QLabel(Form)\n self.FP_Label_2.setGeometry(QtCore.QRect(580, 400, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.FP_Label_2.setFont(font)\n self.FP_Label_2.setObjectName(\"FP_Label_2\")\n self.label_15 = QtWidgets.QLabel(Form)\n self.label_15.setGeometry(QtCore.QRect(300, 10, 151, 31))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setBold(True)\n font.setWeight(75)\n self.label_15.setFont(font)\n self.label_15.setObjectName(\"label_15\")\n self.EO_Label_2 = QtWidgets.QLabel(Form)\n self.EO_Label_2.setGeometry(QtCore.QRect(580, 150, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.EO_Label_2.setFont(font)\n self.EO_Label_2.setObjectName(\"EO_Label_2\")\n self.EI_Label_2 = QtWidgets.QLabel(Form)\n self.EI_Label_2.setGeometry(QtCore.QRect(580, 100, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.EI_Label_2.setFont(font)\n self.EI_Label_2.setObjectName(\"EI_Label_2\")\n self.Error_Label = QtWidgets.QLabel(Form)\n self.Error_Label.setGeometry(QtCore.QRect(200, 340, 371, 31))\n self.Error_Label.setFont(font)\n self.Error_Label.setObjectName(\"Error_Label\")\n self.Error_Label.setText(\"\")\n self.horizontalLayoutWidget_7 = QtWidgets.QWidget(Form)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(10, 240, 521, 31))\n self.horizontalLayoutWidget_7.setObjectName(\"horizontalLayoutWidget_7\")\n self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_7)\n self.horizontalLayout_7.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_7.setObjectName(\"horizontalLayout_7\")\n self.label_16 = QtWidgets.QLabel(self.horizontalLayoutWidget_7)\n self.label_16.setObjectName(\"label_16\")\n self.horizontalLayout_7.addWidget(self.label_16)\n self.ILF_lineedit_2 = QtWidgets.QLineEdit(self.horizontalLayoutWidget_7)\n self.ILF_lineedit_2.setMinimumSize(QtCore.QSize(100, 0))\n self.ILF_lineedit_2.setMaximumSize(QtCore.QSize(50, 16777215))\n self.ILF_lineedit_2.setObjectName(\"ILF_lineedit_2\")\n self.horizontalLayout_7.addWidget(self.ILF_lineedit_2)\n self.radioButton_19 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_7)\n self.radioButton_19.setObjectName(\"radioButton_19\")\n self.horizontalLayout_7.addWidget(self.radioButton_19)\n self.radioButton_20 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_7)\n self.radioButton_20.setObjectName(\"radioButton_20\")\n self.horizontalLayout_7.addWidget(self.radioButton_20)\n self.radioButton_21 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_7)\n self.radioButton_21.setObjectName(\"radioButton_21\")\n self.horizontalLayout_7.addWidget(self.radioButton_21)\n self.TC_Label_2 = QtWidgets.QLabel(Form)\n self.TC_Label_2.setGeometry(QtCore.QRect(580, 340, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.TC_Label_2.setFont(font)\n self.TC_Label_2.setObjectName(\"TC_Label_2\")\n self.horizontalLayoutWidget_8 = QtWidgets.QWidget(Form)\n self.horizontalLayoutWidget_8.setGeometry(QtCore.QRect(10, 190, 521, 31))\n self.horizontalLayoutWidget_8.setObjectName(\"horizontalLayoutWidget_8\")\n self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_8)\n self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_8.setObjectName(\"horizontalLayout_8\")\n self.label_17 = QtWidgets.QLabel(self.horizontalLayoutWidget_8)\n self.label_17.setObjectName(\"label_17\")\n self.horizontalLayout_8.addWidget(self.label_17)\n self.EInq_lineedit_2 = QtWidgets.QLineEdit(self.horizontalLayoutWidget_8)\n self.EInq_lineedit_2.setMinimumSize(QtCore.QSize(100, 0))\n self.EInq_lineedit_2.setMaximumSize(QtCore.QSize(50, 16777215))\n self.EInq_lineedit_2.setObjectName(\"EInq_lineedit_2\")\n self.horizontalLayout_8.addWidget(self.EInq_lineedit_2)\n self.radioButton_22 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_8)\n self.radioButton_22.setObjectName(\"radioButton_22\")\n self.horizontalLayout_8.addWidget(self.radioButton_22)\n self.radioButton_23 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_8)\n self.radioButton_23.setObjectName(\"radioButton_23\")\n self.horizontalLayout_8.addWidget(self.radioButton_23)\n self.radioButton_24 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_8)\n self.radioButton_24.setObjectName(\"radioButton_24\")\n self.horizontalLayout_8.addWidget(self.radioButton_24)\n self.Language_Label_2 = QtWidgets.QLabel(Form)\n self.Language_Label_2.setGeometry(QtCore.QRect(440, 500, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.Language_Label_2.setFont(font)\n self.Language_Label_2.setObjectName(\"Language_Label_2\")\n self.horizontalLayoutWidget_9 = QtWidgets.QWidget(Form)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(10, 290, 521, 31))\n self.horizontalLayoutWidget_9.setObjectName(\"horizontalLayoutWidget_9\")\n self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_9)\n self.horizontalLayout_9.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_9.setObjectName(\"horizontalLayout_9\")\n self.label_18 = QtWidgets.QLabel(self.horizontalLayoutWidget_9)\n self.label_18.setObjectName(\"label_18\")\n self.horizontalLayout_9.addWidget(self.label_18)\n self.EIF_lineedit_2 = QtWidgets.QLineEdit(self.horizontalLayoutWidget_9)\n self.EIF_lineedit_2.setMinimumSize(QtCore.QSize(100, 0))\n self.EIF_lineedit_2.setMaximumSize(QtCore.QSize(50, 16777215))\n self.EIF_lineedit_2.setObjectName(\"EIF_lineedit_2\")\n self.horizontalLayout_9.addWidget(self.EIF_lineedit_2)\n self.radioButton_25 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_9)\n self.radioButton_25.setObjectName(\"radioButton_25\")\n self.horizontalLayout_9.addWidget(self.radioButton_25)\n self.radioButton_26 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_9)\n self.radioButton_26.setObjectName(\"radioButton_26\")\n self.horizontalLayout_9.addWidget(self.radioButton_26)\n self.radioButton_27 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_9)\n self.radioButton_27.setObjectName(\"radioButton_27\")\n self.horizontalLayout_9.addWidget(self.radioButton_27)\n self.verticalLayoutWidget_2 = QtWidgets.QWidget(Form)\n self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(10, 380, 201, 201))\n self.verticalLayoutWidget_2.setObjectName(\"verticalLayoutWidget_2\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)\n self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.computefp_btn_2 = QtWidgets.QPushButton(self.verticalLayoutWidget_2)\n self.computefp_btn_2.setObjectName(\"computefp_btn_2\")\n self.verticalLayout_2.addWidget(self.computefp_btn_2)\n self.vaf_btn_2 = QtWidgets.QPushButton(self.verticalLayoutWidget_2)\n self.vaf_btn_2.setObjectName(\"vaf_btn_2\")\n self.verticalLayout_2.addWidget(self.vaf_btn_2)\n self.codesize_btn_2 = QtWidgets.QPushButton(self.verticalLayoutWidget_2)\n self.codesize_btn_2.setObjectName(\"codesize_btn_2\")\n self.verticalLayout_2.addWidget(self.codesize_btn_2)\n self.chooselang_btn_2 = QtWidgets.QPushButton(self.verticalLayoutWidget_2)\n self.chooselang_btn_2.setObjectName(\"chooselang_btn_2\")\n self.verticalLayout_2.addWidget(self.chooselang_btn_2)\n self.CodeSize_Label_2 = QtWidgets.QLabel(Form)\n self.CodeSize_Label_2.setGeometry(QtCore.QRect(580, 490, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.CodeSize_Label_2.setFont(font)\n self.CodeSize_Label_2.setObjectName(\"CodeSize_Label_2\")\n self.label_19 = QtWidgets.QLabel(Form)\n self.label_19.setGeometry(QtCore.QRect(310, 490, 121, 31))\n font = QtGui.QFont()\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n self.label_19.setFont(font)\n self.label_19.setObjectName(\"label_19\")\n self.label_20 = QtWidgets.QLabel(Form)\n self.label_20.setGeometry(QtCore.QRect(20, 340, 81, 25))\n font = QtGui.QFont()\n font.setPointSize(10)\n font.setBold(True)\n font.setWeight(75)\n self.label_20.setFont(font)\n self.label_20.setObjectName(\"label_20\")\n self.VAF_Label_2 = QtWidgets.QLabel(Form)\n self.VAF_Label_2.setGeometry(QtCore.QRect(580, 440, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.VAF_Label_2.setFont(font)\n self.VAF_Label_2.setObjectName(\"VAF_Label_2\")\n self.horizontalLayoutWidget_10 = QtWidgets.QWidget(Form)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(10, 90, 521, 31))\n self.horizontalLayoutWidget_10.setObjectName(\"horizontalLayoutWidget_10\")\n self.horizontalLayout_10 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_10)\n self.horizontalLayout_10.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_10.setObjectName(\"horizontalLayout_10\")\n self.label_21 = QtWidgets.QLabel(self.horizontalLayoutWidget_10)\n self.label_21.setObjectName(\"label_21\")\n self.horizontalLayout_10.addWidget(self.label_21)\n self.EI_lineedit_2 = QtWidgets.QLineEdit(self.horizontalLayoutWidget_10)\n self.EI_lineedit_2.setMinimumSize(QtCore.QSize(100, 0))\n self.EI_lineedit_2.setMaximumSize(QtCore.QSize(50, 16777215))\n self.EI_lineedit_2.setObjectName(\"EI_lineedit_2\")\n self.horizontalLayout_10.addWidget(self.EI_lineedit_2)\n self.radioButton_28 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_10)\n self.radioButton_28.setObjectName(\"radioButton_28\")\n self.horizontalLayout_10.addWidget(self.radioButton_28)\n self.radioButton_29 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_10)\n self.radioButton_29.setObjectName(\"radioButton_29\")\n self.horizontalLayout_10.addWidget(self.radioButton_29)\n self.radioButton_30 = QtWidgets.QRadioButton(self.horizontalLayoutWidget_10)\n self.radioButton_30.setObjectName(\"radioButton_30\")\n self.horizontalLayout_10.addWidget(self.radioButton_30)\n self.EInq_Label_2 = QtWidgets.QLabel(Form)\n self.EInq_Label_2.setGeometry(QtCore.QRect(580, 200, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.EInq_Label_2.setFont(font)\n self.EInq_Label_2.setObjectName(\"EInq_Label_2\")\n self.label_22 = QtWidgets.QLabel(Form)\n self.label_22.setGeometry(QtCore.QRect(240, 60, 47, 13))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.label_22.setFont(font)\n self.label_22.setObjectName(\"label_22\")\n self.EIF_Label_2 = QtWidgets.QLabel(Form)\n self.EIF_Label_2.setGeometry(QtCore.QRect(580, 300, 71, 16))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.EIF_Label_2.setFont(font)\n self.EIF_Label_2.setObjectName(\"EIF_Label_2\")\n\n # comment start\n self.chooselang_btn_2.clicked.connect(self.displaylang)\n self.vaf_btn_2.clicked.connect(self.vafdialog)\n self.computefp_btn_2.clicked.connect(self.calculatefp)\n self.EI_lineedit_2.setText(\"0\")\n self.EO_lineedit_2.setText(\"0\")\n self.EInq_lineedit_2.setText(\"0\")\n self.ILF_lineedit_2.setText(\"0\")\n self.EIF_lineedit_2.setText(\"0\")\n self.codesize_btn_2.clicked.connect(self.codesize)\n # comment end\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def calculatefp(self):\n self.choice = 0\n try:\n if int(self.EI_lineedit_2.text()) < 0 or int(self.EO_lineedit_2.text()) < 0 or int(\n self.EInq_lineedit_2.text()) < 0 or int(self.ILF_lineedit_2.text()) < 0 or int(\n self.EIF_lineedit_2.text()) < 0:\n self.Error_Label.setText(\"Enter positive numbers only!\")\n self.Error_Label.setStyleSheet(\"color: red\")\n return\n except:\n self.Error_Label.setText(\"Enter numbers only!\")\n self.Error_Label.setStyleSheet(\"color: red\")\n return\n\n self.Error_Label.setText(\"\")\n self.ei = int(self.EI_lineedit_2.text())\n if self.radioButton_28.isChecked():\n self.choice = 3\n elif self.radioButton_29.isChecked():\n self.choice = 4\n elif self.radioButton_30.isChecked():\n self.choice = 6\n self.result = self.ei * self.choice\n self.EI_Label_2.setText(str(self.result))\n\n self.eo = int(self.EO_lineedit_2.text())\n if self.radioButton_16.isChecked():\n self.choice = 4\n elif self.radioButton_17.isChecked():\n self.choice = 5\n elif self.radioButton_18.isChecked():\n self.choice = 7\n self.result = self.eo * self.choice\n self.EO_Label_2.setText(str(self.result))\n\n self.einq = int(self.EInq_lineedit_2.text())\n if self.radioButton_22.isChecked():\n self.choice = 3\n elif self.radioButton_23.isChecked():\n self.choice = 4\n elif self.radioButton_24.isChecked():\n self.choice = 6\n self.result = self.einq * self.choice\n self.EInq_Label_2.setText(str(self.result))\n\n self.ilf = int(self.ILF_lineedit_2.text())\n if self.radioButton_19.isChecked():\n self.choice = 7\n elif self.radioButton_20.isChecked():\n self.choice = 10\n elif self.radioButton_21.isChecked():\n self.choice = 15\n self.result = self.ilf * self.choice\n self.ILF_Label_2.setText(str(self.result))\n\n self.eif = int(self.EIF_lineedit_2.text())\n if self.radioButton_25.isChecked():\n self.choice = 5\n elif self.radioButton_26.isChecked():\n self.choice = 7\n elif self.radioButton_27.isChecked():\n self.choice = 10\n self.result = self.eif * self.choice\n self.EIF_Label_2.setText(str(self.result))\n\n # ********************\n self.totalcount = int(self.EI_Label_2.text()) + int(self.EO_Label_2.text()) + int(\n self.EInq_Label_2.text()) + int(self.ILF_Label_2.text()) + int(self.EIF_Label_2.text())\n self.TC_Label_2.setText(str(self.totalcount))\n self.vaf_value = int(self.VAF_Label_2.text())\n self.fp = self.totalcount * (Decimal('0.65') + (Decimal('0.01') * Decimal(self.vaf_value)))\n self.FP_Label_2.setText(str(int(self.fp)))\n # *********************\n\n def displaylang(self):\n self.Dialog_3 = QtWidgets.QDialog()\n self.codesizeobj = SE_select_language.Ui_Dialog()\n self.codesizeobj.setupUi(self.Dialog_3)\n self.Dialog_3.show()\n self.response = self.Dialog_3.exec_()\n\n if self.response == QtWidgets.QDialog.Accepted:\n self.displaylang_result, self.lang = self.codesizeobj.getvalue()\n\n def vafdialog(self):\n self.Dialog = QtWidgets.QDialog()\n self.vaf_obj = SE_VAF.Ui_Dialog()\n self.vaf_obj.setupUi(self.Dialog)\n self.Dialog.show()\n self.response = self.Dialog.exec_()\n\n if self.response == QtWidgets.QDialog.Accepted:\n self.VAF_Label_2.setText(str(self.vaf_obj.get_vaf_value()))\n\n def codesize(self):\n self.CodeSize_Label_2.setText(str(self.displaylang_result * int(self.fp)))\n self.Language_Label_2.setText(self.lang)\n\n def save(self):\n # self.new_dict[]\n # print(\"FP new dict contains {}\".format(self.new_dict))\n self.new_dict = {}\n self.new_dict[\"EI_lineedit\"] = self.EI_lineedit_2.text()\n self.new_dict[\"EO_lineedit\"] = self.EO_lineedit_2.text()\n self.new_dict[\"EInq_lineedit\"] = self.EInq_lineedit_2.text()\n self.new_dict[\"ILF_lineedit\"] = self.ILF_lineedit_2.text()\n self.new_dict[\"EIF_lineedit\"] = self.EIF_lineedit_2.text()\n ##\n self.new_dict[\"EI_Label\"] = self.EI_Label_2.text()\n self.new_dict[\"EO_Label\"] = self.EO_Label_2.text()\n self.new_dict[\"EInq_Label\"] = self.EInq_Label_2.text()\n self.new_dict[\"ILF_Label\"] = self.ILF_Label_2.text()\n self.new_dict[\"EIF_Label\"] = self.EIF_Label_2.text()\n self.new_dict[\"TC_Label\"] = self.TC_Label_2.text()\n self.new_dict[\"FP_Label\"] = self.FP_Label_2.text()\n self.new_dict[\"VAF_Label\"] = self.VAF_Label_2.text()\n self.new_dict[\"CodeSize_Label\"] = self.CodeSize_Label_2.text()\n ##\n if self.radioButton_28.isChecked():\n self.new_dict[\"radioButton_28\"] = True\n if self.radioButton_29.isChecked():\n self.new_dict[\"radioButton_29\"] = True\n if self.radioButton_30.isChecked():\n self.new_dict[\"radioButton_30\"] = True\n if self.radioButton_16.isChecked():\n self.new_dict[\"radioButton_16\"] = True\n if self.radioButton_17.isChecked():\n self.new_dict[\"radioButton_17\"] = True\n if self.radioButton_18.isChecked():\n self.new_dict[\"radioButton_18\"] = True\n if self.radioButton_22.isChecked():\n self.new_dict[\"radioButton_22\"] = True\n if self.radioButton_23.isChecked():\n self.new_dict[\"radioButton_23\"] = True\n if self.radioButton_24.isChecked():\n self.new_dict[\"radioButton_24\"] = True\n if self.radioButton_19.isChecked():\n self.new_dict[\"radioButton_19\"] = True\n if self.radioButton_20.isChecked():\n self.new_dict[\"radioButton_20\"] = True\n if self.radioButton_21.isChecked():\n self.new_dict[\"radioButton_21\"] = True\n if self.radioButton_25.isChecked():\n self.new_dict[\"radioButton_25\"] = True\n if self.radioButton_26.isChecked():\n self.new_dict[\"radioButton_26\"] = True\n if self.radioButton_27.isChecked():\n self.new_dict[\"radioButton_27\"] = True\n ##\n self.new_dict[\"language\"] = self.Language_Label_2.text()\n ##\n # print(\"FP is returning: {}\".format(self.new_dict))\n return self.new_dict\n\n def restore_data(self):\n self.EI_lineedit_2.setText(self.new_dict[\"EI_lineedit\"])\n self.EO_lineedit_2.setText(self.new_dict[\"EO_lineedit\"])\n self.EInq_lineedit_2.setText(self.new_dict[\"EInq_lineedit\"])\n self.ILF_lineedit_2.setText(self.new_dict[\"ILF_lineedit\"])\n self.EIF_lineedit_2.setText(self.new_dict[\"EIF_lineedit\"])\n self.EI_Label_2.setText(str(self.new_dict[\"EI_Label\"]))\n self.EO_Label_2.setText(self.new_dict[\"EO_Label\"])\n self.EInq_Label_2.setText(self.new_dict[\"EInq_Label\"])\n self.ILF_Label_2.setText(self.new_dict[\"ILF_Label\"])\n self.EIF_Label_2.setText(self.new_dict[\"EIF_Label\"])\n self.TC_Label_2.setText(self.new_dict[\"TC_Label\"])\n self.FP_Label_2.setText(self.new_dict[\"FP_Label\"])\n self.VAF_Label_2.setText(self.new_dict[\"VAF_Label\"])\n self.CodeSize_Label_2.setText(self.new_dict[\"CodeSize_Label\"])\n ##\n if \"radioButton_28\" in self.new_dict:\n self.radioButton_28.setChecked(True)\n if \"radioButton_29\" in self.new_dict:\n self.radioButton_29.setChecked(True)\n if \"radioButton_30\" in self.new_dict:\n self.radioButton_30.setChecked(True)\n if \"radioButton_16\" in self.new_dict:\n self.radioButton_16.setChecked(True)\n if \"radioButton_17\" in self.new_dict:\n self.radioButton_17.setChecked(True)\n if \"radioButton_18\" in self.new_dict:\n self.radioButton_18.setChecked(True)\n if \"radioButton_22\" in self.new_dict:\n self.radioButton_22.setChecked(True)\n if \"radioButton_23\" in self.new_dict:\n self.radioButton_23.setChecked(True)\n if \"radioButton_24\" in self.new_dict:\n self.radioButton_24.setChecked(True)\n if \"radioButton_19\" in self.new_dict:\n self.radioButton_19.setChecked(True)\n if \"radioButton_20\" in self.new_dict:\n self.radioButton_20.setChecked(True)\n if \"radioButton_21\" in self.new_dict:\n self.radioButton_21.setChecked(True)\n if \"radioButton_25\" in self.new_dict:\n self.radioButton_25.setChecked(True)\n if \"radioButton_26\" in self.new_dict:\n self.radioButton_26.setChecked(True)\n if \"radioButton_27\" in self.new_dict:\n self.radioButton_27.setChecked(True)\n #\n if self.new_dict[\"language\"] == \"Assembler\":\n self.displaylang_result, self.lang = (337, \"Assembler\")\n self.Language_Label_2.setText(\"Assembler\")\n elif self.new_dict[\"language\"] == \"ADA\":\n self.displaylang_result, self.lang = (154, \"ADA\")\n self.Language_Label_2.setText(\"ADA\")\n elif self.new_dict[\"language\"] == \"C\":\n self.displaylang_result, self.lang = (148,\"C\")\n self.Language_Label_2.setText(\"C\")\n elif self.new_dict[\"language\"] == \"C++\":\n self.displaylang_result, self.lang = (59, \"C++\")\n self.Language_Label_2.setText(\"C++\")\n elif self.new_dict[\"language\"] == \"C#\":\n self.displaylang_result, self.lang = (58, \"C#\")\n self.Language_Label_2.setText(\"C#\")\n elif self.new_dict[\"language\"] == \"COBOL\":\n self.displaylang_result, self.lang = (80, \"COBOL\")\n self.Language_Label_2.setText(\"COBOL\")\n if self.new_dict[\"language\"] == \"FORTRAN\":\n self.displaylang_result, self.lang = (90, \"FORTRAN\")\n self.Language_Label_2.setText(\"FORTRAN\")\n elif self.new_dict[\"language\"] == \"HTML\":\n self.displaylang_result, self.lang = (43, \"HTML\")\n self.Language_Label_2.setText(\"HTML\")\n elif self.new_dict[\"language\"] == \"Java\":\n self.displaylang_result, self.lang = (55, \"Java\")\n self.Language_Label_2.setText(\"Java\")\n elif self.new_dict[\"language\"] == \"JavaScript\":\n self.displaylang_result, self.lang = (54, \"JavaScript\")\n self.Language_Label_2.setText(\"JavaScript\")\n elif self.new_dict[\"language\"] == \"VB Script\":\n self.displaylang_result, self.lang = (38, \"VB Script\")\n self.Language_Label_2.setText(\"VB Script\")\n elif self.new_dict[\"language\"] == \"Visual Basic\":\n self.displaylang_result, self.lang = (50, \"Visual Basic\")\n self.Language_Label_2.setText(\"Visual Basic\")\n\n def retranslateUi(self, Form):\n _translate = QtCore.QCoreApplication.translate\n Form.setWindowTitle(_translate(\"Form\", \"Form\"))\n self.label_12.setText(_translate(\"Form\", \"Complex\"))\n self.ILF_Label_2.setText(_translate(\"Form\", \"0\"))\n self.label_13.setText(_translate(\"Form\", \"Average\"))\n self.label_14.setText(_translate(\"Form\", \"External Outputs\"))\n self.radioButton_16.setText(_translate(\"Form\", \"4\"))\n self.radioButton_17.setText(_translate(\"Form\", \"5\"))\n self.radioButton_18.setText(_translate(\"Form\", \"7\"))\n self.FP_Label_2.setText(_translate(\"Form\", \"0\"))\n self.label_15.setText(_translate(\"Form\", \"Weighting Factors\"))\n self.EO_Label_2.setText(_translate(\"Form\", \"0\"))\n self.EI_Label_2.setText(_translate(\"Form\", \"0\"))\n self.label_16.setText(_translate(\"Form\", \"Internal Logic Files\"))\n self.radioButton_19.setText(_translate(\"Form\", \"7\"))\n self.radioButton_20.setText(_translate(\"Form\", \"10\"))\n self.radioButton_21.setText(_translate(\"Form\", \"15\"))\n self.TC_Label_2.setText(_translate(\"Form\", \"0\"))\n self.label_17.setText(_translate(\"Form\", \"External Inquiries\"))\n self.radioButton_22.setText(_translate(\"Form\", \"3\"))\n self.radioButton_23.setText(_translate(\"Form\", \"4\"))\n self.radioButton_24.setText(_translate(\"Form\", \"6\"))\n self.Language_Label_2.setText(_translate(\"Form\", \"None\"))\n self.label_18.setText(_translate(\"Form\", \"Ext Interface Files\"))\n self.radioButton_25.setText(_translate(\"Form\", \"5\"))\n self.radioButton_26.setText(_translate(\"Form\", \"7\"))\n self.radioButton_27.setText(_translate(\"Form\", \"10\"))\n self.computefp_btn_2.setText(_translate(\"Form\", \"Compute FP\"))\n self.vaf_btn_2.setText(_translate(\"Form\", \"Value Adjustments\"))\n self.codesize_btn_2.setText(_translate(\"Form\", \"Compute Code Size\"))\n self.chooselang_btn_2.setText(_translate(\"Form\", \"Change Language\"))\n self.CodeSize_Label_2.setText(_translate(\"Form\", \"0\"))\n self.label_19.setText(_translate(\"Form\", \"Current Language\"))\n self.label_20.setText(_translate(\"Form\", \"Total Count\"))\n self.VAF_Label_2.setText(_translate(\"Form\", \"0\"))\n self.label_21.setText(_translate(\"Form\", \"External Inputs\"))\n self.radioButton_28.setText(_translate(\"Form\", \"3\"))\n self.radioButton_29.setText(_translate(\"Form\", \"4\"))\n self.radioButton_30.setText(_translate(\"Form\", \"6\"))\n self.EInq_Label_2.setText(_translate(\"Form\", \"0\"))\n self.label_22.setText(_translate(\"Form\", \"Simple\"))\n self.EIF_Label_2.setText(_translate(\"Form\", \"0\"))\n self.radioButton_29.setChecked(True)\n self.radioButton_17.setChecked(True)\n self.radioButton_23.setChecked(True)\n self.radioButton_20.setChecked(True)\n self.radioButton_26.setChecked(True)\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n Form = QtWidgets.QWidget()\n ui = Ui_Form()\n ui.setupUi(Form, \"First\")\n Form.show()\n sys.exit(app.exec_())\n","repo_name":"roshangardi/FunctionPointGUI","sub_path":"SE_application/SE_functionPoint.py","file_name":"SE_functionPoint.py","file_ext":"py","file_size_in_byte":29025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"18120024161","text":"from astropy import wcs as pywcs\nfrom collections import OrderedDict\nfrom astropy.io import fits\nfrom .headerlet import parse_filename\nimport numpy as np\n\n\ndef is_wcs_identical(scifile, file2, sciextlist, fextlist, scikey=\" \",\n file2key=\" \", verbose=False):\n \"\"\"\n Compares the WCS solution of 2 files.\n\n Parameters\n ----------\n scifile: string\n name of file1 (usually science file)\n IRAF style extension syntax is accepted as well\n for example scifile[1] or scifile[sci,1]\n file2: string\n name of second file (for example headerlet)\n sciextlist - list\n a list of int or tuple ('SCI', 1), extensions in the first file\n fextlist - list\n a list of int or tuple ('SIPWCS', 1), extensions in the second file\n scikey: string\n alternate WCS key in scifile\n file2key: string\n alternate WCS key in file2\n verbose: bool\n True: print to stdout\n\n Notes\n -----\n These can be 2 science observations or 2 headerlets\n or a science observation and a headerlet. The two files\n have the same WCS solution if the following are the same:\n\n - rootname/destim\n - primary WCS\n - SIP coefficients\n - NPOL distortion\n - D2IM correction\n\n \"\"\"\n result = True\n diff = OrderedDict()\n fobj, fname, close_file = parse_filename(file2)\n sciobj, sciname, close_scifile = parse_filename(scifile)\n diff['file_names'] = [scifile, file2]\n if get_rootname(scifile) != get_rootname(file2):\n # logger.info('Rootnames do not match.')\n diff['rootname'] = (\"%s: %s\", \"%s: %s\") % (sciname, get_rootname(scifile), file2,\n get_rootname(file2))\n result = False\n for i, j in zip(sciextlist, fextlist):\n w1 = pywcs.WCS(sciobj[i].header, sciobj, key=scikey)\n w2 = pywcs.WCS(fobj[j].header, fobj, key=file2key)\n diff['extension'] = [get_extname_extnum(sciobj[i]), get_extname_extnum(fobj[j])]\n if not np.allclose(w1.wcs.crval, w2.wcs.crval, rtol=10**(-7)):\n # logger.info('CRVALs do not match')\n diff['CRVAL'] = w1.wcs.crval, w2.wcs.crval\n result = False\n if not np.allclose(w1.wcs.crpix, w2.wcs.crpix, rtol=10**(-7)):\n # logger.info('CRPIX do not match')\n diff['CRPIX'] = w1.wcs.crpix, w2.wcs.crpix\n result = False\n if not np.allclose(w1.wcs.cd, w2.wcs.cd, rtol=10**(-7)):\n # logger.info('CDs do not match')\n diff['CD'] = w1.wcs.cd, w2.wcs.cd\n result = False\n if not (np.array(w1.wcs.ctype) == np.array(w2.wcs.ctype)).all():\n # logger.info('CTYPEs do not match')\n diff['CTYPE'] = w1.wcs.ctype, w2.wcs.ctype\n result = False\n if w1.sip or w2.sip:\n if (w2.sip and not w1.sip) or (w1.sip and not w2.sip):\n diff['sip'] = 'one sip extension is missing'\n result = False\n if not np.allclose(w1.sip.a, w2.sip.a, rtol=10**(-7)):\n diff['SIP_A'] = 'SIP_A differ'\n result = False\n if not np.allclose(w1.sip.b, w2.sip.b, rtol=10**(-7)):\n # logger.info('SIP coefficients do not match')\n diff['SIP_B'] = (w1.sip.b, w2.sip.b)\n result = False\n if w1.cpdis1 or w2.cpdis1:\n if w1.cpdis1 and not w2.cpdis1 or w2.cpdis1 and not w1.cpdis1:\n diff['CPDIS1'] = \"CPDIS1 missing\"\n result = False\n if w1.cpdis2 and not w2.cpdis2 or w2.cpdis2 and not w1.cpdis2:\n diff['CPDIS2'] = \"CPDIS2 missing\"\n result = False\n if not np.allclose(w1.cpdis1.data, w2.cpdis1.data, rtol=10**(-7)):\n # logger.info('NPOL distortions do not match')\n diff['CPDIS1_data'] = (w1.cpdis1.data, w2.cpdis1.data)\n result = False\n if not np.allclose(w1.cpdis2.data, w2.cpdis2.data, rtol=10**(-7)):\n # logger.info('NPOL distortions do not match')\n diff['CPDIS2_data'] = (w1.cpdis2.data, w2.cpdis2.data)\n result = False\n if w1.det2im1 or w2.det2im1:\n if w1.det2im1 and not w2.det2im1 or \\\n w2.det2im1 and not w1.det2im1:\n diff['DET2IM'] = \"Det2im1 missing\"\n result = False\n if not np.allclose(w1.det2im1.data, w2.det2im1.data, rtol=10**(-7)):\n # logger.info('Det2Im corrections do not match')\n diff['D2IM1_data'] = (w1.det2im1.data, w2.det2im1.data)\n result = False\n if w1.det2im2 or w2.det2im2:\n if w1.det2im2 and not w2.det2im2 or \\\n w2.det2im2 and not w1.det2im2:\n diff['DET2IM2'] = \"Det2im2 missing\"\n result = False\n if not np.allclose(w1.det2im2.data, w2.det2im2.data, rtol=10**(-7)):\n # logger.info('Det2Im corrections do not match')\n diff['D2IM2_data'] = (w1.det2im2.data, w2.det2im2.data)\n result = False\n if not result and verbose:\n for key in diff:\n print(key, \":\\t\", diff[key][0], \"\\t\", diff[key][1])\n if close_file:\n fobj.close()\n if close_scifile:\n sciobj.close()\n return result, diff\n\n\ndef get_rootname(fname):\n \"\"\"\n Returns the value of ROOTNAME or DESTIM\n \"\"\"\n\n hdr = fits.getheader(fname)\n try:\n rootname = hdr['ROOTNAME']\n except KeyError:\n try:\n rootname = hdr['DESTIM']\n except KeyError:\n rootname = fname\n return rootname\n\n\ndef get_extname_extnum(ext):\n \"\"\"\n Return (EXTNAME, EXTNUM) of a FITS extension\n \"\"\"\n extname = \"\"\n extnum = 1\n extname = ext.header.get('EXTNAME', extname)\n extnum = ext.header.get('EXTVER', extnum)\n return (extname, extnum)\n","repo_name":"spacetelescope/stwcs","sub_path":"stwcs/wcsutil/wcsdiff.py","file_name":"wcsdiff.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"}
+{"seq_id":"1387417014","text":"from collections import defaultdict\nimport sys\ninput = sys.stdin.readline\n\n\nclass TrieNode:\n def __init__(self, key, data=None):\n self.children = defaultdict(str)\n self.key = key\n self.data = data\n\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode(None)\n\n def insert(self, string):\n curr_node = self.root\n\n for char in string:\n if char not in curr_node.children:\n curr_node.children[char] = TrieNode(char)\n curr_node = curr_node.children[char]\n curr_node.data = string\n\n def search(self, string):\n curr_node = self.root\n\n for char in string:\n if char in curr_node.children:\n curr_node = curr_node.children[char]\n else:\n return False\n if curr_node.data:\n return True\n return False\n\n\nn, m = map(int, input().split())\ntrie = Trie()\ncnt = 0\nfor i in range(n + m):\n string = input().strip()\n if i < n:\n trie.insert(string)\n else:\n if trie.search(string):\n cnt += 1\nprint(cnt)\n\n","repo_name":"Dltmd202/BOJ-ProblemSlove","sub_path":"python/14425/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"35516961485","text":"import mmap\nimport os\nimport sys\nimport tempfile\n\nthis_file = os.path.abspath(__file__)\nthis_dir = os.path.split(this_file)[0]\nroot_dir = os.path.split(this_dir)[0]\npywayland_dir = os.path.join(root_dir, \"pywayland\")\nif os.path.exists(pywayland_dir):\n sys.path.append(root_dir)\n\nfrom pywayland.client import Display # noqa: E402\nfrom pywayland.protocol.wayland import ( # noqa: E402\n WlCompositor,\n WlSeat,\n WlShell,\n WlShm,\n)\n\n\ndef create_shm_buffer(touch, width, height):\n stride = width * 4\n size = stride * height\n\n with tempfile.TemporaryFile() as f:\n f.write(b\"\\x64\" * size)\n f.flush()\n\n fd = f.fileno()\n touch[\"data\"] = mmap.mmap(\n fd, size, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE\n )\n pool = touch[\"shm\"].create_pool(fd, size)\n touch[\"buffer\"] = pool.create_buffer(\n 0, width, height, stride, WlShm.format.argb8888.value\n )\n pool.destroy()\n\n\ndef handle_touch_down(wl_touch, serial, time, surface, id, x, y):\n # touch = wl_touch.user_data\n # touch_paint(touch, x, y, id)\n return 0\n\n\ndef handle_touch_motion(wl_touch, time, id, x, y):\n # touch = wl_touch.user_data\n # touch_paint(touch, x, y, id)\n return 0\n\n\ndef handle_seat_capabilities(wl_seat, capabilities):\n print(\"capabilities\")\n seat = wl_seat.user_data\n touch = seat[\"touch\"]\n\n if (capabilities & WlSeat.capability.touch.value) and seat[\"wl_touch\"] is None:\n seat[\"wl_touch\"] = wl_seat.get_touch()\n seat[\"wl_touch\"].user_data = touch\n seat[\"wl_touch\"].dispatcher[\"down\"] = handle_touch_down\n # seat['wl_touch'].dispatcher['up'] = handle_touch_up\n seat[\"wl_touch\"].dispatcher[\"motion\"] = handle_touch_motion\n elif not (capabilities & WlSeat.capability.touch.value) and seat[\"wl_touch\"]:\n seat[\"wl_touch\"].destroy()\n seat[\"wl_touch\"] = None\n return 1\n\n\ndef handle_shm_format(wl_shm, fmt):\n print(\"format\")\n touch = wl_shm.user_data\n\n if fmt == WlShm.format.argb8888.value:\n touch[\"has_argb\"] = True\n return 1\n\n\ndef handle_shell_surface_ping(wl_shell_surface, serial):\n print(\"ping\")\n wl_shell_surface.pong(serial)\n return 1\n\n\ndef handle_registry_global(wl_registry, id_num, iface_name, version):\n print(\"global\", id_num, iface_name)\n\n touch = wl_registry.user_data\n if iface_name == \"wl_compositor\":\n touch[\"compositor\"] = wl_registry.bind(id_num, WlCompositor, version)\n elif iface_name == \"wl_seat\":\n seat = {}\n seat[\"touch\"] = touch\n seat[\"wl_touch\"] = None\n\n wl_seat = wl_registry.bind(id_num, WlSeat, version)\n wl_seat.dispatcher[\"capabilities\"] = handle_seat_capabilities\n wl_seat.user_data = seat\n seat[\"seat\"] = wl_seat\n elif iface_name == \"wl_shell\":\n touch[\"shell\"] = wl_registry.bind(id_num, WlShell, version)\n elif iface_name == \"wl_shm\":\n touch[\"has_argb\"] = False\n\n shm = wl_registry.bind(id_num, WlShm, version)\n shm.user_data = touch\n shm.dispatcher[\"format\"] = handle_shm_format\n touch[\"shm\"] = shm\n return 1\n\n\ndef touch_create(width, height):\n touch = {}\n\n # Make the display and get the registry\n touch[\"display\"] = Display()\n touch[\"display\"].connect()\n\n touch[\"registry\"] = touch[\"display\"].get_registry()\n touch[\"registry\"].user_data = touch\n touch[\"registry\"].dispatcher[\"global\"] = handle_registry_global\n\n touch[\"display\"].dispatch()\n touch[\"display\"].roundtrip()\n touch[\"display\"].roundtrip()\n\n if not touch[\"has_argb\"]:\n print(\"WL_SHM_FORMAT_ARGB32 not available\", file=sys.stderr)\n touch[\"display\"].disconnect()\n return\n\n touch[\"width\"] = width\n touch[\"height\"] = height\n touch[\"surface\"] = touch[\"compositor\"].create_surface()\n touch[\"shell_surface\"] = touch[\"shell\"].get_shell_surface(touch[\"surface\"])\n create_shm_buffer(touch, width, height)\n\n if touch[\"shell_surface\"]:\n print(\"shell\")\n touch[\"shell_surface\"].dispatcher[\"ping\"] = handle_shell_surface_ping\n touch[\"shell_surface\"].set_toplevel()\n\n touch[\"surface\"].user_data = touch\n touch[\"shell_surface\"].set_title(\"simple-touch\")\n\n touch[\"surface\"].attach(touch[\"buffer\"], 0, 0)\n touch[\"surface\"].damage(0, 0, width, height)\n touch[\"surface\"].commit()\n\n return touch\n\n\ndef main():\n touch = touch_create(600, 500)\n\n while touch[\"display\"].dispatch() != -1:\n pass\n\n touch[\"display\"].disconnect()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"flacjacket/pywayland","sub_path":"example/simple-touch.py","file_name":"simple-touch.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"48"}
+{"seq_id":"29672134935","text":"# lstm model\nimport numpy as np\nimport time\nimport keras_metrics as km\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.layers import LSTM\n\nimport tensorflow as tf\nsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n\ntrainX = np.loadtxt('X_train.txt', delimiter=\" \")\ntrainy = np.loadtxt('y_train.txt')\ntestX = np.loadtxt('Xs_test.txt', delimiter=\" \")\ntesty = np.loadtxt('ys_test.txt')\n\nxmin = np.array([0,0,0,0,0,0,0,-48,0,-15.0234742,0,0,0,0,0,0,-3276.8,0,0,0])\nxmax = np.array([3,99.6094,16383.75,99.6094,99.6094,254,3,143.25,3,104.6948357,99.603,25.8984375,99.609375,99.609375,99.609375,99.609375,3276.8,1016,15,15])\nxptp = xmax - xmin\ntrainX = (trainX - xmin) / xptp\ntestX = (testX - xmin) / xptp\n\nshape = np.shape(trainX)\ntrainX = trainX.reshape(shape[0],1,shape[1])\nshape = np.shape(trainy)\ntrainy = trainy.reshape(shape[0],1)\nshape = np.shape(testX)\ntestX = testX.reshape(1,1,shape[0])\nshape = np.shape(testy)\nprint(shape)\ntesty = testy.reshape(1,1)\n\n# fit and evaluate a model\n\nepochs, batch_size, n_neurons, dropout = 50, 128, 50, 0.5\nn_timesteps, n_features, n_outputs = trainX.shape[1], trainX.shape[2], trainy.shape[1]\nmodel = Sequential()\nmodel.add(LSTM(n_neurons, input_shape=(n_timesteps,n_features)))\nmodel.add(Dropout(dropout))\nmodel.add(Dense(n_neurons, activation='relu'))\nmodel.add(Dense(n_outputs, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['binary_accuracy', km.binary_precision(), km.binary_recall(), km.binary_true_positive(), km.binary_false_positive(), km.binary_true_negative(), km.binary_false_negative()])\n# fit network\nmodel.fit(trainX, trainy, epochs=epochs, batch_size=batch_size, verbose=1)\n# evaluate model\n_, ba, pr, rec, tp, fp, tn, fn = model.evaluate(testX, testy, batch_size=batch_size, verbose=0)\nstart_eval = time.time()\nout = model.predict_classes(testX)\nend_eval = time.time() - start_eval\nprint(end_eval)\n#print(ba, pr, rec, end_eval)\n#print(hist.history)\n","repo_name":"zadid56/in-vehicle-security","sub_path":"scripts/lstm_class_test.py","file_name":"lstm_class_test.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"33522920976","text":"from LL.LL_SetPilot import SetPilot\n\nimport csv\n\nclass SetPilot_file:\n\n def set_Pilot_file(self, other):\n with open('Crew.csv', 'a', newline='') as destination_file:\n wr = csv.writer(destination_file, dialect='excel')\n wr.writerow(other)\n\nif __name__ == \"__main__\":\n SetPilot_file().set_Pilot_file(SetPilot().setpilot())","repo_name":"gunnsa/Nan_Air_hopur20","sub_path":"Glósur/IO_SetPilot.py","file_name":"IO_SetPilot.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"20073297644","text":"# AI for Games - Beat the Snake game\r\n# Testing the AI\r\n\r\n# Importing the libraries\r\nimport enviroment as env\r\nfrom brain import Brain\r\nimport pygame as pg\r\nimport numpy as np\r\nimport random\r\nimport math\r\n\r\n# Defining the parameters\r\nnLastStates = 4\r\nfilepathToOpen = 'model_data/test1.h5'\r\nslowdown = 75\r\n\r\n# Creating the Environment and the Brain\r\nenv = env.Enviroment(\"test\")\r\nbrain = Brain((6, 7, nLastStates))\r\nmodel = brain.loadModel(filepathToOpen)\r\n\r\n\r\n# Initializing the pygame window\r\nenv.drawScreen()\r\n\r\n# Making a function that will reset game states\r\ndef resetStates():\r\n currentState = np.zeros((1, 6, 7, nLastStates))\r\n \r\n for i in range(nLastStates):\r\n currentState[:,:,:,i] = env.getBoard()\r\n \r\n return currentState, currentState\r\n\r\n# Starting the main loop\r\nwhile True:\r\n # Resetting the game and the game states\r\n env.reset()\r\n currentState, nextState = resetStates()\r\n gameOver = False\r\n \r\n # Playing the game\r\n while not gameOver: \r\n\r\n # Choosing an action to play\r\n valid_moves = env.getValidMoves()\r\n\r\n # else, choose the action with the highest q-value, but only from the valid moves\r\n\r\n qvalues = model.predict(currentState)\r\n print(\"valid moves: \", valid_moves)\r\n print(\"qvalues: \", qvalues)\r\n \r\n # remove the q-values for invalid moves by setting invalid moves to negative infinity\r\n for i in range(7):\r\n if i not in valid_moves:\r\n qvalues[0][i] = -math.inf\r\n\r\n print(\"new qvalues: \", qvalues)\r\n action = np.argmax(qvalues[0])\r\n print(\"action: \", action)\r\n \r\n # Updating the environment\r\n\r\n # make the ai move\r\n state, reward_1, gameOver = env.tryMove(action, 1)\r\n \r\n # Adding new game frame to next state and deleting the oldest one from next state\r\n state = np.reshape(state, (1, env.nRows, env.nColumns, 1))\r\n nextState = np.append(nextState, state, axis = 3)\r\n nextState = np.delete(nextState, 0, axis = 3)\r\n \r\n # Updating current state\r\n currentState = nextState\r\n\r\n # Displaying the game\r\n env.drawScreen()\r\n env.display()\r\n\r\n # get the player's move, filtering for valid moves\r\n valid_moves = env.getValidMoves()\r\n action = None\r\n while action not in valid_moves:\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_1:\r\n action = 0\r\n if event.key == pg.K_2:\r\n action = 1\r\n if event.key == pg.K_3:\r\n action = 2\r\n if event.key == pg.K_4:\r\n action = 3\r\n if event.key == pg.K_5:\r\n action = 4\r\n if event.key == pg.K_6:\r\n action = 5\r\n if event.key == pg.K_7:\r\n action = 6\r\n\r\n\r\n # make the player's move\r\n state, reward_2, gameOver = env.tryMove(action, 2)\r\n \r\n \r\n env.drawScreen()\r\n env.display()\r\n\r\n # Slow down the game\r\n pg.time.wait(slowdown)\r\n","repo_name":"JonathanBergen/sattler-coursework","sub_path":"light-blue-connect4/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"8342126876","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('user/', include('authentication.urls')),\n path('our-team/', include('our_team.urls')),\n path('review/', include('client_review.urls')),\n path('contact/', include('contact_us.urls')),\n path('slider/', include('homepage_slider.urls')),\n path('promotion/', include('promotion.urls')),\n path('service/', include('service.urls')),\n path('project/', include('catkin_project.urls'))\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"sharif181/catkin","sub_path":"catkin/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"43492351566","text":"def read_file(FileName: str, SpeciesName: str):\n \"\"\"Will take in a histogram.dat (single-species) and turn it into a list of lists\n\n Args:\n FileName (str): Path to the histogram.dat file\n SpeciesName (str): The name of the specific species you want to examine. Should be in the .dat file.\n\n Returns:\n list of lists: Has many lists, where each sub-list is a new time stamp that includes time at list[i][0]. You can find list \n of number of each complex type in list[i][1]. List of the number of species count in complex in list[i][2].\n \"\"\"\n \n #general vars \n hist = [] # main list that holds each timestamp\n hist_temp = [] # holds all info in 1 timestamp.\n hist_conv = [] # number of species in this complex type at 1 timestamp\n hist_count = [] # num of this complex type at 1 timestamp\n \n #eads through the file\n with open(FileName, 'r') as file:\n for line in file.readlines():\n \n #determining what the line holds\n if line[0:4] == 'Time':\n \n #if this is NOT the first run, add the temp lists to the main list\n if hist_count != [] and hist_conv != []:\n hist_temp.append(hist_count)\n hist_temp.append(hist_conv)\n hist.append(hist_temp)\n \n #reset the temp lists\n hist_count = []\n hist_conv = []\n hist_temp = []\n\n #set time to start of new temp list\n hist_temp.append(float(line.strip('Time (s): ')))\n \n #if the line holds species information\n else:\n\n #split the line and determine if it has the right species name\n string = '\t' + str(SpeciesName) + ': '\n line = line.strip('. \\n').split(string)\n if len(line) != 2:\n raise Exception('invalid species name')\n \n #adds values to the sub - temp list\n else:\n hist_count.append(int(line[0]))\n hist_conv.append(int(line[1]))\n \n #if it is the last run, add it in (needs to be here b/c temps are added at start of new time, not end of previous time)\n hist_temp.append(hist_count)\n hist_temp.append(hist_conv)\n hist.append(hist_temp)\n \n return hist\n\n\n","repo_name":"mjohn218/io_nerdss","sub_path":"ioNERDSSPyPi/ioNERDSS/functions/histograms/single_species/read_file.py","file_name":"read_file.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"17919089233","text":"import logging\nimport logging.handlers\n\nlog_formatter = logging.Formatter('%(asctime)s %(levelname)s %(module)s %(message)s')\n\nlog_file_handler = logging.handlers.RotatingFileHandler('pokemon.log', maxBytes=1024*1024, backupCount=10)\nlog_file_handler.setLevel(logging.INFO)\nlog_file_handler.setFormatter(log_formatter)\n\nlog_console_handler = logging.StreamHandler()\nlog_console_handler.setLevel(logging.INFO)\nlog_console_handler.setFormatter(log_formatter)\n\n\ndef configure_logger(name):\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n logger.addHandler(log_file_handler)\n logger.addHandler(log_console_handler)\n return logger\n","repo_name":"hflabs/pokemon","sub_path":"server/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"48"}
+{"seq_id":"30112821493","text":"def spy_game(nums):\n code = [0,0,7]\n pointer = 0\n for num in nums:\n if pointer == 3:\n return True\n if num == code[pointer] and pointer < 3:\n pointer += 1\n return pointer > 2\n\n# Check\nprint(spy_game([1,2,4,0,0,7,5]))\nprint(spy_game([1,0,2,4,0,5,7]))\nprint(spy_game([1,7,2,0,4,5,0]))\n\n\ndef count_primes(num):\n list_primes = [2]\n count = 3\n while count <= num:\n for i in list_primes:\n if count % i == 0:\n count += 2\n break\n else:\n list_primes.append(count)\n count += 2\n print(list_primes)\n return len(list_primes)\n\n\n# Check\nprint(count_primes(100))","repo_name":"JAntonioMarin/PythonBootcamp","sub_path":"Section6/48.py","file_name":"48.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"42698535191","text":"import functools\nimport asyncio as aio\nimport typer\nimport traceback\n\ndef blocking_run(f):\n\t@functools.wraps(f)\n\tdef block_fn(*args, **kwargs):\n\t\taio.run(f(*args, **kwargs))\n\treturn block_fn\n\ndef catch_error(f):\n\t@functools.wraps(f)\n\tdef smooth(*args, **kwargs):\n\t\ttry:\n\t\t\tf(*args, **kwargs)\n\t\texcept Exception as e:\n\t\t\ttyper.secho(f\"Failure: {e}\", fg=typer.colors.RED, err=True)\n\t\t\tshow_tb = typer.prompt(f\"See full traceback? ([y, yes]/[n, any])\", default=\"n\").lower() in [\"y\", \"yes\"]\n\t\t\tif show_tb:\n\t\t\t\ttraceback.print_exc()\n\t\t\telse:\n\t\t\t\traise typer.Abort()\n\treturn smooth\n\n\n","repo_name":"ankitsainidev/nkit","sub_path":"nkit/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"14883260146","text":"import re\n\nfrom tqdm import tqdm\n\nINPUT_TXT = \"input.txt\"\n# INPUT_TXT = \"input-small.txt\"\n\n\nVAR_NAMES = set(\"wxyz\")\n\n\ndef solve_part1(lines):\n # move imp lines to the bottom\n index = 0\n while True:\n line = lines[index]\n if line == \"inp w\":\n next_line = lines[index + 1]\n if \"w\" not in next_line.split(\" \", 1)[1]:\n lines[index + 1] = line\n lines[index] = next_line\n index += 1\n if index == len(lines):\n break\n\n # merge mul 0 and add\n index = 0\n while True:\n line = lines[index]\n m = re.match(\"mul (.) 0\", line)\n if m:\n variable_name = m.group(1)\n next_line = lines[index + 1]\n mm = re.match(f\"add {variable_name} (.*)\", next_line)\n if mm:\n addition = mm.group(1)\n lines[index + 1] = f\"set {variable_name} {addition}\"\n del lines[index]\n\n index += 1\n if index == len(lines) - 1:\n break\n\n # merge eql eql\n index = 0\n while True:\n line = lines[index]\n if line == \"eql x w\" and lines[index + 1] == \"eql x 0\":\n lines[index + 1] = \"neql x w\"\n del lines[index]\n index += 1\n if index == len(lines) - 1:\n break\n #\n # # drop add 0\n # lines = list(filter(lambda x: not re.match(\"add . 0$\", x), lines))\n\n # drop div 1\n lines = list(filter(lambda x: not re.match(\"div . 1$\", x), lines))\n\n with open(\"new-input.txt\", \"w\") as out:\n for line in lines:\n out.write(line + \"\\n\")\n\n # block by input reads\n indices = []\n for i, line in enumerate(lines):\n if line == \"inp w\":\n indices.append(i)\n indices.append(len(lines))\n blocks = []\n for i, j in zip(indices, indices[1:]):\n blocks.append(lines[i + 1 : j])\n pre_input_block = lines[: indices[0]]\n\n # pre-input\n state = {v: 0 for v in VAR_NAMES}\n apply_steps(state, pre_input_block)\n print(\"pre input state:\", sorted(state))\n\n ranges = find_ranges(blocks)\n print(ranges)\n output = check(state, blocks, 0, ranges)\n print(output)\n\n\ndef check(start_state, blocks, block_index, ranges):\n if not blocks:\n return start_state[\"z\"] == 0\n\n vals = range(9, 0, -1)\n if len(blocks) > 10:\n vals = tqdm(vals, desc=str(len(blocks)) + \" \" * (14 - len(blocks)))\n for inp in vals:\n state = {**start_state, \"w\": inp}\n apply_steps(state, blocks[0])\n\n if block_index + 1 in ranges and state[\"z\"] % 26 not in ranges[block_index + 1]:\n continue\n\n ch = check(state, blocks[1:], block_index + 1, ranges)\n if ch:\n return inp + ch\n\n\ndef apply_steps(state, block):\n for step in block:\n make_step(state, step)\n\n\ndef make_step(state, step):\n spl = step.split(\" \")\n command = spl[0]\n target = spl[1]\n if command == \"add\":\n state[target] += other(spl, state)\n elif command == \"mul\":\n state[target] *= other(spl, state)\n elif command == \"div\":\n state[target] //= other(spl, state)\n elif command == \"mod\":\n state[target] %= other(spl, state)\n elif command == \"eql\":\n state[target] = 1 if state[target] == other(spl, state) else 0\n elif command == \"neql\":\n state[target] = 1 if state[target] != other(spl, state) else 0\n elif command == \"set\":\n state[target] = other(spl, state)\n else:\n raise Exception(\"Unknown command \", command)\n\n\ndef other(spl, values):\n other = spl[2]\n return values[other] if other in VAR_NAMES else int(other)\n\n\ndef find_ranges(blocks):\n ranges = {}\n for i, block in enumerate(blocks):\n for line in block:\n m = re.match(\"add x ([^z]+)\", line)\n if m:\n num = int(m.group(1))\n if num <= 9:\n r1 = 1 - num\n r2 = 9 - num\n ranges[i] = range(min(r1, r2), max(r1, r2) + 1)\n return ranges\n\n\ndef main():\n with open(INPUT_TXT) as f:\n lines = [line.strip() for line in f.readlines()]\n print(f\"{len(lines)} read\")\n\n result_part1 = solve_part1(lines)\n result_part2 = 0\n\n # TODO:\n # - drop DIV x 1\n # - drop ADD x 0\n # - merge eql, eql into nql\n # - merge mul x 0, add x y -> set x y\n\n print()\n print(\"##########\")\n print(f\"Result part 1: {result_part1}\")\n print(f\"Result part 2: {result_part2}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mkopec87/advent_of_code","sub_path":"src/2021/day24/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"4670508285","text":"import unittest\nimport os\nfrom sqltxt.table import Table \nfrom sqltxt.column import Column, ColumnName, AmbiguousColumnNameError\nfrom sqltxt.expression import Expression\n\nclass TableTest(unittest.TestCase):\n\n def setUp(self):\n\n self.data_path = os.path.join(os.path.dirname(__file__), '../data')\n\n table_header = [\"col_a\", \"col_b\"]\n table_contents = \"\"\"1,1\n2,3\n3,2\"\"\"\n\n self.table_a = Table.from_cmd(\n name = 'table_a', \n cmd = 'echo -e \"{0}\"'.format(table_contents), \n columns = table_header\n )\n\n table_header = [\"col_a\", \"col_b\"]\n table_contents = \"\"\"1,w\n2,x\n2,y\n5,z\"\"\"\n\n self.table_b = Table.from_cmd(\n name = 'table_b', \n cmd = 'echo -e \"{0}\"'.format(table_contents), \n columns = table_header\n )\n\n def test_subset_rows(self):\n \n conditions = [\n [Expression('col_b', '==', '1'), 'or', Expression('col_a', '==', '2')]\n ]\n self.table_a.subset_rows(conditions)\n \n cmds_actual = self.table_a.cmds\n cmds_expected = [\n 'echo -e \"1,1\\n2,3\\n3,2\"',\n \"awk -F',' 'OFS=\\\",\\\" { if (($2 == 1 || $1 == 2)) { print $1,$2 } }'\"]\n self.assertEqual(cmds_actual, cmds_expected)\n\n def test_order_columns(self):\n\n col_name_order = [ColumnName('col_b'), ColumnName('col_a')]\n self.table_a.order_columns(col_name_order)\n \n cmds_actual = self.table_a.cmds\n cmds_expected = ['echo -e \"1,1\\n2,3\\n3,2\"', \"awk -F',' 'OFS=\\\",\\\" { print $2,$1 }'\"]\n self.assertEqual(cmds_actual, cmds_expected)\n\n def test_sort(self):\n \n sort_by_col_names = [ColumnName('col_a'), ColumnName('col_b')]\n self.table_a.sort(sort_by_col_names)\n\n cmds_actual = self.table_a.cmds\n cmds_expected = ['echo -e \"1,1\\n2,3\\n3,2\"', \"sort -t, -k 1,1 -k 2,2\"]\n self.assertEqual(cmds_actual, cmds_expected)\n\n sort_by_cols = [self.table_a.get_column_for_name(cn) for cn in sort_by_col_names]\n self.assertEqual(self.table_a.sorted_by, sort_by_cols)\n\n def test_is_sorted_by(self):\n\n table_from_cmd = Table.from_cmd(\n name = 'table_a', \n cmd = 'echo -e \"\"',\n columns = ['col_a', 'col_b'])\n\n table_from_cmd.sorted_by = [Column('table_a.col_a'), Column('table_a.col_b')]\n\n self.assertTrue(table_from_cmd.is_sorted_by([0]))\n self.assertFalse(table_from_cmd.is_sorted_by([1]))\n self.assertTrue(table_from_cmd.is_sorted_by([0,1]))\n\n def test_get_column_for_name_raises_on_ambiguity(self):\n\n table_from_cmd = Table.from_cmd(\n name = 'table_a', \n cmd = 'echo -e \"\"',\n columns = ['col_a', 'col_a'])\n\n with self.assertRaisesRegexp(AmbiguousColumnNameError, 'Ambiguous column reference'):\n table_from_cmd.get_column_for_name(ColumnName('col_a'))\n\n table_from_cmd = Table.from_cmd(\n name = 'table_a', \n cmd = 'echo -e \"\"',\n columns = ['ta.col_a', 'tb.col_a'])\n\n with self.assertRaisesRegexp(AmbiguousColumnNameError, 'Ambiguous column reference'):\n table_from_cmd.get_column_for_name(ColumnName('col_a'))\n\n first_column = Column('ta.col_a')\n first_column.add_name('col_alpha')\n second_column = Column('tb.col_a')\n table_from_cmd = Table.from_cmd(\n name = 'table_a', \n cmd = 'echo -e \"\"',\n columns = [first_column, second_column])\n\n with self.assertRaisesRegexp(AmbiguousColumnNameError, 'Ambiguous column reference'):\n table_from_cmd.get_column_for_name(ColumnName('col_a'))\n\n def test_sample_rows(self):\n self.table_a.sample_rows(1)\n cmds_actual = self.table_a.cmds\n cmds_expected = ['echo -e \"1,1\\n2,3\\n3,2\"',\n \"\"\"awk -v seed=$RANDOM -v n={0} '\n BEGIN {{ srand(seed) }}\n NR <= n {{ reservoir[NR] = $0 }}\n NR > n {{ M = int(rand() * NR) + 1; if (M <= n) {{ reservoir[M] = $0 }}}}\n END {{ for (key in reservoir) {{ print reservoir[key] }}}}'\"\"\".format(1)\n ]\n self.assertEqual(cmds_actual, cmds_expected)\n\n def test_get_cmd_str(self):\n\n table_from_file = Table.from_file_path(os.path.join(self.data_path, 'table_a.txt'))\n\n # output from a file-backed Table to STDOUT\n cmd_actual = table_from_file.get_cmd_str()\n cmd_expected = 'tail -n+2 {}/table_a.txt'.format(self.data_path)\n self.assertEqual(cmd_actual, cmd_expected)\n\n table_from_cmd = Table.from_cmd(\n 'table_a', \n cmd = 'echo -e \"1,2,3,4\"', \n columns = ['col_a', 'col_b', 'col_c', 'col_d'])\n\n # output from a command-backed Table to STDOUT\n cmd_actual = table_from_cmd.get_cmd_str()\n cmd_expected = 'echo -e \"1,2,3,4\"'\n self.assertEqual(cmd_actual, cmd_expected)\n\n # add a command, then output\n table_from_cmd.cmds += ['sort']\n\n # to STDOUT\n cmd_actual = table_from_cmd.get_cmd_str()\n cmd_expected = 'echo -e \"1,2,3,4\" | sort'\n self.assertEqual(cmd_actual, cmd_expected)\n","repo_name":"shahin/sqltxt","sub_path":"tests/unit/table_test.py","file_name":"table_test.py","file_ext":"py","file_size_in_byte":5179,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"29764458504","text":"import os\nfrom abc import ABC, abstractmethod\nfrom typing import List\n\nfrom omegaconf import DictConfig, OmegaConf, open_dict\n\nfrom nemo.collections.asr.parts.utils import asr_module_utils\nfrom nemo.collections.common import tokenizers\nfrom nemo.utils import logging\n\n\nclass ASRBPEMixin(ABC):\n \"\"\" ASR BPE Mixin class that sets up a Tokenizer via a config\n\n This mixin class adds the method `_setup_tokenizer(...)`, which can be used by ASR models\n which depend on subword tokenization.\n\n The setup_tokenizer method adds the following parameters to the class -\n - tokenizer_cfg: The resolved config supplied to the tokenizer (with `dir` and `type` arguments).\n - tokenizer_dir: The directory path to the tokenizer vocabulary + additional metadata.\n - tokenizer_type: The type of the tokenizer. Currently supports `bpe` and `wpe`.\n - vocab_path: Resolved path to the vocabulary text file.\n\n In addition to these variables, the method will also instantiate and preserve a tokenizer\n (subclass of TokenizerSpec) if successful, and assign it to self.tokenizer.\n \"\"\"\n\n def _setup_tokenizer(self, tokenizer_cfg: DictConfig):\n # Prevent tokenizer parallelism (unless user has explicitly set it)\n if 'TOKENIZERS_PARALLELISM' not in os.environ:\n os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n\n self.tokenizer_cfg = OmegaConf.to_container(tokenizer_cfg, resolve=True) # type: dict\n self.tokenizer_dir = self.tokenizer_cfg.pop('dir') # Remove tokenizer directory\n self.tokenizer_type = self.tokenizer_cfg.pop('type').lower() # Remove tokenizer_type\n\n self.hf_tokenizer_kwargs = self.tokenizer_cfg.pop(\"hf_kwargs\", {}) # Remove HF tokenizer kwargs\n\n # Preserve config\n if hasattr(self, 'cfg') and 'tokenizer' in self.cfg:\n self.cfg.tokenizer.dir = self.tokenizer_dir\n self.cfg.tokenizer.type = self.tokenizer_type\n\n if 'hf_kwargs' in tokenizer_cfg:\n with open_dict(self.cfg.tokenizer):\n self.cfg.tokenizer.hf_kwargs = tokenizer_cfg.get('hf_kwargs')\n\n if self.tokenizer_type not in ['bpe', 'wpe']:\n raise ValueError(\n \"`tokenizer.type` must be either `bpe` for SentencePiece tokenizer or \"\n \"`wpe` for BERT based tokenizer\"\n )\n\n if self.tokenizer_type == 'bpe':\n # This is a BPE Tokenizer\n if 'model_path' in self.tokenizer_cfg:\n model_path = self.tokenizer_cfg.get('model_path')\n else:\n model_path = os.path.join(self.tokenizer_dir, 'tokenizer.model')\n model_path = self.register_artifact('tokenizer.model_path', model_path)\n self.model_path = model_path\n\n if 'special_tokens' in self.tokenizer_cfg:\n special_tokens = self.tokenizer_cfg['special_tokens']\n\n if special_tokens is not None:\n raise ValueError(\"`special_tokens` are no longer supported for SentencePiece based tokenizers.\")\n\n # Update special tokens\n self.tokenizer = tokenizers.SentencePieceTokenizer(model_path=model_path)\n\n if 'vocab_path' in self.tokenizer_cfg:\n vocab_path = self.tokenizer_cfg.get('vocab_path')\n else:\n vocab_path = os.path.join(self.tokenizer_dir, 'vocab.txt')\n vocab_path = self.register_artifact('tokenizer.vocab_path', vocab_path)\n self.vocab_path = vocab_path\n\n try:\n if 'spe_tokenizer_vocab' in self.tokenizer_cfg:\n spe_vocab_path = self.tokenizer_cfg.get('spe_tokenizer_vocab')\n else:\n spe_vocab_path = os.path.join(self.tokenizer_dir, 'tokenizer.vocab')\n spe_vocab_path = self.register_artifact('tokenizer.spe_tokenizer_vocab', spe_vocab_path)\n self.spe_vocab_path = spe_vocab_path\n except FileNotFoundError:\n # fallback case for older checkpoints that did not preserve the tokenizer.vocab\n self.spe_vocab_path = None\n\n vocabulary = {}\n for i in range(self.tokenizer.vocab_size):\n piece = self.tokenizer.ids_to_tokens([i])\n piece = piece[0]\n vocabulary[piece] = i + 1\n\n # wrapper method to get vocabulary conveniently\n def get_vocab():\n return vocabulary\n\n # attach utility values to the tokenizer wrapper\n self.tokenizer.tokenizer.vocab_size = len(vocabulary)\n self.tokenizer.tokenizer.get_vocab = get_vocab\n self.tokenizer.tokenizer.all_special_tokens = self.tokenizer.special_token_to_id\n\n else:\n # This is a WPE Tokenizer\n # If path from previous registration exists, remove it\n if 'vocab_path' in self.tokenizer_cfg:\n vocab_path = self.tokenizer_cfg.get('vocab_path')\n else:\n vocab_path = os.path.join(self.tokenizer_dir, 'vocab.txt')\n vocab_path = self.register_artifact('tokenizer.vocab_path', vocab_path)\n self.vocab_path = vocab_path\n\n # If path from previous registration exists, remove it\n if 'vocab_path' in self.tokenizer_cfg:\n self.tokenizer_cfg.pop('vocab_path')\n\n self.tokenizer = tokenizers.AutoTokenizer(\n pretrained_model_name='bert-base-cased',\n vocab_file=self.vocab_path,\n mask_token=self.hf_tokenizer_kwargs.get('mask_token', None),\n bos_token=self.hf_tokenizer_kwargs.get('bos_token', None),\n eos_token=self.hf_tokenizer_kwargs.get('eos_token', None),\n pad_token=self.hf_tokenizer_kwargs.get('pad_token', None),\n sep_token=self.hf_tokenizer_kwargs.get('sep_token', None),\n cls_token=self.hf_tokenizer_kwargs.get('cls_token', None),\n unk_token=self.hf_tokenizer_kwargs.get('unk_token', None),\n use_fast=self.hf_tokenizer_kwargs.get('use_fast', False),\n )\n\n logging.info(\n \"Tokenizer {} initialized with {} tokens\".format(\n self.tokenizer.__class__.__name__, self.tokenizer.vocab_size\n )\n )\n\n\nclass ASRModuleMixin(ABC):\n \"\"\"\n ASRModuleMixin is a mixin class added to ASR models in order to add methods that are specific\n to a particular instantiation of a module inside of an ASRModel.\n\n Each method should first check that the module is present within the subclass, and support additional\n functionality if the corresponding module is present.\n \"\"\"\n\n def change_conv_asr_se_context_window(self, context_window: int, update_config: bool = True):\n \"\"\"\n Update the context window of the SqueezeExcitation module if the provided model contains an\n `encoder` which is an instance of `ConvASREncoder`.\n\n Args:\n context_window: An integer representing the number of input timeframes that will be used\n to compute the context. Each timeframe corresponds to a single window stride of the\n STFT features.\n\n Say the window_stride = 0.01s, then a context window of 128 represents 128 * 0.01 s\n of context to compute the Squeeze step.\n update_config: Whether to update the config or not with the new context window.\n \"\"\"\n asr_module_utils.change_conv_asr_se_context_window(\n self, context_window=context_window, update_config=update_config\n )\n\n\nclass DiarizationMixin(ABC):\n @abstractmethod\n def diarize(self, paths2audio_files: List[str], batch_size: int = 1) -> List[str]:\n \"\"\"\n Takes paths to audio files and returns speaker labels\n Args:\n paths2audio_files: paths to audio fragment to be transcribed\n\n Returns:\n Speaker labels\n \"\"\"\n pass\n","repo_name":"Xianchao-Wu/nemo_bidecoder","sub_path":"collections/asr/parts/mixins/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":8033,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"}
+{"seq_id":"45082372836","text":"import asyncio\nfrom .methods import *\nfrom db.db import DB\nfrom .message_handler import message_handler\nfrom .callback_handler import callback_handler\n\nasync def check_updates(token, update):\n if \"message\" in update:\n await message_handler(token, update)\n elif \"callback_query\":\n await callback_handler(token, update)\n else:\n pass\n\n\nasync def run(token):\n try:\n update_id = (await get_updates(token))[-1]['update_id']\n except:\n update_id = 0\n \n try:\n bot_username = (await get_me(token))['username']\n except KeyError:\n return\n \n while True:\n try:\n if DB().get_user_bot(bot_username) is None:\n return\n \n updates = await get_updates(token, update_id)\n for update in updates:\n if update_id < update['update_id']:\n update_id = update['update_id']\n await check_updates(token, update)\n \n \n await asyncio.sleep(2)\n except:\n await asyncio.sleep(10)\n","repo_name":"olegtititele/tg_onlyfans","sub_path":"handlers/tg_user_bot/userbot.py","file_name":"userbot.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"31383884234","text":"\"\"\"\r\nPrime summations\r\nProblem 77\r\n\r\nIt is possible to write ten as the sum of primes in exactly five different ways:\r\n\r\n7 + 3\r\n5 + 5\r\n5 + 3 + 2\r\n3 + 3 + 2 + 2\r\n2 + 2 + 2 + 2 + 2\r\n\r\nWhat is the first value which can be written as the sum of primes in over five thousand different ways?\r\n\r\nLink: https://projecteuler.net/problem=77\r\n\r\nDate solved:\r\n09/10/2022 \r\n\"\"\"\r\n\r\n\r\nANSWER = 71\r\n\r\n# imports\r\n\r\nfrom functools import lru_cache\r\n\r\nfrom maths.sequences.special_sequences import PrimesSeq\r\n\r\n# solution\r\n\r\n\r\nprimes = PrimesSeq().seq\r\n\r\n\r\n@lru_cache(100)\r\ndef H(n, a):\r\n if a == n:\r\n return 1\r\n if a == 1:\r\n return not n % 2\r\n if a > n:\r\n return 0\r\n\r\n summation = 0\r\n i = 0\r\n p = primes[i]\r\n while p <= a and p <= n - a:\r\n summation += H(n - a, p)\r\n i += 1\r\n p = primes[i]\r\n\r\n return summation\r\n\r\n\r\ndef f(n):\r\n\r\n summation = 0\r\n i = 0\r\n p = primes[i]\r\n while p <= n:\r\n summation += H(n, p)\r\n i += 1\r\n p = primes[i]\r\n\r\n return summation\r\n\r\n\r\ndef solution():\r\n\r\n threshold = 5000\r\n\r\n n = 2\r\n while True:\r\n if f(n) > threshold:\r\n return n\r\n n += 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n from time import perf_counter\r\n\r\n t0 = perf_counter()\r\n sol = solution()\r\n t1 = perf_counter()\r\n print(f\"solution = {sol} in {t1-t0: 0.4f} seconds\")\r\n print(\"answer =\", ANSWER)\r\n","repo_name":"lsabor/project_euler","sub_path":"000-100/70s/077_25_Prime_summations.py","file_name":"077_25_Prime_summations.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"13732948750","text":"import requests\nimport json\nimport os\nimport errno\nimport re\n\n# Import links for CSV downloads\nwith open(\"./output/all_csv_links.json\") as f:\n data = json.load(f)\n\nfor i,csv_link in enumerate(data):\n # Extract all tournament ids from 'tournament_id=##' part of link\n matches = re.findall(\".*_id=([0-9]*)\", csv_link)\n tournament_id = matches[0]\n\n print(\"Downloading \" + str(tournament_id) + \" from \" + csv_link)\n print(str(i+1) + \" of \" + str(len(data)))\n\n # Create directory to file if needed\n filename = \"./tourney_csvs/\" + str(tournament_id) + \".csv\"\n if not os.path.exists(os.path.dirname(filename)):\n try:\n os.makedirs(os.path.dirname(filename))\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n \n # Write to file\n r = requests.get(csv_link, allow_redirects=True)\n with open(filename, \"w\") as f:\n f.write(r.content)","repo_name":"colinfong/askfred_scraper","sub_path":"download_csvs.py","file_name":"download_csvs.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"2668274035","text":"'''\n* Title: GraphicsDrawer source code\n* Author: Smith, J\n* Date: 2011\n* Code version: 2.0\n* Availability: http://www.graphicsdrawer.com\n'''\n\nimport time\nimport user\nimport tweepy\nimport psycopg2\n\nauth = tweepy.OAuthHandler(user.CONSUMER_KEY, user.CONSUMER_KEY_SECRET)\nauth.set_access_token(user.ACCESS_TOKEN, user.ACCESS_TOKEN_SECRET)\napi = tweepy.API(auth)\n\n\nclass MyStreamListener(tweepy.StreamListener):\n\n def __init__(self, time_limit=300):\n self.start_time = time.time()\n self.limit = time_limit\n super(MyStreamListener, self).__init__()\n\n def on_connect(self):\n print(\"Connected to Twitter API.\")\n\n def on_status(self, status):\n\n # Tweet ID\n tweet_id = status.id\n\n # User ID\n user_id = status.user.id\n # Username\n username = status.user.name\n\n # Tweet\n if status.truncated == True:\n tweet = status.extended_tweet['full_text']\n hashtags = status.extended_tweet['entities']['hashtags']\n else:\n tweet = status.text\n hashtags = status.entities['hashtags']\n\n # Read hastags\n hashtags = read_hashtags(hashtags)\n\n # Retweet count\n retweet_count = status.retweet_count\n # Language\n lang = status.lang\n\n # If tweet is not a retweet and tweet is in English\n if not hasattr(status, \"retweeted_status\") and lang == \"en\":\n # Connect to database\n dbConnect(user_id, username, tweet_id, tweet, retweet_count, hashtags)\n\n if (time.time() - self.start_time) > self.limit:\n print(time.time(), self.start_time, self.limit)\n return False\n\n def on_error(self, status_code):\n if status_code == 420:\n # Returning False in on_data disconnects the stream\n return False\n\n# Extract hashtags\ndef read_hashtags(tag_list):\n hashtags = []\n for tag in tag_list:\n hashtags.append(tag['text'])\n return hashtags\n\n# commands = (# Table 1\n# '''Create Table TwitterUser(User_Id BIGINT PRIMARY KEY, User_Name TEXT);''',\n# # Table 2\n# '''Create Table TwitterTweet(Tweet_Id BIGINT PRIMARY KEY,\n# User_Id BIGINT,\n# Tweet TEXT,\n# Retweet_Count INT,\n# CONSTRAINT fk_user\n# FOREIGN KEY(User_Id)\n# REFERENCES TwitterUser(User_Id));''',\n# # Table 3\n# '''Create Table TwitterEntity(Id SERIAL PRIMARY KEY,\n# Tweet_Id BIGINT,\n# Hashtag TEXT,\n# CONSTRAINT fk_user\n# FOREIGN KEY(Tweet_Id)\n# REFERENCES TwitterTweet(Tweet_Id));''')\n\n# Connection to database server\n# need to allow ip address on GCP first - remember to convert to CIDR format with \"to\" address\nconn = psycopg2.connect(host=\"34.86.177.25\", database=\"postgres\", user='postgres', password = 'COVID_type8eat')\n\n# Create cursor to execute SQL commands\ncur = conn.cursor()\n\n# Execute SQL commands\n# for command in commands:\n# # Create tables\n# cur.execute(command)\n\n# Close communication with server\nconn.commit()\ncur.close()\nconn.close()\n\n# Insert Tweet data into database\ndef dbConnect(user_id, user_name, tweet_id, tweet, retweet_count, hashtags):\n # need to allow ip address first - remember to convert to CIDR format with \"to\" address\n conn = psycopg2.connect(host=\"34.86.177.25\", database=\"postgres\", user= 'postgres', password = 'COVID_type8eat')\n\n cur = conn.cursor()\n\n # insert user information\n command = '''INSERT INTO TwitterUser (user_id, user_name) VALUES (%s,%s) ON CONFLICT\n (User_Id) DO NOTHING;'''\n cur.execute(command, (user_id, user_name))\n\n # insert tweet information\n command = '''INSERT INTO TwitterTweet (tweet_id, user_id, tweet, retweet_count) VALUES (%s,%s,%s,%s);'''\n cur.execute(command, (tweet_id, user_id, tweet, retweet_count))\n\n # insert entity information\n for i in range(len(hashtags)):\n hashtag = hashtags[i]\n command = '''INSERT INTO TwitterEntity (tweet_id, hashtag) VALUES (%s,%s);'''\n cur.execute(command, (tweet_id, hashtag))\n\n # Commit changes\n conn.commit()\n\n # Disconnect\n cur.close()\n conn.close()\n\nmyStreamListener = MyStreamListener()\nmyStream = tweepy.Stream(auth=api.auth, listener=myStreamListener,\n tweet_mode=\"extended\")\nmyStream.filter(track=['covid','coronavirus','pandemic','covid19','covid-19'])","repo_name":"shoang22/hackgt","sub_path":"db/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"6669455287","text":"import requests\nimport base64\nimport random\nimport string\nimport urllib\nimport urllib.parse\nfrom http.server import BaseHTTPRequestHandler\nfrom dotenv import dotenv_values\n\nimport spotifyclient\n\nconfig = {\n **dotenv_values('.env'),\n **dotenv_values('.env.local'),\n}\nfrom oauthlib.oauth2 import WebApplicationClient\n\n\ndef random_name(n):\n return ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(n)])\n\n\nclass CallbackServer(BaseHTTPRequestHandler):\n g_oauth_state = None\n g_access_token = None\n g_refresh_token = None\n\n spotify_client = None\n# primary_device_id = None\n\n VUE_APP_SPOTIFY_CLIENT_ID = config['VUE_APP_SPOTIFY_CLIENT_ID']\n VUE_APP_SPOTIFY_CLIENT_SECRET = config['VUE_APP_SPOTIFY_CLIENT_SECRET']\n\n def __init__(self, *args):\n print(f'CallbackServer::init start {args}')\n BaseHTTPRequestHandler.__init__(self, *args)\n print('CallbackServer::init finish')\n\n def callback_method(self, path, query, redirect_uri):\n print(f'path={path}, query = {query}')\n\n if path == '/callback':\n params = urllib.parse.parse_qs(query)\n print('CODE')\n print(params['code'][0])\n print('STATE')\n print(f'g_oauth_state = {self.g_oauth_state}')\n print(params['state'][0])\n print(self.g_oauth_state)\n if CallbackServer.g_oauth_state == params['state'][0]:\n print('OK!')\n data = {\n 'code': params['code'][0],\n 'redirect_uri': redirect_uri,\n 'grant_type': 'authorization_code'\n }\n encoded = base64.b64encode(\n f'{CallbackServer.VUE_APP_SPOTIFY_CLIENT_ID}:{CallbackServer.VUE_APP_SPOTIFY_CLIENT_SECRET}'.encode(\n 'utf-8')).decode(\"ascii\")\n print(encoded)\n print(redirect_uri)\n response = requests.post(\n 'https://accounts.spotify.com/api/token',\n data=data,\n headers={\n 'Authorization': f'Basic {encoded}'\n }\n )\n print(response)\n print(response.text)\n # print(response.json())\n res_data = response.json()\n CallbackServer.spotify_client = spotifyclient.SpotifyClient(\n access_token=res_data['access_token'],\n refresh_token=res_data['refresh_token']\n )\n CallbackServer.g_access_token = res_data['access_token']\n CallbackServer.g_refresh_token = res_data['refresh_token']\n return 'oauth OK!'\n else:\n return 'oauth NG!'\n\n return ['Hello', 'World!', 'with', query]\n\n def do_GET(self):\n parsed_path = urllib.parse.urlparse(self.path)\n print(self.headers['Host'])\n print(self.path)\n print(parsed_path)\n print(parsed_path.path)\n path = parsed_path.path\n query = parsed_path.query\n\n host = self.headers['Host']\n redirect_uri = f'http://{host}/callback'\n\n if query == 'oauth':\n scope = [\n 'user-library-read',\n 'user-modify-playback-state',\n 'user-read-email',\n 'user-read-playback-state',\n 'user-read-private',\n 'user-read-recently-played'\n ]\n state = random_name(16)\n CallbackServer.g_oauth_state = state\n print(f'g_oauth_state = {CallbackServer.g_oauth_state}')\n oauth = WebApplicationClient(CallbackServer.VUE_APP_SPOTIFY_CLIENT_ID)\n url, headers, body = oauth.prepare_authorization_request('https://accounts.spotify.com/authorize',\n redirect_url=redirect_uri,\n scope=scope,\n state=state)\n\n self.send_response(302)\n self.send_header('Location', url)\n self.end_headers()\n return\n\n elif path == '/callback':\n result = self.callback_method(parsed_path.path, query, redirect_uri)\n self.send_response(302)\n self.send_header('Location', '/spotify1')\n self.end_headers()\n # self.end_headers()\n # message = result\n # self.wfile.write(message.encode('utf-8'))\n return\n\n elif path == '/spotify1':\n CallbackServer.spotify_client.get(\n '/v1/me/player/devices'\n )\n self.send_response(200)\n self.end_headers()\n message = 'devices'\n self.wfile.write(message.encode('utf-8'))\n return\n\n\n\n else:\n self.send_response(200)\n self.end_headers()\n message = query\n self.wfile.write(message.encode('utf-8'))\n return\n\n def ir1(self, name):\n print(f'ir1 {name}')\n CallbackServer.spotify_client.get_devices()\n CallbackServer.spotify_client.play_or_pause()\n\n def play(self):\n\n pass\n","repo_name":"naoki-iwami/rasprebby-pi-infrared","sub_path":"spotifyutil.py","file_name":"spotifyutil.py","file_ext":"py","file_size_in_byte":5349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"43700224086","text":"from __future__ import division\nfrom __future__ import print_function\nfrom builtins import range\nfrom dolfin import *\nfrom dolfin_adjoint import *\nfrom cslvr.inputoutput import get_text, print_text, print_min_max\nfrom cslvr.d3model import D3Model\nfrom cslvr.d2model import D2Model\nfrom cslvr.d1model import D1Model\nfrom cslvr.physics import Physics\nfrom cslvr.helper import VerticalBasis, VerticalFDBasis, \\\n raiseNotDefined\nfrom copy import deepcopy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport os\nimport json\n\n\n\n\n\n\nclass Energy(Physics):\n\t\"\"\"\n\tAbstract class outlines the structure of an energy conservation.\n\t\"\"\"\n\n\tdef __new__(self, model, *args, **kwargs):\n\t\t\"\"\"\n\t\tCreates and returns a new Energy object.\n\t\t\"\"\"\n\t\tinstance = Physics.__new__(self, model)\n\t\treturn instance\n\n\t# TODO: `energy_flux_mode` and `stabilization_method` are specific to the\n\t# D3Model energy solvers.\n\tdef __init__(self, model, momentum,\n\t solve_params = None,\n\t transient = False,\n\t use_lat_bc = False,\n\t energy_flux_mode = 'B_ring',\n\t stabilization_method = 'GLS'):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\ts = \"::: INITIALIZING ENERGY :::\"\n\t\tprint_text(s, cls=self)\n\t\t# save the starting values, as other algorithms might change the\n\t\t# values to suit their requirements :\n\t\tif isinstance(solve_params, dict):\n\t\t\tpass\n\t\telif solve_params == None:\n\t\t\tsolve_params = self.default_solve_params()\n\t\t\ts = \"::: using default parameters :::\"\n\t\t\tprint_text(s, cls=self)\n\t\t\ts = json.dumps(solve_params, sort_keys=True, indent=2)\n\t\t\tprint_text(s, '230')\n\t\telse:\n\t\t\ts = \">>> Energy REQUIRES A 'dict' INSTANCE OF SOLVER \" + \\\n\t\t\t \"PARAMETERS, NOT %s <<<\"\n\t\t\tprint_text(s % type(solve_params) , 'red', 1)\n\t\t\tsys.exit(1)\n\n\t\tself.momentum_s = momentum\n\t\tself.solve_params_s = deepcopy(solve_params)\n\t\tself.transient_s = transient\n\t\tself.use_lat_bc_s = use_lat_bc\n\t\tself.energy_flux_mode_s = energy_flux_mode\n\t\tself.stabilization_method_s = stabilization_method\n\n\t\tself.T_ini = self.model.T.copy(True)\n\t\tself.W_ini = self.model.W.copy(True)\n\n\t\tself.initialize(model, momentum, solve_params, transient,\n\t\t use_lat_bc, energy_flux_mode, stabilization_method)\n\n\tdef initialize(self, model, momentum, solve_params=None, transient=False,\n\t use_lat_bc=False, energy_flux_mode='B_ring',\n\t stabilization_method='GLS', reset=False):\n\t\t\"\"\"\n\t\tHere we set up the problem, and do all of the differentiation and\n\t\tmemory allocation type stuff. Note that any Energy object *must*\n\t\tcall this method. See the existing child Energy objects for reference.\n\t\t\"\"\"\n\t\traiseNotDefined()\n\n\tdef make_transient(self, time_step):\n\t\t\"\"\"\n\t\tset the energy system to transient form.\n\t\t\"\"\"\n\t\ts = \"::: RE-INITIALIZING ENERGY PHYSICS WITH TRANSIENT FORM :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tself.model.init_time_step(time_step)\n\n\t\tself.initialize(model = self.model,\n\t\t momentum = self.momentum_s,\n\t\t solve_params = self.solve_params_s,\n\t\t transient = True,\n\t\t use_lat_bc = self.use_lat_bc_s,\n\t\t energy_flux_mode = self.energy_flux_mode_s,\n\t\t stabilization_method = self.stabilization_method_s,\n\t\t reset = True)\n\n\tdef make_steady_state(self):\n\t\t\"\"\"\n\t\tset the energy system to steady-state form.\n\t\t\"\"\"\n\t\ts = \"::: RE-INITIALIZING ENERGY PHYSICS WITH STEADY-STATE FORM :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tself.initialize(model = self.model,\n\t\t momentum = self.momentum_s,\n\t\t solve_params = self.solve_params_s,\n\t\t transient = False,\n\t\t use_lat_bc = self.use_lat_bc_s,\n\t\t energy_flux_mode = self.energy_flux_mode_s,\n\t\t stabilization_method = self.stabilization_method_s,\n\t\t reset = True)\n\n\tdef set_basal_flux_mode(self, mode):\n\t\t\"\"\"\n\t\treset the energy system to use zero energy basal flux.\n\t\t\"\"\"\n\t\ts = \"::: RE-INITIALIZING ENERGY PHYSICS NEUMANN BASAL BC TO \" + \\\n\t\t \"\\'%s\\' :::\" % mode\n\t\tprint_text(s, cls=self)\n\n\t\tself.initialize(model = self.model,\n\t\t momentum = self.momentum_s,\n\t\t solve_params = self.solve_params_s,\n\t\t transient = self.transient_s,\n\t\t use_lat_bc = self.use_lat_bc_s,\n\t\t energy_flux_mode = mode,\n\t\t stabilization_method = self.stabilization_method_s,\n\t\t reset = True)\n\n\tdef reset(self):\n\t\t\"\"\"\n\t\treset the energy system to the original configuration.\n\t\t\"\"\"\n\t\ts = \"::: RE-INITIALIZING ENERGY PHYSICS :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tself.model.init_T(self.T_ini)\n\t\tself.model.init_W(self.W_ini)\n\n\t\tself.initialize(model = self.model,\n\t\t momentum = self.momentum_s,\n\t\t solve_params = self.solve_params_s,\n\t\t transient = self.transient_s,\n\t\t use_lat_bc = self.use_lat_bc_s,\n\t\t energy_flux_mode = self.energy_flux_mode_s,\n\t\t stabilization_method = self.stabilization_method_s,\n\t\t reset = True)\n\n\tdef color(self):\n\t\t\"\"\"\n\t\treturn the default color for this class.\n\t\t\"\"\"\n\t\treturn '213'\n\n\tdef get_ice_thermal_conductivity(self):\n\t\t\"\"\"\n\t\tReturns the thermal conductivity for ice.\n\t\t\"\"\"\n\t\treturn self.model.spy * 9.828 * exp(-0.0057*self.model.T)\n\n\tdef get_ice_heat_capacity(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\treturn 146.3 + 7.253*self.model.T\n\n\tdef get_bulk_thermal_conductivity(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tk_i = self.get_ice_thermal_conductivity()\n\t\tk_w = self.model.spy * self.model.k_w\n\t\tW = self.model.W\n\t\treturn (1-W)*k_i + W*k_w\n\n\tdef get_bulk_heat_capacity(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tc_i = self.get_ice_heat_capacity()\n\t\tc_w = self.model.c_w\n\t\tW = self.model.W\n\t\treturn (1-W)*c_i + W*c_w\n\n\tdef get_bulk_density(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tW = self.model.W\n\t\trho_i = self.model.rho_i\n\t\trho_w = self.model.rho_w\n\t\treturn (1-W)*rho_i + W*rho_w\n\n\tdef get_enthalpy_gradient_conductivity(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\t# coefficient for non-advective water flux (enthalpy-gradient) :\n\t\tk_c = conditional( gt(self.model.W, 0.0), self.model.k_0, 1 )\n\t\tk = self.get_bulk_thermal_conductivity()\n\t\treturn k_c * k\n\n\tdef get_enthalpy_gradient_diffusivity(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\tc = self.get_bulk_heat_capacity()\n\t\trho = self.get_bulk_density()\n\t\tkappa = self.get_enthalpy_gradient_conductivity()\n\t\treturn kappa / (rho*c)\n\n\tdef get_grid_peclet_number(self):\n\t\tr\"\"\"\n\t\tReturns the grid P\\'{e}clet number.\n\t\t\"\"\"\n\t\trho = self.get_bulk_density()\n\t\tc = self.get_bulk_heat_capacity()\n\t\tkappa = self.get_enthalpy_gradient_conductivity()\n\t\tu = self.momentum.get_velocity()\n\t\th = self.model.h\n\t\tut = rho*u - grad(kappa/c)\n\t\tu_norm = sqrt(dot(ut, ut) + DOLFIN_EPS)\n\t\treturn u_norm*h / (2*kappa/c)\n\n\tdef get_temperature_flux_vector(self):\n\t\t\"\"\"\n\t\tReturns the temperature flux vector.\n\t\t\"\"\"\n\t\tT = self.model.T\n\t\tk = self.get_bulk_thermal_conductivity()\n\t\treturn k * grad(T)\n\n\tdef get_temperature_melting_flux_vector(self):\n\t\t\"\"\"\n\t\tReturns the temperature-melting flux vector.\n\t\t\"\"\"\n\t\tTm = self.model.T_melt\n\t\tk = self.get_bulk_thermal_conductivity()\n\t\treturn k * grad(Tm)\n\n\tdef get_basal_melting_rate(self):\n\t\t\"\"\"\n\t\tReturns the basal melting rate.\n\t\t\"\"\"\n\t\tq_geo = self.model.q_geo # geothermal heat\n\t\tq_fric = self.model.q_fric # friction heat\n\t\tL_f = self.model.L_f # latent heat of freezing\n\t\trho_b = self.model.rhob # bulk density\n\t\tn_b = self.model.n_b # outward unit normal on B\n\t\tT = self.model.T # temperature\n\t\tk = self.get_ice_thermal_conductivity()\n\t\tq = k * grad(T) # heat flux\n\t\treturn (q_geo + q_fric - dot(q, n_b)) / (L_f * rho_b)\n\n\tdef get_internal_friction_heat(self):\n\t\t\"\"\"\n\t\tRetuns the internal friction heat; the strain heating.\n\t\t\"\"\"\n\t\t# collect the velocity vector to be of the same dimension os the model :\n\t\tu = self.momentum.get_velocity()\n\t\tepsdot = self.momentum.effective_strain_rate(u) + self.model.eps_reg\n\t\teta = self.momentum.get_viscosity(u)\n\t\treturn 4 * eta * epsdot\n\n\tdef get_external_friction_heat(self):\n\t\tr\"\"\"\n\t\tRetuns the external friction heat over the lower surface given by\n\n\t\t.. math::\n\n\t\t \\begin{align}\n\t\t q_{\\mathrm{fric}} = \\beta \\underline{u}_{\\Vert} \\cdot \\underline{u}_{\\Vert}\n\t\t \\end{align}\n\n\t\twith tangential component of velocity\n\t\t:math:`\\underline{u}_{\\Vert} = \\underline{u} - (\\underline{u} \\cdot \\hat{\\underline{n}} ) \\hat{\\underline{n}}`.\n\t\t\"\"\"\n\t\tu = self.momentum.get_velocity() # velocity\n\t\tB_ring = self.model.B_ring # lower suface-mass balance\n\t\tbeta = self.model.beta # friction coefficient\n\t\tn_b = self.model.n_b # outward unit normal on B\n\t\tu_t = u - dot(u,n_b) * n_b # tangential component of u\n\t\treturn beta * dot(u_t, u_t)\n\n\tdef default_solve_params(self):\n\t\t\"\"\"\n\t\tReturns a set of default solver parameters that yield good performance\n\t\t\"\"\"\n\t\tparams = {'solver' : 'mumps',\n\t\t 'use_surface_climate' : False}\n\t\treturn params\n\n\tdef solve_surface_climate(self):\n\t\t\"\"\"\n\t\tCalculates PDD, surface temperature given current model geometry and\n\t\tsaves to model.T_surface.\n\t\t\"\"\"\n\t\ts = \"::: solving surface climate :::\"\n\t\tprint_text(s, cls=self)\n\t\tmodel = self.model\n\n\t\tT_w = model.T_w(0)\n\t\tS = model.S.vector().get_local()\n\t\tlat = model.lat.vector().get_local()\n\t\tlon = model.lon.vector().get_local()\n\n\t\t# greenland :\n\t\tTn = 41.83 - 6.309e-3*S - 0.7189*lat - 0.0672*lon + T_w\n\n\t\t## antarctica :\n\t\t#Tn = 34.46 - 0.00914*S - 0.27974*lat\n\n\t\t# Apply the lapse rate to the surface boundary condition\n\t\tmodel.init_T_surface(Tn)\n\n\tdef adjust_S_ring(self):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\ts = \"::: solving surface accumulation/ablation :::\"\n\t\tprint_text(s, cls=self)\n\t\tmodel = self.model\n\n\t\tT_w = model.T_w(0)\n\t\tT = model.T_surface.vector().get_local()\n\n\t\tS_ring = 2.5 * 2**((T-T_w)/10)\n\n\t\tif model.N_OMEGA_FLT > 0:\n\t\t\tshf_dofs = np.where(model.mask.vector().get_local() == 0.0)[0]\n\t\t\tS_ring[model.shf_dofs] = -100\n\n\t\tmodel.init_S_ring(S_ring)\n\n\tdef form_cost_ftn(self, kind='abs'):\n\t\t\"\"\"\n\t\tForms and returns a cost functional for use with adjoint.\n\t\tSaves to self.J.\n\t\t\"\"\"\n\t\ts = \"::: forming water-optimization cost functional :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\t\ttheta = self.get_unknown()\n\t\tthetam = model.theta\n\t\tdGamma_bg = model.dGamma_bg()\n\t\ttheta_c = model.theta_melt + model.Wc*model.L_f\n\n\t\tif kind == 'TV':\n\t\t\tself.J = sqrt((theta - theta_c)**2 + 1e-15) * dGamma_bg\n\t\t\tself.Jp = sqrt((thetam - theta_c)**2 + 1e-15) * dGamma_bg\n\t\t\ts = \" - using TV cost functional :::\"\n\t\telif kind == 'L2':\n\t\t\tself.J = 0.5 * (theta - theta_c)**2 * dGamma_bg\n\t\t\tself.Jp = 0.5 * (thetam - theta_c)**2 * dGamma_bg\n\t\t\ts = \" - using L2 cost functional :::\"\n\t\telif kind == 'abs':\n\t\t\tself.J = abs(theta - theta_c) * dGamma_bg\n\t\t\tself.Jp = abs(thetam - theta_c) * dGamma_bg\n\t\t\ts = \" - using absolute value objective functional :::\"\n\t\telse:\n\t\t\ts = \">>> ADJOINT OBJECTIVE FUNCTIONAL MAY BE 'TV', 'L2' \" + \\\n\t\t\t \"or 'abs', NOT '%s' <<<\" % kind\n\t\t\tprint_text(s, 'red', 1)\n\t\t\tsys.exit(1)\n\t\tprint_text(s, cls=self)\n\n\tdef calc_misfit(self):\n\t\t\"\"\"\n\t\tCalculates the misfit,\n\t\t\"\"\"\n\t\ts = \"::: calculating misfit L-infty norm ||theta - theta_c|| :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\n\t\t# set up functions for surface (s) and current objective (o) :\n\t\ttheta_s = Function(model.Q)\n\t\ttheta_o = Function(model.Q)\n\n\t\t# calculate L_inf norm :\n\t\ttheta_v = model.theta.vector().get_local()\n\t\ttheta_m_v = model.theta_melt.vector().get_local()\n\t\tWc_v = model.Wc.vector().get_local()\n\t\ttheta_c_v = theta_m_v + Wc_v * model.L_f(0)\n\t\ttheta_o.vector().set_local(np.abs(theta_v - theta_c_v))\n\t\ttheta_o.vector().apply('insert')\n\n\t\t# apply difference over only grounded surface :\n\t\tbc_theta = DirichletBC(model.Q, theta_o, model.ff, model.GAMMA_B_GND)\n\t\tbc_theta.apply(theta_s.vector())\n\n\t\t# calculate L_inf vector norm :\n\t\tD = MPI.max(mpi_comm_world(), theta_s.vector().max())\n\n\t\ts = \"||theta - theta_c|| : %.3E\" % D\n\t\tprint_text(s, '208', 1)\n\t\treturn D\n\n\tdef calc_functionals(self):\n\t\t\"\"\"\n\t\tUsed to facilitate printing the objective function in adjoint solves.\n\t\t\"\"\"\n\t\ttry:\n\t\t\tR = assemble(self.Rp, annotate=False)\n\t\texcept AttributeError:\n\t\t\tR = 0.0\n\t\tJ = assemble(self.Jp, annotate=False)\n\t\tprint_min_max(R, 'R')\n\t\tprint_min_max(J, 'J')\n\t\treturn (R, J)\n\n\tdef calc_obj(self):\n\t\t\"\"\"\n\t\tUsed to facilitate printing the objective function in adjoint solves.\n\t\t\"\"\"\n\t\tJ = assemble(self.Jp, annotate=False)\n\t\tprint_min_max(J, 'J')\n\t\treturn J\n\n\tdef partition_energy(self, annotate=False):\n\t\t\"\"\"\n\t\tsolve for the water content model.W and temperature model.T.\n\t\t\"\"\"\n\t\t# TODO: the operation below breaks dolfin-adjoint annotation.\n\t\t# temperature solved with quadradic formula, using expression for c :\n\t\ts = \"::: calculating temperature :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\t\tT_w = model.T_w(0)\n\n\t\t# temperature is a quadradic function of energy :\n\t\ttheta_v = model.theta.vector().get_local()\n\t\tT_n_v = (-146.3 + np.sqrt(146.3**2 + 2*7.253*theta_v)) / 7.253\n\t\tT_v = T_n_v.copy()\n\t\tTp_v = T_n_v.copy()\n\n\t\t# create pressure-adjusted temperature for rate-factor :\n\t\tTp_v[Tp_v > T_w] = T_w\n\t\tmodel.init_Tp(Tp_v)\n\n\t\t# correct for the pressure-melting point :\n\t\tT_melt_v = model.T_melt.vector().get_local()\n\t\ttheta_melt_v = model.theta_melt.vector().get_local()\n\t\twarm = theta_v >= theta_melt_v\n\t\tcold = theta_v < theta_melt_v\n\t\tT_v[warm] = T_melt_v[warm]\n\t\tmodel.init_T(T_v)\n\n\t\t# water content solved diagnostically :\n\t\ts = \"::: calculating water content :::\"\n\t\tprint_text(s, cls=self)\n\t\tW_v = (theta_v - theta_melt_v) / model.L_f(0)\n\n\t\t# update water content :\n\t\tW_v[W_v < 0.0] = 0.0 # no water where frozen, please.\n\t\tW_v[W_v > 1.0] = 1.0 # no hot water, please.\n\t\tmodel.assign_variable(model.W0, model.W)\n\t\tmodel.init_W(W_v)\n\n\tdef optimize_water_flux(self, max_iter, bounds=(-1e8, 0), method='ipopt',\n\t adj_save_vars=None, adj_callback=None):\n\t\t\"\"\"\n\t\tdetermine the correct basal-mass balance saved (currently) to\n\t\t``model.B_ring``.\n\t\t\"\"\"\n\t\ts = '::: optimizing for water-flux in %i maximum iterations :::'\n\t\tprint_text(s % max_iter, cls=self)\n\n\t\tmodel = self.model\n\n\t\t# reset entire dolfin-adjoint state :\n\t\tadj_reset()\n\n\t\t# starting time :\n\t\tt0 = time()\n\n\t\t# need this for the derivative callback :\n\t\tglobal counter\n\t\tcounter = 0\n\n\t\t# functional lists to be populated :\n\t\tglobal Rs, Js, Ds\n\t\tRs = []\n\t\tJs = []\n\t\tDs = []\n\n\t\t# now solve the control optimization problem :\n\t\ts = \"::: starting adjoint-control optimization with method '%s' :::\"\n\t\tprint_text(s % method, cls=self)\n\n\t\tdef eval_cb(I, B_ring):\n\t\t\ts = '::: adjoint objective eval post callback function :::'\n\t\t\tprint_text(s, cls=self)\n\t\t\tprint_min_max(I, 'I')\n\t\t\tprint_min_max(B_ring, 'B_ring')\n\n\t\t# objective gradient callback function :\n\t\tdef deriv_cb(I, dI, B_ring):\n\t\t\tglobal counter, Rs, Js\n\t\t\tif method == 'ipopt':\n\t\t\t\ts0 = '>>> '\n\t\t\t\ts1 = 'iteration %i (max %i) complete'\n\t\t\t\ts2 = ' <<<'\n\t\t\t\ttext0 = get_text(s0, 'red', 1)\n\t\t\t\ttext1 = get_text(s1 % (counter, max_iter), 'red')\n\t\t\t\ttext2 = get_text(s2, 'red', 1)\n\t\t\t\tif MPI.rank(mpi_comm_world())==0:\n\t\t\t\t\tprint(text0 + text1 + text2)\n\t\t\t\tcounter += 1\n\t\t\ts = '::: adjoint obj. gradient post callback function :::'\n\t\t\tprint_text(s, cls=self)\n\t\t\tprint_min_max(dI, 'dI/B_ring')\n\n\t\t\t# update the DA current velocity to the model for evaluation\n\t\t\t# purposes only; the model.assign_variable function is\n\t\t\t# annotated for purposes of linking physics models to the adjoint\n\t\t\t# process :\n\t\t\ttheta_opt = DolfinAdjointVariable(model.theta).tape_value()\n\t\t\tmodel.init_theta(theta_opt)\n\n\t\t\t# print functional values :\n\t\t\tmodel.B_ring.assign(B_ring, annotate=False)\n\t\t\tftnls = self.calc_functionals()\n\t\t\tD = self.calc_misfit()\n\n\t\t\t# functional lists to be populated :\n\t\t\tRs.append(ftnls[0])\n\t\t\tJs.append(ftnls[1])\n\t\t\tDs.append(D)\n\n\t\t\t# call that callback, if you want :\n\t\t\tif adj_callback is not None:\n\t\t\t\tadj_callback(I, dI, B_ring)\n\n\t\t# solve the momentum equations with annotation enabled :\n\t\ts = '::: solving forward problem for dolfin-adjoint annotatation :::'\n\t\tprint_text(s, cls=self)\n\t\tself.solve(annotate=True)\n\n\t\t# get the cost, regularization, and objective functionals :\n\t\tI = self.J\n\t\ttry:\n\t\t\tI += self.R\n\t\texcept AttributeError:\n\t\t\tprint_text(' - not using regularization -', cls=self)\n\n\t\t# define the control variable :\n\t\tm = Control(model.B_ring, value=model.B_ring)\n\n\t\t# state the minimization problem :\n\t\tF = ReducedFunctional(Functional(I), m, eval_cb_post=eval_cb,\n\t\t derivative_cb_post=deriv_cb)\n\n\t\t# optimize with scipy's fmin_l_bfgs_b :\n\t\tif method == 'l_bfgs_b':\n\t\t\tout = minimize(F, method=\"L-BFGS-B\", tol=1e-9, bounds=bounds,\n\t\t\t options={\"disp\" : True,\n\t\t\t \"maxiter\" : max_iter,\n\t\t\t \"gtol\" : 1e-5})\n\t\t\tB_ring_opt = out[0]\n\n\t\t# or optimize with IPOpt (preferred) :\n\t\telif method == 'ipopt':\n\t\t\ttry:\n\t\t\t\timport pyipopt\n\t\t\texcept ImportError:\n\t\t\t\tinfo_red(\"\"\"You do not have IPOPT and/or pyipopt installed.\n\t\t\t\t When compiling IPOPT, make sure to link against HSL,\n\t\t\t\t as it is a necessity for practical problems.\"\"\")\n\t\t\t\traise\n\t\t\tproblem = MinimizationProblem(F, bounds=bounds)\n\t\t\tparameters = {\"tol\" : 1e-8,\n\t\t\t \"acceptable_tol\" : 1e-6,\n\t\t\t \"maximum_iterations\" : max_iter,\n\t\t\t \"print_level\" : 5,\n\t\t\t \"ma97_order\" : \"metis\",\n\t\t\t \"ma86_order\" : \"metis\",\n\t\t\t \"linear_solver\" : \"ma57\"}\n\t\t\tsolver = IPOPTSolver(problem, parameters=parameters)\n\t\t\tB_ring_opt = solver.solve()\n\n\t\t# let's see it :\n\t\tprint_min_max(B_ring_opt, 'B_ring_opt')\n\n\t\t# extrude the flux up and make the optimal control variable available :\n\t\tB_ring_ext = model.vert_extrude(B_ring_opt, d='up')\n\t\tmodel.init_B_ring(B_ring_ext)\n\t\t#Control(model.B_ring).update(B_ring_ext) # FIXME: does this work?\n\n\t\t# save state to unique hdf5 file :\n\t\tif isinstance(adj_save_vars, list):\n\t\t\ts = '::: saving variables in list arg adj_save_vars :::'\n\t\t\tprint_text(s, cls=self)\n\t\t\tout_file = model.out_dir + 'w_opt.h5'\n\t\t\tfoutput = HDF5File(mpi_comm_world(), out_file, 'w')\n\t\t\tfor var in adj_save_vars:\n\t\t\t\tmodel.save_hdf5(var, f=foutput)\n\t\t\tfoutput.close()\n\n\t\t# calculate total time to compute\n\t\ttf = time()\n\t\ts = tf - t0\n\t\tm = s / 60.0\n\t\th = m / 60.0\n\t\ts = s % 60\n\t\tm = m % 60\n\t\ttext = \"time to optimize for water flux: %02d:%02d:%02d\" % (h,m,s)\n\t\tprint_text(text, 'red', 1)\n\n\t\t# save all the objective functional values :\n\t\td = model.out_dir + 'objective_ftnls_history/'\n\t\ts = '::: saving objective functionals to %s :::'\n\t\tprint_text(s % d, cls=self)\n\t\tif model.MPI_rank==0:\n\t\t\tif not os.path.exists(d):\n\t\t\t\tos.makedirs(d)\n\t\t\tnp.savetxt(d + 'time.txt', np.array([tf - t0]))\n\t\t\tnp.savetxt(d + 'Rs.txt', np.array(Rs))\n\t\t\tnp.savetxt(d + 'Js.txt', np.array(Js))\n\t\t\tnp.savetxt(d + 'Ds.txt', np.array(Ds))\n\n\t\t\tfig = plt.figure()\n\t\t\tax = fig.add_subplot(111)\n\t\t\t#ax.set_yscale('log')\n\t\t\tax.set_ylabel(r'$\\mathscr{J}\\left(\\theta\\right)$')\n\t\t\tax.set_xlabel(r'iteration')\n\t\t\tax.plot(np.array(Js), 'r-', lw=2.0)\n\t\t\tplt.grid()\n\t\t\tplt.savefig(d + 'J.png', dpi=100)\n\t\t\tplt.close(fig)\n\n\t\t\ttry:\n\t\t\t\tR = self.R\n\t\t\t\tfig = plt.figure()\n\t\t\t\tax = fig.add_subplot(111)\n\t\t\t\tax.set_yscale('log')\n\t\t\t\tax.set_ylabel(r'$\\mathscr{R}\\left(\\alpha\\right)$')\n\t\t\t\tax.set_xlabel(r'iteration')\n\t\t\t\tax.plot(np.array(Rs), 'r-', lw=2.0)\n\t\t\t\tplt.grid()\n\t\t\t\tplt.savefig(d + 'R.png', dpi=100)\n\t\t\t\tplt.close(fig)\n\t\t\texcept AttributeError:\n\t\t\t\tpass\n\n\t\t\tfig = plt.figure()\n\t\t\tax = fig.add_subplot(111)\n\t\t\t#ax.set_yscale('log')\n\t\t\tax.set_ylabel(r'$\\mathscr{D}\\left(\\theta\\right)$')\n\t\t\tax.set_xlabel(r'iteration')\n\t\t\tax.plot(np.array(Ds), 'r-', lw=2.0)\n\t\t\tplt.grid()\n\t\t\tplt.savefig(d + 'D.png', dpi=100)\n\t\t\tplt.close(fig)\n\n\tdef calc_bulk_density(self):\n\t\t\"\"\"\n\t\tCalculate the bulk density stored in ``model.rhob``.\n\t\t\"\"\"\n\t\t# calculate bulk density :\n\t\ts = \"::: calculating bulk density :::\"\n\t\tprint_text(s, cls=self)\n\t\tmodel = self.model\n\t\trhob = project(self.rho, annotate=False)\n\t\tmodel.assign_variable(model.rhob, rhob)\n\n\n\n\n\n\nclass Enthalpy(Energy):\n\t\"\"\"\n\t\"\"\"\n\tdef initialize(self, model, momentum,\n\t solve_params = None,\n\t transient = False,\n\t use_lat_bc = False,\n\t energy_flux_mode = 'B_ring',\n\t stabilization_method = 'GLS',\n\t reset = False):\n\t\t\"\"\"\n\t\tSet up energy equation residual.\n\t\t\"\"\"\n\t\tself.transient = transient\n\n\t\ts = \"::: INITIALIZING ENTHALPY PHYSICS :::\"\n\t\tprint_text(s, cls=self)\n\n\t\t# save the solver parameters and momentum instance :\n\t\tself.solve_params = solve_params\n\t\tself.momentum = momentum\n\t\tself.linear = True\n\n\t\t# save the state of basal boundary flux :\n\t\tself.energy_flux_mode = energy_flux_mode\n\n\t\t# create a facet function for temperate zone :\n\t\tself.ff = MeshFunction('size_t', model.mesh, 2, 0)\n\n\t\tmesh = model.mesh\n\t\tT = model.T\n\t\talpha = model.alpha\n\t\trho_w = model.rho_w\n\t\tL_f = model.L_f\n\t\tW = model.W\n\t\tT_m = model.T_melt\n\t\tB_ring = model.B_ring\n\t\tT_surface = model.T_surface\n\t\ttheta_surface = model.theta_surface\n\t\ttheta_float = model.theta_float\n\t\ttheta_app = model.theta_app\n\t\ttheta_0 = model.theta\n\t\tq_geo = model.q_geo\n\t\th = model.h\n\t\tdt = model.time_step\n\t\tdOmega = model.dOmega()\n\t\tdGamma_bg = model.dGamma_bg()\n\n\t\tself.Q = model.Q\n\n\t\tself.ass_theta = FunctionAssigner(model.Q, self.Q)\n\n\t\tself.set_unknown(Function(self.Q, name='energy.theta'))\n\t\tself.set_trial_function(TrialFunction(self.Q))\n\t\tself.set_test_function(TestFunction(self.Q))\n\n\t\t# define test and trial functions :\n\t\tpsi = self.get_test_function()\n\t\tdtheta = self.get_trial_function()\n\t\ttheta = self.get_unknown()\n\n\t\t# internal friction (strain heat) :\n\t\tQ = self.get_internal_friction_heat()\n\n\t\t# velocity :\n\t\tu = momentum.get_velocity()\n\n\t\t# bulk properties :\n\t\tc = self.get_bulk_heat_capacity()\n\t\tk = self.get_bulk_thermal_conductivity()\n\t\trho = self.get_bulk_density()\n\n\t\t# discontinuous with water, J/(a*m*K) :\n\t\tkappa = self.get_enthalpy_gradient_conductivity()\n\n\t\t# bulk enthalpy-gradient diffusivity\n\t\tXi = self.get_enthalpy_gradient_diffusivity()\n\n\t\t# frictional heating :\n\t\tq_fric = self.get_external_friction_heat()\n\n\t\t# basal heat-flux natural boundary condition :\n\t\tq_tm = self.get_temperature_melting_flux_vector()\n\t\tn = model.N\n\t\tg_w = dot(q_tm, n) + rho_w*L_f*B_ring\n\t\tg_n = q_geo + q_fric\n\t\tif energy_flux_mode == 'zero_energy' or energy_flux_mode == 'B_ring':\n\t\t\ts = \" - using B_ring-energy flux boundary condition -\"\n\t\t\tprint_text(s, cls=self)\n\t\t\tg_b = g_n - alpha*g_w\n\t\telif energy_flux_mode == 'temperate_zone_mark':\n\t\t\ts = \" - using temperate-zone mark energy flux boundary condition -\"\n\t\t\tprint_text(s, cls=self)\n\t\t\tg_b = g_n\n\t\telse:\n\t\t\ts = \">>> PARAMETER 'energy_flux_mode' MAY BE 'zero_energy', \" + \\\n\t\t\t \"'B_ring', or 'temperate_zone_mark', NOT '%s' <<<\"\n\t\t\tprint_text(s % energy_flux_mode , 'red', 1)\n\t\t\tsys.exit(1)\n\n\t\t# configure the module to run in steady state :\n\t\tif not transient:\n\t\t\tprint_text(\" - using steady-state formulation -\", cls=self)\n\t\t\tnu = 1.0\n\t\telse:\n\t\t\tprint_text(\" - using transient formulation -\", cls=self)\n\t\t\tnu = 0.5\n\n\t\t# form time-interpolated unknown :\n\t\ttheta_mid = nu*dtheta + (1 - nu)*theta_0\n\n\t\t# quasi-velocity (see Cummings et al., 2016)\n\t\tut = rho*u - grad(kappa/c)\n\t\tut_norm = sqrt(dot(ut, ut) + DOLFIN_EPS)\n\n\t\t# the Peclet number :\n\t\tPe = self.get_grid_peclet_number()\n\n\t\t# for linear elements :\n\t\tif model.order == 1:\n\t\t xi = 1/tanh(Pe) - 1/Pe\n\n\t\t# for quadradic elements :\n\t\telif model.order == 2:\n\t\t\txi_1 = 0.5*(1/tanh(Pe) - 2/Pe)\n\t\t\txi = ((3 + 3*Pe*xi_1)*tanh(Pe) - (3*Pe + Pe**2*xi_1)) \\\n\t\t\t\t / ((2 - 3*xi_1*tanh(Pe))*Pe**2)\n\n\t\t# intrinsic time parameter :\n\t\ttau = h*xi / (2 * ut_norm)\n\t\tpsihat = psi + tau * dot(ut, grad(psi))\n\n\t\t# the linear differential operator for this problem :\n\t\tdef Lu(theta):\n\t\t\treturn + rho * dot(u, grad(theta)) \\\n\t\t\t - kappa/c * div(grad(theta)) \\\n\t\t\t - dot(grad(kappa/c), grad(theta))\n\n\t\t# the advective part of the operator :\n\t\tdef L_adv(theta):\n\t\t\treturn dot(ut, grad(theta))\n\n\t\t# the adjoint of the operator :\n\t\tdef L_star(theta):\n\t\t\treturn - dot(u, grad(theta)) \\\n\t\t\t - Xi * div(grad(theta)) \\\n\t\t\t + 1/rho * dot(grad(kappa/c), grad(theta))\n\n\t\t# use streamline-upwind/Petrov-Galerkin stabilization :\n\t\tif stabilization_method == 'SUPG':\n\t\t\ts = \" - using streamline-upwind/Petrov-Galerkin stabilization -\"\n\t\t\tLL = lambda x: + L_adv(x)\n\t\t# use Galerkin/least-squares stabilization :\n\t\telif stabilization_method == 'GLS':\n\t\t\ts = \" - using Galerkin/least-squares stabilization -\"\n\t\t\tLL = lambda x: + Lu(x)\n\t\t# use subgrid-scale-model stabilization :\n\t\telif stabilization_method == 'SSM':\n\t\t\ts = \" - using subgrid-scale-model stabilization -\"\n\t\t\tLL = lambda x: - L_star(x)\n\t\tprint_text(s, cls=self)\n\n\t\t# form the residual :\n\t\tresid = + rho * dot(u, grad(theta_mid)) * psi * dOmega \\\n\t\t\t + kappa/c * inner(grad(psi), grad(theta_mid)) * dOmega \\\n\t\t\t - dot(grad(kappa/c), grad(theta_mid)) * psi * dOmega \\\n\t\t\t - g_b * psi * dGamma_bg \\\n\t\t\t - Q * psi * dOmega \\\n\t\t\t + inner(LL(psi), tau*(Lu(theta_mid) - Q)) * dOmega \\\n\n\t\t# add the time derivative term if transient :\n\t\tif transient:\n\t\t\tresid += rho * (dtheta - theta_0) / dt * psi * dOmega\n\n\t\t# set this Physics instance's residual, left-, and right-hand sides :\n\t\tself.set_residual(resid)\n\n\t\t# surface boundary condition :\n\t\ttheta_bcs = []\n\t\tif model.N_GAMMA_S_GND > 0:\n\t\t\ttheta_bcs.append( DirichletBC(self.Q, theta_surface,\n\t\t\t model.ff, model.GAMMA_S_GND) )\n\t\tif model.N_GAMMA_U_GND > 0:\n\t\t\ttheta_bcs.append( DirichletBC(self.Q, theta_surface,\n\t\t\t model.ff, model.GAMMA_U_GND) )\n\t\tif model.N_GAMMA_S_FLT > 0:\n\t\t\ttheta_bcs.append( DirichletBC(self.Q, theta_surface,\n\t\t\t model.ff, model.GAMMA_S_FLT) )\n\t\tif model.N_GAMMA_U_FLT > 0:\n\t\t\ttheta_bcs.append( DirichletBC(self.Q, theta_surface,\n\t\t\t model.ff, model.GAMMA_U_FLT) )\n\n\t\t# apply T_melt conditions of portion of ice in contact with water :\n\t\tif model.N_GAMMA_B_FLT > 0:\n\t\t\ttheta_bcs.append( DirichletBC(self.Q, theta_float,\n\t\t\t model.ff, model.GAMMA_B_FLT) )\n\t\tif model.N_GAMMA_L_UDR > 0:\n\t\t\ttheta_bcs.append( DirichletBC(self.Q, theta_float,\n\t\t\t model.ff, model.GAMMA_L_UDR) )\n\n\t\t# apply lateral ``divide'' boundaries if desired :\n\t\tif use_lat_bc:\n\t\t\ts = \" - using divide-lateral boundary conditions -\"\n\t\t\tprint_text(s, cls=self)\n\t\t\tif model.N_GAMMA_L_DVD > 0:\n\t\t\t\ttheta_bcs.append( DirichletBC(self.Q, model.theta_app,\n\t\t\t\t model.ff, model.GAMMA_L_DVD) )\n\n\t\t# update this Physics instance's list of boundary conditions :\n\t\tself.set_boundary_conditions(theta_bcs)\n\n\t\t# initialize the boundary conditions and thermal properties, if\n\t\t# we have not done so already :\n\t\tif not reset:\n\t\t\t# calculate energy and temperature melting point :\n\t\t\tself.calc_T_melt(annotate=False)\n\n\t\t\tT_v = T.vector().get_local()\n\t\t\tW_v = W.vector().get_local()\n\t\t\tT_s_v = T_surface.vector().get_local()\n\t\t\tT_m_v = T_m.vector().get_local()\n\t\t\tTp_v = T_v.copy()\n\t\t\ttheta_s_v = 146.3*T_s_v + 7.253/2.0*T_s_v**2\n\t\t\ttheta_f_v = 146.3*(T_m_v - 1.0) + 7.253/2.0*(T_m_v - 1.0)**2\n\t\t\ttheta_i_v = 146.3*T_v + 7.253/2.0*T_v**2 + W_v * L_f(0)\n\n\t\t\t# Surface boundary condition :\n\t\t\ts = \"::: calculating energy boundary conditions :::\"\n\t\t\tprint_text(s, cls=self)\n\n\t\t\t# initialize the boundary conditions :\n\t\t\tmodel.init_theta_surface(theta_s_v)\n\t\t\tmodel.init_theta_app(theta_s_v)\n\t\t\tmodel.init_theta_float(theta_f_v)\n\n\t\t\t# initialize energy from W and T :\n\t\t\tmodel.init_theta(theta_i_v)\n\n\tdef calc_Pe(self, avg=False, annotate=annotate):\n\t\tr\"\"\"\n\t\tcalculates the grid P\\'{e}clet number to self.model.Pe.\n\n\t\tif avg=True, calculate the vertical average.\n\t\t\"\"\"\n\t\ts = \"::: calculating Peclet number :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tPe = self.get_grid_peclet_number()\n\t\tif avg: Pe = self.model.calc_vert_average(Pe, annotatate=annotate)\n\t\telse: Pe = project(Pe, solver_type='iterative', annotate=annotate)\n\t\tself.model.assign_variable(self.model.Pe, Pe, annotate=annotate)\n\n\tdef calc_vert_avg_W(self):\n\t\t\"\"\"\n\t\tcalculates the vertical averge water content W, saved to model.Wbar.\n\t\t\"\"\"\n\t\ts = \"::: calculating vertical average internal water content :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tWbar = self.model.calc_vert_average(self.model.W)\n\t\tself.model.init_Wbar(Wbar)\n\n\tdef calc_vert_avg_strain_heat(self):\n\t\t\"\"\"\n\t\tcalculates integrated strain-heating, saved to model.Qbar.\n\t\t\"\"\"\n\t\ts = \"::: calculating vertical average strain heat :::\"\n\t\tprint_text(s, cls=self)\n\n\t\t# calculate downward vertical integral :\n\t\tQ = self.get_internal_friction_heat()\n\t\tQbar = self.model.calc_vert_average(Q)\n\t\tself.model.init_Qbar(Qbar)\n\n\tdef calc_temperate_thickness(self):\n\t\t\"\"\"\n\t\tcalculates the temperate zone thickness, saved to model.alpha_int.\n\t\t\"\"\"\n\t\ts = \"::: calculating temperate zone thickness :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\t\talpha_int = model.vert_integrate(model.alpha, d='down')\n\t\talpha_int = model.vert_extrude(alpha_int, d='up')\n\t\tmodel.init_alpha_int(alpha_int)\n\n\tdef calc_temp_rat(self):\n\t\t\"\"\"\n\t\tcalculates the ratio of the temperate zone, saved to model.temp_rat.\n\t\t\"\"\"\n\t\ts = \"::: calculating ratio of column that is temperate :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\n\t\tself.calc_temperate_thickness()\n\n\t\t# TODO: the operation below breaks dolfin-adjoint annotation.\n\t\tS_v = model.S.vector().get_local()\n\t\tB_v = model.B.vector().get_local()\n\t\talpha_int_v = model.alpha_int.vector().get_local()\n\t\tH_v = S_v - B_v + DOLFIN_EPS\n\t\ttemp_rat_v = alpha_int_v / H_v\n\t\ttemp_rat_v[temp_rat_v < 0.0] = 0.0\n\t\ttemp_rat_v[temp_rat_v > 1.0] = 1.0\n\t\tmodel.init_temp_rat(alpha_int_v / H_v)\n\n\tdef calc_T_melt(self, annotate=False):\n\t\t\"\"\"\n\t\tCalculates temperature melting point model.T_melt and energy melting point\n\t\tmodel.theta_melt.\n\n\t\t\"\"\"\n\t\ts = \"::: calculating pressure-melting temperature :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\n\t\tgamma = model.gamma\n\t\tT_w = model.T_w\n\t\tp = model.p\n\n\t\t# TODO: the operation below breaks dolfin-adjoint annotation.\n\t\tp_v = p.vector().get_local()\n\t\tTm = T_w(0) - gamma(0)*p_v\n\t\ttht_m = 146.3*Tm + 7.253/2.0*Tm**2\n\n\t\tmodel.assign_variable(model.T_melt, Tm, annotate=annotate)\n\t\tmodel.assign_variable(model.theta_melt, tht_m, annotate=annotate)\n\n\tdef get_solve_params(self):\n\t\t\"\"\"\n\t\tReturns the solve parameters.\n\t\t\"\"\"\n\t\treturn self.solve_params\n\n\tdef default_solve_params(self):\n\t\t\"\"\"\n\t\tReturns a set of default solver parameters that yield good performance\n\t\t\"\"\"\n\t\tnparams = {'newton_solver' : {'linear_solver' : 'gmres',\n\t\t 'preconditioner' : 'hypre_amg',\n\t\t 'relative_tolerance' : 1e-13,\n\t\t 'relaxation_parameter' : 1.0,\n\t\t 'maximum_iterations' : 20,\n\t\t 'error_on_nonconvergence' : False}}\n\t\tparams = {'solver' : {'linear_solver' : 'mumps',\n\t\t 'preconditioner' : 'none'},\n\t\t 'nparams' : nparams,\n\t\t 'use_surface_climate' : False}\n\t\treturn params\n\n\tdef mark_temperate_zone(self):\n\t\t\"\"\"\n\t\tmark basal regions with overlying temperate layer to model.alpha.\n\t\t\"\"\"\n\t\ts = \"::: marking basal regions with an overlying temperate layer :::\"\n\t\tprint_text(s, cls=self)\n\n\t\t# TODO: the operation below breaks dolfin-adjoint annotation.\n\t\tW_v = self.model.W.vector().get_local()\n\t\talpha_v = self.model.alpha.vector().get_local()\n\t\talpha_v[:] = 0\n\t\talpha_v[W_v > 0] = 1\n\t\tself.model.init_alpha(alpha_v)\n\n\tdef calc_basal_temperature_flux(self, annotate=False):\n\t\t\"\"\"\n\t\tSolve for the basal temperature flux stored in model.gradT_B.\n\t\t\"\"\"\n\t\t# calculate melt-rate :\n\t\ts = \"::: solving basal temperature flux k \\\\nabla T \\\\cdot n :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tn_b = self.model.n_b\n\t\tq = self.get_temperature_flux_vector()\n\t\tq_dot_n = project(dot(q, n_b), self.model.Q, annotate=annotate)\n\t\tself.model.assign_variable(self.model.gradT_B, q_dot_n, annotate=annotate)\n\t\tprint_min_max(self.model.gradT_B, 'gradT_B')\n\n\tdef calc_basal_temperature_melting_flux(self, annotate=False):\n\t\t\"\"\"\n\t\tSolve for the basal temperature melting flux stored in model.gradTm_B.\n\t\t\"\"\"\n\t\t# calculate melt-rate :\n\t\ts = \"::: solving basal temperature flux k \\\\nabla T_m \\\\cdot n :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tn_b = self.model.n_b\n\t\tq = self.get_temperature_melting_flux_vector()\n\t\tq_dot_n = project(dot(q, n_b), self.model.Q, annotate=annotate)\n\t\tself.model.assign_variable(self.model.gradTm_B, q_dot_n, annotate=annotate)\n\t\tprint_min_max(self.model.gradTm_B, 'gradTm_B')\n\n\tdef calc_basal_melting_rate(self, annotate=False):\n\t\t\"\"\"\n\t\tSolve for the basal melt rate stored in model.Mb.\n\t\t\"\"\"\n\t\t# calculate melt-rate :\n\t\ts = \"::: solving basal-melt-rate :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tM_b = project(self.get_basal_melting_rate(), self.model.Q, \\\n\t\t annotate=annotate)\n\t\tself.model.assign_variable(self.model.Mb, M_b, annotate=annotate)\n\n\tdef calc_q_fric(self):\n\t\tr\"\"\"\n\t\tSolve for the friction heat term stored in ``model.q_fric``.\n\t\t\"\"\"\n\t\t# calculate melt-rate :\n\t\ts = \"::: solving basal friction heat :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tq_fric = project(self.get_external_friction_heat(), self.model.Q, \\\n\t\t annotate=annotate)\n\t\tself.model.assign_variable(self.model.q_fric, q_fric, annotate=annotate)\n\n\tdef derive_temperate_zone(self, annotate=False):\n\t\t\"\"\"\n\t\tSolve the steady-state energy equation, saving enthalpy to model.theta,\n\t\ttemperature to model.T, and water content to model.W such that the\n\t\tregions with overlying temperate ice are properly marked by model.alpha.\n\t\t\"\"\"\n\t\tmodel = self.model\n\n\t\t# solve the energy equation :\n\t\ts = \"::: solving for temperate zone locations :::\"\n\t\tprint_text(s, cls=self)\n\n\t\t# ensure that the boundary-marking process is done in steady state :\n\t\ttransient = False\n\t\tif self.transient:\n\t\t\tself.make_steady_state()\n\t\t\ttransient = True\n\n\t\t# put the physics in temperate zone marking mode :\n\t\tif self.energy_flux_mode != 'temperate_zone_mark':\n\t\t\tzef = True\n\t\t\tmode = self.energy_flux_mode\n\t\t\tself.set_basal_flux_mode('temperate_zone_mark')\n\n\t\t# solve the linear system :\n\t\tsolve(self.get_lhs() == self.get_rhs(), self.get_unknown(),\n\t\t self.get_boundary_conditions(),\n\t\t solver_parameters = self.solve_params['solver'], annotate=annotate)\n\n\t\t# calculate water content :\n\t\t# TODO: the operation below breaks dolfin-adjoint annotation.\n\t\ttheta_v = self.get_unknown().vector().get_local()\n\t\ttheta_melt_v = model.theta_melt.vector().get_local()\n\t\tW_v = (theta_v - theta_melt_v) / model.L_f(0)\n\t\tW_v[W_v < 0.0] = 0.0 # no water where frozen, please.\n\n\t\t# mark appropriately basal regions with an overlying temperate layer :\n\t\t# TODO: the operation below breaks dolfin-adjoint annotation.\n\t\talpha_v = model.alpha.vector().get_local()\n\t\talpha_v[:] = 0\n\t\talpha_v[W_v > 0] = 1\n\t\tmodel.init_alpha(alpha_v)\n\n\t\t# reset to previous energy flux mode, if necessary :\n\t\tif zef:\n\t\t\tself.set_basal_flux_mode(mode)\n\n\t\t# convert back to transient if necessary :\n\t\tif transient:\n\t\t\tenergy.make_transient(time_step = model.time_step)\n\n\tdef update_thermal_parameters(self, annotate=False):\n\t\t\"\"\"\n\t\tfixed-point iterations to make all linearized thermal parameters consistent.\n\t\t\"\"\"\n\t\t# TODO: the operation below breaks dolfin-adjoint annotation.\n\t\tmodel = self.model\n\n\t\t# solve the energy equation :\n\t\ts = \"::: updating thermal parameters :::\"\n\t\tprint_text(s, cls=self)\n\n\t\t# ensure that we have steady state :\n\t\ttransient = False\n\t\tif self.transient:\n\t\t\tself.make_steady_state()\n\t\t\ttransient = True\n\n\t\t# previous theta for norm calculation\n\t\tU_prev = self.get_unknown().copy(True)\n\n\t\t# iteration counter :\n\t\tcounter = 1\n\n\t\t# maximum number of iterations :\n\t\tmax_iter = 1000\n\n\t\t# L_2 erro norm between iterations :\n\t\tabs_error = np.inf\n\t\trel_error = np.inf\n\n\t\t# tolerances for stopping criteria :\n\t\tatol = 1e-7\n\t\trtol = 1e-8\n\n\t\t# perform a fixed-point iteration until the L_2 norm of error\n\t\t# is less than tolerance :\n\t\twhile abs_error > atol and rel_error > rtol and counter <= max_iter:\n\n\t\t\t# solve the linear system :\n\t\t\tsolve(self.get_lhs() == self.get_rhs(), self.get_unknown(),\n\t\t\t self.get_boundary_conditions(),\n\t\t\t solver_parameters = self.solve_params['solver'], annotate=annotate)\n\n\t\t\t# calculate L_2 norms :\n\t\t\tabs_error_n = norm(U_prev.vector() - self.get_unknown().vector(), 'l2')\n\t\t\ttht_nrm = norm(self.get_unknown().vector(), 'l2')\n\n\t\t\t# save convergence history :\n\t\t\tif counter == 1:\n\t\t\t\trel_error = abs_error_n\n\t\t\telse:\n\t\t\t\trel_error = abs(abs_error - abs_error_n)\n\n\t\t\t# print info to screen :\n\t\t\tif model.MPI_rank == 0:\n\t\t\t\ts0 = '>>> '\n\t\t\t\ts1 = 'thermal parameter update iteration %i (max %i) done: ' \\\n\t\t\t\t % (counter, max_iter)\n\t\t\t\ts2 = 'r (abs) = %.2e ' % abs_error\n\t\t\t\ts3 = '(tol %.2e), ' % atol\n\t\t\t\ts4 = 'r (rel) = %.2e ' % rel_error\n\t\t\t\ts5 = '(tol %.2e)' % rtol\n\t\t\t\ts6 = ' <<<'\n\t\t\t\ttext0 = get_text(s0, 'red', 1)\n\t\t\t\ttext1 = get_text(s1, 'red')\n\t\t\t\ttext2 = get_text(s2, 'red', 1)\n\t\t\t\ttext3 = get_text(s3, 'red')\n\t\t\t\ttext4 = get_text(s4, 'red', 1)\n\t\t\t\ttext5 = get_text(s5, 'red')\n\t\t\t\ttext6 = get_text(s6, 'red', 1)\n\t\t\t\tprint(text0 + text1 + text2 + text3 + text4 + text5 + text6)\n\n\t\t\t# update error stuff and increment iteration counter :\n\t\t\tabs_error = abs_error_n\n\t\t\tU_prev = self.get_unknown().copy(True)\n\t\t\tcounter += 1\n\n\t\t\t# update the model variable :\n\t\t\tself.update_model_var(self.get_unknown(), annotate=annotate)\n\n\t\t\t# update the temperature and water content for other physics :\n\t\t\tself.partition_energy(annotate=annotate)\n\n\t\t# convert back to transient if necessary :\n\t\tif transient:\n\t\t\tenergy.make_transient(time_step = model.time_step)\n\n\tdef solve(self, annotate=False):\n\t\t\"\"\"\n\t\tSolve the energy equations, saving energy to ``model.theta``, temperature\n\t\tto ``model.T``, and water content to ``model.W``.\n\t\t\"\"\"\n\t\tmodel = self.model\n\n\t\t# update the surface climate if desired :\n\t\tif self.solve_params['use_surface_climate']: self.solve_surface_climate()\n\n\t\t# solve as defined in ``physics.Physics.solve()`` :\n\t\tsuper(Energy, self).solve(annotate)\n\n\t\t# update the temperature and water content for other physics :\n\t\tself.partition_energy(annotate=False)\n\n\tdef update_model_var(self, u, annotate=False):\n\t\t\"\"\"\n\t\tUpdate the energy function ``self.model.theta`` to those given by ``u``.\n\t\t\"\"\"\n\t\tself.ass_theta.assign(self.model.theta, u, annotate=annotate)\n\t\tprint_min_max(self.model.theta, 'theta')\n\n\n\n\n\n\nclass EnergyHybrid(Energy):\n\t\"\"\"\n\tNew 2D hybrid model.\n\n\tOriginal author: Doug Brinkerhoff: https://dbrinkerhoff.org/\n\t\"\"\"\n\t# TODO: `energy_flux_mode` and `stabilization_method` makes no sense here.\n\tdef initialize(self, model, momentum,\n\t solve_params = None,\n\t transient = False,\n\t use_lat_bc = False,\n\t energy_flux_mode = 'B_ring',\n\t stabilization_method = 'GLS'):\n\t\t\"\"\"\n\t\tSet up energy equation residual.\n\t\t\"\"\"\n\t\ts = \"::: INITIALIZING HYBRID ENERGY PHYSICS :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tif type(model) != D2Model:\n\t\t\ts = \">>> EnergyHybrid REQUIRES A 'D2Model' INSTANCE, NOT %s <<<\"\n\t\t\tprint_text(s % type(model) , 'red', 1)\n\t\t\tsys.exit(1)\n\n\t\t# save the solver parameters :\n\t\tself.solve_params = solve_params\n\n\t\tself.transient = transient\n\n\t\t# CONSTANTS\n\t\tyear = model.spy\n\t\tg = model.g\n\t\tn = model.n\n\n\t\tk = model.k_i\n\t\trho = model.rho_i\n\t\tCp = model.c_i\n\t\tkappa = year*k/(rho*Cp)\n\n\t\tq_geo = model.q_geo\n\t\tS = model.S\n\t\tB = model.B\n\t\tbeta = model.beta\n\t\tT_s = model.T_surface\n\t\tT_w = model.T_w\n\t\tH = model.H\n\t\tH0 = model.H0\n\t\tT_ = model.T_\n\t\tT0_ = model.T0_\n\t\tdeltax = model.deltax\n\t\tsigmas = model.sigmas\n\t\teps_reg = model.eps_reg\n\t\th = model.h\n\t\tdt = model.time_step\n\t\tN_T = model.N_T\n\n\t\tBc = 3.61e-13*year\n\t\tBw = 1.73e3*year # model.a0 ice hardness\n\t\tQc = 6e4\n\t\tQw = model.Q0 # ice act. energy\n\t\tRc = model.R # gas constant\n\t\tgamma = model.gamma # pressure melting point depth dependence\n\n\t\t# get velocity components :\n\t\t# ANSATZ\n\t\tcoef = [lambda s:1.0, lambda s:1./4.*(5*s**4 - 1.0)]\n\t\tdcoef = [lambda s:0.0, lambda s:5*s**3]\n\n\t\tU = momentum.U\n\t\tu_ = [U[0], U[2]]\n\t\tv_ = [U[1], U[3]]\n\n\t\tu = VerticalBasis(u_, coef, dcoef)\n\t\tv = VerticalBasis(v_, coef, dcoef)\n\n\t\t# FUNCTION SPACES\n\t\tQ = model.Q\n\t\tZ = model.Z\n\n\t\t# ENERGY BALANCE\n\t\tPsi = TestFunction(Z)\n\t\tdT = TrialFunction(Z)\n\n\t\tT = VerticalFDBasis(T_, deltax, coef, sigmas)\n\t\tT0 = VerticalFDBasis(T0_, deltax, coef, sigmas)\n\n\t\t# METRICS FOR COORDINATE TRANSFORM\n\t\tdef dsdx(s):\n\t\t\treturn 1./H*(S.dx(0) - s*H.dx(0))\n\n\t\tdef dsdy(s):\n\t\t\treturn 1./H*(S.dx(1) - s*H.dx(1))\n\n\t\tdef dsdz(s):\n\t\t\treturn -1./H\n\n\t\tdef epsilon_dot(s):\n\t\t\treturn ( + (u.dx(s,0) + u.ds(s)*dsdx(s))**2 \\\n\t\t\t + (v.dx(s,1) + v.ds(s)*dsdy(s))**2 \\\n\t\t\t + (u.dx(s,0) + u.ds(s)*dsdx(s))*(v.dx(s,1) + v.ds(s)*dsdy(s)) \\\n\t\t\t + 0.25*((u.ds(s)*dsdz(s))**2 + (v.ds(s)*dsdz(s))**2 \\\n\t\t\t + (+ (u.dx(s,1) + u.ds(s)*dsdy(s)) \\\n\t\t\t + (v.dx(s,0) + v.ds(s)*dsdx(s)))**2) \\\n\t\t\t + eps_reg)\n\n\t\tdef A_v(T):\n\t\t\treturn conditional(le(T,263.15),Bc*exp(-Qc/(Rc*T)),Bw*exp(-Qw/(Rc*T)))\n\n\t\tdef eta_v(s):\n\t\t\treturn A_v(T0.eval(s))**(-1./n)/2.*epsilon_dot(s)**((1.-n)/(2*n))\n\n\t\tdef w(s):\n\t\t\tw_0 = (U[0].dx(0) + U[1].dx(1))*(s-1.)\n\t\t\tw_2 = + (U[2].dx(0) + U[3].dx(1))*(s**(n+2) - s)/(n+1) \\\n\t\t\t + (n+2)/H*U[2]*(1./(n+1)*(s**(n+1) - 1.)*S.dx(0) \\\n\t\t\t - 1./(n+1)*(s**(n+2) - 1.)*H.dx(0)) \\\n\t\t\t + (n+2)/H*U[3]*(+ 1./(n+1)*(s**(n+1) - 1.)*S.dx(1) \\\n\t\t\t - 1./(n+1)*(s**(n+2) - 1.)*H.dx(1))\n\t\t\treturn (u(1)*B.dx(0) + v(1)*B.dx(1)) - 1./dsdz(s)*(w_0 + w_2)\n\n\t\tR_T = 0\n\n\t\tfor i in range(N_T):\n\t\t\t# SIGMA COORDINATE\n\t\t\ts = i/(N_T-1.0)\n\n\t\t\t# EFFECTIVE VERTICAL VELOCITY\n\t\t\tw_eff = u(s)*dsdx(s) + v(s)*dsdy(s) + w(s)*dsdz(s)\n\n\t\t\tif transient:\n\t\t\t\tw_eff += 1.0/H*(1.0 - s)*(H - H0)/dt\n\n\t\t\t# STRAIN HEAT\n\t\t\t#Phi_strain = (2*n)/(n+1)*2*eta_v(s)*epsilon_dot(s)\n\t\t\tPhi_strain = 4*eta_v(s)*epsilon_dot(s)\n\n\t\t\t# STABILIZATION SCHEME\n\t\t\t#Umag = sqrt(u(s)**2 + v(s)**2 + 1e-3)\n\t\t\t#tau = h/(2*Umag)\n\t\t\t#Psihat = Psi[i] + tau*(u(s)*Psi[i].dx(0) + v(s)*Psi[i].dx(1))\n\t\t\tUnorm = sqrt(u(s)**2 + v(s)**2 + DOLFIN_EPS)\n\t\t\tPe = Unorm*h/(2*kappa)\n\t\t\ttau = 1/tanh(Pe) - 1/Pe\n\t\t\tPsihat = Psi[i] + h*tau/(2*Unorm) * (+ u(s)*Psi[i].dx(0) \\\n\t\t\t + v(s)*Psi[i].dx(1) )\n\n\t\t\t# SURFACE BOUNDARY\n\t\t\tif i==0:\n\t\t\t\tR_T += Psi[i]*(T(i) - T_s)*dx\n\t\t\t# BASAL BOUNDARY\n\t\t\telif i==(N_T-1):\n\t\t\t\tR_T += (u(s)*T.dx(i,0) + v(s)*T.dx(i,1))*Psihat*dx\n\t\t\t\tR_T += -Phi_strain/(rho*Cp)*Psi[i]*dx\n\t\t\t\tR_T += -w_eff*q_geo/(rho*Cp*kappa*dsdz(s))*Psi[i]*dx\n\t\t\t\tf = (q_geo + beta*(u(s)**2 + v(s)**2))/(rho*Cp*kappa*dsdz(s))\n\t\t\t\tR_T += -2.*kappa*dsdz(s)**2*(+ (T(N_T-2) - T(N_T-1)) / deltax**2 \\\n\t\t\t\t - f/deltax)*Psi[i]*dx\n\t\t\t# INTERIOR\n\t\t\telse:\n\t\t\t\tR_T += -kappa*dsdz(s)**2.*T.d2s(i)*Psi[i]*dx\n\t\t\t\tR_T += w_eff*T.ds(i)*Psi[i]*dx\n\t\t\t\tR_T += (u(s)*T.dx(i,0) + v(s)*T.dx(i,1))*Psihat*dx\n\t\t\t\tR_T += -Phi_strain/(rho*Cp)*Psi[i]*dx\n\n\t\t\tif transient:\n\t\t\t\tdTdt = (T(i) - T0(i))/dt\n\t\t\t\tR_T += dTdt*Psi[i]*dx\n\n\t\t# PRETEND THIS IS LINEAR (A GOOD APPROXIMATION IN THE TRANSIENT CASE)\n\t\tself.R_T = replace(R_T, {T_:dT})\n\n\t\t# pressure melting point calculation, do not annotate for initial calc :\n\t\tself.Tm = as_vector([T_w - sigma*gamma*rho*g*H for sigma in sigmas])\n\t\tself.calc_T_melt(annotate=False)\n\n\tdef get_solve_params(self):\n\t\t\"\"\"\n\t\tReturns the solve parameters.\n\t\t\"\"\"\n\t\treturn self.solve_params\n\n\tdef default_ffc_options(self):\n\t\t\"\"\"\n\t\tReturns a set of default ffc options that yield good performance\n\t\t\"\"\"\n\t\t#ffc_options = {\"optimize\" : True,\n\t\t# \"eliminate_zeros\" : True,\n\t\t# \"precompute_basis_const\" : True,\n\t\t# \"precompute_ip_const\" : True}\n\t\tffc_options = {\"optimize\" : True}\n\t\treturn ffc_options\n\n\tdef default_solve_params(self):\n\t\t\"\"\"\n\t\tReturns a set of default solver parameters that yield good performance\n\t\t\"\"\"\n\t\tm_params = {'solver' : {'linear_solver': 'mumps'},\n\t\t 'ffc_params' : self.default_ffc_options()}\n\t\treturn m_params\n\n\tdef solve(self, annotate=False):\n\t\t\"\"\"\n\t\tSolves for hybrid energy.\n\t\t\"\"\"\n\t\ts = \"::: solving 'EnergyHybrid' for temperature :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\n\t\t# SOLVE TEMPERATURE\n\t\tsolve(lhs(self.R_T) == rhs(self.R_T), model.T_,\n\t\t solver_parameters=self.solve_params['solver'],\n\t\t form_compiler_parameters=self.solve_params['ffc_params'],\n\t\t annotate=annotate)\n\t\tprint_min_max(model.T_, 'T_')\n\n\t\tif self.transient:\n\t\t\tmodel.T0_.assign(model.T_)\n\n\t\t# correct for pressure melting point :\n\t\tT_v = model.T_.vector().get_local()\n\t\tT_melt_v = model.Tm.vector().get_local()\n\t\tT_v[T_v > T_melt_v] = T_melt_v[T_v > T_melt_v]\n\t\tmodel.assign_variable(model.T_, T_v)\n\n\t\tout_T = model.T_.split(True) # deepcopy avoids projections\n\n\t\tmodel.assign_variable(model.Ts, out_T[0])\n\t\tmodel.assign_variable(model.Tb, out_T[-1])\n\n\t\t# update the melting temperature too :\n\t\tself.calc_T_melt(annotate=annotate)\n\n\tdef calc_T_melt(self, annotate=False):\n\t\t\"\"\"\n\t\tCalculates pressure-melting point in model.T_melt.\n\t\t\"\"\"\n\t\ts = \"::: calculating pressure-melting temperature :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\n\t\tT_melt = project(self.Tm, solver_type='iterative', annotate=annotate)\n\n\t\tTb_m = T_melt.split(True)[-1] # deepcopy avoids projections\n\t\tmodel.assign_variable(model.T_melt, Tb_m)\n\t\tmodel.assign_variable(model.Tm, T_melt)\n\n\n\n\n\n\nclass EnergyFirn(Energy):\n\t\"\"\"\n\t\"\"\"\n\t# TODO: energy flux mode makes no sense here.\n\tdef initialize(self, model, momentum,\n\t solve_params = None,\n\t transient = False,\n\t use_lat_bc = False,\n\t energy_flux_mode = 'B_ring',\n\t reset = False):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\ts = \"::: INITIALIZING FIRN ENERGY PHYSICS :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tif type(model) != D1Model:\n\t\t\ts = \">>> FirnEnergy REQUIRES A 'D1Model' INSTANCE, NOT %s <<<\"\n\t\t\tprint_text(s % type(model) , 'red', 1)\n\t\t\tsys.exit(1)\n\n\t\t# save the solver parameters :\n\t\tself.solve_params = solve_params\n\n\t\tmesh = model.mesh\n\t\tQ = model.Q\n\n\t\tspy = model.spy\n\t\ttheta = model.theta # enthalpy\n\t\ttheta0 = model.theta0 # previous enthalpy\n\t\tT = model.T # temperature\n\t\trhof = model.rho # density of firn\n\t\tsigma = model.sigma # overburden stress\n\t\tr = model.r # grain size\n\t\tw = model.w # velocity\n\t\tm = model.m # mesh velocity\n\t\tdt = model.time_step # timestep\n\t\trho_i = model.rho_i # density of ice\n\t\trho_w = model.rho_w # density of water\n\t\tc_i = model.c_i # heat capacity of ice\n\t\tc_w = model.c_w # heat capacity of water\n\t\tk_w = model.k_w # thermal conductivity of water\n\t\tT = model.T\n\t\tT_w = model.T_w\n\t\tL_f = model.L_f\n\t\tthetasp = model.thetasp\n\t\tp = model.p\n\t\tetaw = model.etaw\n\t\trho_w = model.rho_w\n\t\t#w = w - m\n\t\tz = model.x[0]\n\t\tg = model.g\n\t\tS = model.S\n\t\th = model.h\n\t\t#W = model.W\n\t\tdx = model.dx\n\n\t\txi = TestFunction(Q)\n\t\tdtheta = TrialFunction(Q)\n\n\t\t# thermal conductivity parameter :\n\t\t#k_i = model.k_i*(rho / rho_i)**2\n\t\tk_i = 9.828 * exp(-0.0057*T)\n\n\t\t# water content :\n\t\tWm = conditional(lt(theta, c_i*T_w), 0.0, (theta - c_i*T_w)/L_f)\n\n\t\t# bulk properties :\n\t\tkb = k_w * Wm + (1-Wm)*k_i\n\t\tcb = c_w * Wm + (1-Wm)*c_i\n\t\trhob = rho_w * Wm + (1-Wm)*rhof\n\n\t\t# initialize energy :\n\t\tT_v = T.vector().get_local()\n\t\tmodel.assign_variable(theta, c_i(0)*T_v)\n\t\tmodel.assign_variable(theta0, c_i(0)*T_v)\n\n\t\t# boundary condition on the surface :\n\t\tself.thetaBc = DirichletBC(Q, model.theta_surface, model.surface)\n\n\t\t# Darcy flux :\n\t\tk = 0.077 * r**2 * exp(-7.8*rhob/rho_w) # intrinsic permeability\n\t\tphi = 1 - rhob/rho_i # porosity\n\t\tWmi = 0.0057 / (1 - phi) + 0.017 # irriducible water content\n\t\tSe = (Wm - Wmi) / (1 - Wmi) # effective saturation\n\t\tK = k * rho_w * g / etaw # saturated hydraulic cond.\n\t\tkrw = Se**3.0 # relative permeability\n\t\tpsi_m = p / (rho_w * g) # matric potential head\n\t\tpsi_g = z # gravitational potential head\n\t\tpsi = psi_m + psi_g # total water potential head\n\t\tu = - K * krw * psi.dx(0) # darcy water velocity\n\n\t\t# skewed test function in areas with high velocity :\n\t\tPe = (u+w)*h/(2*kb/(rhob*cb))\n\t\ttau = 1/tanh(Pe) - 1/Pe\n\t\txihat = xi + h*tau/2 * xi.dx(0)\n\n\t\t# enthalpy residual :\n\t\teta = 1.0\n\t\ttheta_mid = eta*theta + (1 - eta)*theta0\n\t\tdelta = + kb/(rhob*cb) * inner(theta_mid.dx(0), xi.dx(0)) * dx \\\n\t\t + (theta - theta0)/dt * xi * dx \\\n\t\t + (w + u) * theta_mid.dx(0) * xihat * dx \\\n\t\t - sigma * w.dx(0) / rhob * xi * dx\n\n\t\t# equation to be minimzed :\n\t\tself.J = derivative(delta, theta, dtheta) # jacobian\n\n\t\tself.delta = delta\n\t\tself.u = u\n\t\tself.Wm = Wm\n\t\tself.Wmi = Wmi\n\n\tdef get_solve_params(self):\n\t\t\"\"\"\n\t\tReturns the solve parameters.\n\t\t\"\"\"\n\t\treturn self.solve_params\n\n\tdef default_solve_params(self):\n\t\t\"\"\"\n\t\tReturns a set of default solver parameters that yield good performance\n\t\t\"\"\"\n\t\tparams = {'newton_solver' : {'relaxation_parameter' : 1.0,\n\t\t 'maximum_iterations' : 25,\n\t\t 'error_on_nonconvergence' : False,\n\t\t 'relative_tolerance' : 1e-10,\n\t\t 'absolute_tolerance' : 1e-10}}\n\t\tm_params = {'solver' : params}\n\t\treturn m_params\n\n\tdef solve(self, annotate=False):\n\t\t\"\"\"\n\t\t\"\"\"\n\t\ts = \"::: solving FirnEnergy :::\"\n\t\tprint_text(s, cls=self)\n\n\t\tmodel = self.model\n\n\t\t# newton's iterative method :\n\t\tsolve(self.delta == 0, model.theta, self.thetaBc, J=self.J,\n\t\t solver_parameters=self.solve_params['solver'],\n\t\t annotate=annotate)\n\n\t\tmodel.assign_variable(model.W0, model.W)\n\t\tmodel.assign_variable(model.W, project(self.Wm, annotate=False))\n\n\t\tT_w = model.T_w(0)\n\t\trho_w = model.rho_w(0)\n\t\trho_i = model.rho_i(0)\n\t\tg = model.g(0)\n\t\tc_i = model.c_i(0)\n\t\tthetasp = c_i * T_w\n\t\tL_f = model.L_f(0)\n\n\t\t# update coefficients used by enthalpy :\n\t\tthetap = model.theta.vector().get_local()\n\t\tthetahigh = np.where(thetap > thetasp)[0]\n\t\tthetalow = np.where(thetap < thetasp)[0]\n\n\t\t# calculate T :\n\t\tTp = thetap / c_i\n\t\tTp[thetahigh] = T_w\n\t\tmodel.assign_variable(model.T, Tp)\n\n\t\t# calculate dW :\n\t\tWp = model.W.vector().get_local()\n\t\tWp0 = model.W0.vector().get_local()\n\t\tdW = Wp - Wp0 # water content change\n\t\tmodel.assign_variable(model.dW, dW)\n\n\t\t# adjust the snow density if water is refrozen :\n\t\trho_v = model.rho.vector().get_local()\n\t\tfreeze = dW < 0\n\t\tmelt = dW > 0\n\t\trho_v[freeze] = rho_v[freeze] - dW[freeze] * model.rho_i(0)\n\t\tmodel.assign_variable(model.rho, rho_v)\n\n\t\t## calculate W :\n\t\t#model.assign_variable(model.W0, model.W)\n\t\t#Wp = model.W.vector().get_local()\n\t\t#Wp[thetahigh] = (thetap[thetahigh] - c_i*T_w) / L_f\n\t\t#Wp[thetalow] = 0.0\n\t\t#Wp0 = model.W0.vector().get_local()\n\t\t#dW = Wp - Wp0 # water content change\n\t\t#model.assign_variable(model.W, Wp)\n\t\t#model.assign_variable(model.dW, dW)\n\n\t\tprint_min_max(model.T, 'T')\n\t\tprint_min_max(model.theta, 'theta')\n\t\tprint_min_max(model.W, 'W')\n\n\t\tp = model.vert_integrate(rho_w * g * model.W)\n\t\tphi = 1 - model.rho/rho_i # porosity\n\t\tWmi = 0.0057 / (1 - phi) + 0.017 # irr. water content\n\t\tmodel.assign_variable(model.p, p)\n\t\tmodel.assign_variable(model.u, project(self.u, annotate=False))\n\t\tmodel.assign_variable(model.Smi, project(Wmi, annotate=False))\n\t\tprint_min_max(model.p, 'p')\n\t\tprint_min_max(model.u, 'u')\n\n\n\n","repo_name":"pf4d/cslvr","sub_path":"cslvr/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":53890,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"}
+{"seq_id":"25117650141","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 14 13:02:03 2022\n\n@author: pywrk\n\"\"\"\nimport sys\nimport h5py\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef applyLUT(count, lut):\n count_flt = count.flatten();\n output = np.zeros_like(count_flt, dtype=lut.dtype)\n for indx in range(count_flt.shape[0]): \n output[indx] = lut[count_flt[indx]]\n output = output.reshape(count.shape)\n return output;\n\ndef scaleDS(ds, ao, sf, fv):\n ds_flt = ds.flatten();\n output = np.zeros_like(ds_flt, dtype=sf.dtype)\n output = ds_flt*sf+ao\n output[ds_flt==fv]=-999.0\n\n output = output.reshape(ds.shape)\n return output\n \ndef dumpData(filename, out_dir):\n jobid = os.path.splitext(os.path.basename(filename))[0]\n\n out_path = out_dir + os.sep + jobid\n if not os.path.exists(out_path):\n os.mkdir(out_path)\n \n fid = h5py.File(filename, 'r')\n band_names=[\"IMG_TIR1\", \"IMG_TIR2\", \"IMG_MIR\", \"IMG_WV\", \"IMG_VIS\", \"IMG_SWIR\"]\n cal_ds_list = [\"IMG_TIR1_TEMP\", \"IMG_WV_TEMP\", \"IMG_TIR2_TEMP\", \"IMG_MIR_TEMP\", \"IMG_VIS_ALBEDO\"]\n \n for bname in band_names:\n count_ds = fid[bname][:];\n print(\"writing \" + bname)\n count_ds.tofile(out_path + os.sep + bname + \".bin\")\n for dsname in cal_ds_list:\n if dsname.startswith(bname):\n lut = fid[dsname][:]\n cal_ds = applyLUT(count_ds, lut) \n# plt.figure()\n# plt.imshow(cal_ds.squeeze())\n print(\"writing \" + dsname)\n cal_ds.tofile(out_path + os.sep + dsname +\".bin\")\n geo_ds_list=[\"Latitude\", \"Longitude\", \"Latitude_WV\", \"Longitude_WV\", \"Latitude_VIS\", \"Longitude_VIS\"]\n for dsname in geo_ds_list:\n ds = fid[dsname]\n fv = ds.attrs['_FillValue'][0]\n sf = ds.attrs['scale_factor'][0]\n ao = ds.attrs['add_offset'][0]\n scaled_ds = scaleDS(ds[:], ao, sf, fv)\n print(\"writing \" + dsname)\n scaled_ds.tofile(out_path + os.sep + dsname +\".bin\")\n \n fid.close()\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print(\"Usage: \" + sys.argv[0] + \"
', '').replace('', '').replace(' ', '').replace('_', ' '))\n","repo_name":"jshota/cs539-group_assignments","sub_path":"hw6/hw6-data/restore_spaces.py","file_name":"restore_spaces.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"30936499573","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models\nfrom nets.vgg import *\nfrom net_utils import *\nfrom losses import *\n\nMODE_LIST = ['s2s', 'x2x', 'xs2s', 'xs2x']\n\nmean = torch.FloatTensor([0.485, 0.456, 0.406]).view([1,3,1,1])\nstd = torch.FloatTensor([0.229, 0.224, 0.225]).view([1,3,1,1])\n\n\nclass Lateral(nn.Module):\n\tdef __init__(self, in_channel, kernel_size, out_channel=None, shortcut_conv=False, prelu=True):\n\t\tsuper(Lateral, self).__init__()\n\t\tif out_channel is None:\n\t\t\tout_channel = in_channel\n\t\tself.in_channel = in_channel\n\t\tself.out_channel = out_channel\n\t\tself.kernel_size = kernel_size\n\t\tif prelu:\n\t\t\tself.net = nn.Sequential(\n\t\t\t\tnn.PReLU(),\n\t\t\t\tnn.Conv2d(in_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2),\n\t\t\t\tnn.PReLU(),\n\t\t\t\tnn.Conv2d(out_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2)\n\t\t\t\t)\t\t\n\t\telse:\n\t\t\tself.net = nn.Sequential(\n\t\t\t\tnn.Conv2d(in_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2),\n\t\t\t\tnn.PReLU(),\n\t\t\t\tnn.Conv2d(out_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2),\n\t\t\t\tnn.PReLU(),\n\t\t\t\tnn.Conv2d(out_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2)\n\t\t\t\t)\t\n\t\tif (self.out_channel != self.in_channel) and shortcut_conv:\n\t\t\tself.conv = nn.Conv2d(in_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2)\n\t\t# normal_init_net_conv(self.net)\n\t\tself.shortcut_conv = shortcut_conv\n\t\t\t\n\tdef forward(self, input):\n\t\tassert input.size(1) == self.in_channel, [ input.size(1), self.in_channel ]\n\t\tif self.shortcut_conv:\n\t\t\tif self.out_channel != self.in_channel:\n\t\t\t\treturn self.net(input) + self.conv(input)\n\t\t\telse:\n\t\t\t\treturn self.net(input) + input\n\t\telse:\n\t\t\treturn self.net(input) \n\nclass Upsample(nn.Module):\n\tdef __init__(self, in_channel, out_channel, kernel_size=3):\n\t\tsuper(Upsample, self).__init__()\n\t\tself.in_channel = in_channel\n\t\tself.out_channel = out_channel\n\t\tself.kernel_size = kernel_size\n\t\tself.net = nn.Sequential(\n\t\t\tnn.PReLU(),\n\t\t\tnn.Conv2d(in_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2),\n\t\t\tnn.PReLU(),\n\t\t\tnn.Conv2d(out_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2)\n\t\t\t)\n\t\t# normal_init_net_conv(self.net)\n\n\tdef forward(self, input):\n\t\tassert input.size(1) == self.in_channel, [ input.size(1), self.in_channel ]\n\t\treturn self.net(F.interpolate(input, scale_factor=2, mode='bilinear', align_corners=True))\n\n\nclass Downsample(nn.Module):\n\tdef __init__(self, in_channel, out_channel, kernel_size=3):\n\t\tsuper(Downsample, self).__init__()\n\t\tself.in_channel = in_channel\n\t\tself.out_channel = out_channel\n\t\tself.kernel_size = kernel_size\n\t\tself.net = nn.Sequential(\n\t\t\tnn.PReLU(),\n\t\t\tnn.Conv2d(in_channel, out_channel, kernel_size, stride=2, padding=kernel_size//2),\n\t\t\tnn.PReLU(),\n\t\t\tnn.Conv2d(out_channel, out_channel, kernel_size, stride=1, padding=kernel_size//2)\n\t\t\t)\n\t\t# normal_init_net_conv(self.net)\n\n\tdef forward(self, input):\n\t\tassert input.size(1) == self.in_channel, [ input.size(1), self.in_channel ]\n\t\treturn self.net(input)\n\n\nclass Downflow(nn.Module):\n\tdef __init__(self, in_channels, kernel_size=3):\n\t\tsuper(Downflow, self).__init__()\n\t\tself.in_channels = in_channels\n\t\tself.row0 = Lateral(in_channels[0], kernel_size, shortcut_conv=False)\n\t\tself.row1 = Lateral(in_channels[1], kernel_size, shortcut_conv=False)\n\t\tself.row2 = Lateral(in_channels[2], kernel_size, shortcut_conv=False)\n\t\tself.down01 = Downsample(in_channels[0], in_channels[1])\n\t\tself.down12 = Downsample(in_channels[1], in_channels[2])\n\n\tdef forward(self, row0_input, row1_input, row2_input):\n\t\tassert row0_input.size(1) == self.in_channels[0], [ row0_input.size(1), self.in_channels[0] ]\n\t\tassert row1_input.size(1) == self.in_channels[1], [ row1_input.size(1), self.in_channels[1] ]\n\t\tassert row2_input.size(1) == self.in_channels[2], [ row2_input.size(1), self.in_channels[2] ]\n\n\t\trow0_output = self.row0(row0_input)\n\t\trow1_output = self.row1(row1_input)\n\t\trow2_output = self.row2(row2_input)\n\n\t\trow1_output = self.down01(row0_output) + row1_output\n\t\trow2_output = self.down12(row1_output) + row2_output\n\n\t\treturn row0_output, row1_output, row2_output\n\n\nclass Upflow(nn.Module):\n\tdef __init__(self, in_channels, kernel_size=3):\n\t\tsuper(Upflow, self).__init__()\n\t\tself.in_channels = in_channels\n\t\tself.row0 = Lateral(in_channels[0], kernel_size, shortcut_conv=False)\n\t\tself.row1 = Lateral(in_channels[1], kernel_size, shortcut_conv=False)\n\t\tself.row2 = Lateral(in_channels[2], kernel_size, shortcut_conv=False)\n\t\tself.up10 = Upsample(in_channels[1], in_channels[0])\n\t\tself.up21 = Upsample(in_channels[2], in_channels[1])\n\n\tdef forward(self, row0_input, row1_input, row2_input):\n\t\tassert row0_input.size(1) == self.in_channels[0], [ row0_input.size(1), self.in_channels[0] ]\n\t\tassert row1_input.size(1) == self.in_channels[1], [ row1_input.size(1), self.in_channels[1] ]\n\t\tassert row2_input.size(1) == self.in_channels[2], [ row2_input.size(1), self.in_channels[2] ]\n\n\t\trow0_output = self.row0(row0_input)\n\t\trow1_output = self.row1(row1_input)\n\t\trow2_output = self.row2(row2_input)\n\n\t\trow1_output = self.up21(row2_output) + row1_output\n\t\trow0_output = self.up10(row1_output) + row0_output\n\t\t\n\t\treturn row0_output, row1_output, row2_output\n\n\nclass GridNet(nn.Module):\n\tdef __init__(self, n_channels, n_classes, mode='s2s', split_tail=False, seg_id=False):\n\t\tsuper(GridNet, self).__init__()\n\t\tself.mode = mode\n\t\tself.CELoss = nn.CrossEntropyLoss()\n\t\tself.SSIMLoss = SSIM()\n\t\tself.seg_act = nn.Softmax(dim=1)\n\t\tself.split_tail = split_tail\n\t\tself.seg_id = seg_id\n\t\tif mode == 'x2x':\n\t\t\tself.in_channel = 3*2\n\t\t\tself.out_channel = 3\n\t\telif mode == 'xs2x':\n\t\t\tif not seg_id:\n\t\t\t\tself.in_channel = (3+n_classes)*2\n\t\t\telse:\n\t\t\t\tself.in_channel = (3+1)*2\n\t\t\tself.out_channel = 3\n\t\telif mode == 's2s':\n\t\t\tif not seg_id:\n\t\t\t\tself.in_channel = n_classes*2\n\t\t\t\tself.out_channel = n_classes\n\t\t\telse:\n\t\t\t\tself.in_channel = 2\n\t\t\t\tself.out_channel = n_classes\t\t\t\t\n\t\telif mode == 'xs2s':\n\t\t\tif not seg_id:\n\t\t\t\tself.in_channel = (3+n_classes)*2\n\t\t\t\tself.out_channel = n_classes\n\t\t\telse:\n\t\t\t\tself.in_channel = (3+1)*2\n\t\t\t\tself.out_channel = n_classes\n\t\telif mode == 'xs2xs':\n\t\t\tif not split_tail:\n\t\t\t\tif not seg_id:\n\t\t\t\t\tself.in_channel = (3+n_classes)*2\n\t\t\t\t\tself.out_channel = (3+n_classes)\n\t\t\t\telse:\n\t\t\t\t\tself.in_channel = (3+1)*2\n\t\t\t\t\tself.out_channel = 3+n_classes\n\t\t\telse:\n\t\t\t\tif not seg_id:\n\t\t\t\t\tself.in_channel = (3+n_classes)*2\n\t\t\t\t\tself.out_channel = 3\n\t\t\t\t\tself.out_channel_seg = n_classes\n\t\t\t\telse:\n\t\t\t\t\tself.in_channel = (3+1)*2\n\t\t\t\t\tself.out_channel = 3\n\t\t\t\t\tself.out_channel_seg = n_classes\n\t\telif mode == 'wing':\n\t\t\tif not seg_id:\n\t\t\t\tself.in_channel = (3+n_classes)*2 + 3\n\t\t\t\tself.out_channel = n_classes\n\t\t\telse:\n\t\t\t\tself.in_channel = (3 + 1)*2 + 3\n\t\t\t\tself.out_channel = n_classes\n\n\t\telse:\n\t\t\traise Exception(\"mode doesnt exist !\")\n\n\t\tself.n_channels = n_channels\n\t\tself.head = Lateral(self.in_channel, 3, n_channels[0], shortcut_conv=True, prelu=False)\n\n\t\t# nn.Sequential(\n\t\t# \tnn.PReLU(),\n\t\t# \tnn.Conv2d(self.in_channel, n_channels[0], 3, stride=1, padding=1),\n\t\t# \tnn.PReLU(),\n\t\t# \tnn.Conv2d(n_channels[0], n_channels[0], 3, stride=1, padding=1)\n\t\t# \t)\n\n\t\tself.neck_down01 = Downsample(n_channels[0], n_channels[1], 3)\n\t\tself.neck_down12 = Downsample(n_channels[1], n_channels[2], 3)\n\n\t\tself.body_down0 = Downflow(n_channels, 3)\n\t\tself.body_down1 = Downflow(n_channels, 3)\n\n\t\tself.body_up0 = Upflow(n_channels, 3)\n\t\tself.body_up1 = Upflow(n_channels, 3)\n\t\tself.body_up2 = Upflow(n_channels, 3)\n\n\t\tself.tail = Lateral(n_channels[0], 3, self.out_channel, shortcut_conv=False, prelu=True)\n\t\tif self.split_tail:\n\t\t\tself.tail_seg = Lateral(n_channels[0], 3, self.out_channel_seg, shortcut_conv=False, prelu=True)\n\n\t\tif self.mode[-1] == 'x' or self.mode == 'xs2xs':\n\t\t\tvgg19 = torchvision.models.vgg19(pretrained=True)\n\t\t\tself.vgg_net = my_vgg(vgg19)\n\t\t\tfor param in self.vgg_net.parameters():\n\t\t\t\tparam.requires_grad = False\n\n\n\tdef GDLLoss(self, input, gt):\n\t\tbs, c, h, w = input.size()\n\n\t\tw_gdl = torch.abs(input[:,:,:,1:] - input[:,:,:,:w-1])\n\t\th_gdl = torch.abs(input[:,:,1:,:] - input[:,:,:h-1,:])\n\n\t\tgt_w_gdl = torch.abs(gt[:,:,:,1:] - gt[:,:,:,:w-1])\n\t\tgt_h_gdl = torch.abs(gt[:,:,1:,:] - gt[:,:,:h-1,:])\n\t\t\n\t\tloss = torch.mean(torch.abs(w_gdl-gt_w_gdl)) + torch.mean(torch.abs(h_gdl-gt_h_gdl))\n\t\treturn loss\n\n\tdef _normalize(self, x):\n\t\tgpu_id = x.get_device()\n\t\treturn (x - mean.cuda(gpu_id)) / std.cuda(gpu_id)\n\n\tdef VGGLoss(self, pred_feat, true_feat):\n\t\tloss = 0\n\t\tfor i in range(len(pred_feat)):\n\t\t\tloss += (true_feat[i] - pred_feat[i]).abs().mean()\n\t\treturn loss/len(pred_feat)\n\n\tdef L1Loss(self, input, gt):\n\t\ttheta = 0.001\n\t\t# fg_indices = [4,5,6,7,11,12,13,14,15,16,17,18]\n\t\tdiff = (input-gt)**2\n\t\t# diff[:,fg_indices] = 4*diff[:,fg_indices]\n\t\treturn torch.sqrt(diff + theta**2)\n\n\n\tdef forward(self, input, gt=None):\n\t\tassert input.size(1) == self.in_channel, [input.size(), self.in_channel]\n\n\t\t# change to anqi test method\n\t\t# if self.mode=='xs2xs':\n\t\t# \tinput[:,:6] = postprocess_output(input[:,:6])\n\t\t# \tgt[:,:3] = postprocess_output(gt[:,:3])\n\n\t\trow0_out = self.head(input)\n\t\trow1_out = self.neck_down01(row0_out)\n\t\trow2_out = self.neck_down12(row1_out)\n\n\t\trow0_out, row1_out, row2_out = self.body_down0(row0_out, row1_out, row2_out)\n\t\trow0_out, row1_out, row2_out = self.body_down1(row0_out, row1_out, row2_out)\n\t\trow0_out, row1_out, row2_out = self.body_up0(row0_out, row1_out, row2_out)\n\t\trow0_out, row1_out, row2_out = self.body_up1(row0_out, row1_out, row2_out)\n\t\tout, row1_out, row2_out = self.body_up2(row0_out, row1_out, row2_out)\n\n\t\tif not self.split_tail:\n\t\t\tif self.mode =='wing':\n\t\t\t\tout = self.seg_act(self.tail(out))\n\t\t\telif self.mode[-1] != 's':\n\t\t\t\tout = F.tanh(self.tail(out))\n\t\t\t\t# print(\"hhhh\")\n\t\t\telse:\n\t\t\t\tout = self.seg_act(self.tail(out))\n\t\t\t\t# print(torch.nonzero(out).size(0))\n\t\telse:\n\t\t\tassert self.mode=='xs2xs'\n\t\t\tout_seg =self.tail_seg(out)\n\t\t\tout = F.tanh(self.tail(out))\n\n\t\tl1_loss = None\n\t\tgdl_loss = None\n\t\tvgg_loss = None\n\t\tce_loss = None\n\t\tssim_loss = None\n\t\t\t\n\n\t\tif self.training:\n\t\t\t# if self.mode.split('2')[1] in ['x','xs'] or (not self.seg_id ):\n\t\t\tif self.mode[-1] == 'x':\n\t\t\t\tgdl_loss = self.GDLLoss(preprocess_norm(out), preprocess_norm(gt))\n\t\t\t\tl1_loss = self.L1Loss(preprocess_norm(out), preprocess_norm(gt))\n\t\t\t\tssim_loss = self.SSIMLoss(preprocess_norm(out), preprocess_norm(gt)).mean()\n\n\t\t\t\tpredict_feat = self.vgg_net(preprocess_norm(out))\n\t\t\t\ttrue_feat = self.vgg_net(preprocess_norm(gt))\n\t\t\t\tvgg_loss = self.VGGLoss(predict_feat, true_feat)\n\n\t\t\telif self.mode == 'wing' or self.mode.split('2')[1] == 's' :\n\t\t\t\t# gdl_loss = self.GDLLoss(out, gt)\n\t\t\t\t# l1_loss = self.L1Loss(out, gt)\n\t\t\t\tif not self.seg_id:\n\t\t\t\t\tce_loss = self.CELoss(out, torch.argmax(gt, dim=1))\n\t\t\t\telse:\n\t\t\t\t\tce_loss = self.CELoss(out, gt.squeeze(1).long())\n\t\t\t\t\t# gdl_loss = self.GDLLoss(out, gt)\n\t\t\t\t\t# l1_loss = self.L1Loss(out, gt)\n\t\t\t\tvgg_loss = None\n\t\t\telif self.mode == 'xs2xs': ####################### try here\n\t\t\t\t# if self.ce:\n\t\t\t\t# if self.seg_id:\n\t\t\t\t# gdl_loss = self.GDLLoss(out, gt[:,:3])\n\t\t\t\t# l1_loss = self.L1Loss(out, gt[:,:3])\n\t\t\t\t# ssim_loss = 1 - self.SSIMLoss(postprocess_output(out), postprocess_output(gt[:, :3])).mean()\n\t\t\t\tgdl_loss = self.GDLLoss(preprocess_norm(out), preprocess_norm(gt[:,:3]))\n\t\t\t\tl1_loss = self.L1Loss(preprocess_norm(out), preprocess_norm(gt[:,:3]))\n\t\t\t\tssim_loss = self.SSIMLoss(preprocess_norm(out), preprocess_norm(gt[:, :3])).mean()\n\t\t\t\tif not self.seg_id:\n\t\t\t\t\tce_loss = self.CELoss(out_seg, torch.argmax(gt[:, 3:], dim=1))\n\t\t\t\telse:\n\t\t\t\t\tce_loss = self.CELoss(out_seg, gt[:, 3:].squeeze(1).long())\n\t\t\t\t# else:\n\t\t\t\t# \tgdl_loss = self.GDLLoss(out, gt)\n\t\t\t\t# \tl1_loss = self.L1Loss(out, gt)\n\t\t\t\t# else:\n\t\t\t\t# gdl_loss = self.GDLLoss(torch.cat([out, out_seg], dim=1), gt)\n\t\t\t\t# l1_loss = self.L1Loss(torch.cat([out, out_seg], dim=1), gt)\n\t\t\t\tpredict_feat = self.vgg_net(preprocess_norm(out))\n\t\t\t\ttrue_feat = self.vgg_net(preprocess_norm(gt[:, :3]))\n\t\t\t\t\n\t\t\t\tvgg_loss = self.VGGLoss(predict_feat, true_feat)\n\t\t\t# \telse:\n\t\t\t# \t\tvgg_loss = None\n\t\t\t# else:\n\t\t\t# \tvgg_loss = None\n\n\t\t\t# if self.seg_id:\n\t\t\t# \tif self.mode.split('2')[1] == 's':\n\t\t\t# \t\tce_loss = self.celoss(out, gt)\n\t\t\t# \telse: # xs2xs\n\t\t\t# \t\tce_loss = self.celoss(out_seg, gt[:, 3].long())\n\t\t\t# else:\n\t\t\t# \tce_loss = None\n\n\t\tif self.mode == 'xs2xs' and self.split_tail:\n\t\t\tout_seg = self.seg_act(out_seg)\n\t\t\tout = torch.cat([out, out_seg], dim=1)\n\n\t\t\t### todo laplacian pyramid loss for image ###\n\n\t\treturn out, l1_loss, gdl_loss, vgg_loss, ce_loss, ssim_loss\n\n\n\n","repo_name":"lzhangbj/deep_video_interpolation_extrapolation","sub_path":"nets/grid_net.py","file_name":"grid_net.py","file_ext":"py","file_size_in_byte":12550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"7820299227","text":"\nimport pandas as pd\nimport numpy as np\n\n'''分箱坏账率计算'''\ndef binbadrate(df, var, target, grantRateIndicator=0):\n '''\n :param df: 需要计算好坏比率的数据集\n :param var: 需要计算好坏比率的特征\n :param target: 好坏标签\n :param grantRateIndicator: 1返回总体的坏样本率,0不返回\n :return: 每箱的坏样本率,以及总体的坏样本率(当grantRateIndicator==1时)\n '''\n total = df.groupby([var])[target].count()\n total = pd.DataFrame({'total': total})\n bad = df.groupby([var])[target].sum()\n bad = pd.DataFrame({'bad': bad})\n regroup = total.merge(bad, left_index=True, right_index=True, how='left') #数据框左连接操作\n regroup.reset_index(level=0, inplace=True)\n regroup['bad_rate'] = regroup.apply(lambda x: x.bad * 1.0 / x.total, axis=1)\n dicts = dict(zip(regroup[var],regroup['bad_rate']))\n if grantRateIndicator==0:\n return (dicts, regroup)\n N = sum(regroup['total'])\n B = sum(regroup['bad'])\n overallRate = B * 1.0 / N\n return dicts, regroup, overallRate\n\n\n\n'''分箱单调性检验'''\n## determine whether the bad rate is monotone along the sortByVar\ndef monotone(df, sortByVar, target):\n '''\n :param df: the dataset contains the column which should be monotone with the bad rate and bad column\n :param sortByVar: the column which should be monotone with the bad rate\n :param target: the bad column\n :param special_attribute: some attributes should be excluded when checking monotone\n :return:\n '''\n notnull_df = df.loc[~df[sortByVar].isnull()] #排除数据为空的情况\n if len(set(notnull_df[sortByVar])) <= 2:\n return True\n regroup = binbadrate(notnull_df, sortByVar, target)[1] #这里是使用分箱坏账率计算函数\n combined = zip(regroup['total'],regroup['bad'])\n badRate = [x[1]*1.0/x[0] for x in combined]\n\n #数据单调性公式\n badRateMonotone = [(badRate[i]IPL Win Probability
\", unsafe_allow_html=True)\n\ncol1,col2 = st.columns(2)\nwith col1:\n batting_team = st.selectbox('Select Batting Team',sorted(teams))\nwith col2:\n bowling_team = st.selectbox('Select Bowling Team',sorted(teams))\n\nif batting_team == bowling_team :\n st.error('Choose diffrent teams')\n\ncity = st.selectbox('Select city',sorted(city_names))\ntarget = st.number_input('Target')\n\ncol1,col2,col3 = st.columns(3)\nwith col1 :\n score = st.number_input('Score')\nwith col2 :\n wickets = st.number_input('Wickets')\nwith col3 :\n overs = st.number_input('Overs completed ')\n\nif st.button('Predict Probability'):\n runs_left = target - score\n wickets = 10 - wickets\n balls_left = 120 -(overs*6)\n current_run_rate = score/overs\n req_run_rate = (runs_left*6)/balls_left\n\n df = pd.DataFrame({'batting_team':[batting_team],'bowling_team':[bowling_team],'city':[city],'runs_left':[runs_left],'balls_left':[balls_left],'wickets':[wickets],\n 'current_run_rate':[current_run_rate],'req_run_rate':[req_run_rate],'total_runs_x':[target]})\n\n result = pipe.predict_proba(df)\n loss = result[0][0]\n win = result[0][1]\n st.header(batting_team + ' ' + str(round(win*100))+'%')\n st.header(bowling_team + ' '+ str(round(loss*100))+'%')\n\n\n","repo_name":"devrahul9119/Ipl-match-winning-probability","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"24144698720","text":"import sys\nimport socket\ncom = socket.gethostname()\nif com in ('piai-Precision-7920-Tower', 'Normalistui-MacBookPro.local'):\n this_file_name = sys._getframe().f_code.co_filename\n sys.stdin = open(f\"{this_file_name[:-3]}.txt\", \"r\")\n\nT = int(input())\n# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.\nfor test_case in range(1, T + 1):\n\n print(f\"#{test_case}\")\n","repo_name":"Normalist-K/algorithm","sub_path":"study/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"31577050302","text":"from django.http import HttpResponse\nfrom django.conf import settings\nfrom django.views.decorators.http import require_POST\n\nfrom app.models import Athlete\nfrom .utils.getPolyline import getStreamsFromPolyline\nfrom .utils.getLaps import getDeviceLaps, getAutoLaps, getSkiRuns\nfrom .graphs.paceElevGraph import paceElevGraph\nfrom .graphs.model3DGraph import model3DGraph\nfrom .graphs.mapThumbnailGraph import mapThumbnail\nfrom .graphs.annotatedMap import annotatedMap\nfrom .graphs.paceZonesGraph import paceZonesGraph\nfrom .graphs.skiSpeedZonesGraph import skiSpeedZonesGraph\nfrom .graphs.gradeZonesGraph import gradeZonesGraph\nfrom .graphs.lapsBarChart import lapsBarChart\nfrom .graphs.dashboardTable import dashboardTable\nfrom .graphs.dashboardBarChart import dashboardBarChart\nfrom .graphs.dashboardScheduleChart import dashboardScheduleChart\nfrom .graphs.trendsBarChart import trendsBarChart\n\nimport json\nimport datetime\nimport boto3\n\n@require_POST\ndef getPaceElevGraph(request):\n activity = json.loads(request.body)\n athlete = Athlete.objects.get(pk=activity['fields']['athlete'])\n graph = paceElevGraph(activity, athlete)\n return HttpResponse(graph)\n\n@require_POST\ndef get3DModelGraph(request):\n activity = json.loads(request.body)\n athlete = Athlete.objects.get(pk=activity['fields']['athlete'])\n graph = model3DGraph(activity, athlete)\n return HttpResponse(graph)\n\n@require_POST\ndef getMapThumbnail(request):\n activity = json.loads(request.body)\n graph = mapThumbnail(\n activity['streams']['latStream'],\n activity['streams']['lngStream']\n )\n return HttpResponse(graph)\n\n@require_POST\ndef getAnnotatedMap(request):\n activity = json.loads(request.body)\n athlete = Athlete.objects.get(pk=activity['fields']['athlete'])\n graph = annotatedMap(athlete, activity)\n return HttpResponse(graph)\n\n@require_POST\ndef getPaceZonesGraph(request):\n activity = json.loads(request.body)\n athlete = Athlete.objects.get(pk=activity['fields']['athlete'])\n if activity['isAmbulatory']:\n graph = paceZonesGraph(activity, athlete)\n else:\n graph = skiSpeedZonesGraph(activity, athlete)\n return HttpResponse(graph)\n\n@require_POST\ndef getGradeZonesGraph(request):\n activity = json.loads(request.body)\n athlete = Athlete.objects.get(pk=activity['fields']['athlete'])\n graph = gradeZonesGraph(activity, athlete)\n return HttpResponse(graph)\n\n@require_POST\ndef getHeatmap(request):\n athleteId = json.loads(request.body)['athlete']\n athlete = Athlete.objects.get(pk=athleteId)\n client = boto3.client(\n 's3',\n region_name=settings.AWS_REGION_NAME,\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY\n )\n obj = client.get_object(\n Bucket=settings.AWS_HEATMAP_BUCKET_NAME,\n Key=f'heatmap-graph-html-{athlete.id}.html'\n )\n graph = obj['Body'].read().decode('utf-8')\n return HttpResponse(graph)\n\n@require_POST\ndef getlapsBarChartDevice(request):\n activity = json.loads(request.body)\n athlete = Athlete.objects.get(pk=activity['fields']['athlete'])\n laps = getDeviceLaps(activity, athlete)\n graph = lapsBarChart(activity, laps, athlete)\n return HttpResponse(graph)\n\n@require_POST\ndef getlapsBarChartAuto(request):\n activity = json.loads(request.body)\n athlete = Athlete.objects.get(pk=activity['fields']['athlete'])\n if activity['isAmbulatory']:\n laps = getAutoLaps(activity, athlete)\n else:\n laps = getSkiRuns(activity, athlete)\n graph = lapsBarChart(activity, laps, athlete)\n return HttpResponse(graph)\n\n@require_POST\ndef getDashboardTable(request):\n data = json.loads(request.body)\n athlete = Athlete.objects.get(pk=data['athlete'])\n fromDate = datetime.datetime.strptime(data['fromDate'], '%Y-%m-%d')\n toDate = datetime.datetime.strptime(data['toDate'], '%Y-%m-%d')\n table = dashboardTable(fromDate, toDate, athlete)\n return HttpResponse(table)\n\n@require_POST\ndef getDashboardBarChart(request):\n data = json.loads(request.body)\n athlete = Athlete.objects.get(pk=data['athlete'])\n fromDate = datetime.datetime.strptime(data['fromDate'], '%Y-%m-%d')\n toDate = datetime.datetime.strptime(data['toDate'], '%Y-%m-%d')\n metric = data['metric']\n graph = dashboardBarChart(athlete, metric, fromDate, toDate)\n return HttpResponse(graph)\n\n@require_POST\ndef getDashboardScheduleChart(request):\n data = json.loads(request.body)\n athlete = Athlete.objects.get(pk=data['athlete'])\n fromDate = datetime.datetime.strptime(data['fromDate'], '%Y-%m-%d')\n toDate = datetime.datetime.strptime(data['toDate'], '%Y-%m-%d')\n graph = dashboardScheduleChart(athlete, fromDate, toDate)\n return HttpResponse(graph)\n\n@require_POST\ndef getTrendsBarChart(request):\n data = json.loads(request.body)\n athlete = Athlete.objects.get(pk=data['athlete'])\n period = data['period']\n metric = data['metric']\n graph = trendsBarChart(athlete, metric, period)\n return HttpResponse(graph)\n","repo_name":"sfergusond/runcrunch","sub_path":"graph/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4873,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"29771186193","text":"from django.http.response import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import redirect, render\nfrom .models import Inquiry, Listing, Realtor\nfrom .filters import ListingFilter\nfrom django.urls import reverse\nfrom .forms import InquiryForm\nfrom django.contrib.auth.decorators import login_required\n\ndef HomeView(request):\n\ttemplate = \"home.html\"\n\tlistings = Listing.objects.filter(is_published=True)\n\tmyfilter = ListingFilter(request.GET, queryset=listings)\n\tlistings = myfilter.qs\n\tcontext = {\n\t\t'results' : listings,\n\t\t'filter' : myfilter,\n\t}\n\n\treturn render(request, template, context)\n\ndef PropertyDetailView(request, pk):\n\ttemplate = \"property_details.html\"\n\ttry:\n\t\tproperty = Listing.objects.get(id=pk)\n\texcept:\n\t\treturn HttpResponse(\"Property does not exist\")\n\tcontext = {\n 'property' : property,\n\t}\n\n\treturn render(request, template, context)\n\n@login_required\ndef InquiryCreateView(request, pk):\n\ttemplate = \"inquirycreate.html\"\n\tproperty = Listing.objects.get(id=pk)\n\tcontacts = Inquiry.objects.filter(listing=property)\n\tinquiries = contacts.filter(user=request.user)\n\tif not inquiries:\n\t\tform = InquiryForm()\n\t\tif request.method == \"POST\":\n\t\t\tphone = request.POST.get(\"phone\")\n\t\t\tmessage = request.POST.get(\"message\")\n\t\t\tinquiry = Inquiry.objects.create(\n\t\t\t\tlisting=property,\n\t\t\t\tuser=request.user,\n\t\t\t\tphone=phone,\n\t\t\t\tmessage=message\n\t\t\t)\n\t\t\tinquiry.save()\n\t\t\treturn HttpResponseRedirect(reverse('details', args=[str(property.id)]))\n\t\tcontext = {\n\t\t\t'form' : form,\n\t\t\t'property' : property,\n\t\t}\n\n\t\treturn render(request, template, context)\n\telse:\n\t\treturn redirect('dashboard')\n\n@login_required\ndef DashboardView(request):\n\ttemplate = \"dashboard.html\"\n\tcontacts = Inquiry.objects.filter(user=request.user)\n\tcontext = {\n 'contacts' : contacts,\n\t}\n\t\n\treturn render(request, template, context)\n@login_required\ndef DeleteInquiryView(request, id):\n\tif request.method == \"POST\":\n\t\tinquiry = Inquiry.objects.filter(id=id)\n\t\tif inquiry.first().user == request.user:\n\t\t\tinquiry.delete()\n\t\t\treturn redirect('dashboard')\n\t\telse:\n\t\t\treturn redirect('dashboard')\n\telse:\n\t\treturn redirect('dashboard')\n\ndef AboutView(request):\n\ttemplate = \"about.html\"\n\trealtors = Realtor.objects.all()\n\tbest = realtors.filter(is_mvp=True).first()\n\tif best:\n\t\tcontext = {\n\t\t\t'realtors' : realtors,\n\t\t\t'best' : best,\n\n\t\t}\n\telse:\n\t\tcontext = {\n\t\t\t'realtors' : realtors,\n\n\t\t}\n\t\t\n\n\treturn render(request, template, context)","repo_name":"Nepul321/Real-estate-Django","sub_path":"base/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"23633278551","text":"import argparse\nimport numpy as np\nimport h5py\nimport json\nimport string\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom matplotlib import gridspec\nfrom mpl_toolkits.basemap import Basemap\nimport colormaps\n\n\n\ndef plot_panel(\n filename,\n show_colorbar=True,\n xaxis='bottom',\n norm=None,\n cmap=None,\n annotation=None\n):\n with h5py.File(filename) as f:\n correction_factor = 1.0*f['cloud_incidence_2'][::]/f['cloud_incidence_1'][::]\n\n m = Basemap(\n llcrnrlon=-180,\n llcrnrlat=-90,\n urcrnrlon=180,\n urcrnrlat=90\n )\n im = m.imshow(correction_factor.T,\n # im = m.imshow((f['cloud_incidence_1'][::]/f['cloud_incidence_1_total'][::]).T,\n interpolation='nearest',\n norm=norm,\n cmap=cmap\n )\n # if show_colorbar:\n # m.colorbar(im, 'right', size='3%', pad='3%')\n m.drawcoastlines(linewidth=0.1)\n m.drawcountries(linewidth=0.1)\n m.drawparallels(np.arange(-90.,91.,20.), labels=[1,0,0,1], linewidth=0.1, color='#333333', fontsize=10)\n\n if xaxis == 'bottom':\n labels = [0, 0, 0, 1]\n elif xaxis == 'top':\n labels = [0, 0, 1, 0]\n else:\n labels = [0, 0, 0, 0]\n m.drawmeridians(np.arange(-180.,180.,30.), labels=labels, linewidth=0.1, color='#333333', fontsize=10)\n\n if annotation is not None:\n plt.annotate(\n annotation,\n xy=(0, 1),\n xytext=(5, -5),\n ha='left',\n va='top',\n xycoords='axes fraction',\n textcoords='offset points',\n weight='bold'\n )\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Plot correction factor (multi)')\n parser.add_argument('-c', dest='config', help='config file')\n parser.add_argument('-o', dest='outfile', type=str, help='output plot')\n args = parser.parse_args()\n config = json.load(open(args.config))\n\n plt.figure(figsize=(8,12))\n plt.viridis()\n plt.rcParams['font.family'] = 'Open Sans'\n\n nrows = len(config['files'])\n\n gs = gridspec.GridSpec(\n nrows + 1,\n 1,\n wspace=0,\n hspace=0.15,\n height_ratios=(0.3, 0.3, 0.3, 0.015)\n )\n\n norm = mpl.colors.Normalize(0.2, 2)\n cmap = colormaps.parula\n\n for i, filename in enumerate(config['files']):\n plt.subplot(gs[i])\n\n if i == 0:\n xaxis = 'top'\n elif i == nrows - 1:\n xaxis = 'bottom'\n else:\n xaxis = None\n\n plot_panel(\n filename,\n xaxis=xaxis,\n show_colorbar=(i == 0),\n norm=norm,\n cmap=cmap,\n annotation=string.lowercase[i]\n )\n\n plt.annotate(\n config['labels'][i],\n xy=(-0.15, 0.5), xytext=(0, 0),\n xycoords=('axes fraction', 'axes fraction'),\n textcoords='offset points',\n size=14,\n ha='left',\n va='center',\n weight='bold'\n )\n\n cax = plt.subplot(gs[nrows])\n cb = mpl.colorbar.ColorbarBase(\n cax,\n orientation='horizontal',\n extend='both',\n cmap=cmap,\n norm=norm\n )\n cb.set_label('8.3 to 8 km cloud occurrence ratio (1)')\n\n if args.outfile:\n plt.savefig(args.outfile, bbox_inches='tight', pad_inches=0.5)\n else:\n plt.show()\n","repo_name":"peterkuma/clouds-ross-sea-2018","sub_path":"scripts/plot_correction_factor_multi.py","file_name":"plot_correction_factor_multi.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"19351697075","text":"def moveNameInDB(key, dbCursor):\n dbCursor.execute(\"select movename from moves where movename=? collate nocase\", (key,))\n moves = dbCursor.fetchall()\n\n if not moves:\n return False\n return True\n\n\nasync def getCharMoves(char, dbCursor):\n dbCursor.execute(\"select movename from moves where charname=? collate nocase\", (char,))\n moves = dbCursor.fetchall()\n\n if not moves:\n return None\n\n moveString = \"```\"\n for move in moves:\n moveString = moveString + (move[0]) + \"\\n\"\n moveString = moveString + \"```\"\n\n return moveString\n\n\ndef getFrameData(char, move, dbCursor):\n \"\"\"Function returning a list of strings containing framedata\n for each move found in the database. If a precise result is found,\n return that one. If not, return a relaxed result where only similar\n moves are being found.\"\"\"\n\n dbCursor.execute(\"select * from moves where charname=? collate nocase and\\\n movename =? collate nocase\", (char, move))\n\n retVal = dbCursor.fetchall()\n\n if not retVal:\n #Nothing found with precise search, relax the movename reqs\n dbCursor.execute(\"select * from moves where charname=? collate nocase and\\\n movename like ? collate nocase\", (char, '%' + move + '%'))\n retVal = dbCursor.fetchall()\n\n return retVal\n","repo_name":"prki/eddiebot","sub_path":"DbReader.py","file_name":"DbReader.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"2647991512","text":"import os\nimport logging\n\nimport numpy as np\n\nfrom alias.io.numpy_io import load_npy\nfrom alias.io.checkfile_io import (\n save_checkfile\n)\nfrom alias.src.positions import batch_coordinate_loader\nfrom alias.src.surface_parameters import SurfaceParameters\nfrom alias.src.intrinsic_sampling_method import (\n create_intrinsic_surfaces\n)\nfrom alias.src.intrinsic_analysis import (\n create_intrinsic_positions_dxdyz,\n create_intrinsic_den_curve_hist,\n av_intrinsic_distributions\n)\nfrom alias.io.utilities import make_directory\nfrom alias.src.utilities import create_file_name, join_str_values\n\nlog = logging.getLogger(__name__)\n\n\ndef run_alias(trajectory, alias_options, checkpoint=None, topology=None):\n \"\"\"Peform ALIAS on given trajectory,\"\"\"\n\n # Obtain directory for trajectory and create analysis\n # directories\n traj_dir = os.path.dirname(trajectory)\n\n alias_dir = os.path.join(traj_dir, 'alias_analysis')\n data_dir = os.path.join(alias_dir, 'data')\n figure_dir = os.path.join(alias_dir, 'figures')\n\n make_directory(alias_dir)\n make_directory(data_dir)\n make_directory(figure_dir)\n\n # Parse file name to obtain base path for analysis\n # files\n file_name, _ = os.path.splitext(trajectory)\n file_name = os.path.basename(file_name)\n\n # Create a checkpoint file to save intrinsic surface\n # parameters\n if checkpoint is None:\n checkpoint = os.path.join(\n alias_dir, file_name + '_chk.json')\n\n surf_param = SurfaceParameters.from_json(checkpoint)\n\n log.info(\"Loading trajectory file {} using {} topology\".format(\n trajectory, topology))\n surf_param.load_traj_parameters(\n trajectory, topology)\n\n surf_param.select_residue()\n checkfile = surf_param.serialize()\n save_checkfile(checkfile, checkpoint)\n\n surf_param.select_masses()\n checkfile = surf_param.serialize()\n save_checkfile(checkfile, checkpoint)\n\n surf_param.select_center_of_mass()\n checkfile = surf_param.serialize()\n save_checkfile(checkfile, checkpoint)\n\n com_ref = create_file_name([\n surf_param.com_mode,\n join_str_values(surf_param.com_sites)]\n )\n file_name = f\"{file_name}_{com_ref}\"\n\n surf_param.select_orientation_vector()\n checkfile = surf_param.serialize()\n save_checkfile(checkfile, checkpoint)\n\n pos_dir = os.path.join(data_dir, 'pos')\n if not os.path.exists(pos_dir):\n os.mkdir(pos_dir)\n pos_file_name = os.path.join(pos_dir, file_name)\n\n try:\n mol_traj = load_npy(pos_file_name + f'{surf_param.n_frames}_mol_traj')\n cell_dim = load_npy(pos_file_name + f'{surf_param.n_frames}_cell_dim')\n except (FileNotFoundError, IOError):\n\n mol_traj, com_traj, cell_dim, mol_vec = batch_coordinate_loader(\n trajectory, surf_param, topology=topology\n )\n\n np.save(pos_file_name + f'{surf_param.n_frames}_mol_traj', mol_traj)\n np.save(pos_file_name + f'{surf_param.n_frames}_mol_vec', mol_vec)\n np.save(pos_file_name + f'{surf_param.n_frames}_com_traj', com_traj)\n np.save(pos_file_name + f'{surf_param.n_frames}_cell_dim', cell_dim)\n\n surf_param.select_mol_sigma()\n checkfile = surf_param.serialize()\n save_checkfile(checkfile, checkpoint)\n\n surf_param.n_frames = mol_traj.shape[0]\n mean_cell_dim = np.mean(cell_dim, axis=0)\n surf_param.cell_dim = mean_cell_dim.tolist()\n\n checkfile = surf_param.serialize()\n save_checkfile(checkfile, checkpoint)\n\n print(f\"Simulation cell xyz dimensions in Angstoms: \"\n f\"{surf_param.area}\\n\")\n\n print(\"\\n------STARTING INTRINSIC SAMPLING-------\\n\")\n print(\n \"Max wavelength = {:12.4f} sigma \"\n \"Min wavelength = {:12.4f} sigma\".format(\n surf_param.q_max, surf_param.q_min)\n )\n print(\"Max frequency qm = {:6d}\".format(\n surf_param.q_m))\n\n surf_param.select_pivot_density(file_name, data_dir)\n checkfile = surf_param.serialize()\n save_checkfile(checkfile, checkpoint)\n\n freq_range = range(1, surf_param.q_m+1)\n print(\"\\nResolution parameters:\")\n print(\"\\n{:12s} | {:12s} | {:12s}\".format(\n 'qu', \"lambda (sigma)\", \"lambda (nm)\"))\n print(\"-\" * 14 * 5)\n\n for q_u in freq_range:\n print(\"{:12d} | {:12.4f} | {:12.4f}\".format(\n q_u,\n surf_param.wavelength(q_u),\n surf_param.wavelength(q_u) * surf_param.mol_sigma / 10))\n print(\"\")\n\n create_intrinsic_surfaces(\n data_dir, file_name, mean_cell_dim, surf_param.q_m,\n surf_param.n_pivots, surf_param.phi,\n surf_param.mol_sigma, surf_param.n_frames,\n recon=surf_param.recon, ncube=surf_param.n_cube,\n vlim=surf_param.v_lim, tau=surf_param.tau,\n max_r=surf_param.max_r,\n ow_coeff=alias_options.ow_coeff,\n ow_recon=alias_options.ow_recon)\n\n create_intrinsic_positions_dxdyz(\n data_dir, file_name, surf_param.n_mol,\n surf_param.n_frames, surf_param.q_m,\n surf_param.n_pivots, surf_param.phi,\n mean_cell_dim,\n recon=surf_param.recon,\n ow_pos=alias_options.ow_intpos)\n\n create_intrinsic_den_curve_hist(\n data_dir, file_name, surf_param.q_m, surf_param.n_pivots,\n surf_param.phi, surf_param.n_frames,\n surf_param, surf_param.n_slice,\n surf_param.cell_dim,\n recon=surf_param.recon,\n ow_hist=alias_options.ow_hist)\n\n av_intrinsic_distributions(\n data_dir, file_name, surf_param.cell_dim,\n surf_param.n_slice, surf_param.q_m,\n surf_param.n_pivots, surf_param.phi,\n surf_param.n_frames, surf_param.n_frames,\n recon=surf_param.recon,\n ow_dist=alias_options.ow_dist)\n\n print(\"\\n---- ENDING PROGRAM ----\\n\")\n","repo_name":"franklongford/ALIAS","sub_path":"alias/src/run_alias.py","file_name":"run_alias.py","file_ext":"py","file_size_in_byte":5726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"9608328771","text":"#!/usr/bin/python3\n\ndef max_integer(my_list=[]):\n\n if len(my_list) < 1:\n return None\n else:\n max_value = my_list[0]\n for index, num in enumerate(my_list):\n if num > max_value:\n max_value = num\n return max_value\n","repo_name":"gbabohernest/alx-higher_level_programming","sub_path":"0x03-python-data_structures/9-max_integer.py","file_name":"9-max_integer.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"31089283361","text":"import numpy as np, os, cv2\nfrom functions import *\n\ndef parse_bundler(fname,img_shape):\n with open(fname, \"r\") as f:\n f.readline() # Read Bundler Version Line\n ncams = int(f.readline().split()[0])\n focals, Rt, pt_tracks = [], [], []\n for idx in range(ncams):\n focals.append(float(f.readline().split()[0]))\n R = np.array([list(map(float, f.readline().split())) for x in range(3)])\n t = np.array(list(map(float, f.readline().split())))\n Rt.append((R, t))\n while True:\n line = f.readline()\n if line is None or len(line.rstrip()) == 0:\n break\n X = np.array(list(map(float, line.split())))\n f.readline() # Ignore color values\n projs = f.readline().split()\n track = []\n for idx in range(int(projs[0])):\n frame = int(projs[1 + 4*idx]) # Ignore SIFT keypoint number\n x = img_shape[1]/2. + float(projs[3 + 4*idx])\n y = img_shape[0]/2. + float(projs[4 + 4*idx])\n track.append((frame, np.array([x,y], np.float64)))\n pt_tracks.append((X, track))\n return focals, Rt, pt_tracks\n\nclass Bundler:\n def __init__(self, bundler_file, img_files, img_shape, max_dim = 1000, frame_subset = None, cams_file = None):\n self.bundler_file = bundler_file\n self.img_shape = img_shape\n if max_dim is None:\n self.scale = 1.\n else:\n self.scale = min(float(max_dim+0.4) / np.array(self.img_shape[:2], np.float64))\n if not os.path.exists(self.bundler_file):\n raise RuntimeError(\"Bundler Path does not exist: {}\".format(self.bundler_file))\n focals, Rt, tracks = parse_bundler(self.bundler_file, self.img_shape)\n if len(focals) != len(img_files):\n raise RuntimeError(\"Bundler camera count ({0}) not agreeing with specified camera count ({1})\".format(len(focals),len(img_files)))\n frames_ok = np.nonzero(focals)[0].tolist()\n if frame_subset is not None:\n frames_ok = list(set(frames_ok).intersection(frame_subset))\n if cams_file is not None:\n if not os.path.exists(cams_file):\n raise RuntimeWarning(\"Not using good cams - File not found: {}\".format(cams_file))\n with open(cams_file,\"r\") as camf:\n good_cams = list(map(int,camf.readlines()))\n frames_ok = list(set(frames_ok).intersection(good_cams))\n frames_ok = sorted(frames_ok)\n self.img_files = [img_files[idx] for idx in frames_ok]\n self.imgs = dict([(f,cv2.resize(load_img(f,1), (0,0), fx=self.scale, fy=self.scale)) for f in self.img_files])\n if len(img_files) == 0:\n raise RuntimeError('SfM failed: No good cameras')\n self.Ks = np.zeros((len(img_files), 3, 3))\n self.Rs = np.zeros((len(img_files), 3, 3))\n self.ts = np.zeros((len(img_files), 3))\n for idx, frame in enumerate(frames_ok):\n K = -np.array([[-self.scale*focals[frame], 0., -0.5 + self.scale*self.img_shape[1]/2.,],[0., self.scale*focals[frame], -0.5 + self.scale*self.img_shape[0]/2.,],[0., 0., 1.]])\n self.Ks[idx] = K\n self.Rs[idx], self.ts[idx] = Rt[frame]\n\n def get_img(self, frame): return self.imgs[self.img_files[frame]].copy()\n \n def P(self, frame): return np.dot(self.Ks[frame], np.hstack([self.Rs[frame], self.ts[frame, :, np.newaxis]]))\n\n def center(self, frame): return -np.dot(self.Rs[frame].T, self.ts[frame])\n\n def project(self, frame, X):\n X = np.asarray(X.T)\n homog_X = np.concatenate([X, [1.]]) if X.ndim == 1 else np.vstack([X, np.ones(X.shape[1])])\n x = np.dot(self.P(frame), homog_X)\n y = x[:-1] / x[-1]\n return y.T\n\nif __name__ == \"__main__\":\n data_path = \"./Test Data/walden-tree3/\"\n Bundler(data_path + \"bundle/bundle.out\", get_jpg_files(data_path), (3888,2592,3))","repo_name":"abdur75648/COL-780-Assignments","sub_path":"Project/src/bundler.py","file_name":"bundler.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"12449447670","text":"# 해시 _ 베스트엘범 _level3 (통과)\ndef solution(gen, play):\n # mulist = 장르 : [(재생수, 고유번호)]\n # total = 장르 : 총 재생수 \n answer, mulist, total = [], dict(), dict()\n g_len = len(gen) # 장르의 갯수\n\n for i in range(g_len) :\n if gen[i] in mulist: # 장르 key가 존재하면?\n mulist[gen[i]].append((play[i], i)) # (재생수, 고유번호)\n total[gen[i]] = total[gen[i]] + play[i] # 총 재생 수\n else : # 장르 key가 존재안하면?\n mulist[gen[i]] = [(play[i],i)]\n total[gen[i]] = play[i]\n \n # total 을 정렬 _ 재생수를 기준으로 내림차순 정렬\n total_sort_list = sorted(list(total.items()), key=lambda x :-x[1])\n\n for gen, j in total_sort_list:\n if len(mulist[gen]) == 1: # 조건1 ) 곡이 한개라면, 하나만 넣기 **\n answer.append(mulist[gen][0][1])\n else : \n # 조건2 ) 재생 수가 같다면 고유번호 낮은 순 넣기 **\n mulist[gen].sort(key=lambda x:(-x[0], x[1])) \n answer.append(mulist[gen][0][1])\n answer.append(mulist[gen][1][1])\n\n return answer\n\n# 조금 수정해보기\ndef solution2(gen, play):\n answer, mulist, total = [], dict(), dict()\n\n for i, (g, p) in enumerate(zip(gen, play)) : # enumerate와 zip을 사용하기 **\n if gen[i] in mulist: \n mulist[g].append((p,i)) \n total[g] += p # += 연산자 사용하기 **\n else : \n mulist[g] = [(p,i)]\n total[g] = p\n \n for gen, j in sorted(total.items(), key=lambda x :-x[1]):\n for p, go in sorted(mulist[gen], key=lambda x:(-x[0], x[1]))[:2] :\n answer.append(go)\n \n\n # print(answer)\n return answer\n\n\nif __name__ == '__main__':\n genres = [\"classic\", \"pop\", \"classic\", \"classic\", \"pop\"]\t\n plays = [500, 2500, 150, 800, 2500]\t\n solution(genres, plays)\n solution2(genres, plays)","repo_name":"yujing-kim/algorithm_coding_test","sub_path":"ps_python/programmers/2022/hash_bestalbum.py","file_name":"hash_bestalbum.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"9857137631","text":"import RPi.GPIO as GPIO\n\nPWM_FREQ = 40\nLEFT_PWM = 11\nRIGHT_PWM = 3\n\nLEFT_DIR_1 = 13\nLEFT_DIR_2 = 15\n\nRIGHT_DIR_1 = 5\nRIGHT_DIR_2 = 7\n\nMAX_SPEED_LEFT = 0.1142 * 2\nMAX_SPEED_RIGHT = 0.1142 * 2\nMAX_ALLOWED_POWER = 0.5\nWHEELBASE = 0.2\n\n\nclass Driver(object):\n def __init__(self):\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(LEFT_PWM, GPIO.OUT)\n GPIO.setup(RIGHT_PWM, GPIO.OUT)\n GPIO.setup(LEFT_DIR_1, GPIO.OUT)\n GPIO.setup(LEFT_DIR_2, GPIO.OUT)\n GPIO.setup(RIGHT_DIR_1, GPIO.OUT)\n GPIO.setup(RIGHT_DIR_2, GPIO.OUT)\n\n self.left_pwm = GPIO.PWM(LEFT_PWM, PWM_FREQ)\n self.right_pwm = GPIO.PWM(RIGHT_PWM, PWM_FREQ)\n\n self.left_pwm.start(0)\n self.right_pwm.start(0)\n\n def set_speed(self, v_left, v_right):\n # Cap the max speed, so that you do not set values larger than allowed\n v_left = max(min(v_left, MAX_SPEED_LEFT), -MAX_SPEED_LEFT)\n v_right = max(min(v_right, MAX_SPEED_RIGHT), -MAX_SPEED_RIGHT)\n\n # Transform speed to PWM\n v_left /= MAX_SPEED_LEFT / MAX_ALLOWED_POWER\n v_right /= MAX_SPEED_RIGHT / MAX_ALLOWED_POWER\n\n # Controll the motor direction correctly\n if v_left >= 0:\n GPIO.output(LEFT_DIR_1, GPIO.HIGH)\n GPIO.output(LEFT_DIR_2, GPIO.LOW)\n else:\n GPIO.output(LEFT_DIR_1, GPIO.LOW)\n GPIO.output(LEFT_DIR_2, GPIO.HIGH)\n v_left = -v_left\n\n if v_right >= 0:\n GPIO.output(RIGHT_DIR_1, GPIO.HIGH)\n GPIO.output(RIGHT_DIR_2, GPIO.LOW)\n else:\n GPIO.output(RIGHT_DIR_1, GPIO.LOW)\n GPIO.output(RIGHT_DIR_2, GPIO.HIGH)\n v_right = -v_right\n\n # Actually set the duty for the motor\n self.left_pwm.ChangeDutyCycle(v_left)\n self.right_pwm.ChangeDutyCycle(v_right)\n\n def kill(self):\n # When killing reseting the pwm so the motors deinitialize\n self.left_pwm.stop()\n self.right_pwm.stop()\n GPIO.cleanup()\n","repo_name":"SimpleRobots/alice-hardware","sub_path":"pwm_drive.py","file_name":"pwm_drive.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"6074655937","text":"import sys\n\nimport pygame\nfrom pygame.constants import QUIT\nfrom pygame.display import update\n\nfrom settings import Settings\nfrom cell import Cell\n\nclass GameOfLife:\n \"\"\"Overall class to manage game assets and behavior\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game and create game resources\"\"\"\n pygame.init()\n self.settings = Settings()\n self.number_cells_x = int(input(\"Enter number of cells in a row: \"))\n self.cell_width = float(self.settings.screen_width // self.number_cells_x)\n #print(self.cell_width)\n self.number_cells_y = int(self.settings.screen_height // self.cell_width)\n\n self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))\n pygame.display.set_caption(\"Game of Life\")\n\n self.cells = []\n self.to_be_updated = []\n self._create_cells()\n\n self.bg_colour = (self.settings.bg_colour)\n self.waiting = True\n \n def _create_cell(self,row_number,cell_number):\n \"\"\"Creates a cell at given position\"\"\"\n cell = Cell(self)\n cell.x = cell_number * self.cell_width\n cell.y = row_number * self.cell_width\n cell.rect.x = cell.x\n cell.rect.y = cell.y\n return cell\n\n def _create_cells(self):\n \"\"\"Create all cells\"\"\"\n for row_number in range(self.number_cells_y):\n row_cells = []\n row_to_be_updated = []\n for cell_number in range(self.number_cells_x):\n row_cells.append(self._create_cell(row_number,cell_number))\n row_to_be_updated.append(False)\n self.cells.append(row_cells)\n self.to_be_updated.append(row_to_be_updated)\n\n def run_game(self):\n \"\"\"Start the main loop for the game\"\"\"\n while True:\n self._check_event()\n self._update_screen()\n \n def _check_event(self):\n \"\"\"Checks for input from keyboard and mouse\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n sys.exit()\n elif event.key == pygame.K_SPACE:\n self.waiting = not self.waiting\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if self.waiting:\n x,y = pygame.mouse.get_pos()\n cell_addr_y = int(y/self.cell_width)\n cell_addr_x = int(x/self.cell_width)\n self.cells[cell_addr_y][cell_addr_x].update()\n\n def _get_neighbours(self,row_number,col_number):\n alive_neighbours = 0\n if row_number > 0:\n if self.cells[row_number-1][col_number].get_status():\n alive_neighbours += 1\n if row_number < self.number_cells_y -1:\n if self.cells[row_number+1][col_number].get_status():\n alive_neighbours += 1\n if col_number > 0:\n if self.cells[row_number][col_number-1].get_status():\n alive_neighbours += 1\n if col_number < self.number_cells_x -1:\n if self.cells[row_number][col_number+1].get_status():\n alive_neighbours += 1\n if row_number > 0 and col_number > 0:\n if self.cells[row_number-1][col_number-1].get_status():\n alive_neighbours += 1\n if row_number > 0 and col_number < self.number_cells_x -1:\n if self.cells[row_number-1][col_number+1].get_status():\n alive_neighbours += 1\n if row_number < self.number_cells_y -1 and col_number > 0:\n if self.cells[row_number+1][col_number-1].get_status():\n alive_neighbours += 1\n if row_number < self.number_cells_y -1 and col_number < self.number_cells_x -1:\n if self.cells[row_number+1][col_number+1].get_status():\n alive_neighbours += 1\n return alive_neighbours\n\n def _check_cells(self):\n \"\"\"Ckeck for all the cells that need to be updated once the game starts\"\"\"\n for row_number in range(self.number_cells_y):\n for col_number in range(self.number_cells_x):\n alive_neighbours = self._get_neighbours(row_number,col_number)\n \n self.to_be_updated[row_number][col_number] = False\n if self.cells[row_number][col_number].get_status():\n if alive_neighbours < 2:\n self.to_be_updated[row_number][col_number] = True\n elif alive_neighbours > 3:\n self.to_be_updated[row_number][col_number] = True\n else:\n if alive_neighbours == 3:\n self.to_be_updated[row_number][col_number] = True\n\n def _update_cells(self):\n \"\"\"Update cells once the game starts\"\"\"\n for row_number in range(self.number_cells_y):\n for col_number in range(self.number_cells_x):\n if self.to_be_updated[row_number][col_number]:\n self.cells[row_number][col_number].update()\n\n def _update_screen(self):\n \"\"\"Update all the cells and the background\"\"\"\n self.screen.fill(self.bg_colour)\n\n if not self.waiting:\n self._check_cells()\n self._update_cells()\n for row in self.cells:\n for cell in row:\n cell.draw_cell()\n \n pygame.display.flip()\n\nif __name__ == '__main__':\n gl = GameOfLife()\n gl.run_game()","repo_name":"adityakadoo/GameOfLife","sub_path":"game_of_life.py","file_name":"game_of_life.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"29852607034","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://example.com'\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'html.parser')\n\n# Extract and print all the links on the webpage\nlinks = soup.find_all('a')\nfor link in links:\n print(link.get('href'))\n","repo_name":"Daniel-Badura/Coding-Buddies-Community-Contributions","sub_path":"Python Basic Projects/webscrapper.py","file_name":"webscrapper.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"}
+{"seq_id":"27836567704","text":"import json\nimport networkx as nx\nimport operator\n# base_dir = \"/Users/saurav/Desktop/OpenSoft/case_ranking/\"\n\ndef give_best_cases(case_dict, label_names):\n\t'''\n\t\tIn this function, give the input as a list of labels\n\t\tNote - the name of labels must match exactly with that in subject_to_case.txt\n\t'''\n\n # with open('subject_to_case.txt', 'r') as file:\n\t # json_data = file.read()\n\t\t# category_data = json.loads(json_data)\n\n\tcase_score = dict()\n\t# label_count = dict()\n\n\tfor labels in label_names:\n\t\ttry:\n\t\t\twith open(labels + '.txt', 'r') as file:\n\t\t\t\tjson_data = file.read()\n\t\t\t\tlabel_data = json.loads(json_data)\n\t\texcept:\n\t\t\tcontinue\n\t\tlength = len(label_data)\n\t\t# Cases present in label_data\n\t\tfor case in label_data:\n\t\t\tif case in case_dict:\n\t\t\t\tif case not in case_score:\n\t\t\t\t\tcase_score[case] = 0\n\t\t\t\telse:\n\t\t\t\t\tcase_score[case] = case_score[case] + label_data[case]*length\n\n\t# Assigning scores by using common citation graph\n\twith open('case_ranking.txt', 'r') as file:\n\t\tjson_data = file.read()\n\t\tcommon_case_ranking = json.loads(json_data)\n\n\tlength = len(common_case_ranking)\n\tfor case in case_score:\n\t\tif case in common_case_ranking:\n\t\t\tcase_score[case] = case_score[case] + common_case_ranking[case]*length\n\n\n\t# for case in case_score:\n\t# label_count[case] = len(case_dict[case]['categories'])\n\n\t# If case in case_score, then it exist surely in case_dict\n\tcase_score = sorted(case_score.items(), key = operator.itemgetter(1))\n\n\tcase_score_list = []\n\tfor case in case_score:\n\t\tcase_score_list.append(case[0])\n\n\tcase_score_list.sort(key = lambda z: case_dict[z]['value'])\n\tcase_score_list.reverse()\n\t\t\n\treturn case_score_list[:100]\n\nif __name__ == '__main__':\n\tn = int(input(\"Number of Categories\"))\n\tlabel_names = []\n\tfor i in range(n):\n\t\tlabel = input(\"Give Category\")\n\t\tlabel_names.append(label)\n\tprint(label_names)\n\tx = []\n\tx = give_best_cases(label_names)\n\tprint(x)\n","repo_name":"142ayushkumar/LegalAssistant","sub_path":"case_ranking/top_cases_given_labels.py","file_name":"top_cases_given_labels.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"36540086851","text":"import pickle\nfrom oatd import ScrapeOatd\n\nx=1\n# current_user = getuser()\n\n\n# new_dict = dict(test_xx='test', other_la='other la')\n# new_dict.update(new_add='Geeks')\n# x = 1\n# url = 'https://oatd.org/oatd/search?q=eeg&form=basic'\nurl = 'https://oatd.org/oatd/search?q=eeg&form=basic&pubdate.facet=1991' # 88 result , 3 pages\noatd = ScrapeOatd()\nall_result = oatd.scrape_oatd(url)\nprint('complete scrape search result')\nall_website_scrape = oatd.loop_get_specific(all_result)\nprint('complete scrape specific page')\n\nx = 1\n\nwith open('oatd_complete_all_specific_page.pickle', 'wb') as handle:\n pickle.dump(all_website_scrape, handle, protocol=pickle.HIGHEST_PROTOCOL)\n print('complete saving')\n\n# html_oatd_specific_page\n# r = requests.get('https://oatd.org/oatd/record?record=handle\\:11012\\%2F16478&q=eeg')\n# page_soup = Soup(r.text, 'html.parser')","repo_name":"itayoron/Article_Search_Download_Automation","sub_path":"oatd_how_to_use.py","file_name":"oatd_how_to_use.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"73118731027","text":"import pandas as pd\r\nimport os\r\n\r\n\r\nabspath = os.path.abspath(__file__)\r\ndname = os.path.dirname(abspath)\r\nos.chdir(dname)\r\n\r\n\r\nfilename = \"DebtGDP.csv\"\r\ndf = pd.read_csv(filename)\r\nqs = df['date'].str.replace(r'(\\d+) (Q\\d)', r'\\1-\\2')\r\ndf['date'] = pd.PeriodIndex(qs, freq='Q').to_timestamp()\r\n\r\nfilelocation = os.getcwd()\r\nprint(\"Saving as: [ \" + filename + \" ] in: [ \" + filelocation + \" ] \")\r\ndf.to_csv(filename)\r\n","repo_name":"lhkkennedy/lhkkennedy.github.io","sub_path":"html/Debt/quarter-to-date.py","file_name":"quarter-to-date.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"13887005050","text":"#!python\nimport os \nimport pickle\n\nBASEDIR = '/p299/raw/2016/PM/split/'\n\nfiledict = dict()\nfilePathList = []\n\nfor root,dirs,files in os.walk(BASEDIR,topdown=True,followlinks=True):\n #if 'CA' not in root:\n # continue\n #if 'Reports' in root:\n # continue\n #if 'html' in root:\n # continue\n #print(root)\n for file in files:\n if not file.endswith('.gz'):\n continue\n fullpath = os.path.join(root,file)\n filePathList.append(fullpath)\n # fullid = file.split('_')[0]\n # if fullid not in filedict:\n # filedict[fullid] = []\n # if fullpath not in filedict[fullid]:\n # filedict[fullid].append(fullpath)\n print(\"add \",fullpath)\n\nprint('filedict size',len(filedict.keys()))\nprint('fullpath size',len(filePathList))\n\n#with open('filedict.pickle','wb') as fd:\n# pickle.dump(filedict,fd)\nwith open('pickle/filePathList.pickle','wb') as fpl:\n pickle.dump(filePathList,fpl)\nwith open('pickle/filePathList.xls','w') as fx:\n for file in filePathList:\n fx.write(file+'\\n')\n\n","repo_name":"seahurt/OGSManage","sub_path":"squery/scanFile.py","file_name":"scanFile.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"5733252047","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nfrom abc import ABCMeta, abstractmethod\r\nfrom datetime import datetime\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pickle\r\nfrom keras.models import Model\r\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\r\nfrom keras.layers import Layer, Activation\r\nfrom keras import initializers, regularizers, constraints\r\nfrom keras import backend as K\r\nfrom sklearn.model_selection import StratifiedKFold, train_test_split\r\nimport sys\r\nsys.path.append('utils/')\r\nimport config\r\n\r\n\r\n\r\n\r\n\r\nclass Attention(Layer):\r\n def __init__(self, step_dim=config.word_maxlen,\r\n W_regularizer=None, b_regularizer=None,\r\n W_constraint=None, b_constraint=None,\r\n bias=True, **kwargs):\r\n \"\"\"\r\n Keras Layer that implements an Attention mechanism for temporal data.\r\n Supports Masking.\r\n Follows the work of Raffel et al. [https://arxiv.org/abs/1512.08756]\r\n # Input shape\r\n 3D tensor with shape: `(samples, steps, features)`.\r\n # Output shape\r\n 2D tensor with shape: `(samples, features)`.\r\n :param kwargs:\r\n Just put it on top of an RNN Layer (GRU/LSTM/SimpleRNN) with return_sequences=True.\r\n The dimensions are inferred based on the output shape of the RNN.\r\n Example:\r\n model.add(LSTM(64, return_sequences=True))\r\n model.add(Attention())\r\n \"\"\"\r\n self.supports_masking = True\r\n # self.init = initializations.get('glorot_uniform')\r\n self.init = initializers.get('glorot_uniform')\r\n\r\n self.W_regularizer = regularizers.get(W_regularizer)\r\n self.b_regularizer = regularizers.get(b_regularizer)\r\n\r\n self.W_constraint = constraints.get(W_constraint)\r\n self.b_constraint = constraints.get(b_constraint)\r\n\r\n self.bias = bias\r\n self.step_dim = step_dim\r\n self.features_dim = 0\r\n super(Attention, self).__init__(**kwargs)\r\n\r\n def build(self, input_shape):\r\n assert len(input_shape) == 3\r\n\r\n self.W = self.add_weight((input_shape[-1],),\r\n initializer=self.init,\r\n name='{}_W'.format(self.name),\r\n regularizer=self.W_regularizer,\r\n constraint=self.W_constraint)\r\n self.features_dim = input_shape[-1]\r\n\r\n if self.bias:\r\n self.b = self.add_weight((input_shape[1],),\r\n initializer='zero',\r\n name='{}_b'.format(self.name),\r\n regularizer=self.b_regularizer,\r\n constraint=self.b_constraint)\r\n else:\r\n self.b = None\r\n\r\n self.built = True\r\n\r\n def compute_mask(self, input, input_mask=None):\r\n # do not pass the mask to the next layers\r\n return None\r\n\r\n def call(self, x, mask=None):\r\n # eij = K.dot(x, self.W) TF backend doesn't support it\r\n\r\n # features_dim = self.W.shape[0]\r\n # step_dim = x._keras_shape[1]\r\n\r\n features_dim = self.features_dim\r\n step_dim = self.step_dim\r\n\r\n eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)), K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\r\n\r\n if self.bias:\r\n eij += self.b\r\n\r\n eij = K.tanh(eij)\r\n\r\n a = K.exp(eij)\r\n\r\n # apply mask after the exp. will be re-normalized next\r\n if mask is not None:\r\n # Cast the mask to floatX to avoid float64 upcasting in theano\r\n a *= K.cast(mask, K.floatx())\r\n\r\n # in some cases especially in the early stages of training the sum may be almost zero\r\n a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\r\n\r\n a = K.expand_dims(a)\r\n weighted_input = x * a\r\n return K.sum(weighted_input, axis=1)\r\n\r\n def compute_output_shape(self, input_shape):\r\n # return input_shape[0], input_shape[-1]\r\n return input_shape[0], self.features_dim\r\n\r\n\r\ndef squash(x, axis=-1):\r\n # s_squared_norm is really small\r\n # s_squared_norm = K.sum(K.square(x), axis, keepdims=True) + K.epsilon()\r\n # scale = K.sqrt(s_squared_norm)/ (0.5 + s_squared_norm)\r\n # return scale * x\r\n s_squared_norm = K.sum(K.square(x), axis, keepdims=True)\r\n scale = K.sqrt(s_squared_norm + K.epsilon())\r\n return x / scale\r\n\r\n\r\nclass Capsule(Layer):\r\n def __init__(self, num_capsule, dim_capsule, routings=3, kernel_size=(9, 1), share_weights=True,\r\n activation='default', **kwargs):\r\n super(Capsule, self).__init__(**kwargs)\r\n self.num_capsule = num_capsule\r\n self.dim_capsule = dim_capsule\r\n self.routings = routings\r\n self.kernel_size = kernel_size\r\n self.share_weights = share_weights\r\n if activation == 'default':\r\n self.activation = squash\r\n else:\r\n self.activation = Activation(activation)\r\n\r\n def build(self, input_shape):\r\n super(Capsule, self).build(input_shape)\r\n input_dim_capsule = input_shape[-1]\r\n if self.share_weights:\r\n self.W = self.add_weight(name='capsule_kernel',\r\n shape=(1, input_dim_capsule,\r\n self.num_capsule * self.dim_capsule),\r\n # shape=self.kernel_size,\r\n initializer='glorot_uniform',\r\n trainable=True)\r\n else:\r\n input_num_capsule = input_shape[-2]\r\n self.W = self.add_weight(name='capsule_kernel',\r\n shape=(input_num_capsule,\r\n input_dim_capsule,\r\n self.num_capsule * self.dim_capsule),\r\n initializer='glorot_uniform',\r\n trainable=True)\r\n\r\n def call(self, u_vecs):\r\n if self.share_weights:\r\n u_hat_vecs = K.conv1d(u_vecs, self.W)\r\n else:\r\n u_hat_vecs = K.local_conv1d(u_vecs, self.W, [1], [1])\r\n\r\n batch_size = K.shape(u_vecs)[0]\r\n input_num_capsule = K.shape(u_vecs)[1]\r\n u_hat_vecs = K.reshape(u_hat_vecs, (batch_size, input_num_capsule,\r\n self.num_capsule, self.dim_capsule))\r\n u_hat_vecs = K.permute_dimensions(u_hat_vecs, (0, 2, 1, 3))\r\n # final u_hat_vecs.shape = [None, num_capsule, input_num_capsule, dim_capsule]\r\n\r\n b = K.zeros_like(u_hat_vecs[:, :, :, 0]) # shape = [None, num_capsule, input_num_capsule]\r\n for i in range(self.routings):\r\n b = K.permute_dimensions(b, (0, 2, 1)) # shape = [None, input_num_capsule, num_capsule]\r\n c = K.softmax(b)\r\n c = K.permute_dimensions(c, (0, 2, 1))\r\n b = K.permute_dimensions(b, (0, 2, 1))\r\n outputs = self.activation(K.batch_dot(c, u_hat_vecs, [2, 2]))\r\n if i < self.routings - 1:\r\n b = K.batch_dot(outputs, u_hat_vecs, [2, 3])\r\n\r\n return outputs\r\n\r\n def compute_output_shape(self, input_shape):\r\n return (None, self.num_capsule, self.dim_capsule)","repo_name":"zle1992/atec","sub_path":"models/layers/Attention.py","file_name":"Attention.py","file_ext":"py","file_size_in_byte":7351,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"48"}
+{"seq_id":"25655435005","text":"import sys\nfrom collections import defaultdict\n\nsys.setrecursionlimit(10 ** 7)\nrl = sys.stdin.readline\n\n\ndef factorization(n):\n arr = []\n temp = n\n for i in range(2, int(-(-n ** 0.5 // 1)) + 1):\n if temp % i == 0:\n cnt = 0\n while temp % i == 0:\n cnt += 1\n temp //= i\n arr.append([i, cnt])\n \n if temp != 1:\n arr.append([temp, 1])\n if not arr:\n arr.append([n, 1])\n \n return arr\n\n\ndef mod_div(x, y, mod=10 ** 9 + 7):\n return x * pow(y, mod - 2, mod) % mod\n\n\ndef solve():\n _ = int(rl())\n A = list(map(int, rl().split()))\n MOD = 10 ** 9 + 7\n \n max_exp = defaultdict(int)\n for ai in A:\n facts = factorization(ai)\n for fact, m in facts:\n if max_exp[fact] < m:\n max_exp[fact] = m\n \n lcm = 1\n for num, exp in max_exp.items():\n lcm = lcm * pow(num, exp, MOD) % MOD\n \n ans = sum([mod_div(lcm, ai) for ai in A]) % MOD\n print(ans)\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"ABC/ABC152/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"74681547984","text":"from __future__ import annotations\nimport shutil\nimport os\n\n\nimport xml.etree.ElementTree as ET\nfrom xml.etree.ElementTree import Element\n\nimport vsdx\nfrom .shapes import Shape\n\n\nclass Connect:\n \"\"\"Connect class to represent a connection between two `Shape` objects\"\"\"\n def __init__(self, xml: Element=None, page: vsdx.Page=None):\n if page is None:\n return\n if type(xml) is Element: # create from xml\n self.xml = xml\n self.page = page # type: vsdx.Page\n self.from_id = xml.attrib.get('FromSheet') # ref to the connector shape\n self.to_id = xml.attrib.get('ToSheet') # ref to the shape where the connector terminates\n self.from_rel = xml.attrib.get('FromCell') # i.e. EndX / BeginX\n self.to_rel = xml.attrib.get('ToCell') # i.e. PinX\n\n @staticmethod\n def create(page: vsdx.Page=None, from_shape: Shape = None, to_shape: Shape = None) -> Shape:\n \"\"\"Create a new Connect object between from_shape and to_shape\n\n :returns: a new Connect object\n :rtype: Shape\n \"\"\"\n\n if from_shape and to_shape: # create new connector shape and connect items between this and the two shapes\n # create new connect shape and get id\n media = vsdx.Media()\n connector_shape = media.straight_connector.copy(page) # default to straight connector\n connector_shape.text = '' # clear text used to find shape\n if not os.path.exists(page.vis._masters_folder):\n # Add masters folder to directory if not already present\n shutil.copytree(media._media_vsdx._masters_folder, page.vis._masters_folder)\n page.vis.load_master_pages() # load copied master page files into VisioFile object\n # add new master to document relationship\n page.vis._add_document_rel(rel_type=\"http://schemas.microsoft.com/visio/2010/relationships/masters\",\n target=\"masters/masters.xml\")\n # create masters/master1 elements in [Content_Types].xml\n page.vis._add_content_types_override(content_type=\"application/vnd.ms-visio.masters+xml\",\n part_name_path=\"/visio/masters/masters.xml\")\n page.vis._add_content_types_override(content_type=\"application/vnd.ms-visio.master+xml\",\n part_name_path=\"/visio/masters/master1.xml\")\n elif connector_shape.shape_name not in page.vis._titles_of_parts_list():\n print(f\"Warning: Updating existing Page/Master relationships not yet fully implemented. This may cause unexpected outputs.\")\n # vsdx has masters - but not this shape\n # todo: Complete this scenario\n #print(\"conn master page\", connector_shape.master_shape.page.filename)\n #print(\"max page file num\", [p.filename[-5:-4] for p in page.vis.master_pages])\n #print(\"max page id\", [p.page_id for p in page.vis.master_pages])\n rel_num = max([int(p.filename[-5:-4]) for p in page.vis.master_pages]) +1\n master_file_path = os.path.join(page.vis.directory, 'visio', 'masters', f'master{rel_num}.xml')\n #print(f\"m_num={rel_num} master_file_path={master_file_path}\")\n shutil.copy(connector_shape.master_shape.page.filename, master_file_path)\n # todo: ensure master page ID and RId is unique, update shape master_id to refer to new master\n # todo: update mast file name, and add content type override\n # todo: update masters.xml file contents?\n # todo: update visio/pages/_rels/page3.xml.rels - add:
\"\r\n f\"/api/v1.0/precipitation\"\r\n f\"- Dates and temperature observations from the last year
\"\r\n\r\n f\"/api/v1.0/stations\"\r\n f\"- List of stations
\"\r\n\r\n f\"/api/v1.0/tobs\"\r\n f\"- Temperature Observations from the past year
\"\r\n\r\n f\"/api/v1.0/
\"\r\n\r\n f\"/api/v1.0/
\"\r\n )\r\n\r\n@app.route(\"/api/v1.0/precipitation\")\r\ndef pcrp():\r\n today = datetime.datetime.today()\r\n today = today.date()\r\n last_year = today - datetime.timedelta(365)\r\n pcp_year = list(session.query(Measurement.date, Measurement.prcp).filter((Measurement.date <= today, Measurement.date >= last_year)).all())\r\n return jsonify(pcp_year)\r\n\r\n@app.route(\"/api/v1.0/stations\")\r\ndef station_list():\r\n st_list = session.query(Station.station).all()\r\n all_stations= list(np.ravel(st_list))\r\n return jsonify(all_stations)\r\n\r\n@app.route(\"/api/v1.0/tobs\")\r\ndef temp_year():\r\n today = datetime.datetime.today()\r\n today = today.date()\r\n last_year = today - datetime.timedelta(365)\r\n temp_year = session.query(Measurement.date, Measurement.tobs).filter((Measurement.date <= today, Measurement.date >= last_year)).all()\r\n return jsonify(temp_year)\r\n\r\n@app.route(\"/api/v1.0/
\"\r\n# f\"Available Routes:
\"\r\n\r\n# f\"/api/v1.0/precipitation
\"\r\n# f\"Returns dates and temperature from the last year.
\"\r\n\r\n# f\"/api/v1.0/stations
\"\r\n# f\"Returns a json list of stations.
\"\r\n\r\n# f\"/api/v1.0/tobs
\"\r\n# f\"Returns list of Temperature Observations(tobs) for previous year.
\"\r\n\r\n# f\"/api/v1.0/yyyy-mm-dd/
\"\r\n# f\"Returns an Average, Max, and Min temperatures for a given start date.
\"\r\n\r\n# f\"/api/v1.0/yyyy-mm-dd/yyyy-mm-dd/
\"\r\n# f\"Returns an Average, Max, and Min temperatures for a given date range.\"\r\n\r\n \r\n# )\r\n\r\n# # Note - here we are getting the db variables\r\n# # within the same thread that's servicing the request\r\n# # So we don't throw some programming error on Windows machines\r\n# @app.route(\"/api/v1.0/precipitation\")\r\n# def precipitation():\r\n# # connection to the db, session, tables\r\n# session, Measurement, Station = get_session_tables()\r\n# \"\"\"Return Dates and Temp from the last year.\"\"\"\r\n# precip_analysis = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= \"2016-08-23\").\\\r\n# filter(Measurement.date <= \"2017-08-23\").all()\r\n\r\n# # creates JSONified list\r\n# precipitation_list = [precip_analysis]\r\n\r\n# return jsonify(precipitation_list)\r\n\r\n# if __name__ == '__main__':\r\n# app.run(debug=True)","repo_name":"damianmc88/SQLAlchemy_Climate","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"7036930811","text":"#!/usr/bin/python3\n\"\"\"Write a function that queries the Reddit API and prints the titles\nof the first 10 hot posts listed for a given subreddit.\"\"\"\nimport requests\n\n\ndef top_ten(subreddit):\n \"\"\"Print first 10 hot posts listed for a given subreddit\"\"\"\n url = \"https://www.reddit.com/r/{}/hot/.json\".format(subreddit)\n headers = {\n \"User-Agent\": \"cyrusDev@alx-holbertonschool\"\n }\n params = {\n \"limit\": 10\n }\n response = requests.get(url, headers=headers, params=params,\n allow_redirects=False)\n if response.status_code == 404:\n print(\"None\")\n return\n posts = response.json().get(\"data\").get(\"children\")\n for post in posts:\n print(post.get(\"data\").get(\"title\"))\n","repo_name":"cyrusDev1/alx-system_engineering-devops","sub_path":"0x16-api_advanced/1-top_ten.py","file_name":"1-top_ten.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"13598491937","text":"#!/usr/bin/python3\n# MDDocGUI\nimport sys\nimport os\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QWidget, QCheckBox, QApplication, QMainWindow, QFileDialog, QTableView, QMessageBox\nfrom PyQt5.uic import loadUi\nimport time\nimport string\nfrom MDDoc import MDDoc\nfrom subprocess import call\nimport http.server\nimport socketserver\n# Load paremeters\n#import Param\n#Param.param.init('H:/cloud/cloud_data/Projects/REFT/Software/GUIApp/REFTCode/init/init.xml')\n#Param.param.read()\n#Param.param.printParams()\n\nfileDirMDDoc = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(fileDirMDDoc + '\\\\init')\nimport Param\n\nimport threading\nfrom shutil import copyfile, rmtree\nfrom YAML import YAML\n#param = Param('H:/cloud/cloud_data/Projects/MDDoc/init/init.xml')\n#param.read()\n\n\n \nclass MDDocGUI(QMainWindow):\n \n # Events\n keyPressed = QtCore.pyqtSignal(QtCore.QEvent)\n drawing = None\n orders = None\n params = None\n current_order = None\n milling = None\n doc = MDDoc()\n httpd = None\n doc_exist = False\n doc_open = False\n thread_server = None\n yaml = YAML()\n paramsRestart = dict() \n ui = None\n \n def __init__(self):\n # Init GUI \n print('test')\n Param.param.read()\n Param.param.printParams()\n self.params=Param.param.params;\n \n \n print('UIPath: ', self.params['UIPath'])\n UIPath = self.params['UIPath']\n super(MDDocGUI,self).__init__()\n \n self.ui = loadUi(UIPath, self)\n self.setWindowTitle('MDDoc')\n \n # Init parameter\n self.paramsRestart = self.yaml.load(self.params['ParamsRestartPath'])\n self.SourceFolder.setText(self.paramsRestart['SourceFolder'])\n self.DestinationFolder.setText(self.paramsRestart['DestinationFolder'])\n \n # Set callback functions\n self.CreateDocButton.clicked.connect(self.on_CreateDocButton)\n self.StatusLine.append(\"Initialization started\")\n self.SourceButton.clicked.connect(self.on_SourceButton)\n self.DestinationButton.clicked.connect(self.on_DestinationButtonButton)\n \n self.OpenDocButton.clicked.connect(self.on_OpenDocButton)\n self.CloseDocButton.clicked.connect(self.on_CloseDocButton)\n \n \n self.SourceFolder.textChanged.connect(self.on_textChanged_SourceFolder)\n self.DestinationFolder.textChanged.connect(self.on_textChanged_DestinationFolder)\n \n SourceFolder = self.SourceFolder.text()\n DestinationFolder = self.DestinationFolder.text()\n self.doc_exist = os.path.isfile(DestinationFolder + '/index.html')\n \n if (not os.path.isdir(SourceFolder)) or (not os.path.isdir(DestinationFolder)):\n self.CreateDocButton.setEnabled(False)\n \n self.OpenDocButton.setEnabled(self.doc_exist)\n self.CloseDocButton.setEnabled(self.doc_open)\n \n #self.ui.btnExit.clicked.connect(self.close)\n #self.ui.actionExit.triggered.connect(self.close)\n \n #self.milling = Milling.Milling('milling', self.params['DatabaseSQLitePath'])\n #reload(DrawingClass)\n \n # Drawing tab\n #self.LoadOrdersButton.clicked.connect(self.on_LoadOrdersButton)\n #self.CreateDrawingButton.clicked.connect(self.on_CreateDrawingButton)\n #self.OrdersTable.clicked.connect(self.on_clicked_OrdersTable) \n #self.StatusLine.append(\"Initialization started\")\n \n # Milling tab\n #self.LoadOrdersMillingButton.clicked.connect(self.on_LoadOrdersButton)\n #self.CreateMillingButton.clicked.connect(self.on_clicked_CreateMillingButton)\n #self.OrdersMillingTable.clicked.connect(self.on_clicked_OrdersMillingTable) \n \n def closeEvent(self, event):\n print(\"event\")\n reply = QtWidgets.QMessageBox.question(self, 'Message',\n \"Are you sure to quit?\", QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)\n\n if reply == QtWidgets.QMessageBox.Yes: \n self.paramsRestart['SourceFolder'] = self.SourceFolder.text()\n self.paramsRestart['DestinationFolder'] = self.DestinationFolder.text()\n self.yaml.save(self.paramsRestart, self.params['ParamsRestartPath'])\n event.accept()\n else:\n event.ignore()\n \n def serverfunc(self, DestinationFolder):\n os.chdir(DestinationFolder) \n PORT = 8000\n Handler = http.server.SimpleHTTPRequestHandler \n with socketserver.TCPServer((\"\", PORT), Handler) as self.httpd:\n self.httpd.serve_forever()\n self.StatusLine.append('Closing server')\n \n @pyqtSlot()\n def on_textChanged_SourceFolder(self):\n SourceFolder = self.SourceFolder.text()\n DestinationFolder = self.DestinationFolder.text()\n if (not os.path.isdir(SourceFolder)) or (not os.path.isdir(DestinationFolder)):\n self.CreateDocButton.setEnabled(False)\n else:\n self.CreateDocButton.setEnabled(True)\n \n @pyqtSlot()\n def on_textChanged_DestinationFolder(self):\n SourceFolder = self.SourceFolder.text()\n DestinationFolder = self.DestinationFolder.text()\n if (not os.path.isdir(SourceFolder)) or (not os.path.isdir(DestinationFolder)):\n self.CreateDocButton.setEnabled(False)\n else:\n self.CreateDocButton.setEnabled(True)\n self.doc_exist = os.path.isfile(DestinationFolder + '/index.html')\n self.OpenDocButton.setEnabled(self.doc_exist)\n\n \n @pyqtSlot()\n def on_CloseDocButton(self):\n print('on_CloseDocButton')\n self.httpd.shutdown()\n self.thread_server.join()\n #self.thread_server._stop()\n DestinationFolder = self.DestinationFolder.text()\n self.doc_exist = os.path.isfile(DestinationFolder + '/index.html')\n self.OpenDocButton.setEnabled(self.doc_exist)\n self.doc_open = False\n self.CloseDocButton.setEnabled(self.doc_open)\n \n @pyqtSlot()\n def on_OpenDocButton(self): \n DestinationFolder = self.DestinationFolder.text()\n if os.path.isdir(DestinationFolder):\n call([\"C:/Program Files/Mozilla Firefox/firefox.exe\", \"-new-window\", \"http://127.0.0.1:8000/\"]) \n self.thread_server = threading.Thread(target=self.serverfunc,args=[self.DestinationFolder.text()])\n self.thread_server.start()\n self.StatusLine.append('Opening server')\n self.doc_open = True\n self.CloseDocButton.setEnabled(self.doc_open)\n self.OpenDocButton.setEnabled(not self.doc_open)\n else:\n self.StatusLine.append('Destination folder not found!')\n self.doc_open = False\n self.CloseDocButton.setEnabled(self.doc_open)\n\n @pyqtSlot()\n def on_SourceButton(self): \n self.SourceFolder.setText(str(QFileDialog.getExistingDirectory(self, \"Select source folder\")))\n \n @pyqtSlot()\n def on_DestinationButtonButton(self): \n self.DestinationFolder.setText(str(QFileDialog.getExistingDirectory(self, \"Select destination folder\")))\n \n @pyqtSlot()\n def on_CreateDocButton(self): \n if self.CopyCheckBox.isChecked():\n # Deep copy\n sourceFolder = self.SourceFolder.text()\n destinationFolder = self.DestinationFolder.text()\n if not sourceFolder:\n self.StatusLine.append(\"Source folder is not defined!\")\n return\n if not destinationFolder:\n self.StatusLine.append(\"Target folder is not defined!\")\n return\n YMlFilepath = self.params['YMLPath']\n created = self.doc.createMKDocs(sourceFolder, destinationFolder, YMlFilepath)\n else:\n # Extract markdown files and copy in tmp folder\n sourceFolder = self.SourceFolder.text()\n destinationFolder = self.DestinationFolder.text() \n if not sourceFolder:\n self.StatusLine.append(\"Source folder is not defined!\")\n return\n if not destinationFolder:\n self.StatusLine.append(\"Target folder is not defined!\")\n return\n \n num=len(sourceFolder)\n for root, directories, filenames in os.walk(sourceFolder):\n files = [ file for file in filenames if file.endswith( ('.md') ) ]\n for filename in files: \n filepath = os.path.join(root,filename) \n src = filepath\n tmp_path = os.path.dirname(sourceFolder) + \"/tmp\"\n dst = tmp_path + src[num:] \n os.makedirs(os.path.dirname(dst), exist_ok=True)\n copyfile(src, dst)\n \n # Shellow copy\n dir_path = os.path.dirname(os.path.realpath(__file__))\n sourceFolder = dir_path + \"\\\\tmp\"\n destinationFolder = self.DestinationFolder.text()\n YMlFilepath = self.params['YMLPath']\n created = self.doc.createMKDocs(tmp_path, destinationFolder, YMlFilepath) \n \n # Delete tmp folder\n if os.path.exists(tmp_path) and os.path.isdir(tmp_path):\n rmtree(tmp_path)\n if created:\n self.StatusLine.append(\"Documentation creation succeeded.\")\n self.doc_exist = True\n self.OpenDocButton.setEnabled(True)\n else:\n self.StatusLine.append(\"Documentation creation failed.\")\n self.doc_exist = False\n self.OpenDocButton.setEnabled(False)\n \n #@pyqtSlot()\n def on_clicked_OrdersMillingTable(self, signal):\n row = signal.row()\n parameter = self.orders[row][2]\n self.updateParameter(parameter)\n self.current_order = self.orders[row]\n \n #@pyqtSlot()\n def on_clicked_OrdersTable(self, signal):\n row = signal.row()\n parameter = self.orders[row][2]\n self.updateParameter(parameter)\n self.current_order = self.orders[row]\n \n @pyqtSlot()\n def on_LoadOrdersButton(self):\n \n print('on_LoadOrdersButton')\n # Init OrdersTable\n self.orders = self.drawing.database.getOrders()\n self.OrdersTable.setSelectionBehavior(QTableView.SelectRows);\n self.OrdersMillingTable.setSelectionBehavior(QTableView.SelectRows);\n self.model = QtGui.QStandardItemModel(parent=self)\n self.model.takeRow\n header = ['OrderID', 'FurnitureID', 'Paremter']\n self.model.setHorizontalHeaderLabels(header)\n \n # Set orders data\n row = 0\n for o in self.orders:\n for column in range(len(header)):\n item = QtGui.QStandardItem()\n item.setText(str(o[column]))\n self.model.setItem(row, column, item)\n row = row + 1\n self.OrdersTable.setModel(self.model)\n self.OrdersMillingTable.setModel(self.model)\n \n @pyqtSlot()\n def on_CreateDrawingButton(self): \n # Start FreeCAD and open furniture\n furnitureID = self.current_order[0]\n column = 'name'\n furnitureName = self.drawing.database.getFurniture(furnitureID, column)[0][0]\n furnituresPath = self.drawing.database.getParameter('furnituresPath')[0]\n furnitureFilePath = furnituresPath + '/' + furnitureName + '/' + furnitureName + '.FCStd'\n freecadPath = self.params['FreeCADPath']\n self.drawing.startFreecad(furnitureFilePath, freecadPath)\n \n def updateParameter(self, parameter):\n \n # Split milling part names\n self.Parameters.setText('')\n params = parameter.split(\",\")\n for txt in params:\n txt=txt.replace(\" \", \"\")\n self.Parameters.append(txt)\n \ndef isfloat(x):\n try:\n float(x)\n except ValueError:\n return False\n else:\n return True\n\ndef isint(x):\n try:\n int(x)\n except ValueError:\n return False\n else:\n return True\n\ndef startGUI():\n # Start GUI\n app = QApplication(sys.argv)\n widget = MDDocGUI()\n widget.show();\n app.aboutToQuit.connect(app.deleteLater)\n sys.exit(app.exec_())\n \ndef main():\n\n # Start GUI\n startGUI()\n \nif __name__ == '__main__':\n main()","repo_name":"Berni1557/MDDoc","sub_path":"MDDocGUI.py","file_name":"MDDocGUI.py","file_ext":"py","file_size_in_byte":12550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"26219942262","text":"\"\"\"\napi.py\n- provides the API endpoints for consuming and producing\n REST requests and responses\n\"\"\"\n\nfrom flask import request\nfrom flask_restful import Resource\nfrom datetime import datetime, timedelta\n\nimport json\nimport requests\n\n# Free API limits - 5 requests per minute and 500 per day\nAV_API_URL = \"https://www.alphavantage.co/query?apikey=9G4G4R3GA5E5ENSZ&\"\n\n# Data store init state\nstore = {\n 'cash_value': 0,\n 'portfolio': {\n 'VFINX': {\n # 'name': 'Vanguard 500 Index Fund Investor Shares',\n 'quantity': 0,\n 'price': None,\n },\n 'NAESX': {\n # 'name': 'Vanguard Small Capitalization Index Fund Investor Shares',\n 'quantity': 0,\n 'price': None,\n },\n 'VGTSX': {\n # 'name': 'Vanguard Total International Stock Index Fund Investor Shares',\n 'quantity': 0,\n 'price': None,\n },\n 'VBMFX': {\n # 'name': 'Vanguard Total Bond Market Index Fund Investor Shares',\n 'quantity': 0,\n 'price': None,\n }\n },\n 'last_updated': { # when was the price last updated from Alpha Vantage\n 'VFINX': None,\n 'NAESX': None,\n 'VGTSX': None,\n 'VBMFX': None,\n },\n}\n\n\nclass Cash(Resource):\n def get(self):\n # Default to 200 OK\n return {'cashValue': store['cash_value']}\n\n def post(self):\n data = request.get_json()\n transfer_amount = float(data['transferAmount'])\n\n if store['cash_value'] + transfer_amount < 0:\n return {}, 403 # Forbidden\n else:\n store['cash_value'] += transfer_amount\n return {}, 200\n\n\nclass Portfolio(Resource):\n def get(self):\n status_code = 200\n for symbol in store['portfolio']:\n stock = store['portfolio'][symbol]\n # Only update from Alpha Vantage for first time or max once every 5 minutes\n if store['last_updated'][symbol] == None or datetime.now() - store['last_updated'][symbol] > timedelta(seconds=5*60):\n response = requests.get(\n AV_API_URL + 'function=GLOBAL_QUOTE&symbol=' + symbol)\n try:\n # This works because stock is just a pointer\n stock['price'] = float(\n response.json()[\"Global Quote\"][\"05. price\"])\n store['last_updated'][symbol] = datetime.now()\n except:\n status_code = 429 # Too Many Requests\n\n return {'portfolio': store['portfolio']}, status_code\n\n\nclass Stock(Resource):\n def post(self, symbol):\n stock = store['portfolio'][symbol]\n data = request.get_json()\n transfer_amount = int(data['transferAmount'])\n\n if stock['quantity'] + transfer_amount < 0:\n return {}, 403 # Forbidden\n elif transfer_amount * stock['price'] > store['cash_value']:\n # Make sure they have enough money\n return {}, 403\n else:\n stock['quantity'] += transfer_amount\n store['cash_value'] -= transfer_amount * stock['price']\n return {}, 200\n","repo_name":"viv-li/bonsai","sub_path":"backend/bonsaiapi/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"20689504016","text":"def solution1(a, b, k):\n count_tiny = 0\n concat_numbers = []\n for i, j in zip(a, reversed(b)):\n temp_j = j\n count_digits = 0\n while temp_j != 0:\n temp_j = temp_j // 10\n count_digits += 1\n concat_number = i * count_digits + j\n concat_numbers.append(concat_number)\n for num in concat_numbers:\n if num < k:\n count_tiny += 1\n return count_tiny\nprint(solution1([1,2,3], [1,2,3], 31))\n\ndef solution(a, k):\n list_of_sums = []\n count = 0\n for i in range(len(a) - 1):\n for j in range(i+1, len(a)):\n list_of_sums.append(a[i] + a[j])\n for num in list_of_sums:\n if num % k == 0:\n count += 1\n return count\n\ndef solution2(a, k):\n nums = [a[i] + a[j] for i in range(len(a) - 1) for j in range(i+1, len(a)) if (a[i] + a[j]) % k == 0]\n print(nums)\n return len(nums)\nprint(solution2([1, 2, 3, 4, 5], 3))\n\ndef solution(a, k):\n if k == 0:\n return 0\n else:\n return len([a[i] + a[j] for i in range(len(a) - 1) for j in range(i+1, len(a)) \\\n if (a[i] + a[j]) % k == 0])","repo_name":"nadia-paz/ds-learning","sub_path":"python/data_structures/exercises2.py","file_name":"exercises2.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"13235107821","text":"# classwork\ndef doNow(s):\n if len(s) >= 3:\n if s[-3:] == \"ing\":\n return s + \"ly\"\n else:\n return s + \"ing\"\n else:\n return s\n\ndef oddIndex(s):\n return s[::2]\n\n\ndef count(s):\n searched = \"\"\n for i in range(0, len(s)):\n if searched.count(s[i]) == 0:\n searched += s[i]\n if s.count(s[i]) > 1:\n print(s[i], s.count(s[i]))\n\n# homework\ndef index(s, c):\n for i in range(len(s)):\n if(s[i] == c):\n print(\"Current character\", s[i], \"position at\", i)\n\n\n# challenge\ndef replace(s):\n n = s.find(\"not\")\n p = s.find(\"poor\")\n if n == -1 or p == -1:\n return s\n\n n += 3\n\n return s[:p] + \"good\" + s[n:]\n\ndef caesar(s, shift):\n ans = \"\"\n for i in range(0, len(s)):\n if 97 <= ord(s[i]) <= 122:\n ans += chr((((ord(s[i]) - 97) - shift) % 26) + 97)\n elif 65 <= ord(s[i]) <= 90:\n ans += chr((((ord(s[i]) - 65) - shift) % 26) + 65)\n else:\n ans += s[i]\n\n return ans\n","repo_name":"aaaronhsu/MKS22QA","sub_path":"Unit 2 - Strings and Lists/2_25moreStrings.py","file_name":"2_25moreStrings.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"2477918955","text":"import csv\n\n\nclass Loan:\n '''\n Loan class.\n '''\n\n def __init__(self, id, interest_rate, default_likelihood, amount, state):\n '''\n :param id: str, loan id\n :param interest_rate: float, interest rate\n :param default_likelihood: float, default likelihood\n :param amount: int, amount\n :param state: str, state code\n id: facility if only if assigned\n '''\n self.id = id\n self.interest_rate = interest_rate\n self.default_likelihood = default_likelihood\n self.amount = amount\n self.state = state\n self.facility_id = None\n\n def __repr__(self):\n return (\n f'Loan [id:{self.id}, '\n f'interest_rate:{self.interest_rate}, '\n f'default_likelihood:{self.default_likelihood}, '\n f'amount:{self.amount}, '\n f'state:{self.state}]'\n )\n\n @staticmethod\n def load(file):\n '''\n Load plain Loans objects from the input file.\n\n :param file: path to loans.csv\n '''\n loan_dict = csv.DictReader(open(file, mode='r'))\n loans = []\n\n for line in loan_dict:\n loan = Loan(id=line['id'],\n amount=int(line['amount']),\n interest_rate=float(line['interest_rate']),\n default_likelihood=float(line['default_likelihood']),\n state=line['state'])\n loans.append(loan)\n\n return loans\n","repo_name":"beaglebagel/code_sample","sub_path":"sample_1/loan.py","file_name":"loan.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"27805904390","text":"'''\nCreated on Oct 5, 2016\n\n@author: fredrik\n'''\n'''\nCreated on Oct 3, 2016\n\n@author: fredrik\n'''\n\nimport numpy as np\nimport os\nfrom os.path import dirname, join\nfrom bokeh.plotting import Figure\nfrom bokeh.models import ColumnDataSource, Range1d\nfrom bokeh.models.widgets import Select\nfrom classVeWK3 import varyingElastance\n\nimport h5py\n\n\nclass SetupApp:\n \n def __init__(self):\n \n \n self.T = 1.\n N = 250\n self.cardiacCycles = 5\n self.t = np.linspace(0, self.T*self.cardiacCycles, N*self.cardiacCycles + 1)\n\n self.veWK3 = varyingElastance(self.t, self.T)\n \n t, P, P_LV, Q, E, V = self.veWK3.solveNCycle(Ncycles=self.cardiacCycles)\n t_last_cycle = np.linspace(self.T*(self.cardiacCycles - 1), self.T*(self.cardiacCycles - 0), 1001)\n P_last, P_LV_last, Q_last, E_last, V_last = self.getLastCycle(t_last_cycle, t, P, P_LV, Q, E, V)\n \n self.source_p = ColumnDataSource(data=dict(x=t, y=P))\n self.source_p_LV = ColumnDataSource(data=dict(x=t, y=P_LV))\n self.source_LV_loop = ColumnDataSource(data=dict(x=V, y=P_LV))\n \n self.source_p_last = ColumnDataSource(data=dict(x=t_last_cycle, y=P_last))\n self.source_p_LV_last = ColumnDataSource(data=dict(x=t_last_cycle, y=P_LV_last))\n self.source_q_last = ColumnDataSource(data=dict(x=t_last_cycle, y=Q_last))\n self.source_E_last = ColumnDataSource(data=dict(x=[], y=[]))\n # Set up plot_line y = a*x + b\n self.plot_P = Figure(plot_height=400, plot_width=550, title=\"aortic and ventricular pressure\",\n x_axis_label=\"t\", y_axis_label=\"P [mmHg]\",\n tools=\"crosshair,pan,reset,save,wheel_zoom\",\n y_range=[0, 200])\n self.plot_LV_loop = Figure(plot_height=400, plot_width=550, title=\"PV-loop\",\n x_axis_label=\"V [ml]\", y_axis_label=\"P [mmHg]\",\n tools=\"crosshair,pan,reset,save,wheel_zoom\",\n x_range=[0, 200], y_range=[0, 200])\n\n self.plot_P_last = Figure(plot_height=400, plot_width=550, title=\"aortic and ventricular pressure (last cardiac cycle)\",\n x_axis_label=\"t\", y_axis_label=\"P [mmHg]\",\n tools=\"crosshair,pan,reset,save,wheel_zoom\",\n y_range=[0, 200])\n\n self.plot_flow_or_elastance_last = Figure(plot_height=400, plot_width=550, title=\"flow\",\n x_axis_label=\"t\", y_axis_label=\"flow [ml/s]\",\n tools=\"crosshair,pan,reset,save,wheel_zoom\",\n )\n \n self.plot_P.line('x', 'y', source=self.source_p, color='blue', line_alpha=0.6, line_width=2)\n self.plot_P.line('x', 'y', source=self.source_p_LV, color='green', line_alpha=0.6, line_width=2)\n\n self.plot_LV_loop.line('x', 'y', source=self.source_LV_loop, color='blue', line_alpha=0.6, line_width=2)\n \n self.plot_P_last.line('x', 'y', source=self.source_p_last, color='blue', line_alpha=0.6, line_width=2, legend=\"aorta\")\n self.plot_P_last.line('x', 'y', source=self.source_p_LV_last, color='green', line_alpha=0.6, line_width=2, legend=\"left ventricle\")\n \n self.plot_flow_or_elastance_last.line('x', 'y', source=self.source_q_last, color='blue', line_alpha=0.6, line_width=2)\n self.plot_flow_or_elastance_last.line('x', 'y', source=self.source_E_last, color='blue', line_alpha=0.6, line_width=2)\n \n self.resistanceSelect = Select(title=\"selcet total resistance\", value=\"1.25\", options=[\"1\", \"1.25\", \"1.5\"])\n self.resistanceFactorSelect = Select(title=\"selcet factor for proximal resistance\", value=\"0.1\", options=[\"0.05\", \"0.1\", \"0.15\", \"0.2\"])\n self.complianceSelect = Select(title=\"selcet total compliance\", value=\"2.0\", options=[\"1\", \"1.5\", \"2.0\", \"2.5\"])\n self.eMaxSelect = Select(title=\"selcet E max\", value=\"2.0\", options=[\"1\", \"1.5\", \"2.0\", \"2.5\"])\n self.eMinSelect = Select(title=\"selcet E min\", value=\"0.06\", options=[\"0.03\", \"0.06\", \"0.09\", \"0.12\"])\n self.tPeakSelect = Select(title=\"selcet time to peak\", value=\"0.32\", options=[\"0.25\", \"0.28\", \"0.30\", \"0.32\"])\n self.RvSelect = Select(title=\"selcet mitral resistance\", value=\"0.005\", options=[\"0.0025\", \"0.005\", \"0.01\", \"0.05\"])\n self.n1Select = Select(title=\"select elastance shape-function n1\", value=\"1.32\", options=[\"1.1\", \"1.2\", \"1.32\", \"1.4\"])\n self.n2Select = Select(title=\"select elastance shape-function n2\", value=\"21.9\", options=[\"15\", \"21.9\", \"25\", \"30\"])\n self.flowOrElastanceSelect = Select(title=\"show flow or elastance\", value=\"flow\", options=[\"flow\", \"elastance\"])\n self.nCyclesSelect = Select(title=\"select number of cycles\", value=\"5\", options=[\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\"])\n self.nTimePointsSelect = Select(title=\"select time-points per cycle\", value=\"250\", options=[\"100\", \"150\", \"200\", \"250\", \"500\", \"1000\", \"2000\", \"3000\", \"4000\", \"5000\", \"6000\", \"7000\", \"8000\", \"9000\", \"10000\"])\n\n self.symbolicSelect = Select(title=\"use symbolic differentiation\", value=\"True\", options=[\"True\", \"False\"])\n self.isoSelect = Select(title=\"use integrated iso eq\", value=\"True\", options=[\"True\", \"False\"])\n\n \n\n\n self.Widgetlist = [self.resistanceSelect, self.resistanceFactorSelect, self.complianceSelect,\n self.eMaxSelect, self.eMinSelect, self.tPeakSelect, self.RvSelect,\n self.n1Select, self.n2Select, self.flowOrElastanceSelect, self.nCyclesSelect, \n self.nTimePointsSelect, self.symbolicSelect, self.isoSelect]\n \n def update_data(self, attrname, old, new):\n \n \n R_tot = float(self.resistanceSelect.value)\n\n R_factor = float(self.resistanceFactorSelect.value)\n C_tot = float(self.complianceSelect.value)\n Emax = float(self.eMaxSelect.value)\n\n Emin = float(self.eMinSelect.value)\n TPeak = float(self.tPeakSelect.value)\n Rv = float(self.RvSelect.value)\n n1 = float(self.n1Select.value)\n n2 = float(self.n2Select.value)\n flowOrElastance = self.flowOrElastanceSelect.value\n self.cardiacCycles = int(self.nCyclesSelect.value)\n symbolic_differentiation = (self.symbolicSelect.value)\n integrated_iso_eq = (self.isoSelect.value)\n N = int(self.nTimePointsSelect.value)\n t = np.linspace(0, self.T*self.cardiacCycles, N*self.cardiacCycles + 1)\n \n \n \n self.veWK3.initializeWKParams(R_tot=R_tot, C_tot=C_tot, R1_frac=R_factor)\n self.veWK3.Emax = Emax\n self.veWK3.Emin = Emin\n self.veWK3.TPeak = TPeak\n self.veWK3.Rv = Rv\n self.veWK3.n1 = n1\n self.veWK3.n2 = n2\n \n if symbolic_differentiation == \"True\":\n self.veWK3.symbolic_differentiation = True\n else:\n self.veWK3.symbolic_differentiation = False\n\n if integrated_iso_eq == \"True\":\n self.veWK3.integrated_iso_eq = True\n else:\n self.veWK3.integrated_iso_eq = False\n \n self.veWK3.t = t\n t, P, P_LV, Q, E, V = self.veWK3.solveNCycle(Ncycles=self.cardiacCycles)\n \n t_last_cycle = np.linspace(self.T*(self.cardiacCycles - 1), self.T*(self.cardiacCycles - 0), 1001)\n \n P_last, P_LV_last, Q_last, E_last, V_last = self.getLastCycle(t_last_cycle, t, P, P_LV, Q, E, V)\n \n self.source_p.data = dict(x=t, y=P)\n self.source_p_LV.data = dict(x=t, y=P_LV)\n self.source_LV_loop.data = dict(x=V_last, y=P_LV_last)\n self.source_p_last.data = dict(x=t_last_cycle, y=P_last)\n self.source_p_LV_last.data = dict(x=t_last_cycle, y=P_LV_last)\n \n if flowOrElastance == \"flow\":\n self.source_q_last.data = dict(x=t_last_cycle, y=Q_last)\n self.source_E_last.data = dict(x=[], y=[])\n self.plot_flow_or_elastance_last.title.text = \"flow\"\n self.plot_flow_or_elastance_last.yaxis.axis_label = \"flow [ml/s]\"\n else:\n self.source_q_last.data = dict(x=[], y=[])\n self.source_E_last.data = dict(x=t_last_cycle, y=E_last)\n self.plot_flow_or_elastance_last.title.text = \"elastance\"\n self.plot_flow_or_elastance_last.yaxis.axis_label = \"E [mmHg/ml]\"\n \n \n #self.plotQ.title.text = \"Qm = ({0}, {1}); (reference, ecmo)\".format(Qm, Qm_ecmo)\n \n def getLastCycle(self, t_last, t, P, P_LV, Q, E, V):\n \n P_last = np.interp(t_last, t, P)\n P_LV_last = np.interp(t_last, t, P_LV)\n Q_last = np.interp(t_last, t, Q)\n E_last = np.interp(t_last, t, E)\n V_last = np.interp(t_last, t, V)\n \n return P_last, P_LV_last, Q_last, E_last, V_last\n \n\n","repo_name":"Fredf10/apps","sub_path":"VeWK3/classCreateSimpleApp.py","file_name":"classCreateSimpleApp.py","file_ext":"py","file_size_in_byte":9069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"24028555215","text":"import cv2\r\nimport numpy\r\nimport face_recognition\r\nimport os\r\n\r\npath = \"img\"\r\nimages = []\r\nclassNames = []\r\nmyList = os.listdir(path)\r\nprint(myList)\r\n\r\nfor i in myList:\r\n #loads the images\r\n currImg = cv2.imread(f'{path}/{i}')\r\n images.append(currImg)\r\n #without .jpg\r\n classNames.append(os.path.splitext(i)[0])\r\nprint(images)\r\nprint(classNames)\r\n\r\ndef findEncoding(images):\r\n encodeList = []\r\n \r\n for img in images:\r\n # for better Results\r\n img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\r\n \r\n # recognize the face\r\n encode = face_recognition.face_encodings(img)[0]\r\n encodeList.append(encode)\r\n return encodeList\r\n\r\nencodeList = findEncoding(images)\r\nprint(\"Encoding Completed\\n\")\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n # cap.read() return 2 content\r\n success, img = cap.read()\r\n\r\n # size reduce will speed the process 1/4th\r\n imgS = cv2.resize(img,(0,0),None,0.25,0.25)\r\n imgS = cv2.cvtColor(imgS,cv2.COLOR_BGR2RGB)\r\n\r\n facesCurrFrame = face_recognition.face_locations(imgS)\r\n encodeCurrFrame = face_recognition.face_encodings(imgS,facesCurrFrame)\r\n\r\n for encodeFace,faceLoc in zip(encodeCurrFrame,facesCurrFrame):\r\n matches = face_recognition.compare_faces(encodeList,encodeFace)\r\n faceDis = face_recognition.face_distance(encodeList,encodeFace)\r\n #print(faceDis)\r\n matchIndex = numpy.argmin(faceDis)\r\n if matches[matchIndex]:\r\n name = classNames[matchIndex]\r\n #print(name)\r\n y1,x2,y2,x1 = faceLoc\r\n y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4\r\n # form rectange around the face\r\n cv2.rectangle(img,(x1,y1),(x2,y2),(564,255,0),2)\r\n # form rectangle in which we write name\r\n cv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)\r\n # for name\r\n cv2.putText(img, name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)\r\n \r\n cv2.imshow('Webcam',img)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n# Release handle to the webcam\r\nvideo_capture.release()\r\ncv2.destroyAllWindows()","repo_name":"Dikshant20011891/Face-Recognition","sub_path":"faceRecog.py","file_name":"faceRecog.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"11932911187","text":"import shutil\nimport tempfile\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import override_settings\n\nfrom posts.models import Comment, Post\nfrom .test_config import CREATE_REVERSE, BaseTestCase\n\nSMALL_JPG = (\n b'\\x47\\x49\\x46\\x38\\x39\\x61\\x02\\x00'\n b'\\x01\\x00\\x80\\x00\\x00\\x00\\x00\\x00'\n b'\\xFF\\xFF\\xFF\\x21\\xF9\\x04\\x00\\x00'\n b'\\x00\\x00\\x00\\x2C\\x00\\x00\\x00\\x00'\n b'\\x02\\x00\\x01\\x00\\x00\\x02\\x02\\x0C'\n b'\\x0A\\x00\\x3B'\n)\nUPLOADED = SimpleUploadedFile(\n name='small.jpg',\n content=SMALL_JPG,\n content_type='image/jpg'\n)\nUPLOADED_EDIT = SimpleUploadedFile(\n name='small_edit.jpg',\n content=SMALL_JPG,\n content_type='image/jpg'\n)\nPATH_TO_IMAGE = f'posts/{UPLOADED.name}'\nPATH_TO_IMAGE_EDIT = f'posts/{UPLOADED_EDIT.name}'\nTEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)\n\n\n@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)\nclass PostFormTests(BaseTestCase):\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)\n\n def test_create_post_show_correct_context(self):\n \"\"\"Шаблон create_form сформирован с правильным контекстом.\"\"\"\n responses = {\n self.authors_client.get(CREATE_REVERSE):\n 'create',\n self.authors_client.get(\n self.POST_EDIT_REVERSE): 'edit'\n }\n for response, act in responses.items():\n if act == 'create':\n form_fields = {\n 'text': forms.fields.CharField,\n 'group': forms.models.ModelChoiceField\n }\n for value, expected in form_fields.items():\n with self.subTest(value=value):\n form_field = response.context['form'].fields[value]\n self.assertIsInstance(form_field, expected)\n elif act == 'edit':\n form_instance = response.context['form'].instance\n self.assertEqual(form_instance, self.posts)\n\n def test_post_form_create_post(self):\n \"\"\"Валидная форма создает пост\"\"\"\n posts_count = Post.objects.count()\n form_data = {\n 'text': 'Test text',\n 'group': self.first_group.pk,\n 'image': UPLOADED\n }\n self.authors_client.post(\n CREATE_REVERSE,\n data=form_data,\n follow=True\n )\n post = Post.objects.latest('pub_date')\n self.assertEqual(Post.objects.count(), posts_count + 1)\n self.assertEqual(post.text, form_data['text'])\n self.assertEqual(post.group.pk, form_data['group'])\n self.assertEqual(post.author, self.author)\n self.assertEqual(post.image, PATH_TO_IMAGE)\n\n def test_post_form_edit_post(self):\n \"\"\"Валидная форма редактирует пост\"\"\"\n post_count = Post.objects.all().count()\n form_data_edit = {\n 'text': 'Edited',\n 'group': self.first_group.pk,\n 'image': UPLOADED_EDIT\n }\n response = self.authors_client.post(\n self.POST_EDIT_REVERSE,\n data=form_data_edit,\n follow=True\n )\n post = Post.objects.get(text=form_data_edit['text'])\n\n self.assertRedirects(response, self.POST_DETAIL_REVERSE)\n self.assertEqual(post_count, Post.objects.all().count())\n self.assertEqual(post.text, form_data_edit['text'])\n self.assertEqual(post.group.id, form_data_edit['group'])\n self.assertEqual(post.author, self.author)\n self.assertEqual(post.image, PATH_TO_IMAGE_EDIT)\n\n\nclass CommentFormTest(BaseTestCase):\n def test_authorized_user_comment_post(self):\n comment_count = Comment.objects.all().count()\n comment_data = {\n 'text': 'Test comment',\n 'post': self.posts,\n 'author': self.author\n }\n response = self.authors_client.post(\n self.COMMENT_REVERSE,\n data=comment_data,\n follow=True\n )\n self.assertRedirects(\n response, self.POST_DETAIL_REVERSE\n )\n created_comment = Comment.objects.latest('created')\n self.assertEqual(Comment.objects.all().count(), comment_count + 1)\n self.assertEqual(created_comment.text, comment_data['text'])\n self.assertEqual(created_comment.post, comment_data['post'])\n self.assertEqual(created_comment.author, comment_data['author'])\n response = self.authors_client.get(\n self.POST_DETAIL_REVERSE)\n self.assertIn(created_comment, response.context['comments'])\n","repo_name":"alekswonder/Yatube","sub_path":"yatube/posts/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":4760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"37787200501","text":"def fac(n):\n if n==1:\n return 1\n else:\n return n*fac(n-1)\n\n\nprint(fac(6))\n\n#斐波那契数列\ndef fib(n):\n if n==1:\n return 1\n elif n==2:\n return 1\n else:\n return fib(n-1)+fib(n-2)\n\n#斐波那契数列第六位上的数\nprint(fib(6))\n\n#输出这个数列前六位\nfor i in range(1,7):\n print(fib(i))","repo_name":"weeinee/python-study","sub_path":"project/递归函数.py","file_name":"递归函数.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15530218595","text":"\"\"\"Feature selection.\n\n\"\"\"\n\n\n# import numba as nb\nimport numpy as np\nimport pandas as pd\nimport sklearn as skl\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import Lasso\nfrom unipy.stats.formula import from_formula\nfrom unipy.stats.metrics import vif\n\n\n__all__ = ['lasso_rank',\n 'feature_selection_vif']\n\n\n# Defining a Lasso generic function\ndef _lasso_for_loop(data, X=None, y=None, alpha=.0001, *args, **kwargs):\n\n # Fit to the model\n lassoReg = Lasso(alpha=alpha, fit_intercept=True,\n normalize=True, precompute=False,\n max_iter=1e5, tol=1e-7,\n warm_start=False, positive=False,\n selection='cyclic', *args, **kwargs)\n\n lassoReg.fit(data[X], data[y].squeeze())\n yPredict = lassoReg.predict(data[X])\n\n # Return the result in pre-defined format\n rss = np.sum((yPredict - data[y].squeeze()) ** 2)\n ret = [rss]\n ret.extend([lassoReg.intercept_])\n ret.extend(lassoReg.coef_)\n\n return ret, yPredict\n\n\ndef lasso_rank(formula=None, X=None, y=None, data=None,\n alpha=np.arange(1e-5, 1e-2, 1e-4), k=2, plot=False,\n *args, **kwargs):\n \"\"\"Feature selection by LASSO regression.\n\n Parameters\n ----------\n formula:\n R-style formula string\n\n X: list-like\n Column values for X.\n\n y: list-like\n A column value for y.\n\n data: pandas.DataFrame\n A DataFrame.\n\n alpha: Iterable\n An Iterable contains alpha values.\n k: int\n Threshold of coefficient matrix\n\n plot: Boolean (default: False)\n True if want to plot the result.\n\n Returns\n -------\n rankTbl: pandas.DataFrame\n Feature ranking by given ``k``.\n\n minIntercept: pandas.DataFrame\n The minimum intercept row in coefficient matrix.\n\n coefMatrix: pandas.DataFrame\n A coefficient matrix.\n\n kBest: pandas.DataFrame\n When Given ``k``, The best intercept row in coefficient matrix.\n\n kBestPredY: dict\n A predicted ``Y`` with ``kBest`` alpha.\n\n Example\n -------\n >>> import unipy.dataset.api as dm\n >>> dm.init()\n ['cars', 'anscombe', 'iris', 'nutrients', 'german_credit_scoring_fars2008', 'winequality_red', 'winequality_white', 'titanic', 'car90', 'diabetes', 'adult', 'tips', 'births_big', 'breast_cancer', 'air_quality', 'births_small']\n >>> wine_red = dm.load('winequality_red')\n Dataset : winequality_red\n >>>\n >>> ranked, best_by_intercept, coefTbl, kBest, kBestPred = lasso_rank(X=wine_red.columns.drop('quality'), y=['quality'], data=wine_red)\n >>> ranked\n rank lasso_coef abs_coef\n volatile_acidity 1 -0.675725 0.675725\n alcohol 2 0.194865 0.194865\n >>> best_by_intercept\n RSS Intercept fixed_acidity volatile_acidity \\\n alpha_0.00121 691.956364 3.134874 0.002374 -1.023793\n\n citric_acid residual_sugar chlorides free_sulfur_dioxide \\\n alpha_0.00121 0.0 0.0 -0.272912 -0.0\n\n total_sulfur_dioxide density pH sulphates alcohol \\\n alpha_0.00121 -0.000963 -0.0 -0.0 0.505956 0.264552\n\n var_count\n alpha_0.00121 6\n >>>\n \"\"\"\n if formula is not None:\n X, y = from_formula(formula)\n else:\n X = list(X)\n y = y\n\n # Iterate over the alpha values\n coefMatrix = {'alpha_%.5f' % a: _lasso_for_loop(data, X=X, y=y, alpha=a, *args, **kwargs)[0] for a in alpha}\n predict = {'alpha_%.5f' % a: _lasso_for_loop(data, X=X, y=y, alpha=a, *args, **kwargs)[1] for a in alpha}\n\n coefMatrix = pd.DataFrame(coefMatrix).T\n coefMatrix.columns = ['RSS', 'Intercept'] + X\n coefMatrix['var_count'] = coefMatrix.apply(np.count_nonzero, axis=1) - 2\n\n # Filter by thresh >= var_count\n kBest = coefMatrix[coefMatrix['var_count'] <= k]\n kBest = kBest.loc[kBest[['var_count']].idxmax()]\n kBest = kBest.loc[kBest[['Intercept']].idxmin()]\n\n # Minumum Intercept\n minIntercept = coefMatrix.loc[coefMatrix[['Intercept']].idxmin()]\n\n # Get Predicted Y value\n alphaVal = kBest.index[0]\n kBestPredY = {alphaVal: predict[alphaVal]}\n\n # Get a Rank Table\n lassoVal = kBest.iloc[:, kBest.squeeze().nonzero()[0].tolist()[2:-1]]\n filteredTbl = pd.concat([lassoVal.T, abs(lassoVal).T], axis=1)\n filteredTbl.columns = ['lasso_coef', 'abs_coef']\n filteredTbl = filteredTbl.sort_values(by='abs_coef', ascending=False)\n filteredTbl['rank'] = range(1, len(filteredTbl) + 1)\n rankTbl = filteredTbl[['rank', 'lasso_coef', 'abs_coef']]\n\n # Plots\n #fig = plt.figure(figsize=(12, 9))\n #title = 'Top {} variables : absolute coefficient by Lasso'.format(len(filteredTbl))\n #rankTbl['abs_coef'].plot(kind='barh')\n #fig.suptitle(title, fontsize=14, fontweight='bold')\n #plt.tight_layout(pad=5)\n\n return rankTbl, minIntercept, coefMatrix, kBest, kBestPredY\n\n\ndef feature_selection_vif(data, thresh=5.0):\n '''Stepwise Feature Selection for multivariate analysis.\n\n It calculates OLS regressions and the variance inflation factors iterating\n all explanatory variables. If the maximum VIF of a variable is over the\n given threshold, It will be dropped. This process is repeated until all\n VIFs are lower than the given threshold.\n\n Recommended threshold is lower than 5, because if VIF is greater than 5,\n then the explanatory variable selected is highly collinear with the other\n explanatory variables, and the parameter estimates will have large standard\n errors because of this.\n\n Parameters\n ----------\n data : DataFrame, (rows: observed values, columns: multivariate variables)\n design dataframe with all explanatory variables, as for example used in\n regression\n\n thresh : int, float\n A threshold of VIF\n\n Returns\n -------\n Filtered_data : DataFrame\n A subset of the input DataFame\n\n dropped_List : DataFrame\n 'var' column : dropped variable names from input data columns\n 'vif' column : variance inflation factor of dropped variables\n\n Notes\n -----\n This function does not save the auxiliary regression.\n\n See Also\n --------\n statsmodels.stats.outliers_influence.variance_inflation_factor\n\n References\n ----------\n http://en.wikipedia.org/wiki/Variance_inflation_factor\n\n '''\n assert isinstance(data, pd.DataFrame)\n\n # Create Dropped variable list\n dropped = pd.DataFrame(columns=['var', 'vif'])\n\n # Startswith 'drop = True'(Assume that some variables will be dropped)\n dropCondition = True\n\n # Calculate a VIF & Drop columns(variables)\n while dropCondition:\n\n # 1. Calculate a VIF\n vifDict = {col: vif(data.loc[:, col], data.loc[:, data.columns != col])\n for col in data.columns}\n\n # Get the MAXIMUM VIF\n maxVar = max(vifDict, key=vifDict.get)\n maxVal = vifDict[maxVar]\n\n # 2. IF VIF values are over the threshold, THEN drop it\n if maxVal >= thresh:\n\n # Keep it\n dropped = dropped.append({'var': maxVar, 'vif': maxVal},\n ignore_index=True)\n\n # Drop it\n data = data.drop(maxVar, axis=1)\n\n # Print it\n print(\"Dropping '\" + str(maxVar) + \"' \" + \" VIF: \" + str(maxVal))\n\n # Since a variable has been dropped, the assumption remains\n dropCondition = True\n\n else:\n\n # No variable dropped, the assumption has been rejected\n dropCondition = False\n\n # Print Massages\n remainsMsg = '# Remaining Variables '\n msgWrapper = '-' * (len(remainsMsg)+1)\n\n print('\\n' + msgWrapper + '\\n' + remainsMsg + '\\n' + msgWrapper)\n print(list(data.columns))\n print('\\n')\n\n droppedMsg = '# Dropped Variables '\n msgWrapper = '-' * (len(remainsMsg)+1)\n print('\\n' + msgWrapper + '\\n' + droppedMsg + '\\n' + msgWrapper)\n print(list(dropped.loc[:, 'var']))\n print('\\n')\n\n return data, dropped\n","repo_name":"pydemia/unipy","sub_path":"unipy/stats/feature_selection.py","file_name":"feature_selection.py","file_ext":"py","file_size_in_byte":8127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"37689410932","text":"class PriorityQueue(object):\n def __init__(self):\n self._head = None\n self._tail = None\n self._count = 0\n \n def is_empty(self):\n return self._count == 0\n \n def __len__(self):\n return self._count\n \n def __str__(self):\n current_node = self._head\n string_list = []\n while current_node is not None:\n string_list.append(str((current_node.item, current_node.priority)))\n current_node = current_node.next\n return str(string_list)\n \n def enqueue(self, item, priority):\n new_entry = _PriorityQEntry(item, priority)\n if self.is_empty():\n self._head = new_entry\n else:\n self._tail.next = new_entry\n \n self._tail = new_entry \n self._count += 1\n \n def dequeue(self):\n assert not self.is_empty(), \"cannot pop from empty queue\"\n\n max_priority_entry = self._head\n pre_entry = None\n\n current_node = self._head\n pre_node = None\n while current_node is not None:\n if current_node.priority > max_priority_entry.priority:\n pre_entry = pre_node\n max_priority_entry = current_node\n \n pre_node = current_node\n current_node = current_node.next\n \n item = max_priority_entry.item\n \n if max_priority_entry == self._head:\n self._head = self._head.next\n else:\n pre_entry.next = max_priority_entry.next\n \n self._count -= 1\n \n return item\n \nclass _PriorityQEntry(object):\n def __init__(self, item, priority, link=None):\n self.item = item\n self.priority = priority\n self.next = link\n \n \ndef main():\n print(\"create new priority\")\n Q = PriorityQueue()\n print()\n \n print(\"add (1,2)\")\n Q.enqueue(1,2)\n \n print(\"add (3,5)\")\n Q.enqueue(3,5)\n \n print(\"add (6,1)\")\n Q.enqueue(6,1)\n \n print(\"add (2,4)\")\n Q.enqueue(2,4)\n \n print(\"add (0,2)\")\n Q.enqueue(0,2)\n \n print(\"add (125,2)\")\n Q.enqueue(125,2)\n \n print(\"add (325,2)\")\n Q.enqueue(325,2)\n \n print()\n \n print(\"Queue: \")\n print(Q)\n \n print(\"dequeue: %d\"% Q.dequeue())\n print(Q)\n print()\n \n print(\"dequeue: %d\"% Q.dequeue())\n print(Q)\n print()\n \n print(\"dequeue: %d\"% Q.dequeue())\n print(Q)\n print()\n \n print(\"dequeue: %d\"% Q.dequeue())\n print(Q)\n print()\n\n \nif __name__ == \"__main__\":\n main()\n \n \n \n \n \n \n \n \n \n \n ","repo_name":"yuhanliu0121/learnDataStructure","sub_path":"Chapter8_Queue/5_priorityQueue_linkedlist.py","file_name":"5_priorityQueue_linkedlist.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15520206415","text":"from board import Board\nfrom player import Player\n\nclass Gomoku:\n\tdef __init__(self):\n\t\tself.player1 = Player(1)\n\t\tself.player2 = Player(2)\n\t\tself.board = Board()\n\n\t#self is object itself (in this case gomoku)\n\t#capitalize objects and classes\n\tdef play(self):\n\t\twhile True:\n\t\t\tturn_x = raw_input(\"Player 1 turn x: \")\t\n\t\t\tturn_y = raw_input(\"Player 1 turn y: \")\n\t\t\t\n\t\t\twhile not (self.player1.check_legal(self.board,int(turn_x),int(turn_y))):\n\t\t\t\tturn_x = raw_input(\"Player 1 turn x: \")\t\n\t\t\t\tturn_y = raw_input(\"Player 1 turn y: \")\n\t\t\tself.player1.move(self.board,int(turn_x),int(turn_y))\n\t\t\t\n\t\t\tif self.player1.win(self.board,int(turn_x),int(turn_y)):\n\t\t\t\tprint(\"Player 1 wins\")\n\t\t\t\treturn\n\t\t\t\n\t\t\tturn_x = raw_input(\"Player 2 turn x: \")\t\n\t\t\tturn_y = raw_input(\"Player 2 turn y: \")\n\n\t\t\twhile not (self.player2.check_legal(self.board,int(turn_x),int(turn_y))):\n\t\t\t\tturn_x = raw_input(\"Player 2 turn x: \")\t\n\t\t\t\tturn_y = raw_input(\"Player 2 turn y: \")\n\t\t\tself.player2.move(self.board,int(turn_x),int(turn_y))\n\t\t\t\n\t\t\tif self.player2.win(self.board,int(turn_x),int(turn_y)):\n\t\t\t\tprint(\"Player 2 wins\")\n\t\t\t\treturn\n\ngame = Gomoku()\ngame.play()\n\n","repo_name":"purriah/Gomoku","sub_path":"gomoku.py","file_name":"gomoku.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"5901210117","text":"from alibabacloud_resourcemanager20200331.client import Client as ResourceManager20200331Client\nfrom alibabacloud_tea_openapi import models as open_api_models\nfrom alibabacloud_resourcemanager20200331 import models as resource_manager_20200331_models\nfrom alibabacloud_ecs20140526.client import Client as Ecs20140526Client\nfrom alibabacloud_ecs20140526 import models as ecs_20140526_models\nfrom Tea.exceptions import TeaException\nfrom alibabacloud_bssopenapi20171214.client import Client as BssOpenApi20171214Client\nfrom alibabacloud_bssopenapi20171214 import models as bss_open_api_20171214_models\nfrom alibabacloud_tea_util import models as util_models\nfrom alibabacloud_tea_util.client import Client as UtilClient\n\nimport sys,datetime,hashlib\nfrom units import consul_kv,consul_svc\nfrom units.cloud import sync_ecs\nfrom units.cloud import notify\n\ndef exp(account,collect_days,notify_days,notify_amount):\n ak,sk = consul_kv.get_aksk('alicloud',account)\n now = datetime.datetime.utcnow().strftime('%Y-%m-%dT16:00:00Z')\n collect = (datetime.datetime.utcnow() + datetime.timedelta(days=collect_days+1)).strftime('%Y-%m-%dT16:00:00Z')\n config = open_api_models.Config(access_key_id=ak,access_key_secret=sk)\n config.endpoint = f'business.aliyuncs.com'\n client = BssOpenApi20171214Client(config)\n query_available_instances_request = bss_open_api_20171214_models.QueryAvailableInstancesRequest(\n renew_status='ManualRenewal',\n end_time_start=now,\n end_time_end=collect)\n runtime = util_models.RuntimeOptions()\n amount_response = client.query_account_balance()\n try:\n exp = client.query_available_instances_with_options(query_available_instances_request, runtime)\n exp_list = exp.body.to_map()['Data']['InstanceList']\n exp_dict = {}\n isnotify_list = consul_kv.get_keys_list(f'ConsulManager/exp/isnotify/alicloud/{account}')\n isnotify_list = [i.split('/')[-1] for i in isnotify_list]\n notify_dict = {}\n amount_dict = {}\n for i in exp_list:\n notify_id = hashlib.md5(str(i).encode(encoding='UTF-8')).hexdigest()\n endtime = datetime.datetime.strptime(i['EndTime'],'%Y-%m-%dT%H:%M:%SZ') + datetime.timedelta(hours=8)\n endtime_str = endtime.strftime('%Y-%m-%d')\n iname = consul_svc.get_sid(i['InstanceID'])['instance']['Meta']['name'] if i['ProductCode'] == 'ecs' else 'Null'\n exp_dict[i['InstanceID']] = {'Region':i.get('Region','Null'),'Product':i['ProductCode'],\n 'Name':iname,'EndTime':endtime_str,'notify_id':notify_id,\n 'Ptype':i.get('ProductType',i['ProductCode'])}\n if (endtime - datetime.datetime.now()).days < notify_days and notify_id not in isnotify_list:\n notify_dict[i['InstanceID']] = exp_dict[i['InstanceID']]\n consul_kv.put_kv(f'ConsulManager/exp/lists/alicloud/{account}/exp', exp_dict)\n amount = float(amount_response.body.data.available_amount.replace(',',''))\n consul_kv.put_kv(f'ConsulManager/exp/lists/alicloud/{account}/amount',{'amount':amount})\n if amount < notify_amount:\n amount_dict = {'amount':amount}\n exp_config = consul_kv.get_value('ConsulManager/exp/config')\n wecomwh = exp_config.get('wecomwh','')\n dingdingwh = exp_config.get('dingdingwh','')\n feishuwh = exp_config.get('feishuwh','')\n if notify_dict != {}:\n msg = [f'### 阿里云账号 {account}:\\n### 以下资源到期日小于 {notify_days} 天:']\n for k,v in notify_dict.items():\n iname = k if v['Name'] == 'Null' else v['Name']\n msg.append(f\"- {v['Region']}:{v['Product']}:{iname}:{v['EndTime']}\")\n content = '\\n'.join(msg)\n if exp_config['switch'] and exp_config.get('wecom',False):\n notify.wecom(wecomwh,content)\n if exp_config['switch'] and exp_config.get('dingding',False):\n notify.dingding(dingdingwh,content)\n if exp_config['switch'] and exp_config.get('feishu',False):\n title = '阿里云资源到期通知'\n md = content\n notify.feishu(feishuwh,title,md)\n if amount_dict != {}:\n content = f'### 阿里云账号 {account}:\\n### 可用余额:{amount} 元'\n if exp_config['switch'] and exp_config.get('wecom',False):\n notify.wecom(wecomwh,content)\n if exp_config['switch'] and exp_config.get('dingding',False):\n notify.dingding(dingdingwh,content)\n if exp_config['switch'] and exp_config.get('feishu',False):\n title = '阿里云余额不足通知'\n md = content\n notify.feishu(feishuwh,title,md)\n\n except Exception as error:\n UtilClient.assert_as_string(error.message)\n\ndef group(account):\n ak,sk = consul_kv.get_aksk('alicloud',account)\n now = datetime.datetime.now().strftime('%m%d/%H:%M')\n config = open_api_models.Config(access_key_id=ak,access_key_secret=sk)\n config.endpoint = f'resourcemanager.aliyuncs.com'\n client = ResourceManager20200331Client(config)\n list_resource_groups_request = resource_manager_20200331_models.ListResourceGroupsRequest(page_size=100)\n try:\n proj = client.list_resource_groups(list_resource_groups_request)\n proj_list = proj.body.resource_groups.to_map()['ResourceGroup']\n group_dict = {i['Id']:i['DisplayName'] for i in proj_list}\n consul_kv.put_kv(f'ConsulManager/assets/alicloud/group/{account}',group_dict)\n count = len(group_dict)\n data = {'count':count,'update':now,'status':20000,'msg':f'同步资源组成功!总数:{count}'}\n consul_kv.put_kv(f'ConsulManager/record/jobs/alicloud/{account}/group', data)\n print('【JOB】===>', 'alicloud_group', account, data, flush=True)\n except TeaException as e:\n emsg = e.message.split('. ',1)[0]\n print(\"【code:】\",e.code,\"\\n【message:】\",emsg, flush=True)\n data = consul_kv.get_value(f'ConsulManager/record/jobs/alicloud/{account}/group')\n if data == {}:\n data = {'count':'无','update':f'失败{e.code}','status':50000,'msg':emsg}\n else:\n data['update'] = f'失败{e.code}'\n data['msg'] = emsg\n consul_kv.put_kv(f'ConsulManager/record/jobs/alicloud/{account}/group', data)\n except Exception as e:\n data = {'count':'无','update':f'失败','status':50000,'msg':str(e)}\n consul_kv.put_kv(f'ConsulManager/record/jobs/alicloud/{account}/group', data)\n\ndef ecs(account,region):\n ak,sk = consul_kv.get_aksk('alicloud',account)\n now = datetime.datetime.now().strftime('%m%d/%H:%M')\n group_dict = consul_kv.get_value(f'ConsulManager/assets/alicloud/group/{account}')\n\n config = open_api_models.Config(access_key_id=ak,access_key_secret=sk)\n config.endpoint = f'ecs.{region}.aliyuncs.com'\n client = Ecs20140526Client(config)\n\n next_token = '0'\n ecs_dict = {}\n try:\n while next_token != '':\n describe_instances_request = ecs_20140526_models.DescribeInstancesRequest(\n max_results=100,\n region_id=region,\n next_token=next_token\n )\n ecs = client.describe_instances(describe_instances_request)\n ecs_list = ecs.body.instances.to_map()['Instance']\n ecs_dict_temp = {i['InstanceId']:{\n 'name':i['InstanceName'],'group':group_dict.get(i['ResourceGroupId'],'无'),'ostype':i['OSType'].lower(),\n 'status':i['Status'],'region':region,\n 'ip':i[\"InnerIpAddress\"][\"IpAddress\"] if len(i[\"InnerIpAddress\"][\"IpAddress\"]) != 0 else i['NetworkInterfaces']['NetworkInterface'][0]['PrimaryIpAddress'],\n 'cpu':f\"{i['Cpu']}核\",'mem':f\"{str(round(i['Memory']/1024,1)).rstrip('.0')}GB\",'exp':i['ExpiredTime'].split('T')[0],'ecstag': i.get('Tags',{}).get('Tag',[])\n }for i in ecs_list}\n ecs_dict.update(ecs_dict_temp)\n next_token = ecs.body.next_token\n\n count = len(ecs_dict)\n off,on = sync_ecs.w2consul('alicloud',account,region,ecs_dict)\n data = {'count':count,'update':now,'status':20000,'on':on,'off':off,'msg':f'ECS同步成功!总数:{count},开机:{on},关机:{off}'}\n consul_kv.put_kv(f'ConsulManager/record/jobs/alicloud/{account}/ecs/{region}', data)\n print('【JOB】===>', 'alicloud_ecs', account,region, data, flush=True)\n except TeaException as e:\n emsg = e.message.split('. ',1)[0]\n print(\"【code:】\",e.code,\"\\n【message:】\",emsg, flush=True)\n data = consul_kv.get_value(f'ConsulManager/record/jobs/alicloud/{account}/ecs/{region}')\n if data == {}:\n data = {'count':'无','update':f'失败{e.code}','status':50000,'msg':emsg}\n else:\n data['update'] = f'失败{e.code}'\n data['msg'] = emsg\n consul_kv.put_kv(f'ConsulManager/record/jobs/alicloud/{account}/ecs/{region}', data)\n except Exception as e:\n data = {'count':'无','update':f'失败','status':50000,'msg':str(e)}\n consul_kv.put_kv(f'ConsulManager/record/jobs/alicloud/{account}/ecs/{region}', data)\n","repo_name":"xugaopeng1/ConsulManager","sub_path":"flask-consul/units/cloud/alicloud.py","file_name":"alicloud.py","file_ext":"py","file_size_in_byte":9340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"}
+{"seq_id":"14450406717","text":"\n\"\"\"\nTest that
\n ▌ ▐ v1.0\n █▙▁▁▁▁▁▟█\n ''')\n\ndef show_menu():\n print(\"\\nPlease chose actions to affect on your device :\\n\")\n print(Fore.LIGHTBLUE_EX + \"┌─[1] \" + Fore.RESET + \"Give a hostname\")\n print(Fore.LIGHTBLUE_EX + \"├─[2] \" + Fore.RESET + \"Create enable password\")\n print(Fore.LIGHTBLUE_EX + \"├─[3] \" + Fore.RESET + \"Create user and password\")\n print(Fore.LIGHTBLUE_EX + \"├─[4] \" + Fore.RESET + \"Create Vlans\")\n print(Fore.LIGHTBLUE_EX + \"├─[5] \" + Fore.RESET + \"Add default gateway\")\n print(Fore.LIGHTBLUE_EX + \"├─[6] \" + Fore.RESET + \"Add ip route\")\n print(Fore.LIGHTBLUE_EX + \"├─[7] \" + Fore.RESET + \"Configure interfaces\")\n print(Fore.LIGHTBLUE_EX + \"│ ├─[1] \" + Fore.RESET + \"Add switchports\")\n print(Fore.LIGHTBLUE_EX + \"│ └─[2] \" + Fore.RESET + \"Change interface speed\")\n print(Fore.LIGHTBLUE_EX + \"└─[8] \" + Fore.RESET + \"Exit pyCISCO and write configuration file\\n\")\n\ninfos_switch = []\nvlan_id_list = []\nConfigSwitch = ConfigSwitch(InfosSwitch=infos_switch, InfosVlan=vlan_id_list)\n\ndef test(line: str) -> None:\n print(\n Fore.YELLOW + f\"[+] New line saved : \\n{line}\" + Fore.RESET if line\n else Fore.RED + \"\\nInvalid input.\" + Fore.RESET\n )\n\ndef app_start():\n show_menu()\n try:\n choice = int(input(\"\\nYour selection: \"))\n except ValueError:\n print(Fore.RED + \"\\nInvalid option. Please enter 1-8 or press CTRL+C to exit: \\n\" + Fore.RESET)\n app_start()\n except KeyboardInterrupt:\n print(Fore.RED + \"\\nExiting pyCISCO ...\\n\" + Fore.RESET)\n exit(0)\n else:\n if choice == 1:\n hostname = str(input(\"\\nEnter the name of your device : \"))\n if hostname:\n hostname_line = ConfigSwitch.add_hostname(hostname)\n test(hostname_line)\n\n elif choice == 2:\n enable_pwd = str(input(\"\\nEnter the enable password : \"))\n if enable_pwd:\n enable_pwd_line = ConfigSwitch.add_enable_pwd(enable_pwd)\n test(enable_pwd_line)\n\n elif choice == 3:\n user_pwd_infos = str(input(\"\\nEnter the infos (username:password:password_type(5,7,8,9)): \"))\n if user_pwd_infos:\n user_pwd_device_line = ConfigSwitch.add_user_pwd_line(user_pwd_infos)\n test(user_pwd_device_line)\n\n elif choice == 4:\n vlan_infos = str(input(\"\\nEnter the vlan infos (id:name:ip_address:mask) : \"))\n if vlan_infos:\n vlan_config_line = ConfigSwitch.create_vlan(vlan_infos)\n test(vlan_config_line)\n\n elif choice == 5:\n ip = str(input(\"\\nEnter the ip adress : \"))\n if ip:\n default_gateway_line = ConfigSwitch.add_default_gateway(ip)\n test(default_gateway_line)\n\n elif choice == 6:\n ip_route_infos = str(input(\"\\nEnter the ip infos for ip route (IPdst:MASKdst IPsrc:MASKsrc) : \"))\n if ip_route_infos:\n ip_route_line = ConfigSwitch.add_ip_route(ip_route_infos)\n test(ip_route_line)\n\n elif choice == 7:\n interface_config_lines = ConfigSwitch.configure_interface()\n for interface_config_line in interface_config_lines:\n test(interface_config_line)\n\n elif choice == 8:\n print(Fore.YELLOW + \"\\n[+] Writing configuration in 'config.txt' ...\" + Fore.RESET)\n ConfigSwitch.write_configuration(infos_switch)\n print(Fore.YELLOW + \"\\n[+] Configuration writed\" + Fore.RESET)\n exit(0)\n else:\n print(Fore.RED + \"\\nInvalid option. Please enter 1-8 or press CTRL + C to exit: \\n\" + Fore.RESET)\n app_start()\n\ndef main():\n banner()\n while True:\n app_start()\n\n# Start Here\nif __name__ == \"__main__\":\n main()","repo_name":"0xSp3ctra/pyCISCO","sub_path":"pycisco.py","file_name":"pycisco.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"13751216682","text":"# The output data is prepared by representing each output as a binary vector of categories\nimport torch.utils.data as utils\n\ndataset_size = 45000\nnum_epochs = 1\nlog_interval = 500\n\nvgg_model = models.vgg16(pretrained=True).cuda()\nvgg_features = nn.Sequential(*list(vgg_model.features.children())[:])\nvgg_new = nn.Sequential(*list(vgg_model.classifier.children())[:-2])\n\nclass E2E(nn.Module):\n def __init__(self):\n super(E2E, self).__init__()\n self.feature = vgg_features \n self.fc1 = vgg_new\n self.fc2 = cfy_model\n \n def forward(self, x):\n x1= self.feature(x)\n x1 = x1.view(x1.size(0), -1)\n x2 = self.fc1(x1)\n out = self.fc2(x2)\n return out\n \n#transform image \nimg_size = 224\nloader = transforms.Compose([\n transforms.Scale(img_size),\n transforms.CenterCrop(img_size),\n transforms.ToTensor(),\n]) \n\n#load image \ndef load_image(filename):\n image = Image.open(filename).convert('RGB')\n image_tensor = loader(image).float()\n return image_tensor.cuda()\n\n\ntrain_class = []\nval_class = []\n\n#binary target train vector \nfor train_id in train_ids[:45000]: \n temp_class = np.zeros(80)\n for i,category in enumerate(train_id_to_categories[train_id]):\n temp_class[category_to_idx[category]] = 1\n \n train_class.append(temp_class)\n\n#binary target val vector \nfor val_id in val_ids[:100]: \n temp_class = np.zeros(80)\n for i,category in enumerate(val_id_to_categories[val_id]):\n temp_class[category_to_idx[category]] = 1\n \n val_class.append(temp_class)\n \ntensor_x_val = torch.stack([load_image(val_id_to_file[k]) for k in val_ids[:50]]) \ntensor_y_val = torch.stack([torch.Tensor(i) for i in val_class[:50]])\n\n#train fn\ndef train(comb_model,learning_rate,batch_size,num_epochs):\n \n criterion = nn.MultiLabelSoftMarginLoss() \n optimizer = torch.optim.Adam(comb_model.parameters(), lr=learning_rate)\n \n for epoch in range(num_epochs):\n loss_vector_train = [] \n loss_vector_val = [] \n for b in range(int(dataset_size/batch_size)):\n \n tensor_x = torch.stack([load_image(train_id_to_file[k]) for k in train_ids[batch_size*b:batch_size*(b+1)]])\n tensor_y = torch.stack([torch.Tensor(i) for i in train_class[batch_size*b:batch_size*(b+1)]])\n \n # Convert torch tensor to Variable\n img = Variable(tensor_x)\n labels = Variable(torch.FloatTensor(tensor_y)).cuda()\n \n comb_model.train()\n # Forward + Backward + Optimize\n optimizer.zero_grad() # zero the gradient buffer\n outputs = comb_model(img)\n loss_train = criterion(outputs, labels)\n loss_train.backward()\n optimizer.step()\n \n loss_vector_train.append(loss_train.data[0])\n \n comb_model.eval()\n out_val = comb_model(Variable(tensor_x_val))\n labels_val = Variable(torch.FloatTensor(tensor_y_val)).cuda()\n loss_val = criterion(out_val, labels_val)\n \n loss_vector_val.append(loss_val.data[0])\n \n if (b % log_interval == 0): \n print('batch %d %.6f %.6f' %(b,loss_train.data[0],loss_val.data[0]))\n \n #print(len(loss_vector))\n np.save(open('outputs/loss_vector_train'+str(learning_rate)+str(batch_size), 'wb+'), loss_vector_train) \n np.save(open('outputs/loss_vector_val'+str(learning_rate)+str(batch_size), 'wb+'), loss_vector_val) \n \n# Finally train the model\n\nlearning_rate_vec = [0.001,0.0001,0.00001]\nbatch_size_vec = [25,40,50]\nfor lr in learning_rate_vec:\n for bs in batch_size_vec:\n comb_model = E2E()\n comb_model.cuda()\n train(comb_model,lr, bs, num_epochs)\n torch.save(comb_model.state_dict(), './comb_model'+str(lr)+str(bs)+'.pth')\n\n\n\nprint('training done')","repo_name":"kevinbdsouza/ObjectDetection","sub_path":"hyperparameter.py","file_name":"hyperparameter.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"10500512942","text":"# Linked List in python\n# Node class\n# Node class has a constructor that sets the data passed in, and optionally\n# and prev_node\n# It also has a str method to give a string representation for printing.\n# Note that prev_node is only used for Doubly Linked Lists.\n# Operations: Add, Find, Remove, Print_list\n\n\nclass Node:\n\n def __init__(self, d, n=None, p=None):\n\n self.data = d\n self.next_node = n\n self.prev_node = p\n\n def __str__(self):\n return '(' + str(self.data) + ')'\n\n\nclass LinkedList:\n\n def __init__(self, r=None):\n\n self.root = r\n self.size = 0\n\n def add(self, d):\n\n new_node = Node(d, self.root)\n self.root = new_node\n self.size += 1\n\n def find(self, d):\n\n this_node = self.root\n\n while this_node is not None:\n if this_node.data == d:\n return d\n else:\n this_node = this_node.next_node\n return None\n\n def remove(self, d):\n\n this_node = self.root\n prev_node = None\n\n while this_node is not None:\n\n if this_node.data == d:\n\n if prev_node is not None:\n prev_node.next_node = this_node.next_node\n\n else:\n self.root = this_node.next_node\n self.size -= 1\n return True\n\n else:\n\n prev_node = this_node\n this_node = this_node.next_node\n\n return False\n\n def print_list(self):\n\n this_node = self.root\n while this_node is not None:\n print(this_node, end='->')\n this_node = this_node.next_node\n print('None')\n\n\nmy_list = LinkedList()\nmy_list.add(5)\nmy_list.add(8)\nmy_list.add(12)\nmy_list.print_list()\n\nprint(\"size=\"+str(my_list.size))\nmy_list.remove(8)\nprint(\"size=\"+str(my_list.size))\nprint(my_list.find(5))\nprint(my_list.root)\n\n\n\n","repo_name":"SamanehGhafouri/DataStructuresInPython","sub_path":"linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"23144228626","text":"class LightBulb:\n @staticmethod\n def turn_on():\n print(\"LightBulb: turned on...\")\n\n @staticmethod\n def turn_off():\n print(\"LightBulb: turned off...\")\n\n\nclass ElectricPowerSwitch:\n\n def __init__(self, light_bulb: LightBulb):\n self.lightBulb = light_bulb\n self.on = False\n\n def press(self):\n if self.on:\n self.lightBulb.turn_off()\n self.on = False\n else:\n self.lightBulb.turn_on()\n self.on = True\n\n\nif __name__ == '__main__':\n lb = LightBulb()\n switch = ElectricPowerSwitch(lb)\n switch.press()\n switch.press()\n","repo_name":"aviz92/PythonCourses","sub_path":"PythonCourses/BetterPython/N2_dependency_inversion/dependency-inversion-before.py","file_name":"dependency-inversion-before.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"11136124965","text":"from panda3d.core import *\r\nimport math\r\n\r\n\r\nclass Tile():\r\n \"\"\"\r\n Create a thin (zscale reduced) tile object based on a polygonal prism,\r\n with the correct texture or colour, with collider nodes at the tips, and\r\n an optional large one (if the tile is square) at the c of g. Shape can be\r\n scaled (scale), and rotated (phase). The symmetric rotation specifier (sym_rot)\r\n was included to identify when a spinning tile could stop spinning - eg 90 degrees\r\n for a square tile vs 180 degrees for a rectagle and 360 degrees for a triangle,\r\n but is not important now that tiles are moved with a fixed orientation.\r\n \"\"\"\r\n\r\n def __init__(self, pos, shape, face_color, tip_rad, p_tag=\"fred\", zscale=0.05, name=\"Tile\",\r\n cg=[0,0], cg_rad=1, sym_rot=90, phase=0, scale=1, hopper=False):\r\n self.sym_rot = sym_rot\r\n self.phase = phase\r\n self.name = p_tag\r\n\r\n if isinstance(face_color, tuple):\r\n # if it is a tuple, then it is an RGBA\r\n self.gNode = TilePoly(shape, face_color)\r\n self.np = render.attachNewNode(self.gNode.node)\r\n self.np.setScale(scale, scale, zscale)\r\n else:\r\n # otherwise assume it is a texture string path\r\n white = (1, 1, 1, 1)\r\n self.gNode = TilePoly(shape, white)\r\n self.np = render.attachNewNode(self.gNode.node)\r\n self.np.setScale(scale, scale, zscale)\r\n tex1 = loader.loadTexture(face_color)\r\n self.np.setTexture(tex1)\r\n self.np.setPos(pos)\r\n self.np.setH(phase)\r\n\r\n colliderNode = CollisionNode(\"collider\" + name)\r\n # Add central collider node\r\n if hopper:\r\n colliderNode.addSolid(CollisionSphere(*cg, 0, (cg_rad + tip_rad)/scale))\r\n # Add the satellite collision solids and location identifier nodes\r\n # at the corners, compensating for scale so that the collision solids\r\n # are the same size regardless of tile scale\r\n for i, corner in enumerate(shape):\r\n colliderNode.addSolid(CollisionSphere(*corner, 0, tip_rad/scale))\r\n corner_node = self.np.attachNewNode('cnr' + str(i))\r\n corner_node.setPos(*corner, 0)\r\n\r\n self.collider = self.np.attachNewNode(colliderNode)\r\n self.collider.setPythonTag(\"owner\", self)\r\n self.collider.show()\r\n\r\n def corner_nodes(self):\r\n return sorted(self.np.findAllMatches('cnr*'), key=lambda np: np.name)\r\n\r\n\r\nclass TilePoly():\r\n \"\"\"\r\n Generate a 3D solid in xyz plane from a 2D polygon in xy plane\r\n \"\"\"\r\n\r\n def __init__(self, shape, face_color):\r\n # 2D Polygon and its 2D normals\r\n self.xys = shape[:]\r\n xy_normals = calcNormals(self.xys)\r\n\r\n \"\"\"\r\n Coverage triangle indices for the top polygonal face (counter clockwise - illustrated) and\r\n bottom polygonal face (clockwise - not shown). Fails for some concave polygons like the cross.\r\n \r\n .4 \r\n . \\\r\n . .3\r\n . . | \r\n . . .2\r\n .. . /\r\n 0 --- 1\r\n \"\"\"\r\n tri_top = [[0, vix + 1, vix + 2] for vix in range(len(self.xys) - 2)]\r\n tri_bot = [[0, vix - 1, vix - 2] for vix in range(len(self.xys), 2, -1)]\r\n\r\n # To hold vertex numbers belonging to the rectangular faces whose normals are xy normals\r\n rects = {}\r\n\r\n \"\"\"\r\n Forward (counter clockwise) and back (clockwise) triangle indices for covering rectangular faces\r\n 2 --------- 3\r\n | b f |\r\n | x |\r\n | f b |\r\n 0 --------- 1\r\n \"\"\"\r\n tri_fwd = [[0, 1, 3], [0, 3, 2]]\r\n tri_back = [[1, 0, 2], [1, 2, 3]]\r\n\r\n # Bottom face then top face\r\n zs = [-1, 1]\r\n\r\n # To hold vertex numbers belonging to the bottom and top faces\r\n polys = {}\r\n\r\n # All the vertex positions of the solid\r\n xyzs = [xy + [z] for z in zs for xy in self.xys]\r\n\r\n # There must be 3 separate vertices at each vertex position, each with a different normal,\r\n # which always points outwards from the solid\r\n format = GeomVertexFormat.getV3n3c4()\r\n vertexData = GeomVertexData('prism', format, Geom.UHStatic)\r\n vertexData.setNumRows(3 * len(xyzs))\r\n\r\n vertices = GeomVertexWriter(vertexData, 'vertex')\r\n normals = GeomVertexWriter(vertexData, 'normal')\r\n colors = GeomVertexWriter(vertexData, 'color')\r\n\r\n # sat is saturated 8 bits (+ 1) to use as denominator\r\n sat = 256\r\n white = (1, 1, 1, 1)\r\n brown = (0xa0 / sat, 0x98 / sat, 0x7c / sat, 1)\r\n\r\n for pos_num, xyz in enumerate(xyzs):\r\n edge_fwd = pos_num % len(self.xys)\r\n edge_back = (edge_fwd - 1) % len(self.xys)\r\n edge_nums = [edge_back, edge_fwd]\r\n for i in range(3):\r\n vertices.addData3f(*xyz)\r\n vnum = pos_num * 3 + i\r\n if i in [0, 1]:\r\n edge_num = edge_nums[i]\r\n normal = xy_normals[edge_num] + [0]\r\n rects.setdefault(edge_num, []).append(vnum)\r\n else:\r\n z_vec = xyz[2]\r\n normal = [0, 0, z_vec]\r\n polys.setdefault(z_vec, []).append(vnum)\r\n\r\n normals.addData3f(*normal)\r\n color = white if normal[2] == -1 else face_color\r\n colors.addData4f(color)\r\n\r\n # Store the tessellation triangles, counter clockwise from front.\r\n # Each vertex assigned to a triangle must have a normal vector that\r\n # points outwards from the triangle face, which thus determines which\r\n # of the 3 possible vertexes to chose at any given vertex position.\r\n # Each triangle's vertices should be specified in counter clockwise\r\n # order from the perspective of the vertices' normals (i.e. looking at the\r\n # outside of the face).\r\n primitive = GeomTriangles(Geom.UHStatic)\r\n\r\n # Cover the rectangular faces around the edges\r\n for edge_num in rects:\r\n # cater for wrap around back to the zeroth edge number\r\n tri_ix_pairs = tri_back if edge_num == (len(self.xys) - 1) else tri_fwd\r\n for tri_ixs in tri_ix_pairs:\r\n vnums = [rects[edge_num][tri_ix] for tri_ix in tri_ixs]\r\n primitive.addVertices(*vnums)\r\n\r\n # Cover the polygonal faces on the top and bottom\r\n for poly in polys:\r\n # Use clockwise indexing on the bottom (negative normal) face and\r\n # counter clockwise on the top (positive normal) face\r\n faces = tri_bot if poly < 0 else tri_top\r\n for tri_ixs in faces:\r\n vnums = [polys[poly][tri_ix] for tri_ix in tri_ixs]\r\n primitive.addVertices(*vnums)\r\n\r\n geom = Geom(vertexData)\r\n geom.addPrimitive(primitive)\r\n\r\n self.node = GeomNode('prism gnode')\r\n self.node.addGeom(geom)\r\n\r\n\r\nclass Vector2D():\r\n \"\"\"\r\n 2D working in x-y plane with z = 0\r\n \"\"\"\r\n\r\n def __init__(self, p1, p2):\r\n self.p1 = p1\r\n self.p2 = p2\r\n self.dx = p2.x - p1.x\r\n self.dy = p2.y - p1.y\r\n self.hyp2 = self.dx * self.dx + self.dy * self.dy\r\n self.hyp = math.sqrt(self.hyp2)\r\n\r\n def norm_2D(self):\r\n return Vec3D(self.dy / self.hyp, -self.dx / self.hyp, 0)\r\n\r\n def tan_2D(self):\r\n return Vec3D(self.dx / self.hyp, self.dy / self.hyp, 0)\r\n\r\n def dist_from_2D(self, p, infinite=False):\r\n \"\"\" Distance of p0 from line segment or line through p1 and p2 \"\"\"\r\n t = ((p.x - self.p1.x) * self.dx + (p.y - self.p1.y) * self.dy) / self.hyp2\r\n if t < 0 and not infinite:\r\n # closest is p1\r\n d2x = p.x - self.p1.x\r\n d2y = p.y - self.p1.y\r\n elif t > 1 and not infinite:\r\n # closest is p2\r\n d2x = p.x - self.p2.x\r\n d2y = p.y - self.p2.y\r\n else:\r\n # closest is a projection onto the line\r\n d2x = p.x - (self.p1.x + t * self.dx)\r\n d2y = p.y - (self.p1.y + t * self.dy)\r\n return math.sqrt(d2x * d2x + d2y * d2y)\r\n\r\n\r\ndef normal_2D(p1, p2):\r\n \"\"\"\r\n 2D working in x-y plane with points represented as 2 element lists.\r\n Mapping is y2 = p2[1], x2 = p2[0], y1 = p1[1], x1 = p1[0]\r\n \"\"\"\r\n x_diff = p2[0] - p1[0]\r\n y_diff = p2[1] - p1[1]\r\n hyp = math.sqrt(x_diff * x_diff + y_diff * y_diff)\r\n # right hand normal circulating counter clockwise\r\n return [y_diff / hyp, -x_diff / hyp]\r\n\r\ndef rotate_by_1(my_list):\r\n return my_list[1:] + my_list[:1]\r\n\r\ndef calcNormals(points):\r\n return [normal_2D(p1, p2) for p1, p2 in zip(points, rotate_by_1(points))]\r\n\r\nif __name__ == '__main__':\r\n p1 = Vec3D(1, 2, 0)\r\n p2 = Vec3D(5, 7, 0)\r\n p3 = Vec3D(52, 3, 0)\r\n seg = Vector2D(p1, p2)\r\n dp3 = seg.dist_from_2D(p3)\r\n inf_dp3 = seg.dist_from_2D(p3, infinite=True)\r\n print('dp3', dp3)\r\n print('inf_dp3', inf_dp3)\r\n\r\n\r\n\r\n\r\n","repo_name":"friedgit/victorian-tiled-path","sub_path":"tile_poly.py","file_name":"tile_poly.py","file_ext":"py","file_size_in_byte":9210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"33355616491","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\n\n\ndef get_logger(name=__name__, stream=False):\n formatter = logging.Formatter('[%(levelname)s] %(asctime)s %(filename)s:\\n %(message)s\\n')\n logger = logging.getLogger(name)\n\n file_handler = logging.FileHandler(name + '.log') # Instantiate the file handler\n file_handler.setFormatter(formatter)\n file_handler.setLevel(logging.WARNING) # only logs warnings level or higher\n logger.addHandler(file_handler)\n\n if stream:\n stream_handler = logging.StreamHandler() # Instantiate the stream handler AKA the console\n stream_handler.setFormatter(formatter)\n stream_handler.setLevel(logging.DEBUG) # shows everything on console\n logger.addHandler(stream_handler)\n\n # We add both handlers to the logger\n\n logger.setLevel(logging.DEBUG) # Logger registers all logs\n\n return logger\n","repo_name":"CoreDumped-ETSISI/core-dumped-telegram-bot","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"74832647506","text":"n,m = map(int,input().split())\nstrings = []\nchecks = []\nfor i in range(n):\n strings.append(input())\nfor i in range(m):\n checks.append(input())\ncount = 0\nfor check in checks:\n if check in strings:\n count +=1\nprint(count) \n","repo_name":"Jarry-Ha/TIL_github","sub_path":"1_python/1.study/2.baekjoon/14425.py","file_name":"14425.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"5732878137","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\nimport os\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\nimport tensorflow as tf\r\ntfconfig = tf.ConfigProto()\r\ntfconfig.gpu_options.allow_growth = True\r\nsession = tf.Session(config=tfconfig)\r\nimport sys\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pickle\r\nimport keras\r\nfrom keras.models import *\r\nfrom keras.layers import *\r\nfrom keras.optimizers import *\r\nfrom keras.preprocessing import sequence\r\nfrom keras.regularizers import l2\r\nfrom keras import backend as K\r\nfrom keras.engine.topology import Layer\r\nfrom keras.backend.tensorflow_backend import set_session\r\nimport time\r\nfrom tensorflow.contrib import learn\r\nfrom sklearn.model_selection import train_test_split\r\nimport keras.backend as K\r\nfrom keras.callbacks import TensorBoard\r\nfrom keras.callbacks import Callback\r\nfrom sklearn.metrics import log_loss\r\nfrom keras.activations import softmax\r\nsys.path.append('models')\r\nfrom CNN import cnn_v1, cnn_v2, model_conv1D_, Siamese_LSTM, drmm_tks\r\nfrom ESIM import esim, decomposable_attention\r\nfrom ABCNN import ABCNN\r\nfrom bimpm import bimpm\r\nsys.path.append('utils/')\r\nsys.path.append('feature/')\r\nimport config\r\nfrom Feats import data_2id, add_hum_feats\r\nfrom help import score, train_batch_generator, train_batch_generator3, train_test, get_X_Y_from_df\r\nfrom CutWord import read_cut,read_cut_es\r\n\r\ndef load_data():\r\n print('load data')\r\n data = read_cut_es() #cut word\r\n print(data)\r\n data = data_2id(data,['q1_es_cut','q2_es_cut']) # 2id\r\n print(data)\r\n data = add_hum_feats(data,config.train_feats) #生成特征并加入\r\n data = add_hum_feats(data, config.train_feats) # 生成特征并加入\r\n\r\n x_train, y_train = get_X_Y_from_df(data, config.data_augment)\r\n print(len(x_train[2]))\r\n \r\n return x_train, y_train\r\n\r\n\r\ndef make_train_cv_data(X_train, Y_train, Model, model_name, epoch_nums, kfolds):\r\n\r\n from keras.models import model_from_json\r\n\r\n json_string = Model.to_json()\r\n\r\n S_train = np.zeros((Y_train.shape[0], epoch_nums))\r\n S_Y = np.zeros((Y_train.shape[0], 1))\r\n\r\n train_df = pd.DataFrame()\r\n X, Y = X_train, Y_train\r\n from sklearn.model_selection import KFold\r\n kf = KFold(n_splits=kfolds, shuffle=True)\r\n k = 0\r\n \r\n epoch_nums =1 \r\n p, r, f ,l= [], [], [] ,[] \r\n for train_index, test_index in kf.split(Y):\r\n k += 1\r\n model = model_from_json(json_string)\r\n model.compile(loss='binary_crossentropy',\r\n optimizer='adam', metrics=['acc'])\r\n K.set_value(model.optimizer.lr, 0.005)\r\n for epoch_num in range(epoch_nums):\r\n \r\n if config.feats == []:\r\n x_train = [X[0][train_index, :], X[1][train_index, :], X[2][train_index]]\r\n x_dev = [X[0][test_index, :], X[1][test_index, :],X[2][test_index]] \r\n else:\r\n \r\n x_train = [X[0][train_index, :], X[1][train_index, :], X[2][train_index, :]]\r\n x_dev = [X[0][test_index, :], X[1][test_index, :],X[2][test_index, :]] \r\n y_train=Y[train_index,:]\r\n y_dev = Y[test_index, :]\r\n print('kf: ', k)\r\n print('epoch_num: ', epoch_num + 1)\r\n # print(x_train[0].shape, x_train[1].shape,\r\n # x_train[2].shape, y_train.shape)\r\n # print(x_dev[0].shape, x_dev[1].shape, x_dev[2].shape, y_dev.shape)\r\n\r\n model.fit_generator(\r\n train_batch_generator3(x_train, y_train, config.batch_size),\r\n epochs=5,\r\n steps_per_epoch=int(y_train.shape[0] / config.batch_size),\r\n validation_data=(x_dev, y_dev),\r\n class_weight={0: 1, 1: 4},\r\n\r\n )\r\n pred = model.predict(x_dev, batch_size=config.batch_size)\r\n pre, rec, f1 = score(y_dev, pred)\r\n \r\n loss = log_loss(y_dev, pred)\r\n \r\n S_train[test_index, epoch_num] = pred[:, 1]\r\n print('p r f1 ', pre, rec, f1)\r\n print('logloss:',loss)\r\n train_df['epoch_{0}'.format(epoch_num)] = S_train[:, epoch_num]\r\n train_df['label'] = Y_train[:, 1]\r\n p.append(pre)\r\n r.append(rec)\r\n f.append(f1)\r\n l.append(loss)\r\n \r\n model.save(config.stack_path+\"_%s_%s.h5\" %\r\n (model_name, k))\r\n print('p r f1 logloss')\r\n print(np.array([p, r, f, l]))\r\n print('mean :', np.mean(np.array([p, r, f, l]),axis=1))\r\n train_df.to_csv(config.stack_path+'train_%s.csv' % (k),\r\n index=False, )\r\n\r\n\r\ndef do_train_cv(model_name, model, epoch_nums, kfolds):\r\n X_train, Y_train = load_data()\r\n make_train_cv_data(X_train, Y_train, model, model_name, epoch_nums, kfolds)\r\n\r\n\r\ndef main(model_name):\r\n print('model name', model_name)\r\n if model_name == 'bimpm':\r\n model = bimpm()\r\n if model_name == 'drmmt':\r\n model = drmm_tks()\r\n\r\n if model_name == 'cnn':\r\n\r\n model = model_conv1D_()\r\n if model_name == 'slstm':\r\n\r\n model = Siamese_LSTM()\r\n\r\n if model_name == 'esim':\r\n model = esim()\r\n\r\n if model_name == 'dam':\r\n model = decomposable_attention()\r\n if model_name == 'abcnn':\r\n\r\n model = ABCNN(\r\n left_seq_len=config.word_maxlen, right_seq_len=config.word_maxlen, depth=3,\r\n nb_filter=100, filter_widths=[5, 4, 3],\r\n collect_sentence_representations=True, abcnn_1=True, abcnn_2=True,\r\n # mode=\"euclidean\",\r\n mode=\"cos\",\r\n # mode='dot'\r\n )\r\n do_train_cv(model_name, model, epoch_nums=1, kfolds=5)\r\n #train(x_train, y_train, x_dev, y_dev, model_name, model)\r\n\r\nif __name__ == '__main__':\r\n\r\n main(sys.argv[1])\r\n # do_cv()\r\n","repo_name":"zle1992/CIKM","sub_path":"cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":5806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"19022866175","text":"#Given an array, rotate the array to the right by k steps, where k is non-negative.\nnums=[-1,-100,3,99]\nk = 2\n\nwhile k>0:\n\tnums.insert(0,nums.pop(-1))\n\tk=k-1\n\nprint(nums)\nprint(\"\\r\")\n\n\n#Given an array of integers and an integer k, find out whether there are two distinct indices i and j in \n#the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.\nnums = [1,0,1,1]\nk = 1\nflag=0\n\nd={}\n\nfor i,n in enumerate(nums):\n\tif n not in d:\n\t\td[n]=i\n\telse:\n\t\tif i-d[n]<=k:\n\t\t\tflag=1\n\t\telse:\n\t\t\td[n]=i\n\n\nif flag==0:\n\tprint(\"false\")\nelse:\n\tprint(\"true\")\nprint(\"\\r\")\n\n\n#Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.\nnums=[1]\n\nn=len(nums)\n\nsumm=(n*(n+1))//2\nif summ!=sum(nums):\n\tif summ>sum(nums):\n\t\tprint(summ-sum(nums))\n\telse:\n\t\tprint(sum(nums)-summ)\n\nif (summ==1 and n==1) or (summ==sum(nums) and 0 not in nums):\n\tprint(\"0\")\nprint(\"\\r\")\n\n\n\n#Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n#method 1 \nnums=[0,1,0,3,12]\ni=0\nwhile sum(nums[i:])!=0:\n\tif nums[i]==0:\n\t\tnums.append(0)\n\t\tnums.pop(i)\n\telse:\n\t\ti=i+1\n\nprint(nums)\n\n#method 2 \nnums=[0,1,0,3,12]\nc = 0\ni=0\nwhile c Dear {name}
, Hope you and your family is healthy and happy.
{msg}
After this report please don't forget to consult with doctors.
May god bless you!\",\n \"CustomID\": \"Smart Healthcare\"\n }\n ]\n }\n result = mailjet.send.create(data=data)\n print(result.status_code)\n print(result.json())\n\n\ndef diagnose_disease(symptoms):\n cancer = ['bloating', 'pelvic pain', 'abdominal pain', 'difficulty eating', 'feeling full quickly', 'urinary urgency']\n diabetes = ['urinate', 'blurry vision', 'very tired', 'dry skin', 'very hungry']\n flu = ['fever', 'running nose', 'headache', 'bodyache', 'ache', 'pain']\n\n cancer_pts = 0\n flu_pts = 0\n diabetes_pts = 0\n\n for s in symptoms:\n cancer_pts = cancer_pts + cancer.count(s)\n flu_pts = flu_pts + flu.count(s)\n diabetes_pts = diabetes_pts + diabetes.count(s)\n\n if cancer_pts > flu_pts and cancer_pts > diabetes_pts:\n return 'You may suffer from cancer. Please go check for cancer test.'\n elif flu_pts > cancer_pts and flu_pts > diabetes_pts:\n return 'You may suffer from flu. Yo don\\'t need any test. Just need to consult a doctor.'\n else:\n return 'You may suffer from diabetes. Please go check for diabetes test.'\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"soni-chanchal/AI-ML-Medical-Technology","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"40150432752","text":"import re\n\nclass BingoCard:\n \n def __init__(self, numbers):\n self.numbers = numbers.copy()\n self.marked = [[False]*5 for _ in range(5)]\n \n def __repr__(self):\n return '\\n'.join([' '.join([str(number) for number in line]) for line in self.numbers])\n \n def mark(self, mark_number):\n for line_number, line in enumerate(self.numbers):\n for index, number in enumerate(line):\n if number == mark_number:\n self.marked[line_number][index] = True\n return\n \n def is_bingo(self):\n for i in range(5):\n if all(self.marked[i]) or all(self.marked[j][i] for j in range(5)):\n return True\n return False\n\n \n def score(self, drawn_number):\n unmarked_sum = 0\n for i in range(5):\n for j in range(5):\n unmarked_sum += self.numbers[i][j] if not self.marked[i][j] else 0\n return unmarked_sum * drawn_number\n\ncards = []\nr = r'([0-9]+[ ]*)'\nwith open('input/day4.txt', 'r', encoding='utf8') as file:\n drawn_numbers = [int(number) for number in file.readline().split(',')]\n file.readline() # skip line\n numbers = []\n for line in file:\n if line == '\\n':\n cards.append(BingoCard(numbers))\n numbers = []\n else:\n numbers.append([int(m.strip()) for m in re.findall(r,line)])\n cards.append(BingoCard(numbers))\n\n# Part 1\nfor drawn_number in drawn_numbers:\n for card in cards:\n card.mark(drawn_number)\n winners = [card for card in cards if card.is_bingo()]\n if winners:\n winner = winners[0]\n print(winner.score(drawn_number))\n break\n\n# Part 2\nfor drawn_number in drawn_numbers:\n drawn_number = int(drawn_number)\n for card in cards:\n card.mark(drawn_number)\n if len(cards) == 1:\n last_card = cards[0]\n cards = [card for card in cards if not card.is_bingo()]\n if len(cards) == 0:\n print(last_card.score(drawn_number))\n break","repo_name":"andrew-paul-thompson/advent-of-code-2021","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"21370571602","text":"import gi\ngi.require_version('Gtk', '4.0')\nfrom gi.repository import Gtk\n\nfrom .Config import Config\nfrom .Users import Users\nfrom .MainWindow import MainWindow\nfrom . import Common\n\n_tr = Config._tr\n\n\nclass UsersMenu:\n\n def __init__(self):\n\n self.menu_gui()\n\n\n def menu_gui(self):\n \"\"\"\n Generate menu GUI.\n \"\"\"\n\n # Popover\n self.menu_po = Gtk.Popover()\n\n # Grid (main)\n main_grid = Common.menu_main_grid()\n self.menu_po.set_child(main_grid)\n\n # Label - menu title (Users)\n label = Common.menu_title_label(_tr(\"Users\"))\n main_grid.attach(label, 0, 0, 1, 1)\n\n # Notebook\n notebook = Gtk.Notebook()\n notebook.set_hexpand(True)\n notebook.set_vexpand(True)\n main_grid.attach(notebook, 0, 1, 1, 1)\n\n # Tab pages and ScrolledWindow\n # \"Add/Remove Columns\" tab\n label = Gtk.Label()\n label.set_label(_tr(\"Add/Remove Columns\"))\n self.grid_add_remove_columns_tab = Gtk.Grid()\n self.grid_add_remove_columns_tab.set_margin_top(15)\n self.grid_add_remove_columns_tab.set_margin_bottom(5)\n self.grid_add_remove_columns_tab.set_margin_start(5)\n self.grid_add_remove_columns_tab.set_margin_end(5)\n self.grid_add_remove_columns_tab.set_row_spacing(5)\n notebook.append_page(self.grid_add_remove_columns_tab, label)\n\n # Button (Reset)\n self.reset_button = Common.reset_button()\n main_grid.attach(self.reset_button, 0, 2, 1, 1)\n\n # \"Add/Remove Columns\" tab GUI\n self.add_remove_columns_tab_gui()\n\n # GUI signals\n self.gui_signals()\n\n\n def add_remove_columns_tab_gui(self):\n \"\"\"\n Generate \"Add/Remove Columns\" tab GUI objects.\n \"\"\"\n\n # Grid\n grid = Gtk.Grid()\n grid.set_margin_top(5)\n grid.set_margin_bottom(5)\n grid.set_margin_start(5)\n grid.set_margin_end(5)\n grid.set_column_spacing(10)\n grid.set_row_spacing(3)\n self.grid_add_remove_columns_tab.attach(grid, 0, 0, 1, 1)\n\n # Label - tab title (Add/Remove Columns)\n label = Common.title_label(_tr(\"Add/Remove Columns\"))\n grid.attach(label, 0, 0, 2, 1)\n\n # CheckButton (User)\n self.user_cb = Common.checkbutton(_tr(\"User\"), None)\n self.user_cb.set_active(True)\n self.user_cb.set_sensitive(False)\n grid.attach(self.user_cb, 0, 1, 1, 1)\n\n # CheckButton (Full Name)\n self.full_name_cb = Common.checkbutton(_tr(\"Full Name\"), None)\n grid.attach(self.full_name_cb, 0, 2, 1, 1)\n\n # CheckButton (Logged In)\n self.logged_in_cb = Common.checkbutton(_tr(\"Logged In\"), None)\n grid.attach(self.logged_in_cb, 0, 3, 1, 1)\n\n # CheckButton (UID)\n self.uid_cb = Common.checkbutton(_tr(\"UID\"), None)\n grid.attach(self.uid_cb, 0, 4, 1, 1)\n\n # CheckButton (GID)\n self.gid_cb = Common.checkbutton(_tr(\"GID\"), None)\n grid.attach(self.gid_cb, 0, 5, 1, 1)\n\n # CheckButton (Processes)\n self.processes_cb = Common.checkbutton(_tr(\"Processes\"), None)\n grid.attach(self.processes_cb, 0, 6, 1, 1)\n\n # CheckButton (Home Directory)\n self.home_directory_cb = Common.checkbutton(_tr(\"Home Directory\"), None)\n grid.attach(self.home_directory_cb, 1, 1, 1, 1)\n\n # CheckButton (Group)\n self.group_cb = Common.checkbutton(_tr(\"Group\"), None)\n grid.attach(self.group_cb, 1, 2, 1, 1)\n\n # CheckButton (Terminal)\n self.terminal_cb = Common.checkbutton(_tr(\"Terminal\"), None)\n grid.attach(self.terminal_cb, 1, 3, 1, 1)\n\n # CheckButton (Start Time)\n self.start_time_cb = Common.checkbutton(_tr(\"Start Time\"), None)\n grid.attach(self.start_time_cb, 1, 4, 1, 1)\n\n # CheckButton (CPU)\n self.cpu_cb = Common.checkbutton(_tr(\"CPU\"), None)\n grid.attach(self.cpu_cb, 1, 5, 1, 1)\n\n\n def gui_signals(self):\n \"\"\"\n Connect GUI signals.\n \"\"\"\n\n self.menu_po.connect(\"show\", self.on_menu_po_show)\n self.reset_button.connect(\"clicked\", self.on_reset_button_clicked)\n\n\n def connect_signals(self):\n \"\"\"\n Connect some of the signals to be able to disconnect them for setting GUI.\n \"\"\"\n\n self.user_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.full_name_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.logged_in_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.uid_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.gid_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.processes_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.home_directory_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.group_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.terminal_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.start_time_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n self.cpu_cb.connect(\"toggled\", self.on_add_remove_checkbuttons_toggled)\n\n\n def disconnect_signals(self):\n \"\"\"\n Disconnect some of the signals for setting GUI.\n \"\"\"\n\n self.user_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.full_name_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.logged_in_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.uid_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.gid_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.processes_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.home_directory_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.group_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.terminal_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.start_time_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n self.cpu_cb.disconnect_by_func(self.on_add_remove_checkbuttons_toggled)\n\n\n def on_menu_po_show(self, widget):\n \"\"\"\n Run code when customizations menu popover is shown.\n \"\"\"\n \n try:\n self.disconnect_signals()\n except TypeError:\n pass\n self.set_gui()\n self.connect_signals()\n\n\n def on_reset_button_clicked(self, widget):\n \"\"\"\n Reset customizations.\n \"\"\"\n\n # Load default settings\n Config.config_default_users_func()\n Config.config_save_func()\n\n Common.update_tab_and_menu_gui(self, Users)\n\n\n def on_add_remove_checkbuttons_toggled(self, widget):\n \"\"\"\n Run a function for adding/removing columns to treeview.\n \"\"\"\n\n self.add_remove_columns()\n\n\n def set_gui(self):\n \"\"\"\n Set GUI items.\n \"\"\"\n\n # Set GUI objects on Add/Remove Column tab\n if 0 in Config.users_treeview_columns_shown:\n self.user_cb.set_active(True)\n else:\n self.user_cb.set_active(False)\n if 1 in Config.users_treeview_columns_shown:\n self.full_name_cb.set_active(True)\n else:\n self.full_name_cb.set_active(False)\n if 2 in Config.users_treeview_columns_shown:\n self.logged_in_cb.set_active(True)\n else:\n self.logged_in_cb.set_active(False)\n if 3 in Config.users_treeview_columns_shown:\n self.uid_cb.set_active(True)\n else:\n self.uid_cb.set_active(False)\n if 4 in Config.users_treeview_columns_shown:\n self.gid_cb.set_active(True)\n else:\n self.gid_cb.set_active(False)\n if 5 in Config.users_treeview_columns_shown:\n self.processes_cb.set_active(True)\n else:\n self.processes_cb.set_active(False)\n if 6 in Config.users_treeview_columns_shown:\n self.home_directory_cb.set_active(True)\n else:\n self.home_directory_cb.set_active(False)\n if 7 in Config.users_treeview_columns_shown:\n self.group_cb.set_active(True)\n else:\n self.group_cb.set_active(False)\n if 8 in Config.users_treeview_columns_shown:\n self.terminal_cb.set_active(True)\n else:\n self.terminal_cb.set_active(False)\n if 9 in Config.users_treeview_columns_shown:\n self.start_time_cb.set_active(True)\n else:\n self.start_time_cb.set_active(False)\n if 10 in Config.users_treeview_columns_shown:\n self.cpu_cb.set_active(True)\n else:\n self.cpu_cb.set_active(False)\n\n\n def add_remove_columns(self):\n \"\"\"\n Add/Remove columns to treeview.\n \"\"\"\n\n Config.users_treeview_columns_shown = []\n\n if self.user_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(0)\n if self.full_name_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(1)\n if self.logged_in_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(2)\n if self.uid_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(3)\n if self.gid_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(4)\n if self.processes_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(5)\n if self.home_directory_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(6)\n if self.group_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(7)\n if self.terminal_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(8)\n if self.start_time_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(9)\n if self.cpu_cb.get_active() == True:\n Config.users_treeview_columns_shown.append(10)\n\n # Apply changes immediately (without waiting update interval).\n Common.treeview_column_order_width_row_sorting(None, None, Users)\n\n Common.save_tab_settings(Users)\n\n\nUsersMenu = UsersMenu()\n\n","repo_name":"hakandundar34coding/system-monitoring-center","sub_path":"src/UsersMenu.py","file_name":"UsersMenu.py","file_ext":"py","file_size_in_byte":10413,"program_lang":"python","lang":"en","doc_type":"code","stars":849,"dataset":"github-code","pt":"48"}
+{"seq_id":"44268432642","text":"# 子集。这个题目主要的思路点在于,对每一次的数组递归除最后一位外的其他位,然后将所有结果*2,一部分加上新的最后一位,另一部分不变\n# 最后,在加上空集即可。\nclass Solution(object):\n def subsets(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n import copy\n result = self.func(nums)\n return result+[[]]\n\n def func(self,nums):\n if len(nums)<=1:\n return [nums]\n \n now = nums[-1]\n pre = self.func(nums[:len(nums)-1])\n pre_now = copy.deepcopy(pre)\n for i in pre_now:\n i += [now]\n return pre+pre_now+[[now]]","repo_name":"whywhs/Leetcode","sub_path":"Leetcode78_M.py","file_name":"Leetcode78_M.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"25066069386","text":"from __future__ import absolute_import, division, print_function\n\nfrom os import environ, getcwd\nfrom os.path import join\n\nimport shutil\nimport re\nimport os\nimport argparse\nimport keras\nimport numpy as np\nimport pandas as pd\nimport sklearn as skl\nimport tensorflow as tf\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications import DenseNet169, InceptionResNetV2, DenseNet201\nfrom keras.applications import NASNetMobile\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.metrics import binary_accuracy, binary_crossentropy, kappa_error\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom custom_layers import *\nfrom mura import Mura\n\npd.set_option('display.max_rows', 20)\npd.set_option('precision', 4)\nnp.set_printoptions(precision=4)\n\nenviron['TF_CPP_MIN_LOG_LEVEL'] = '2' # Shut up tensorflow!\nprint(\"tf : {}\".format(tf.__version__))\nprint(\"keras : {}\".format(keras.__version__))\nprint(\"numpy : {}\".format(np.__version__))\nprint(\"pandas : {}\".format(pd.__version__))\nprint(\"sklearn : {}\".format(skl.__version__))\n\n# Hyper-parameters / Globals\nBATCH_SIZE = 4 # tweak to your GPUs capacity\nIMG_HEIGHT = 420 # ResNetInceptionv2 & Xception like 299, ResNet50/VGG/Inception 224, NASM 331\nIMG_WIDTH = IMG_HEIGHT\nCHANNELS = 3\nDIMS = (IMG_HEIGHT, IMG_WIDTH, CHANNELS) # blame theano\nMODEL_TO_EVAL1 = './models/DenseNet169_420_HUMERUS.hdf5'\nMODEL_TO_EVAL2 = './models/DenseNet169_420_HAND.hdf5'\nMODEL_TO_EVAL3 = './models/DenseNet169_420_FINGER.hdf5'\nMODEL_TO_EVAL4 = './models/DenseNet169_420_FOREARM.hdf5'\nMODEL_TO_EVAL5 = './models/DenseNet169_420_ELBOW.hdf5'\nMODEL_TO_EVAL6 = './models/DenseNet169_420_SHOULDER.hdf5'\nMODEL_TO_EVAL7 = './models/DenseNet169_420_WRIST.hdf5'\nMODEL_TO_EVAL8 = './models/DenseNet169_420_NEW_HIST.hdf5'\nDATA_DIR = 'data_val/'\nEVAL_CSV = 'valid.csv'\nEVAL_DIR = 'data/val/'\n\nparser = argparse.ArgumentParser(description='Input Path')\nparser.add_argument('input_filename',default='valid_image_paths.csv', type=str)\nparser.add_argument('output_path', default='prediction.csv', type=str)\nproc_data_dir = join(os.getcwd(), 'data/val/')\nproc_train_dir = join(proc_data_dir, 'train')\nproc_val_dir = join(proc_data_dir, 'val')\n\n\nclass ImageString(object):\n _patient_re = re.compile(r'patient(\\d+)')\n _study_re = re.compile(r'study(\\d+)')\n _image_re = re.compile(r'image(\\d+)')\n _study_type_re = re.compile(r'XR_(\\w+)')\n\n def __init__(self, img_filename):\n\n self.img_filename = img_filename\n self.patient = self._parse_patient()\n self.study = self._parse_study()\n self.image_num = self._parse_image()\n self.study_type = self._parse_study_type()\n self.image = self._parse_image()\n self.normal = self._parse_normal()\n self.valid = self._parse_valid()\n\n\n def flat_file_name(self):\n return \"{}_{}_patient{}_study{}_{}_image{}.png\".format(self.valid, self.study_type, self.patient, self.study,\n self.normal, self.image)\n\n def _parse_patient(self):\n return int(self._patient_re.search(self.img_filename).group(1))\n\n def _parse_study(self):\n return int(self._study_re.search(self.img_filename).group(1))\n\n def _parse_image(self):\n return int(self._image_re.search(self.img_filename).group(1))\n\n def _parse_study_type(self):\n return self._study_type_re.search(self.img_filename).group(1)\n\n def _parse_normal(self):\n return \"normal\" if (\"negative\" in self.img_filename) else \"abnormal\"\n\n def _parse_normal_label(self):\n return 1 if(\"negative\" in self.img_filename) else 0\n\n def _parse_valid(self):\n return \"valid\" if (\"valid\" in self.img_filename) else \"test\"\n\ndef preprocess_img(img):\n # Histogram normalization in v channel\n hsv = color.rgb2hsv(img)\n hsv[:, :, 2] = exposure.equalize_hist(hsv[:, :, 2])\n img = color.hsv2rgb(hsv)\n\n # central square crop\n min_side = min(img.shape[:-1])\n centre = img.shape[0] // 2, img.shape[1] // 2\n img = img[centre[0] - min_side // 2:centre[0] + min_side // 2,\n centre[1] - min_side // 2:centre[1] + min_side // 2,\n :]\n\n # rescale to standard size\n img = transform.resize(img, (IMG_SIZE, IMG_SIZE))\n\n # roll color axis to axis 0\n img = np.rollaxis(img, -1)\n\n return img\n\ndef eval(args=None):\n\n args= parser.parse_args()\n\n # load up our csv with validation factors\n data_dir = join(getcwd(), DATA_DIR)\n eval_csv = join(data_dir, EVAL_CSV)\n\n true_labels=[]\n\n ###########################################\n df = pd.read_csv(args.input_filename, names=['img', 'label'], header=None)\n samples = [tuple(x) for x in df.values]\n # for img, label in samples:\n # #assert (\"negative\" in img) is (label is 0)\n # enc = ImageString(img)\n # true_labels.append(enc._parse_normal_label())\n # cat_dir = join(proc_val_dir, enc.normal)\n # if not os.path.exists(cat_dir):\n # os.makedirs(cat_dir)\n # shutil.copy2(enc.img_filename, join(cat_dir, enc.flat_file_name()))\n\n\n ###########################################\n\n eval_datagen = ImageDataGenerator(rescale=1./255\n# , histogram_equalization=True\n )\n eval_generator = eval_datagen.flow_from_directory(\n EVAL_DIR, class_mode='binary', shuffle=False,target_size=(IMG_HEIGHT, IMG_WIDTH), batch_size=BATCH_SIZE)\n n_samples = eval_generator.samples\n base_model = DenseNet169(input_shape=DIMS, weights='imagenet', include_top=False) #weights='imagenet'\n x = base_model.output\n x = GlobalAveragePooling2D(name='avg_pool')(x) # comment for RESNET\n # x = WildcatPool2d()(x)\n\n x = Dense(1, activation='sigmoid', name='predictions')(x)\n model = Model(inputs=base_model.input, outputs=x)\n model.load_weights(MODEL_TO_EVAL8)\n model.compile(optimizer=Adam(lr=1e-3)\n , loss=binary_crossentropy\n# , loss=kappa_error\n , metrics=['binary_accuracy'])\n score, acc = model.evaluate_generator(eval_generator, n_samples / BATCH_SIZE)\n print(model.metrics_names)\n print('==> Metrics with eval')\n print(\"loss :{:0.4f} \\t Accuracy:{:0.4f}\".format(score, acc))\n y_pred = model.predict_generator(eval_generator, n_samples / BATCH_SIZE)\n\n# print(y_pred)\n# df_filenames = pd.Series(np.array(eval_generator.filenames), name='filenames')\n# df_classes = pd.Series(np.array(y_pred), name='classes')\n\n# prediction_data = pd.concat([df_filenames, df_classes,])\n# prediction_data.to_csv(args.output_path + \"/prediction.csv\")\n\n mura = Mura(eval_generator.filenames, y_true = eval_generator.classes, y_pred1=y_pred, y_pred2=y_pred, y_pred3=y_pred, y_pred4= y_pred, y_pred5= y_pred, output_path= args.output_path)\n print(mura.metrics_by_encounter())\n\n\nif __name__ == '__main__':\n eval()\n","repo_name":"ynswon/MURA","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6980,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"28718153267","text":"from django.core.urlresolvers import reverse_lazy\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\nfrom .models import InfusionsoftProfile, UserProfile, UserPrivateProfile\nfrom .forms import UserProfileForm, UserPrivateProfileForm\n\n\n@login_required\ndef update_infusionsoft_tags(request):\n '''\n updates users tags with infusionsofts\n '''\n redirect = request.GET.get('next') if request.GET.get('next') else reverse_lazy(\"users:redirect\")\n\n profile = InfusionsoftProfile.objects.get_or_create(user=request.user)[0]\n profile.update_tags()\n\n return HttpResponseRedirect(redirect)\n\n@login_required\ndef update_user_profile(request):\n user_profile = UserProfile.objects.get_or_create(user=request.user)[0]\n form = UserProfileForm(instance=user_profile)\n if request.method == 'POST':\n form = UserProfileForm(request.POST, instance=user_profile)\n if form.is_valid:\n form.save()\n return HttpResponseRedirect(reverse_lazy(\"users:detail\", \n kwargs={\"pk\": request.user.pk}))\n context = {'form': form}\n return render_to_response(\"profiles/edit.html\", context, \n context_instance=RequestContext(request))\n\n\n@login_required\ndef update_user_private_profile(request):\n user_profile = UserPrivateProfile.objects.get_or_create(user=request.user)[0]\n form = UserPrivateProfileForm(instance=user_profile)\n if request.method == 'POST':\n form = UserPrivateProfileForm(request.POST, instance=user_profile)\n if form.is_valid:\n form.save()\n return HttpResponseRedirect(reverse_lazy(\"users:detail\", \n kwargs={\"pk\": request.user.pk}))\n context = {'form': form}\n return render_to_response(\"profiles/edit.html\", context, \n context_instance=RequestContext(request))\n\n","repo_name":"WebPowerLabs/django-trainings","sub_path":"dtf/profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"20640080639","text":"import os\nimport sys\n\nimport cv2\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nfrom radical_analysis_tool.radical_analysis_mainwindow import Ui_MainWindow\nfrom utils.Functions import creatBlankRGBImageWithSize, rgb2qimage, get_3_point_water_radical_img, drawline\n\n\nclass RadicalAnalysisGUI(QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(RadicalAnalysisGUI, self).__init__()\n self.setupUi(self)\n\n self.open_pushButton.clicked.connect(self.handle_open_button)\n self.analyze_pushButton.clicked.connect(self.handle_analyze_button)\n self.a_listWidget.itemClicked.connect(self.handle_a_list_widgt_item_click)\n self.b_listWidget.itemClicked.connect(self.handle_b_list_widgt_item_click)\n\n self.merged_scene = QGraphicsScene()\n self.merged_scene.setBackgroundBrush(Qt.gray)\n self.merged_graphicsView.setScene(self.merged_scene)\n self.merged_scene.setSceneRect(QRectF())\n self.merged_graphicsView.fitInView(self.merged_scene.sceneRect(), Qt.KeepAspectRatio)\n\n self.a_scene = QGraphicsScene()\n self.a_scene.setBackgroundBrush(Qt.gray)\n self.a_graphicsView.setScene(self.a_scene)\n self.a_scene.setSceneRect(QRectF())\n self.a_graphicsView.fitInView(self.a_scene.sceneRect(), Qt.KeepAspectRatio)\n\n self.b_scene = QGraphicsScene()\n self.b_scene.setBackgroundBrush(Qt.gray)\n self.b_graphicsView.setScene(self.b_scene)\n self.b_scene.setSceneRect(QRectF())\n self.b_graphicsView.fitInView(self.b_scene.sceneRect(), Qt.KeepAspectRatio)\n\n\n self.image_path = \"\"\n\n self.a_image = None\n self.b_image = None\n\n\n def handle_open_button(self):\n print(\"open clicked\")\n self.image_path = str(QFileDialog.getExistingDirectory(self, \"Select Directory\"))\n\n image_names = [f for f in os.listdir(self.image_path) if \".png\" in f or \".jpg\" in f or \".jpeg\" in f]\n for i in range(len(image_names)):\n item_a = QListWidgetItem(image_names[i])\n self.a_listWidget.addItem(item_a)\n item_b = QListWidgetItem(image_names[i])\n self.b_listWidget.addItem(item_b)\n\n def handle_analyze_button(self):\n print(\"analyze clicked\")\n\n if self.a_image is None or self.b_image is None:\n print(\"a image or b image is none\")\n return\n\n a_radical = get_3_point_water_radical_img(self.a_image)\n b_radical = get_3_point_water_radical_img(self.b_image)\n\n if a_radical is None or b_radical is None:\n print(\"a or b radical is none\")\n return\n\n bk_rgb = creatBlankRGBImageWithSize(self.a_image.shape)\n\n # draw mizi grid\n drawline(bk_rgb, (0,0), (bk_rgb.shape[0]-1, bk_rgb.shape[1]-1), (0, 0, 255), 1, gap=4)\n drawline(bk_rgb, (0, bk_rgb.shape[1] - 1), (bk_rgb.shape[0] - 1, 0), (0, 0, 255), 1, gap=4)\n drawline(bk_rgb, (0, int(bk_rgb.shape[1]/2)), (bk_rgb.shape[0]-1, int(bk_rgb.shape[1]/2)), (0, 0, 255), 1, gap=4)\n drawline(bk_rgb, (int(bk_rgb.shape[0]/2), 0), (int(bk_rgb.shape[0]/2), bk_rgb.shape[1] - 1), (0, 0, 255), 1, gap=4)\n\n\n for x in range(self.a_image.shape[0]):\n for y in range(self.a_image.shape[1]):\n if a_radical[x][y] == 0 and b_radical[x][y] == 0:\n bk_rgb[x][y] = (0, 0, 0) # black\n if a_radical[x][y] == 0 and b_radical[x][y] != 0:\n bk_rgb[x][y] = (0, 0, 255) # red\n if a_radical[x][y] != 0 and b_radical[x][y] == 0:\n bk_rgb[x][y] = (0, 255, 0) # green\n\n qimg = rgb2qimage(bk_rgb)\n qimg_pix = QPixmap.fromImage(qimg)\n\n self.merged_scene.addPixmap(qimg_pix)\n self.merged_scene.setSceneRect(QRectF())\n self.merged_graphicsView.fitInView(self.merged_scene.sceneRect(), Qt.KeepAspectRatio)\n self.merged_scene.update()\n\n def handle_a_list_widgt_item_click(self, item):\n print(\"item b clicked\")\n img_name = item.text().strip()\n img_path = os.path.join(self.image_path, img_name)\n if not os.path.exists(img_path):\n print(\"not a image found!\")\n return\n\n self.a_image = cv2.imread(img_path, 0)\n\n a_qimg = QImage(img_path)\n a_qimg_pix = QPixmap.fromImage(a_qimg)\n # self.a_scene.addPixmap(a_qimg_pix)\n self.a_scene.addPixmap(a_qimg_pix)\n self.a_scene.setSceneRect(QRectF())\n self.a_graphicsView.fitInView(self.a_scene.sceneRect(), Qt.KeepAspectRatio)\n self.a_scene.update()\n\n def handle_b_list_widgt_item_click(self, item):\n print(\"item b clicked\")\n img_name = item.text().strip()\n img_path = os.path.join(self.image_path, img_name)\n if not os.path.exists(img_path):\n print(\"not a image found!\")\n return\n\n self.b_image = cv2.imread(img_path, 0)\n\n b_qimg = QImage(img_path)\n b_qimg_pix = QPixmap.fromImage(b_qimg)\n # self.b_scene.addPixmap(b_qimg_pix)\n self.b_scene.addPixmap(b_qimg_pix)\n self.b_scene.setSceneRect(QRectF())\n self.b_graphicsView.fitInView(self.b_scene.sceneRect(), Qt.KeepAspectRatio)\n self.b_scene.update()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n MainWindow = RadicalAnalysisGUI()\n MainWindow.show()\n sys.exit(app.exec_())\n\n\n\n\n\n # img_path = \"./temp/瀛.png\"\n #\n # threshold = 1. / 4\n #\n # img = cv2.imread(img_path, 0)\n #\n # bk = get_3_point_water_radical_img(img)\n #\n # # rects = getAllMiniBoundingBoxesOfImage(img)\n # # print(len(rects))\n #\n # # cv2.line(img, (int(threshold*img.shape[0]), 0), (int(threshold*img.shape[0]), img.shape[1]), 0, 2 )\n # #\n # # for rect in rects:\n # # cent_x = rect[0] + int(rect[2] / 2)\n # #\n # # if cent_x <= threshold * img.shape[1]:\n # # cv2.rectangle(img, (rect[0], rect[1]), (rect[0]+rect[2], rect[1]+rect[3]), 0, 2)\n #\n #\n #\n #\n # cv2.imshow(\"1\", bk)\n #\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()","repo_name":"plateaukao/CSInTraditionalChineseCalligraphy","sub_path":"radical_analysis_tool/radical_analysis_gui.py","file_name":"radical_analysis_gui.py","file_ext":"py","file_size_in_byte":6120,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"}
+{"seq_id":"8589181924","text":"\"\"\"\nin order to share your fixtures across your entire module, py.test \nsuggests you define all your fixtures within one single conftest.py file.\n~ https://gist.github.com/peterhurford/09f7dcda0ab04b95c026c60fa49c2a68\n\nAdditionally, they do not need to be imported in tests that depend on them.\nJust use by name.\n\"\"\"\nimport logging\n\nimport pytest\nfrom grapl_tests_common.clients.grapl_web_client import GraplWebClient\n\n\n@pytest.fixture(\n # Reuse the same actix session for the entire test run session.\n # (yes, two unrelated uses of 'session')\n scope=\"session\"\n)\ndef actix_session() -> str:\n return GraplWebClient().get_actix_session()\n\n\n# Applies it to every test function automatically.\n@pytest.fixture(scope=\"function\", autouse=True)\ndef set_noisy_loggers_to_log_level_info(caplog: pytest.LogCaptureFixture) -> None:\n # We globally declare every logger should use DEBUG in `exec_pytest`,\n # and here we piecemeal set some of the less useful loggers to a\n # different level.\n\n # Ideally we'd be able to do this with a regex or something - I've opened a\n # discussion here: https://github.com/pytest-dev/pytest/discussions/8925\n logger_names = (\n \"botocore.auth\",\n \"botocore.endpoint\",\n \"botocore.hooks\",\n \"botocore.loaders\",\n \"botocore.parsers\",\n \"botocore.retryhandler\",\n \"urllib3.connectionpool\",\n )\n for logger_name in logger_names:\n caplog.set_level(logging.INFO, logger=logger_name)\n","repo_name":"macasieb/grapl","sub_path":"src/python/e2e-test-runner/e2e_test_runner/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"}
+{"seq_id":"7810703996","text":"# import the necessary packages\nprint(\"beginning execution\")\nimport grip\nimport time\nimport cv2 as cv\nimport pyrealsense2 as rs\nimport numpy as np\nimport altusi.visualizer as vis\nimport robot\nimport ikpy\nprint(\"libraries imported\")\n\ngp = grip.GripPipeline()\nprint(\"grip instantiated\")\n\nSEARCH_LR = 0\nALIGN_UD = 1\nIK = 2\nGRAB = 3\nHOME = 4\n\nstage = 0\ntracking = 0\n\nmy_chain = ikpy.chain.Chain.from_urdf_file(\"./niryo_one.urdf\")\n\n#object_detector = ObjectDetector()\n\nhome_pin = 13 #GPIO pin connected to set home switch\ndelay = 1.2 # seconds\nangle = 2 #degrees\n\nxlen = 640\nylen = 480\n\nx_center = xlen / 2\ny_center = ylen / 2\n\nx_range_low = x_center - 20\nx_range_high = x_center + 20\ny_range_low = y_center - 20\ny_range_high = y_center + 20\n\n# initialize the camera and grab a reference to the raw camera capture\nprint(\"loading camera\")\npipeline = rs.pipeline()\nconfig = rs.config()\nconfig.enable_stream(rs.stream.depth, xlen, ylen, rs.format.z16, 30)\nconfig.enable_stream(rs.stream.color, xlen, ylen, rs.format.bgr8, 30)\npipeline.start(config)\nprint(\"camera loaded\")\n\n# allow the camera to warmup\ntime.sleep(0.1)\n\n#instantiate robot\nprint(\"instantiating robot\")\nmy_robot = robot.Robot()\nmy_robot.goReady()\nprint(\"robot went home\")\n\n#call back function for GPIO interrupt\ndef home_pressed(channel):\n print(\"HOME PRESSED\")\n my_robot.resetHome()\n \n\n# capture frames from the camera\n_start_t = time.time()\nstart_time = 0\nwhile True:\n _prx_t = time.time() - _start_t\n _start_t = time.time()\n frames = pipeline.wait_for_frames()\n color_frame = frames.get_color_frame()\n depth_frame = frames.get_depth_frame()\n frm = np.asanyarray(color_frame.get_data())\n _start_t = time.time()\n time.sleep(0.01)\n gp.process(frm)\n bboxes = gp.filter_contours_output\n #scores, bboxes = object_detector.getObjects(frm, def_score=0.4)\n \n\n \n if len(bboxes) > 0 and (time.time() - start_time) > delay:\n tracking = 1\n target = bboxes[0]\n x1, y1, w, h = target\n \n x2 = x1 + w\n y2 = y1 + h\n \n w = x2 - x1\n h = y2 - y1\n \n xmid = int((x1 + x2) /2)\n ymid = int((y1 + y2) /2)\n \n z = depth_frame.get_distance(xmid, ymid)\n increment = 5 \n \n if stage == SEARCH_LR:\n if (xmid < x_range_low):\n print(\"move LEFT\")\n my_robot.moveLR(increment)\n\n my_robot.writeJSON()\n elif (xmid > x_range_high):\n print(\"move RIGHT\")\n my_robot.moveLR(-1 * increment)\n my_robot.writeJSON()\n else:\n print(\"DO NOT MOVE, in the middle X\")\n stage = ALIGN_UD\n continue\n if stage == ALIGN_UD:\n if (ymid < y_range_low):\n print(\"move UP\")\n my_robot.moveUD(increment)\n my_robot.writeJSON()\n elif (ymid > y_range_high):\n print(\"move DOWN\")\n my_robot.moveUD(-1 * increment)\n my_robot.writeJSON()\n else:\n print(\"DO NOT MOVE, in the middle Y\")\n stage = IK\n continue\n if stage == IK:\n pose = my_robot.current_pose[:8]\n pose[1] = 0\n pose[4] = 0\n pose[6] = 0\n pose[7] = 0\n current_position_frame = my_chain.forward_kinematics(pose)\n cyl_x = real_frame[:3,3][0]\n cyl_z = real_frame[:3,3][2]\n\n \n target_vector = [cyl_x + z ,0, cyl_z]\n target_frame = np.eye(4)\n target_frame[:3, 3] = target_vector\n target_angles = my_chain.inverse_kinematics(target_frame)\n target_pose = [my_robot.current_pose[1],target_angles[2],target_angles[3],0,target_angles[5],0,45]\n my_robot.setPose(target_pose)\n time.sleep(4)\n stage = GRAB\n continue\n if stage == GRAB:\n my_robot.moveGrab(-30)\n time.sleep(2)\n stage = HOME\n continue\n if stage == HOME:\n my_robot.goReady()\n time.sleep(4)\n stage = SEARCH_LR\n tracking = 0\n continue\n \n start_time = time.time()\n \n elif (len(bboxes) == 0) and (time.time() - start_time) > delay:\n tracking = 0\n stage = SEARCH_LR\n #go home call\n my_robot.goReady()\n print(\"go home,cant see anything\")\n start_time = time.time()\n \n if len(bboxes):\n frm = vis.plotBBoxes(frm, [(x,y,x+w,y+h) for x,y,w,h in bboxes], len(bboxes) * ['strawberry'], len(bboxes)*[0])\n frm = vis.plotInfo(frm, 'Raspberry Pi - FPS: {:.3f}'.format(1/_prx_t))\n frm = cv.cvtColor(np.asarray(frm), cv.COLOR_BGR2RGB)\n\n # show the frame\n cv.imshow(\"Frame\", frm)\n cv.imwrite(\"../Frontend/frame.jpg\", frm)\n \n key = cv.waitKey(1)\n if key in [27, ord('q')]:\n break\n #time.sleep(2)\n \npipeline.stop()\n","repo_name":"darisoy/RobotArm","sub_path":"pi-dyna-test-env/gripRunner.py","file_name":"gripRunner.py","file_ext":"py","file_size_in_byte":5033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"42018844884","text":"import numpy as np\n\nfrom MCTSAgent.Edge import Edge\nfrom MCTSAgent.Node import Node\nfrom connect4.Game import GameState, GRID_SHAPE\n\nEPSILON = 0.2\nALPHA = 0.8\n\n\ndef computeU(N, P, epsilon, nu, action, sumN):\n U = ((1 - epsilon) * P + epsilon * nu[action]) * np.sqrt(sumN) / (1 + N)\n return U\n\n\nclass MCTS():\n\n def __init__(self, root, cpuct, model, debug=False):\n self.root = root\n # self.nodes_dict is not reset when we change the root of the tree, in order to be able to recover\n # already computed nodes, if the new tree extends to these nodes\n self.nodes_dict = {}\n # As per the cheatsheet: during the selection phase of the MCTS, the tree starts from the root\n # and choses the node which has the maximum value for Q+U, until it reaches a leaf.\n # Q is equal to the mean value of the next state. At the beginning, Q is totally wrong, but after\n # some time, it becomes more and more accurate.\n # U is a function of P (prior proba of selecting the move) and N (number of visits), that increases\n # if the move has not been explored much (ie. if N is small compared to the N of the other moves),\n # or if the prior probability of the action is high. It is also mitigated by cpuct: U = cpuct * function(P, N)\n # Therefore, if cpuct is high, U will keep on being more important than Q, even during the latest\n # stages, and exploration will keep on being favored, rather than exploitation of Q\n self.cpuct = cpuct\n # Model used to evaluate the leaves, each time the selection phase reaches a leaf of the tree.\n # It can be whatever we want: something totally random, a neural network...\n # It just must contain a method predict(self, board) which predicts V (value of the board)\n # and P (probabilies of the actions in this board state)\n self.model = model\n self.debug = debug\n self.addNode(root)\n\n def simulate(self):\n \"\"\"Main function of the MCTS: does one simulation, ie. evaluates and expands the most promising leaf of the tree\n - selection: choses the most promising leaf (step 1 of the cheat sheet)\n - evaluate it: evaluates the allowed actions from this leaf, appends the corresponding nodes to the tree (step 2)\n - backfill the tree with the value of the leaf (step 3)\n \"\"\"\n\n if self.debug:\n state = GameState.from_id(self.root.state_id, GRID_SHAPE)\n print('ROOT NODE...%s', self.root.state_id)\n print(state)\n print('CURRENT PLAYER...%d', state.currentPlayer)\n\n ##### MOVE THE LEAF NODE\n ## YOUR CODE HERE: move to a leaf (call one of the functions below)\n leaf, value, done, breadcrumbs = self.moveToLeaf()\n if self.debug:\n state = GameState.from_id(leaf.state_id, GRID_SHAPE)\n print(state)\n\n ##### EXPAND THE LEAF NODE\n ## YOUR CODE HERE: expand the leaf (call one of the functions below)\n self.expandLeaf(leaf, done)\n\n ##### BACKFILL THE VALUE THROUGH THE TREE\n ## YOUR CODE HERE: backfill the value (call one of the functions below)\n self.backFill(leaf, value, breadcrumbs)\n\n def moveToLeaf(self):\n \"\"\"Goes down the tree until reaches the 'most promising leaf'\"\"\"\n\n if self.debug:\n print('------MOVING TO LEAF------')\n\n # list of the edges from the root to the leaf\n breadcrumbs = []\n currentNode = self.root\n\n done = False\n value = 0\n\n while not currentNode.isLeaf():\n\n if currentNode == self.root:\n epsilon = EPSILON\n nu = np.random.dirichlet([ALPHA] * len(currentNode.edges))\n else:\n epsilon = 0\n nu = [0] * len(currentNode.edges)\n ## YOUR CODE HERE: find the best next node, ie. the one which edge has the biggest Q + U\n ## Hint: each edge of the current node has Q = edge.stats['Q'], P = edge.stats['P'] and N = edge.stats['N']\n ## => you have to find the edge which maximizes Q+U, because that one is pointing out to the best next node\n ## NB: currentNode.edges returns a list of (action, edge), you have to iterate over that list\n ## For each edge: Q is directly found above, U is more complex, you have to compute it\n ## 1) see the comment in __init__(): U = self.cpuct * function(P, N)\n ## 2) basically, function(P, N) = P * sqrt(sum(N)) / (1+N), but we add\n ## randomness at the root node, so function(P, N) becomes:\n ## ((1-epsilon) * P + epsilon * nu[action]) * sqrt(sum(N)) / (1+N), where sum(N) is the sum of N of the edges of currentNode\n\n sumN = 0\n\n for action, edge in currentNode.edges:\n sumN += edge.stats['N']\n\n maxQU = -1\n for idx, (action, edge) in enumerate(currentNode.edges):\n Q = edge.stats['Q']\n P = edge.stats['P']\n N = edge.stats['N']\n U = computeU(N, P, epsilon, nu, idx, sumN)\n if Q + U > maxQU:\n maxQU = Q + U\n bestEdge = edge\n\n # At the very beginning, the tree is a single node, ie. a single leaf, and we don't enter into\n # this loop. Therefore, in that case, currentNode keeps on being the root node, value, done\n # keep the values they have before the loop (ie. 0 and False), and breadcrumbs keeps on being empty\n state = GameState.from_id(currentNode.state_id, GRID_SHAPE)\n # YOUR CODE HERE: run the action corresponding to the best edge\n _, value, done = state.takeAction(bestEdge.action)\n\n ## YOUR CODE HERE: append the selected edge to breadcrumbs\n breadcrumbs.append(bestEdge)\n ## YOUR CODE HERE: the outNode of the selected edge\n currentNode = bestEdge.outNode\n\n return currentNode, value, done, breadcrumbs\n\n def expandLeaf(self, leaf, done):\n\n if self.debug:\n print('------EVALUATING LEAF------')\n\n if not done:\n\n state = GameState.from_id(leaf.state_id, GRID_SHAPE)\n current_proba_victory, action_scores, allowedActions = self.evaluate_action_scores_from_model(state)\n if self.debug:\n print('CURRENT PROBA VICTORY FOR %d: %f', state.currentPlayer, current_proba_victory)\n\n ## YOUR CODE HERE: for all the actions allowed in allowedActions:\n ## - execute the action, which leads to a new state 'newState'.\n ## If the node corresponding to 'newState' is not in nodes_dict, append it using the function self.addNode(node)\n ## Else fetch it from nodes_dict\n ## Then create the Edge linking leaf to that node, with prior = action_scores[action], and add it to leaf.edges\n ## (which is the list of the edges of leaf)\n\n for action in range(len(allowedActions)):\n if allowedActions[action]:\n newState = state.takeAction(action)[0]\n node = Node(newState)\n if node in self.nodes_dict:\n node = self.nodes_dict[node.state_id]\n else:\n self.addNode(node)\n\n leaf.edges.append((action, Edge(leaf, node, action_scores[action], action)))\n\n def evaluate_action_scores_from_model(self, state):\n # state.board has shape (6,7), so it can be considered as a 1-layer image of shape:\n # - either (1,6,7) if channel layer first\n # - or (6,7,1) if channel last as usually done with Keras\n # Plus Keras needs a batch of inputs => we add an additional encapsulating array\n # => resulting shape is (1,1,6,7)\n inputToModel = np.array([[state.get_board_for_neural_network()]], dtype=np.int8)\n\n ## YOUR CODE HERE: let self.model do its predictions\n preds = self.model.predict(inputToModel)\n # preds[0] is an array of shape (1,1): the input was a batch of 1 board, and the neural network\n # predicts one value per board, between -1 and 1 because of the tanh activation for this head\n current_proba_victory = preds[0][0, 0]\n # preds[1] is an array of shape (1,7): the input was a batch of 1 board, and the neural network\n # predicts 7 values per board (the values for each possible action - more precisely a linear value\n # before transformation to a percentage via the softmax)\n logits = preds[1][0]\n\n # Forbidden actions must receive a probability equal to 0, therefore we force the output of the\n # neural network to -100 for them (so that the softmax would transform them to 0)\n allowedActions = state.allowedActions()\n forbiddenActions = [not (isallowed) for isallowed in allowedActions]\n logits[forbiddenActions] = -100\n\n # SOFTMAX\n odds = np.exp(logits)\n action_scores = odds / np.sum(odds)\n\n return ((current_proba_victory, action_scores, allowedActions))\n\n def backFill(self, leaf, value, breadcrumbs):\n \"\"\"breadcrumbs contains the list of edges which led from the root node to the leaf.\n In this function, we iterate over that list, in oder to increment N (number of visits)\n of these edges, and also in order to update their W (total value of the next state)\n and their Q = W / N\n \"\"\"\n\n ## Warning: there is a tricky trap with W: we want to add value or -value, depending on the\n ## player of the edge.\n ## Explanation:\n ## Let's say that the player at the leaf is 'leafPlayer': 'value' contains the value of the\n ## leaf according to 'leafPlayer'\n ## => during the iteration over the edges contained into breadcrumbs:\n ## - if the player of edge.inNode is equal to 'leafPlayer': W = W + value\n ##\t\t- else: W = W - value\n\n if self.debug:\n print('------DOING BACKFILL------')\n\n leafPlayer = GameState.current_player_from_id(leaf.state_id)\n\n ## YOUR CODE HERE:\n ## for each edge of breadcrumbs:\n ## - N is equal to edge.stats['N']. Increment it.\n ## - W is equal to edge.stats['W']. Add value or -value, as per the warning above.\n ## You can get the player of edge.inNode with GameState.current_player_from_id(edge.inNode.state_id)\n ## - update edge.stats['Q'], as per the formula Q = W / N\n\n for edge in breadcrumbs:\n edge.stats['N'] += 1\n if leafPlayer == GameState.current_player_from_id(edge.inNode.state_id):\n edge.stats['W'] += value\n else:\n edge.stats['W'] -= value\n edge.stats['Q'] = edge.stats['W'] / edge.stats['N']\n\n def addNode(self, node):\n self.nodes_dict[node.state_id] = node\n","repo_name":"ZaChr0me/MLUI","sub_path":"PluginSource/python/MCTSAgent/MCTS.py","file_name":"MCTS.py","file_ext":"py","file_size_in_byte":10945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"74134987345","text":"import base64\r\nimport os\r\nfrom urllib.parse import quote as urlquote\r\nimport sys\r\n\r\nfrom whoosh.index import create_in\r\nfrom whoosh.fields import Schema, TEXT, ID\r\n\r\nfrom whoosh.qparser import QueryParser\r\nfrom whoosh import scoring\r\nfrom whoosh.index import open_dir\r\n\r\nfrom flask import Flask, send_from_directory\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output\r\n\r\n\r\nUPLOAD_DIRECTORY = os.getcwd()+\"//upload\"\r\n\r\nALLOWED_EXTENSIONS = {'txt', 'pdf', 'doc','docx'}\r\n\r\ndef allowed_file(filename):\r\n return '.' in filename and \\\r\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\r\n\r\nif not os.path.exists(UPLOAD_DIRECTORY):\r\n os.makedirs(UPLOAD_DIRECTORY)\r\n\r\n\r\n# Normally, Dash creates its own Flask server internally. By creating our own,\r\n# we can create a route for downloading files directly:\r\nserver = Flask(__name__)\r\napp = dash.Dash(server=server)\r\n\r\n\r\n@server.route(\"/download/Python HTTP Test
\"\n response = response_start_line + response_headers + \"\\r\\n\" + response_body\n\n # 向客户端返回响应数据\n client_socket.send(bytes(response, \"utf-8\"))\n else:\n client_socket.shutdown(socket.SHUT_RDWR)\n client_socket.close()\n\n def serve_forever(self):\n serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n serverSocket.bind(self.address)\n serverSocket.listen(128)\n while True:\n clientSocket, clientAddress = serverSocket.accept()\n self._base_handler(clientSocket)\n","repo_name":"qianniaoge/handbook","sub_path":"Python/scripts/server/tcp_socket_server.py","file_name":"tcp_socket_server.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"12457808047","text":"import os\nimport pathlib as pl\nimport subprocess\nimport http.server\nimport socketserver\nimport threading\nimport time\n\nimport pytest\n\nfrom agent_build_refactored.utils.constants import (\n AGENT_VERSION,\n SOURCE_ROOT,\n CpuArch,\n)\nfrom agent_build_refactored.managed_packages.managed_packages_builders import (\n ALL_PACKAGE_BUILDERS,\n AGENT_AIO_PACKAGE_NAME,\n AGENT_NON_AIO_AIO_PACKAGE_NAME,\n)\nfrom tests.end_to_end_tests.managed_packages_tests.remote_machine_tests.tools import (\n create_packages_repo_root,\n get_packages_stable_version,\n is_builder_creates_aio_package,\n)\n\nfrom tests.end_to_end_tests.run_in_remote_machine import DISTROS\n\n\nIN_REMOTE_MACHINE = bool(os.environ.get(\"IN_REMOTE_MACHINE\"))\n\n\ndef add_cmd_args(parser, is_pytest_parser: bool):\n\n if is_pytest_parser:\n add_func = parser.addoption\n else:\n add_func = parser.add_argument\n\n add_func(\"--builder-name\", dest=\"builder_name\", required=True)\n\n add_func(\n \"--package-type\",\n dest=\"package_type\",\n required=True,\n choices=[\"deb\", \"rpm\"],\n help=\"Type of the package to test\",\n )\n\n add_func(\n \"--packages-source\",\n dest=\"packages_source\",\n required=False,\n help=\"Depending on the '--packages-source-type' option, directory or repo tarball with packages to test. \"\n \"If not specified, packages will be built inplace.\",\n )\n\n add_func(\n \"--packages-source-type\",\n dest=\"packages_source_type\",\n choices=[\"dir\", \"repo-tarball\"],\n default=\"dir\",\n required=False,\n )\n\n add_func(\n \"--remote-machine-type\",\n required=True,\n choices=[\"ec2\", \"docker\"],\n help=\"Type of the remote machine for the test. For 'ec2' - run in AWS ec2 instance,\"\n \"'docker' - run in docker container, 'local', run locally.\",\n )\n\n add_func(\n \"--stable-packages-version\",\n dest=\"stable_packages_version\",\n required=False,\n help=\"Version of the latest stable version of package.\",\n )\n\n add_func(\n \"--distro-name\",\n dest=\"distro_name\",\n required=True,\n choices=DISTROS.keys(),\n help=\"Distribution to test.\",\n )\n\n\ndef pytest_collection_modifyitems(config, items):\n if IN_REMOTE_MACHINE:\n return\n\n skip = pytest.mark.skip(\n reason=\"This test is only supposed to be run in a remote machine(docker or ec2)\"\n )\n for item in items:\n item.add_marker(skip)\n\n\ndef pytest_addoption(parser):\n if IN_REMOTE_MACHINE:\n add_cmd_args(parser, is_pytest_parser=True)\n\n\n@pytest.fixture(scope=\"session\")\ndef package_builder_name(request):\n \"\"\"Name of the builder that build tested packages.\"\"\"\n return request.config.option.builder_name\n\n\n@pytest.fixture(scope=\"session\")\ndef package_builder(package_builder_name):\n \"\"\"Builder class that builds tested packges.\"\"\"\n return ALL_PACKAGE_BUILDERS[package_builder_name]\n\n\n@pytest.fixture(scope=\"session\")\ndef package_type(request):\n return request.config.option.package_type\n\n\n@pytest.fixture(scope=\"session\")\ndef remote_machine_type(request):\n \"\"\"\n Fixture with time of the remote machine where tests can run. For now that's ec2 or docker.\n \"\"\"\n return request.config.option.remote_machine_type\n\n\n@pytest.fixture(scope=\"session\")\ndef distro_name(request):\n return request.config.option.distro_name\n\n\n@pytest.fixture(scope=\"session\")\ndef target_distro(distro_name):\n return DISTROS[distro_name]\n\n\n@pytest.fixture(scope=\"session\")\ndef use_aio_package(package_builder_name):\n \"\"\"Fixture flag that tells that a tested package is AIO\"\"\"\n return is_builder_creates_aio_package(package_builder_name=package_builder_name)\n\n\n@pytest.fixture(scope=\"session\")\ndef agent_package_name(use_aio_package):\n if use_aio_package:\n return AGENT_AIO_PACKAGE_NAME\n else:\n return AGENT_NON_AIO_AIO_PACKAGE_NAME\n\n\n@pytest.fixture(scope=\"session\")\ndef stable_packages_version(request):\n return get_packages_stable_version(\n version=request.config.option.stable_packages_version\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef packages_repo_root(\n request, tmp_path_factory, package_builder, stable_packages_version, package_type\n):\n \"\"\"\n Root directory which is served by the mock web server.\n The mock repo is located in ./repo folder, the public key is located in ./repo_public_key.gpg\n :return:\n \"\"\"\n\n return create_packages_repo_root(\n packages_source_type=request.config.option.packages_source_type,\n packages_source=request.config.option.packages_source,\n package_builder=package_builder,\n package_type=package_type,\n stable_packages_version=stable_packages_version,\n output_dir=tmp_path_factory.mktemp(\"packages_repo_root\"),\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef repo_root(packages_repo_root):\n \"\"\"Root directory of the mock repository.\"\"\"\n return packages_repo_root / \"repo\"\n\n\n@pytest.fixture(scope=\"session\")\ndef server_url(packages_repo_root):\n \"\"\"\n This fixture prepares http server with package repository and other needed files.\n \"\"\"\n\n # Create web server which serves repo and public key file.\n class Handler(http.server.SimpleHTTPRequestHandler):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, directory=str(packages_repo_root), **kwargs)\n\n with socketserver.TCPServer((\"\", 0), Handler) as httpd:\n repo_server_thread = threading.Thread(target=httpd.serve_forever)\n repo_server_thread.start()\n\n time.sleep(1)\n\n yield f\"http://localhost:{httpd.socket.getsockname()[1]}\"\n\n httpd.shutdown()\n repo_server_thread.join()\n\n\n@pytest.fixture(scope=\"session\")\ndef repo_url(server_url):\n \"\"\"Url to package repository\"\"\"\n\n return f\"{server_url}/repo\"\n\n\n@pytest.fixture(scope=\"session\")\ndef repo_public_key_url(server_url):\n return f\"{server_url}/repo_public_key.gpg\"\n\n\n@pytest.fixture(scope=\"session\")\ndef convenience_script_path(\n server_url, repo_url, repo_public_key_url, tmp_path_factory\n):\n \"\"\"\n Path to the convenience install script.\n We also start web server that serves mock repo with packages that have to be installed by the\n convenience script.\n \"\"\"\n\n # Build convenience script with current repo and public key urls.\n render_install_script_path = (\n SOURCE_ROOT\n / \"agent_build_refactored/managed_packages/convenience_install_script/render_install_agent_script.sh\"\n )\n\n install_script_path = (\n tmp_path_factory.mktemp(\"install_script\") / \"install-scalyr-agent-2.sh\"\n )\n\n subprocess.run(\n [\n \"bash\",\n str(render_install_script_path),\n repo_url,\n repo_url,\n repo_public_key_url,\n str(install_script_path),\n ],\n check=True,\n )\n\n yield install_script_path\n\n\ndef _get_package_path_from_repo(\n package_filename_glob: str, package_type: str, repo_root: pl.Path\n):\n \"\"\"Helper function that finds package inside repo root.\"\"\"\n if package_type == \"deb\":\n packages_dir = repo_root / \"pool/main/s\"\n elif package_type == \"rpm\":\n packages_dir = repo_root\n else:\n raise Exception(f\"Unknown package type: '{package_type}'\")\n\n found = list(packages_dir.rglob(package_filename_glob))\n assert len(found) == 1\n return found[0]\n\n\ndef _arch_to_package_arch(package_type: str, arch: CpuArch = None):\n if package_type == \"deb\":\n mapping = {\n CpuArch.x86_64: \"amd64\",\n CpuArch.AARCH64: \"arm64\",\n None: \"all\",\n }\n return mapping[arch]\n\n if package_type == \"rpm\":\n mapping = {\n CpuArch.x86_64: \"x86_64\",\n CpuArch.AARCH64: \"aarch64\",\n None: \"noarch\",\n }\n return mapping[arch]\n\n\n@pytest.fixture(scope=\"session\")\ndef agent_package_path(\n repo_root,\n package_builder,\n agent_package_name,\n use_aio_package,\n package_type,\n):\n if repo_root is None:\n return None\n\n if use_aio_package:\n package_arch = _arch_to_package_arch(\n package_type=package_type,\n arch=package_builder.ARCHITECTURE,\n )\n else:\n package_arch = _arch_to_package_arch(\n package_type=package_type,\n arch=None,\n )\n\n if package_type == \"deb\":\n package_filename_glob = (\n f\"{agent_package_name}_{AGENT_VERSION}_{package_arch}.{package_type}\"\n )\n elif package_type == \"rpm\":\n package_filename_glob = (\n f\"{agent_package_name}-{AGENT_VERSION}-1.{package_arch}.{package_type}\"\n )\n else:\n raise Exception(f\"Unknown package type: {package_type}\")\n\n return _get_package_path_from_repo(\n package_filename_glob=package_filename_glob,\n package_type=package_type,\n repo_root=repo_root,\n )\n","repo_name":"scalyr/scalyr-agent-2","sub_path":"tests/end_to_end_tests/managed_packages_tests/remote_machine_tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":8933,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"48"}
+{"seq_id":"12307738393","text":"# tests_random.py\n# This script trys to determine the cause of errors that don't seem to be\n# contained in one module. It works with Python 3\n\nimport binpacking_dynamic as bp\nimport coolcookies\nimport mooproblem\nimport numpy as np\nimport unittest\nimport pickle\nfrom binpacking_dynamic import coordarrays\nfrom solutions_dynamic import MultiSol\n\n\n@unittest.skip('Focus on another')\nclass Tests(unittest.TestCase):\n\n def setUp(self):\n n = 1000\n cookies = coolcookies.makeobjects(n, 100, 'tests/Cookies1000.txt')\n self.moop = mooproblem.MOCookieProblem(n, 24, 300, 8, cookies)\n\n def test_coordarrays2(self):\n # Set up\n with open('tests/solution597.pkl', 'rb') as input:\n solution = pickle.load(input)\n for i in range(solution.openbins):\n print(i, solution.vlrep[i])\n coordarrays(solution)\n mooproblem.checkformismatch(solution)\n fitvals = self.moop.calcfits(solution)\n self.assertEqual(len(fitvals), 3)\n\n\nclass FixTfillLoopTests(unittest.TestCase):\n\n def setUp(self):\n n = 1000\n batchsize = 100\n boxcap = 24\n rackcap = 300\n fillcap = 8\n cookies = coolcookies.makeobjects(n, batchsize, 'tests/Cookies1000.txt')\n self.moop = mooproblem.MOCookieProblem(n, boxcap, rackcap, fillcap, cookies)\n with open('tests/solution143.pkl', 'rb') as input:\n self.solution = pickle.load(input)\n self.solution = self.check_sol_for_rack_violations(self.solution)\n\n @unittest.skip('too much output')\n def test_fix_infinite_loop_fix_tfill(self):\n violations = self.moop.period_fill_limit(self.solution)\n sol = self.moop.fix_tfill(violations, self.solution)\n self.assertEqual(sol.getopenbins(), len(sol.getvlrep()))\n rcl_tfill = self.moop.get_move_restrictions(sol)\n for tk in range(len(rcl_tfill.res_fill)):\n self.assertGreaterEqual(rcl_tfill.res_fill[tk], 0)\n\n @unittest.skip('too much output')\n def test_fix_infinite_loop_all_earlier_boxes_full(self):\n violations = self.moop.period_fill_limit(self.solution)\n rcl_tfill = self.moop.get_move_restrictions(self.solution)\n sol, rcl_tfill = self.moop.select_fix_mode(0, violations,\n rcl_tfill, self.solution)\n violations = self.moop.period_fill_limit(sol)\n sol, rcl_tfill = self.moop.open_colderbox(violations[0], rcl_tfill, sol)\n inew = sol.getopenbins() - 1\n j = sol.vlrep[inew][0]\n tmin = self.moop.cookies.get(j).getbatch() * 600\n self.assertTrue(rcl_tfill.time_feasible(sol.tfill[inew], tmin))\n\n @unittest.skip('too much output')\n def test_fix_open_colderbox(self):\n with open('tests/solution836.pkl', 'rb') as input:\n sol836 = pickle.load(input)\n sol836 = self.check_sol_for_rack_violations(sol836)\n violations = self.moop.period_fill_limit(sol836)\n rcl_tfill = self.moop.get_move_restrictions(sol836)\n for loop in range(3):\n sol836, rcl_tfill = self.moop.select_fix_mode(loop, violations,\n rcl_tfill, sol836)\n violations = self.moop.period_fill_limit(sol836)\n if violations:\n sol836, rcl_tfill = \\\n self.moop.open_colderbox(violations[0], rcl_tfill, sol836)\n rviolations = self.moop.rackcapacity(sol836.getx(), sol836.gettfill())\n self.assertListEqual(rviolations, [])\n\n @unittest.skip('too much output')\n def test_fix_infinite_loop_boxes_not_combining(self):\n with open('tests/solution555.pkl', 'rb') as input:\n sol555 = pickle.load(input)\n sol555 = self.check_sol_for_rack_violations(sol555)\n violations = self.moop.period_fill_limit(sol555)\n ran_correctly = True\n try:\n sol555 = self.moop.fix_tfill(violations, sol555)\n except KeyboardInterrupt:\n ran_correctly = False\n self.assertTrue(ran_correctly)\n\n @unittest.skip('too much output')\n def test_fix_problem_with_adapt_movebins(self):\n with open('tests/sol_14349.pkl', 'rb') as input:\n sol14349 = pickle.load(input)\n sol14349 = self.check_sol_for_rack_violations(sol14349)\n violations = self.moop.period_fill_limit(sol14349)\n self.moop.fix_tfill(violations, sol14349)\n\n @unittest.skip('too much output')\n def test_fix_no_options_at_5400(self):\n with open('tests/momasol_13263.pkl', 'rb') as input:\n sol13263 = pickle.load(input)\n sol13263 = self.check_sol_for_rack_violations(sol13263)\n violations = self.moop.period_fill_limit(sol13263)\n sol13263 = self.moop.fix_tfill(violations, sol13263)\n violations = self.moop.period_fill_limit(sol13263)\n self.assertFalse(violations)\n\n def test_fix_remove_hot_cookies(self):\n with open('tests/momasol_9931.pkl', 'rb') as input:\n sol9931 = pickle.load(input)\n sol9931 = self.check_sol_for_rack_violations(sol9931)\n\n def check_sol_for_rack_violations(self, sol):\n # sol is an instance of a solution class\n rackviolations = self.moop.rackcapacity(sol.getx(), sol.gettfill())\n # We can fix cooling rack violations:\n if rackviolations:\n self.moop.fixcoolingrack(rackviolations, sol)\n return sol\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"kyspencer/GAMMA-PC-A-Greedy-Memetic-Algorithm-for-Storing-Cooling-Objects","sub_path":"SampleScripts/tests/tests_random.py","file_name":"tests_random.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"32660036229","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom collections import defaultdict\nimport sys\nn, m = map(int, sys.stdin.readline().split())\n\narr = []\nfor _ in range(n) :\n word = sys.stdin.readline().rstrip()\n arr.append(word)\n \nfor i in range(m) :\n find = sys.stdin.readline().rstrip()\n if find not in arr :\n print(-1)\n else :\n for j in range(n) :\n if arr[j] == find :\n print(j+1, end=' ')\n print()","repo_name":"KimHyungkeun/Algorithm","sub_path":"HackerRank/ETC/Defaultdict_Tutorial.py","file_name":"Defaultdict_Tutorial.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"45383332876","text":"\"\"\" provides functions to extract, read, and compare qr codes\n\"\"\"\n\nimport numpy as np\nimport cv2\nimport pyzbar.pyzbar as pyzbar\n\n\ndef crop_qr_code(frame):\n \"\"\"crops a qr code from an image and returns it binarized\n\n :param frame: the image\n :type frame: numpy.ndarray\n :return: cropped and binarized qr code\n :rtype: numpy.ndarray\n \"\"\"\n barcode = pyzbar.decode(frame, symbols=[pyzbar.ZBarSymbol.QRCODE])\n retval = None\n if barcode:\n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = frame[:, :, 0]\n\n # Only check first recognized barcode\n qpoints = np.asarray(barcode[0].polygon)\n pts1 = np.float32([qpoints[0], qpoints[3], qpoints[1], qpoints[2]])\n pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])\n M = cv2.getPerspectiveTransform(pts1, pts2)\n dst = cv2.warpPerspective(gray, M, (300, 300))\n ret3, th = cv2.threshold(dst, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n retval = th\n\n return retval\n\n\ndef read_qr_code(qrcode_frame):\n \"\"\"reads a qr code image and returns its decoded information\n\n :param qrcode_frame: image of a qr code\n :return: decoded string\n :type: qrcode_frame: numpy.ndarray\n :rtype: String\n \"\"\"\n\n barcode = pyzbar.decode(qrcode_frame)\n retval = None\n\n if barcode:\n # Handle encoding errors: https://sourceforge.net/p/zbar/discussion/664596/thread/ed7aca9d/#e9bf\n try:\n retval = barcode[0].data.decode(\"ascii\")\n except UnicodeDecodeError:\n retval = barcode[0].data.decode(\"utf-8\").encode(\"sjis\").decode('utf-8')\n\n return retval\n\n\ndef qr_codes_equal(qr1, qr2):\n \"\"\"checks if two qr codes are equal\n\n :param qr1: image of first qr code\n :param qr2: image of second qr code\n :return: True if equal, False if not\n :rtype: bool\n \"\"\"\n\n if qr1 is None or qr2 is None:\n return False\n else:\n string1 = read_qr_code(qr1)\n string2 = read_qr_code(qr2)\n\n return bool(string1 and string2 and string1.strip() == string2.strip())\n","repo_name":"iswunistuttgart/ITArchSoCLib","sub_path":"lib/QRScanner.py","file_name":"QRScanner.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"}
+{"seq_id":"29926369520","text":"# adding imports\nimport os\nimport sqlite3\nfrom flask import Flask ,request,session,g,redirect,url_for,render_template , abort,flash\n\n# constant\nSQL_FILE = 'schema.sql'\n\n# initializing app\napp = Flask(__name__)\n\n#configuration\napp.config.update(dict(\n DATABASE=os.path.join(app.root_path, 'flaskr.db'),\n DEBUG=True,\n SECRET_KEY='development key',\n USERNAME='admin',\n PASSWORD='default'\n))\napp.config.from_envvar('FLASKR_SETTINGS', silent=True)\n\n# basic endpoint\n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\ndef init_db():\n \"\"\"Initializes DB\"\"\"\n with app.app_context():\n db = get_db()\n with app.open_resource(SQL_FILE,mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\ndef connect_db():\n \"\"\"Connects to the specific database.\"\"\"\n rv = sqlite3.connect(app.config['DATABASE'])\n rv.row_factory = sqlite3.Row\n return rv\n\ndef get_db():\n \"\"\"\n Opens database connection in application context if it not already exist\n \"\"\"\n if not hasattr(g,'sqlite_db'):\n g.sqlite_db = connect_db()\n else :\n return g.sqlite_db\n\n\n@app.teardown_appcontext\ndef close_db():\n \"\"\"\n Closes the database connection afte the completion of request\n \"\"\"\n if hasattr(g,'sqlite_db'):\n g.sqlite_db.close()\n\n@app.route(\"/\")\ndef show_entries():\n db = get_db()\n cur = db.execute('select title,text from entries order by id desc')\n entries = cur.fetch_all()\n return render_template('show_entries.html',entries=entries)\n\n@app.route('/add',methods=['POST'])\ndef add_entry():\n if not session.get('logged_in'):\n abort(401)\n db = get_db()\n db.execute('insert into entries(text,title) values (?,?)',[request.form['text'],request.form['title']])\n db.commit()\n flash('New entry was successfully posted')\n return redirect(url_for('show_entries'))\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"voidabhi/flask","sub_path":"Flaskr/Flaskr.py","file_name":"Flaskr.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"21635905271","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 18 10:58:49 2017\n\n@author: tomislav\n\"\"\"\n\nimport cv2\n\n\ndef resize(img, scaleFactor):\n return cv2.resize(img, (int(img.shape[1]*(1/scaleFactor)),\n int(img.shape[0]*(1/scaleFactor))),\n interpolation=cv2.INTER_AREA)\n\n\ndef pyramid(image, scale=1.5, minSize=(500, 300)):\n yield image\n\n while True:\n image = resize(image, scale)\n if image.shape[0] < minSize[1] or image.shape[1] < minSize[0]:\n break\n yield image\n","repo_name":"tbazina/injection-moulding-products-detection-and-recognition","sub_path":"obj_detector/pyramid.py","file_name":"pyramid.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"798691832","text":"from django.test import TestCase, tag\nfrom game.models import Game, Board\nfrom tests.common.constants import BOARD_FIELDS_EXPECTED, FIELD_EMPTY_VAL\n\n\nclass MyTestCase(TestCase):\n @tag('enabled')\n def test_board_default_state(self):\n board = Board()\n\n field_emptiness_statuses = {\n field_name: board.check_if_field_is_empty(field=field_name) for field_name in BOARD_FIELDS_EXPECTED\n }\n self.assertNotIn(\n False, field_emptiness_statuses.values(),\n f\"in default state not all Board fields values were reported as empty:\"\n f\"reported: {field_emptiness_statuses}\"\n )\n\n for _field_name in BOARD_FIELDS_EXPECTED:\n _field_val = getattr(board, _field_name)\n self.assertEqual(\n _field_val, FIELD_EMPTY_VAL,\n f\"Board in default state reported a non-empty `{_field_name}` value:\"\n f\"reported: {_field_val}, expected: {FIELD_EMPTY_VAL}\"\n )\n \n self.assertEqual(\n board.check_if_board_is_full(), (False, 0),\n \"Board in default state reported to be full\"\n )\n\n self.assertFalse(board.win_board(), \"Board in default state reported win condition as met\")\n\n self.assertFalse(\n board.end_game,\n f\"Board in default state reported game end condition to be True - `end_game`={board.end_game}\"\n )\n\n self.assertFalse(\n board.last_move,\n f\"Board in default state reported last move dump as populated - `last_move`={board.last_move}\"\n )\n\n self.assertIsNone(\n board.game,\n f\"Board in default state reported game as populated - `game`={board.game}\"\n )\n\n # game_time = board.get_game_time()\n # self.assertEquals(\n # game_time, 0,\n # f\"Board in default state reported non-0 game time: {game_time}\"\n # )\n\n # @tag('enabled')\n def test_game_default_state(self):\n pass","repo_name":"infoshareacademy/jpydzr1-dkmap-django","sub_path":"tests/test_game/test_game_models.py","file_name":"test_game_models.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"38656640783","text":"t = int(input())\ndef dfs(x, level):\n global ans\n if level > ans :\n ans = level\n return\n for i in graph[x]:\n if not visited[i]:\n visited[i] = 1\n dfs(i, level+1)\n visited[i] = 0\n\nfor tc in range(1, t + 1):\n n,m = map(int,input().split())\n if m == 0:\n print('#{} {}'.format(tc, 0))\n else:\n v = [list(map(int, input().split())) for _ in range(m)]\n graph = [[] for i in range(n+1)]\n ans = -1\n for i in range(m):\n a,b = v[i]\n graph[a].append(b)\n graph[b].append(a)\n for i in range(1,n+1):\n visited = [0] * (n+1)\n dfs(i, 0)\n print('#{} {}'.format(tc, ans))\n\n\n\n","repo_name":"toki0411/Algorithm","sub_path":"SWEA/D3/2814. 최장 경로/최장 경로.py","file_name":"최장 경로.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"30049219132","text":"import logging\nimport os\nfrom os import path\n\nSCRIPT_PATH = path.dirname(path.abspath(__file__))\n\nLOGS_PATH = path.join(SCRIPT_PATH, \"logs\")\nif not path.exists(LOGS_PATH):\n os.makedirs(LOGS_PATH, exist_ok=True)\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.INFO)\nfile_handler = logging.FileHandler(path.join(LOGS_PATH, \"fv.log\"))\nformatter = logging.Formatter(\"%(asctime)s : %(levelname)s : %(name)s : %(message)s\")\nfile_handler.setFormatter(formatter)\nLOGGER.addHandler(file_handler)","repo_name":"AntoineDona/Connect4","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"21238403826","text":"import requests\nimport datetime\n\njson = {\n \"x-app-id\": \"287c85c7\",\n \"x-app-key\": \"5a50f94763fb437309102af392c30a03\",\n \"Content-Type\": \"application/json\"\n}\n\njson1 = {\n \"query\": input(\"What did you do today: \"),\n \"gender\": \"male\",\n \"weight_kg\": 81,\n \"height_cm\": 183,\n \"age\": 20\n}\n\ndate = datetime.date.today()\ntime = str(datetime.datetime.now().hour) + \":\" + str(datetime.datetime.now().minute) + \":\" + str(datetime.datetime.now().second)\na = requests.post(\"https://trackapi.nutritionix.com/v2/natural/exercise\", json = json1, headers=json)\nsheet_inputs = {\n \"sheet1\": {\n \"date\": str(date),\n \"time\": str(time),\n \"exercise\": a.json()[\"exercises\"][0][\"user_input\"],\n \"duration\": str(a.json()[\"exercises\"][0][\"duration_min\"]),\n \"calories\": str(a.json()[\"exercises\"][0][\"nf_calories\"]),\n }\n }\nrequests.post(\"https://api.sheety.co/e727c248aeb3c57bae687178bfc5a928/untitledSpreadsheet/sheet1\", json = sheet_inputs, headers = { \"Authorization Header\": \"Bearer Ksfaq137\"})","repo_name":"Townsend0/habit-tracker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"42121460393","text":"# missing functions\r\n# * ATTACK ... in General\r\n# * BLINK\r\n\r\nimport battlecode as bc\r\nimport random\r\nfrom datetime import datetime\r\n\r\ngc = bc.GameController()\r\ndirections = list(bc.Direction)\r\nmy_team = gc.team()\r\nenemy_team = bc.Team.Red\r\nif my_team == bc.Team.Red:\r\n\tenemy_team = bc.Team.Blue\r\nrandom.seed(datetime.now())\r\n\r\nclass MageClass(object):\r\n\r\n\tdef __init__(self):\r\n\t\tself.marsMap = bc.GameMap.mars_map\r\n\t\tself.earthMap = bc.GameMap.earth_map\r\n\t\t\r\n\t\tself.marsHeight = self.marsMap.height\r\n\t\tself.marsWidth = self.marsMap.width\r\n\t\t\r\n\t\tself.earthHeight = self.earthMap.height\r\n\t\tself.earthWidth = self.earthWidth.width\r\n\t\t\r\n\t\tself.NUMBER_OF_GUESSES = 5\r\n\r\n\tdef blink_attack_mars(self, unit):\r\n\t\tif not gc.is_blink_ready(unit.id):\r\n\t\t\treturn\r\n\t\tif bc.ResearchInfo.get_level(bc.UnitType.Mage) < 4:\r\n\t\t\treturn\r\n\t\t\t\r\n\t\tlocation = unit.location\r\n\t\t\t\r\n\t\tpossible_targets = sense_nearby_units_by_team(location.map_location(), 2, enemy_team)\r\n\t\tif len(possible_targets) > 2:\r\n\t\t\treturn\r\n\t\t\t\r\n\t\tfor guess in range(self.NUMBER_OF_GUESSES):\r\n\t\t\ti = random.randint(0, self.marsHeight-1)\r\n\t\t\tj = random.randint(0, self.marsWidth-1)\r\n\t\t\t\r\n\t\t\ttry:\r\n\t\t\t\ttemp_location = bc.MapLocation(bc.Planet.Mars, i, j)\r\n\t\t\t\tif gc.can_blink(unit.id, temp_location):\r\n\t\t\t\t\tgc.blink(unit.id, temp_location)\r\n\t\t\t\t\treturn\r\n\t\t\t\t\t\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint('Error:', e)\r\n\t\t\t\t# use this to show where the error was\r\n\t\t\t\ttraceback.print_exc()\r\n\r\n\tdef blink_attack_earth(self, unit):\r\n\t\tif not gc.is_blink_ready(unit.id):\r\n\t\t\treturn\r\n\t\tif bc.ResearchInfo.get_level(bc.UnitType.Mage) < 4:\r\n\t\t\treturn\r\n\t\t\t\r\n\t\tlocation = unit.location\r\n\t\t\r\n\t\tpossible_targets = sense_nearby_units_by_team(location.map_location(), 2, enemy_team)\r\n\t\tif len(possible_targets) > 2:\r\n\t\t\treturn\r\n\t\t\t\t\r\n\t\tfor guess in range(self.NUMBER_OF_GUESSES):\r\n\t\t\ti = random.randint(0, self.earthHeight-1)\r\n\t\t\tj = random.randint(0, self.earthWidth-1)\r\n\t\t\t\r\n\t\t\ttry:\r\n\t\t\t\ttemp_location = bc.MapLocation(bc.Planet.Earth, i, j)\r\n\t\t\t\tif gc.can_blink(unit.id, temp_location):\r\n\t\t\t\t\tgc.blink(unit.id, temp_location)\r\n\t\t\t\t\treturn\r\n\t\t\t\t\t\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint('Error:', e)\r\n\t\t\t\t# use this to show where the error was\r\n\t\t\t\ttraceback.print_exc()\r\n","repo_name":"AnPelec/Battlecode-2018","sub_path":"Helping Modules/mage.py","file_name":"mage.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"12187640737","text":"import os\nfrom shutil import copy\n\nsource_base_dir = \"../data2/autoscout/images/\"\ndestination_base_dir = \"../data2/autoscout-data/\"\n\nfor make in os.listdir(source_base_dir):\n make_dir = source_base_dir + make + '/'\n # if make <= 'Buick':\n # print(\"Skipping make %s \" % make)\n # continue\n\n for sub_d in os.listdir(make_dir):\n model = sub_d\n model_dir = make_dir + model + '/'\n\n print(\"Doing %s %s\"% (make, model))\n for f in os.listdir(model_dir):\n destination = destination_base_dir + ( make + '-' + model ) + '/'\n if not os.path.isdir(destination):\n os.makedirs(destination)\n source = model_dir + f\n try:\n copy(source, destination)\n except Exception as e:\n print(e)\n","repo_name":"banda13/Carrecognizer","sub_path":"helpers/scout-data-preloader.py","file_name":"scout-data-preloader.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"31969593929","text":"import sys\nimport itertools\nimport math\nimport collections\n\nwhich = \"sample\"\n\n\nTicket = collections.namedtuple('Ticket', 'seat buyer')\n\ndef solve(n_seats, n_buyers, tickets):\n if n_buyers != 2: return\n print(n_seats, n_buyers, tickets)\n\n by_seat = collections.defaultdict(set)\n by_buyer = collections.defaultdict(set)\n for t in tickets:\n by_seat[t.seat].add(t)\n by_buyer[t.buyer].add(t)\n\n print('seat', dict(by_seat))\n print('buyer', dict(by_buyer))\n print()\n\n\nsys.stdin = open('{}.in'.format(which))\n# sys.stdout = open('{}.out'.format(which), 'w')\n\nT = int(input())\n\nfor i in range(T):\n N, C, M = map(int, input().split())\n tickets = [\n Ticket(*(int(x) -1 for x in input().split()))\n for i in range(M)\n ]\n res = solve(N, C, tickets)\n print(\"Case #{}: {}\".format(i+1, res))\n","repo_name":"eric-wieser/codejam","sub_path":"2017/2/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"26995921183","text":"\"\"\"\nFile: swift_particle_filtering.py\n\nAuthor: Christopher Rowe\nVesion: 1.0.0\nDate: 29/03/2023\n\nComputes filters for SWIFT particle datasets.\n\nPublic API:\n\n class ParticleFilter\n\nDependancies:\n\n numpy\n QuasarCode\n sph_map.py (local file)\n swift_data_expression.py (local file)\n swiftsimio\n typing\n\"\"\"\n\nimport numpy as np\nfrom QuasarCode.Tools import ScriptWrapper\nimport swiftsimio as sw\nfrom typing import List, Union\n\nfrom ..io.swift_data_expression import parse_string\nfrom ..io.swift_parttype_enum import PartType\n\nclass ParticleFilter(object):\n @staticmethod\n def _calculate_filter(data_root_node: sw.SWIFTDataset, limit_fields: Union[str, List[str]], limit_units: Union[str, List[str]], limits_min: Union[None, float, List[float]] = None, limits_max: Union[None, float, List[float]] = None, **kwargs):\n # Handle formatting for there only being one item\n if isinstance(limit_fields, str):\n limit_fields = [limit_fields]\n limit_units = [limit_units]\n if limits_min is not None:\n limits_min = [limits_min]\n if limits_max is not None:\n limits_max = [limits_max]\n\n manual_filter = np.full(parse_string(limit_fields[0], data_root_node).shape[0], True)\n\n for i, field in enumerate(limit_fields):\n field_value = parse_string(field, data_root_node).to(limit_units[i])\n if limits_min is not None and limits_min[i] is not None:\n manual_filter = manual_filter & (field_value >= limits_min[i])\n if limits_max is not None and limits_max[i] is not None:\n manual_filter = manual_filter & (field_value <= limits_max[i])\n\n return manual_filter\n\n def __init__(self, data_root_node: sw.SWIFTDataset, limit_fields: Union[str, List[str]], limit_units: Union[str, List[str]], limits_min: Union[None, float, List[float]] = None, limits_max: Union[None, float, List[float]] = None):\n self.__filter = ParticleFilter._calculate_filter(data_root_node, limit_fields, limit_units, limits_min, limits_max)\n self.__n_items = self.__filter.sum()\n\n def __call__(self, dataset):\n return dataset[self.__filter]\n \n def __len__(self):\n return self.__n_items\n\n @property\n def numpy_filter(self):\n return self.__filter\n \n def update(self, additional_filter: np.ndarray):\n len_new_items = additional_filter.shape[0]\n len_self_items = self.__filter.shape[0]\n\n if len_new_items > len_self_items:\n # New filter is a larger array than the current filter! This is not compattible.\n raise ValueError(\"The new filter has a length of {}. This is larger than (and therfore, incompatible with) the current filter size of {}.\".format(len_new_items, len_self_items))\n elif len_new_items == len_self_items:\n # Same lengths, just do a simple logical and.\n #print(self.__filter)\n #print(type(self.__filter))\n #print(self.__filter[0])\n #print(additional_filter)\n #print(type(additional_filter))\n #print(additional_filter[0])\n self.__filter = self.__filter & additional_filter\n self.__n_items = self.__filter.sum()\n elif len_new_items != len(self):\n # New filter has a size that isn't consistent with the currently filtered subset.\n raise ValueError(\"The new filter has a length of {}. This is smaller than the current filter size of {}, but also not the same as (and therfore, incompatible with) the current filtered subset size of {}.\".format(len_new_items, len_self_items, len(self)))\n elif additional_filter.sum() > 0:\n # Apply to the filtered subset.\n self.__filter[np.where(self.__filter)[0][additional_filter == False]] = False\n self.__n_items = self.__filter.sum()\n else:\n # New filter was valid, but would remove all items. Just overwrite internal filter.\n self.__filter = np.full_like(self.__filter, False)\n self.__n_items = 0\n\n @staticmethod\n def passthrough_filter(data_file: sw.SWIFTDataset, part_type: PartType):\n return ParticleFilter(part_type.get_dataset(data_file), \"masses\", \"Msun\", None, None)\n\n @staticmethod\n def get_command_params():\n return [[\"limit-fields\", None, \"Names (or expressions with no spaces) as a semicolon seperated list of the data set to be used for filtering the list of particles.\", False, False, ScriptWrapper.make_list_converter(\";\"), None],\n [\"limit-units\", None, \"Unit expression for the limits specified. Uses a semicolon seperated list.\", False, False, ScriptWrapper.make_list_converter(\";\"), None],\n [\"limits-min\", None, \"\", False, False, ScriptWrapper.make_list_converter(\";\", float), None],\n [\"limits-max\", None, \"\", False, False, ScriptWrapper.make_list_converter(\";\", float), None]]\n \n @staticmethod\n def check_limits_present(limit_fields: Union[None, str, List[str]] = None, **kwargs):\n return limit_fields is not None\n","repo_name":"QuasarX1/PhD_HPC_Scripts","sub_path":"contra/filters/swift_particle_filtering.py","file_name":"swift_particle_filtering.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"72781496146","text":"# -*- coding:utf-8 -*-\n\"\"\"\n net.py\n ~~~~~~~~\n 网络相关助手函数\n\n :author: Fufu, 2021/6/9\n\"\"\"\nimport math\nimport os\nimport re\nfrom asyncio import create_subprocess_shell, subprocess\nfrom socket import AF_INET, AF_INET6, SOCK_STREAM, socket\nfrom typing import Any, Optional, Tuple, Union\n\nfrom aiohttp import ClientSession, TCPConnector\nfrom icmplib import async_ping\nfrom loguru import logger\n\nfrom .helper import get_int, get_json_loads, get_round\n\n\nasync def request(\n url: str,\n method: str = 'POST',\n *,\n as_json: bool = True,\n throw: bool = False,\n **kwargs: Any,\n) -> Union[dict, Tuple[Any]]:\n \"\"\"发起 HTTP 请求(异步)\"\"\"\n async with ClientSession(connector=TCPConnector(ssl=False)) as client:\n try:\n async with client.request(method, url, **kwargs) as resp:\n res = await resp.text()\n return get_json_loads(res) if as_json else (res, resp.status, dict(resp.headers))\n except Exception as e:\n logger.debug('Exception: {}, {}: {}', e, method, url)\n if throw:\n raise e\n return {} if as_json else ('', 504, {})\n\n\nasync def ping(target: str, count: int = 3, timeout: int = 1000, interval: float = 1.0):\n \"\"\"\n PING 目标网络, 获取延迟丢包 (备用)\n 调用 Windows/Linux 系统 PING 命令, 支持 IPv6\n\n :param target: 目标地址\n :param count: 发送的回显请求数\n :param timeout: 超时时间, Windows 有效\n :param interval: Linux 每次 PING 的时隔\n :return:\n \"\"\"\n err_value = 5000\n windows = os.name == 'nt'\n ret = {\n 'loss': err_value,\n 'minimum': err_value,\n 'maximum': err_value,\n 'average': err_value,\n }\n\n if windows:\n cmd = f'ping -w {timeout} -n {count} {target}'\n else:\n timeout = math.ceil(count * interval)\n cmd = f'ping -i {interval} -c {count} -w {timeout} {target}'\n\n process = await create_subprocess_shell(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # 等待该子进程运行结束\n stdout, errout = await process.communicate()\n\n if len(errout) > 0:\n return ret\n\n # 运行结果\n res = stdout.decode('gbk', 'ignore').strip()\n\n # 丢包率 %\n loss = re.findall(r'(\\d+)%', res)\n if loss:\n ret['loss'] = get_round(loss[0], err_value)\n\n # 延迟\n patt = r'(\\d+)ms.*? (\\d+)ms.*? (\\d+)ms' if windows else r'([\\d.]+)/([\\d.]+)/([\\d.]+)'\n delay = re.findall(patt, res)\n if delay and len(delay[0]) == 3:\n delay = [get_round(x, err_value) for x in delay[0]]\n ret['minimum'] = delay[0]\n if windows:\n ret['maximum'] = delay[1]\n ret['average'] = delay[2]\n else:\n ret['maximum'] = delay[2]\n ret['average'] = delay[1]\n\n return ret\n\n\nasync def pyping(target: str, count: int = 3, timeout: float = 0.7, interval: float = 0.1):\n \"\"\"\n PING 目标网络, 获取延迟丢包\n 基于 icmplib, 支持 IPv6\n\n :param target: 目标地址\n :param count: 发送的回显请求数\n :param timeout: 超时时间\n :param interval: Linux 每次 PING 的时隔\n :return:\n \"\"\"\n host = await async_ping(target, count=count, timeout=timeout, interval=interval)\n if host.is_alive:\n return {\n 'loss': get_round(host.packet_loss * 100),\n 'minimum': host.min_rtt,\n 'maximum': host.max_rtt,\n 'average': host.avg_rtt,\n }\n\n return {\n 'loss': 100,\n 'minimum': 5000,\n 'maximum': 5000,\n 'average': 5000,\n }\n\n\ndef chk_port(\n ip: Union[str, tuple, list],\n port: Optional[int] = None,\n as_ipv6: bool = False,\n timeout: int = 5,\n) -> Tuple[bool, int]:\n \"\"\"\n 检查 TCP 端口连通性\n\n e.g.::\n\n chk_port('baidu.com', 443)\n chk_port('baidu.com:443')\n chk_port(('baidu.com', 443))\n chk_port('baidu.com')\n chk_port('[::1]:443', as_ipv6=True)\n\n :param ip:\n :param port: 默认 80\n :param as_ipv6:\n :param timeout: 超时秒数\n :return:\n \"\"\"\n if not port:\n ip_port = ip if isinstance(ip, (list, tuple)) else str(ip).rsplit(':', 1)\n ip, port = ip_port if len(ip_port) > 1 else (ip_port, None)\n\n try:\n with socket(AF_INET6 if as_ipv6 else AF_INET, SOCK_STREAM) as s:\n s.settimeout(get_int(timeout, 5))\n x = s.connect_ex((str(ip), get_int(port, 80)))\n s.settimeout(None)\n return x == 0, x\n except Exception:\n pass\n\n return False, -1\n","repo_name":"fufuok/PyAgent","sub_path":"src/libs/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"}
+{"seq_id":"4823633840","text":"\"\"\"使用百度云接口和人脸库完成本地合影图片的多人脸识别\"\"\"\nfrom aip import AipFace\nimport base64\nimport dlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math,cv2\nimport os, glob,math\nfrom skimage import io\n\n\"\"\"\n人脸特征点检测 栽植模压模压顶替\n\"\"\"\n\n\n\n\ndef rect_to_bb(rect): # 获得人脸矩形的坐标信息\n x = rect.left()\n y = rect.top()\n w = rect.right() - x\n h = rect.bottom() - y\n return (x, y, w, h)\n\n\"\"\"\n人脸对齐\n\"\"\"\ndef face_alignment(faces):\n predictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\") # 用来预测关键点\n faces_aligned = []\n for face in faces:\n rec = dlib.rectangle(0,0,face.shape[0],face.shape[1])\n shape = predictor(np.uint8(face),rec) # 注意输入的必须是uint8类型\n \n order = [36,45,30,48,54] # left eye, right eye, nose, left mouth, right mouth 注意关键点的顺序,这个在网上可以找\n for j in order:\n x = shape.part(j).x\n y = shape.part(j).y\n #cv2.circle(face, (x, y), 2, (0, 0, 255), -1) #测试加还是不加\n\n eye_center =((shape.part(36).x + shape.part(45).x) * 1./2, # 计算两眼的中心坐标\n (shape.part(36).y + shape.part(45).y) * 1./2)\n dx = (shape.part(45).x - shape.part(36).x) # note: right - right\n dy = (shape.part(45).y - shape.part(36).y)\n\n angle = math.atan2(dy,dx) * 180. / math.pi # 计算角度\n RotateMatrix = cv2.getRotationMatrix2D(eye_center, angle, scale=1) # 计算仿射矩阵\n RotImg = cv2.warpAffine(face, RotateMatrix, (face.shape[0], face.shape[1])) # 进行放射变换,即旋转\n faces_aligned.append(RotImg)\n return faces_aligned\n\ndef feature(path,foces):\n im_raw =cv2.imread(foces).astype('uint8') \n detector = dlib.get_frontal_face_detector()\n gray = cv2.cvtColor(im_raw, cv2.COLOR_BGR2GRAY)\n rects = detector(gray, 1)\n src_faces = []\n for (i, rect) in enumerate(rects):\n (x, y, w, h) = rect_to_bb(rect)\n detect_face = im_raw[y:y+h,x:x+w]\n src_faces.append(detect_face)\n cv2.rectangle(im_raw, (x, y), (x + w, y + h), (0, 255, 0), 2)\n cv2.putText(im_raw, \"Face: {}\".format(i + 1), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n faces_aligned = face_alignment(src_faces)\n #cv2.imshow(\"src\", im_raw) \n for j in os.listdir(path): #清空拟装合影照片中分离人脸目录中的文件\n os.remove(path+'\\\\'+j) \n i = 0\n for face in faces_aligned:\n #cv2.imshow(\"det_{}\".format(i), face)\n i = i + 1 \n io.imsave(path+'\\\\'+'Face{}.jpg'.format(i),face)\n #cv2.imshow(\"Output\", im_raw)\n cv2.waitKey(0)\n\ndef AipFaceRecognition(pathfile):\n \n with open(pathfile,\"rb\") as f: \n # b64encode是编码\n base64_data = base64.b64encode(f.read())\n image = str(base64_data,'utf-8')\n imageType = \"BASE64\" #3种\"URL\",\"FACE_TOKEN\"\n groupIdList = \"qq\" #你上传百度人脸库照片,用户组ID名叫\"qq\"\n \"\"\" 调用人脸搜索 \"\"\"\n a=client.search(image, imageType,groupIdList) \n #print(a['user_list'][2][ 'user_id'],a['user_list'][3][ 'score'])\n return a #['result']['user_list'][0]['user_id']\n\n\nif __name__ == \"__main__\":\n focePath=r'C:\\Users\\Administrator\\Desktop\\1234.jpg' #合影照片\n \"\"\"合影照片中分离人脸子目录\"\"\"\n path = r'zkk' \n \"\"\" 你的 APPID AK SK \"\"\"\n APP_ID = '15427306'\n API_KEY = 'MUlz7ihrX5BiKcOLo6EGRfbq'\n SECRET_KEY = 'vt0Ob07UWpgOiyiKceacv0IqAzACxsCy'\n client = AipFace(APP_ID, API_KEY, SECRET_KEY)\n \n feature(path,focePath)\n userlist=[]\n for i in os.listdir(path):\n pathfile=path+'\\\\'+i\n A=AipFaceRecognition(pathfile)\n if A.get('result',None) !=None:\n if A['result']['user_list'][0]['score']>50: #取相似值大于50%\n #print('{}照片同{}相似度为{}'.format(i,A['result']['user_list'][0]['user_id'],A['result']['user_list'][0]['score']))\n print('{}照片同{}相似'.format(i,A['result']['user_list'][0]['user_id']))\n \n","repo_name":"smists/face","sub_path":"face1.py","file_name":"face1.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"35914715648","text":"class Node:\r\n \"\"\"\r\n A class for a node in a singly-linked list, storing\r\n a data payload and links to next node.\r\n \"\"\"\r\n\r\n def __init__(self, data = None, next = None):\r\n \"\"\"Initialize the node with data payload and link to next node.\"\"\"\r\n self.data = data\r\n self.next = next\r\n\r\n def getdata(self):\r\n \"\"\"Get the node's data payload.\"\"\"\r\n return self.data\r\n\r\n def setdata(self, data = None):\r\n \"\"\"Set the node's data payload.\"\"\"\r\n self.data = data\r\n\r\n def getnext(self):\r\n \"\"\"Get the next linked node.\"\"\"\r\n return self.next\r\n\r\n def setnext(self, node = None):\r\n \"\"\"Set the next linked node.\"\"\"\r\n self.next = node\r\n\r\nclass LinkedList:\r\n \"\"\"\r\n A singly linked list.\r\n \"\"\"\r\n\r\n def __init__(self, data=None, head=None):\r\n self.data = data\r\n self.head = head\r\n \r\n def __iter__(self):\r\n \"\"\"Returns a forward iterator over the list.\"\"\"\r\n node = self.head\r\n while node is not None:\r\n yield node.getdata()\r\n node = node.getnext()\r\n\r\n def __str__(self):\r\n \"\"\"Returns a string representation of the list.\"\"\"\r\n return \" -> \".join([str(x) for x in self])\r\n\r\n def __repr__(self):\r\n \"\"\"Returns a printable representation of the list.\"\"\"\r\n return str(self)\r\n\r\n def __len__(self):\r\n \"\"\"Returns the length of the list.\"\"\"\r\n size = 0\r\n for i in self:\r\n size += 1\r\n return size\r\n def push(self, data):\r\n \"\"\"\r\n Adds a new item to the end of the list.\r\n param data: The new item to append to the list.\r\n returns: None\r\n \"\"\"\r\n if self.head is None:\r\n node = Node()\r\n node.setdata(data)\r\n node.setnext(None)\r\n self.head = node\r\n\r\n else:\r\n node = Node()\r\n node.setdata(data)\r\n itr = self.head\r\n while itr.next:\r\n itr = itr.next\r\n itr.next = node\r\n\r\ndef mergeLists(baseList, tailList):\r\n itr = baseList.head\r\n while itr.next:\r\n itr = itr.next\r\n itr.next = tailList.head\r\n return baseList\r\n\r\n\r\ndef intersection(listA, listB):\r\n lenA = len(listA)\r\n lenB = len(listB)\r\n offset = abs(lenA-lenB)\r\n print(\"Offset: \",offset)\r\n currA = listA.head\r\n currB = listB.head\r\n ## length of listA greater then listB; then offset the listA\r\n if lenA > lenB:\r\n for i in range(offset):\r\n currA = currA.next\r\n ## length of listB greater then listA; then offset the listB\r\n elif lenB > lenA:\r\n for i in range(offset):\r\n currB = currB.next\r\n #print(currA.data)\r\n #print(currB.data)\r\n while currA != None:\r\n #while currA.next:\r\n if currA == currB:\r\n return currA\r\n else:\r\n currA = currA.next\r\n currB = currB.next\r\n\r\n\r\nif __name__ == \"__main__\":\r\n mergeList = LinkedList()\r\n #mergeList.push(130)\r\n #mergeList.push(180)\r\n mergeList.push(190)\r\n\r\n listA = LinkedList()\r\n listA.push(10)\r\n listA.push(11)\r\n listA.push(13)\r\n listA.push(12)\r\n listA.push(15)\r\n listA.push(16)\r\n listA.push(18)\r\n listA=mergeLists(listA,mergeList)\r\n\r\n listB = LinkedList()\r\n listB.push(14)\r\n listB.push(17)\r\n listB.push(19)\r\n listB.push(20)\r\n listB=mergeLists(listB,mergeList)\r\n \r\n\r\n ##two lists created listA and listB\r\n print(\"List A: \",listA)\r\n print(\"List A length\",len(listA))\r\n print(\"List B: \",listB)\r\n print(\"List B length\",len(listB))\r\n common = intersection(listA, listB)\r\n #print(\"First Common: \",intersection(listA, listB).data)\r\n #print(\"First Common: \",intersection(listA, listB))\r\n print(\"First Common element data: \",common.data)\r\n print(\"First Common element: \",common)","repo_name":"deena-dayalan/algorithm","sub_path":"LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"11700791084","text":"from __future__ import division, print_function\n\n# Import Python modules\nimport os\nimport sys\n\n# Import Broadband modules\nimport cc\nimport bband_utils\n\nclass BBToolboxCfg(object):\n \"\"\"\n Define the configuration parameters for the SDSU BBToolbox program\n \"\"\"\n cfgdict = {}\n\n def getval(self, attr):\n try:\n val = self.cfgdict[attr]\n except KeyError:\n print(\"Invalid Source File - Missing attribute: %s\" % (attr))\n print(\"Exiting\")\n sys.exit(1)\n return val\n\n def parse_src(self, a_srcfile):\n \"\"\"\n This function calls bband_utils's parse property file function\n to get a dictionary of key, value pairs and then looks for a\n the parameters needed by bbtoolbox\n \"\"\"\n self.cfgdict = bband_utils.parse_properties(a_srcfile)\n\n val = self.getval(\"depth_to_top\")\n self.DEPTH_TO_TOP = float(val)\n\n val = self.getval(\"fault_length\")\n self.LENGTH = float(val)\n\n val = self.getval(\"dip\")\n self.DIP = float(val)\n\n val = self.getval(\"rake\")\n self.RAKE = float(val)\n\n val = self.getval(\"hypo_along_stk\")\n self.HYPO_ALONG_STK = float(val)\n\n val = self.getval(\"hypo_down_dip\")\n self.HYPO_DOWN_DIP = float(val)\n\n val = self.getval(\"magnitude\")\n self.MAG = float(val)\n\n val = self.getval(\"seed\")\n self.SEED = int(float(val))\n\n # Now look for the optional grid parameters\n if 'grid_x' in self.cfgdict:\n self.grid_x = float(self.getval(\"grid_x\"))\n if 'grid_y' in self.cfgdict:\n self.grid_y = float(self.getval(\"grid_y\"))\n if 'grid_z' in self.cfgdict:\n self.grid_z = float(self.getval(\"grid_z\"))\n\n #\n # Read parameters out of the source file to obtain parameters\n # needed by the BBcoda codes\n #\n fcodes = cc.find_fx_fy_fz(self.HYPO_ALONG_STK,\n self.LENGTH,\n self.DIP,\n self.HYPO_DOWN_DIP,\n self.DEPTH_TO_TOP)\n self.fsx = fcodes[0]\n self.fsy = fcodes[1]\n self.fsz = fcodes[2]\n #print (\"ETH conversion from hypalongstk: \"\n # \"%f flength: %f dip: %f hypdowndip: %f depthtotop: %f\\n\" %\n # (self.HYPO_ALONG_STK,\n # self.LENGTH,\n # self.DIP,\n # self.HYPO_DOWN_DIP,\n # self.DEPTH_TO_TOP))\n #print (\"resulting fsx: %f fxy: %f fsz: %s\\n\" % (self.fsx,\n # self.fsy,\n # self.fsz))\n\n def calculate_stress(self):\n \"\"\"\n This function calculates the stress parameters for SDSU based\n on the depth of the fault. These values are calibrated for use\n in Eastern North America\n \"\"\"\n stress = 16.0 * self.DEPTH_TO_TOP + 225\n stress = stress * 10**6\n\n return stress\n\n def __init__(self, a_srcfile=None):\n \"\"\"\n Set up some parameters for BBToolbox\n \"\"\"\n self.MAG = None\n self.grid_x = None\n self.grid_y = None\n self.grid_z = 125.0\n self.copy_lf_seismograms = True\n\n # Parse src file, if given\n if a_srcfile:\n self.parse_src(a_srcfile)\n\n self.MODALITY = 1\n # GS_FLAG: Don't change it here, override it in the velocity\n # model config file using a 'CODEBASE_SDSU_GS_FLAG = XXX' line\n # 1: Western US (active region),\n # 2: Eastern NA (stable region),\n # 3: Japan\n self.GS_FLAG = 1\n # NGAW_FLAG: Don't change it here, override it in the velocity\n # model config file using a 'CODEBASE_SDSU_NGAW_FLAG = XXX' line\n # 1: NGA-WEST1\n # 2: NGA-WEST2\n self.NGAW_FLAG = 2\n self.KAPPA = 0.04\n self.Q_CODA = 150.0\n self.FDEC = 0.8\n self.AFAC = 41.0\n self.BFAC = 34.0\n self.SOURCE_MECH = \"rs\"\n self.SOURCE_FUNC = \"dreg\"\n self.VERBOSE = \"on\"\n self.TR_SCA = 0.075\n self.STR_FAC = 50.e6\n\n # 06/10/11: Sandarsh MK\n # Note: Setting FMAX = 20.00 Hz will\n # cause BBtoolbox to produce NaNs in 000 and 090 seismograms.\n self.FMAX = 100.00\n\n # 09/22/2020: Correlation flag\n # 0: Do not include correlation\n # 1: Include only inter-frequency correlation\n # 2: Include spatial correlation\n self.corr_flag = 0\n\nif __name__ == \"__main__\":\n BBCODA2 = BBToolboxCfg()\n print(\"Created Test Config Class: %s\" % (os.path.basename(sys.argv[0])))\n","repo_name":"SCECcode/bbp","sub_path":"bbp/comps/bbtoolbox_cfg.py","file_name":"bbtoolbox_cfg.py","file_ext":"py","file_size_in_byte":4721,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"48"}
+{"seq_id":"21028207231","text":"# 创建服务器用到的模块\nimport socketserver\n\n\nclass MySelfServer(socketserver.BaseRequestHandler): # 第一步创建一个自己的server类,继承BaseRequestHandler类\n\n # 重写BaseRequestHandler类中的handle方法,直接写在自己创建的类中就可以了\n def handle(self): # 里面的内容为服务器端跟客户端的所有交互\n while True:\n\n # 接收数据\n self.data = self.request.recv(1024).strip()\n\n # 打印客户端ip地址和发送来的数据,这里可能会问为什么会有self.client_address这个参数,这个在父类构造函数中\n print(\"{} wrote:\".format(self.client_address[0]))\n print(self.data)\n\n # 判断客户端是否断开\n if not self.data:\n print(self.client_address, '的链接断开了!') # 等待接收但接收为空则客户端断开\n break\n\n # 将接收到的数据大写发送回去\n self.request.sendall(self.data.upper())\n\n\nif __name__ == \"__main__\":\n HOST, PORT = \"\", 9999\n\n # 第二步实例化四个类其中之一并传入服务器地址和上面自己创建的服务器类,这里自己实例化的TCPServer\n server = socketserver.ThreadingTCPServer((HOST, PORT), MySelfServer)\n\n # 处理多个请求,这里注意的是虽然是处理多个请求,但是这句话并没有实现并发\n server.serve_forever()","repo_name":"neodeng23/python_tcp_socket","sub_path":"socketserver_demo/mult_server.py","file_name":"mult_server.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"40711862648","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import AdditionalDataHolder, Parsable, ParseNode, SerializationWriter\nfrom kiota_abstractions.store import BackedModel, BackingStore, BackingStoreFactorySingleton\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\n@dataclass\nclass FileEncryptionInfo(AdditionalDataHolder, BackedModel, Parsable):\n \"\"\"\n Contains properties for file encryption information for the content version of a line of business app.\n \"\"\"\n # Stores model information.\n backing_store: BackingStore = field(default_factory=BackingStoreFactorySingleton(backing_store_factory=None).backing_store_factory.create_backing_store, repr=False)\n\n # Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.\n additional_data: Dict[str, Any] = field(default_factory=dict)\n # The key used to encrypt the file content.\n encryption_key: Optional[bytes] = None\n # The file digest prior to encryption. ProfileVersion1 requires a non-null FileDigest.\n file_digest: Optional[bytes] = None\n # The file digest algorithm. ProfileVersion1 currently only supports SHA256 for the FileDigestAlgorithm.\n file_digest_algorithm: Optional[str] = None\n # The initialization vector (IV) used for the encryption algorithm. Must be 16 bytes.\n initialization_vector: Optional[bytes] = None\n # The hash of the concatenation of the IV and encrypted file content. Must be 32 bytes.\n mac: Optional[bytes] = None\n # The key used to compute the message authentication code of the concatenation of the IV and encrypted file content. Must be 32 bytes.\n mac_key: Optional[bytes] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # The profile identifier. Maps to the strategy used to encrypt the file. Currently, only ProfileVersion1 is supported.\n profile_identifier: Optional[str] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> FileEncryptionInfo:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: FileEncryptionInfo\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return FileEncryptionInfo()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n fields: Dict[str, Callable[[Any], None]] = {\n \"encryptionKey\": lambda n : setattr(self, 'encryption_key', n.get_bytes_value()),\n \"fileDigest\": lambda n : setattr(self, 'file_digest', n.get_bytes_value()),\n \"fileDigestAlgorithm\": lambda n : setattr(self, 'file_digest_algorithm', n.get_str_value()),\n \"initializationVector\": lambda n : setattr(self, 'initialization_vector', n.get_bytes_value()),\n \"mac\": lambda n : setattr(self, 'mac', n.get_bytes_value()),\n \"macKey\": lambda n : setattr(self, 'mac_key', n.get_bytes_value()),\n \"@odata.type\": lambda n : setattr(self, 'odata_type', n.get_str_value()),\n \"profileIdentifier\": lambda n : setattr(self, 'profile_identifier', n.get_str_value()),\n }\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n writer.write_bytes_value(\"encryptionKey\", self.encryption_key)\n writer.write_bytes_value(\"fileDigest\", self.file_digest)\n writer.write_str_value(\"fileDigestAlgorithm\", self.file_digest_algorithm)\n writer.write_bytes_value(\"initializationVector\", self.initialization_vector)\n writer.write_bytes_value(\"mac\", self.mac)\n writer.write_bytes_value(\"macKey\", self.mac_key)\n writer.write_str_value(\"@odata.type\", self.odata_type)\n writer.write_str_value(\"profileIdentifier\", self.profile_identifier)\n writer.write_additional_data_value(self.additional_data)\n \n\n","repo_name":"microsoftgraph/msgraph-beta-sdk-python","sub_path":"msgraph_beta/generated/models/file_encryption_info.py","file_name":"file_encryption_info.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"}
+{"seq_id":"34720681201","text":"import pandas as pd\nfrom sklearn import datasets\n\n\ndef get():\n \"\"\"Get training data\"\"\"\n d = datasets.load_iris()\n df = pd.DataFrame(d[\"data\"])\n\n df.columns = d[\"feature_names\"]\n df[\"target\"] = d[\"target\"]\n return df\n","repo_name":"ploomber/soopervisor","sub_path":"tests/assets/my_project/src/my_project/tasks/raw.py","file_name":"raw.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"48"}
+{"seq_id":"13175462451","text":"from graphcast.graphcast import ModelConfig, TaskConfig, GraphCast\nfrom fmbase.util.config import cfg\ndef config_model( **kwargs ) -> ModelConfig:\n\tmc = ModelConfig()\n\tmc.resolution= kwargs.get('resolution', cfg().model.resolution),\n\tmc.mesh_size= kwargs.get('mesh_size', cfg().model.mesh_size),\n\tmc.latent_size= kwargs.get('latent_size', cfg().model.latent_size),\n\tmc.gnn_msg_steps= kwargs.get('gnn_msg_steps', cfg().model.gnn_msg_steps),\n\tmc.hidden_layers= kwargs.get('hidden_layers', cfg().model.hidden_layers),\n\tmc.radius_query_fraction_edge_length= kwargs.get('radius_query_fraction_edge_length', cfg().model.radius_query_fraction_edge_length)\n\treturn mc\n\ndef config_task( **kwargs) -> TaskConfig:\n\tdts = cfg().task.data_timestep\n\ttc = TaskConfig()\n\ttc.input_variables= kwargs.get('input_variables', cfg().task.input_variables)\n\ttc.target_variables= kwargs.get('target_variables', cfg().task.target_variables)\n\ttc.forcing_variables= kwargs.get('forcing_variables', cfg().task.forcing_variables)\n\ttc.pressure_levels= kwargs.get('z_levels', cfg().task.z_levels)\n\ttc.input_duration= kwargs.get('input_duration', f\"{cfg().task.input_steps*dts}h\" )\n\treturn tc","repo_name":"nasa-nccs-hpda/FMGraphcast","sub_path":"fmgraphcast/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"19305383343","text":"import logging\nimport posixpath\nimport socket\nimport sys\nimport urllib.parse\n\n# -------------------------------\n# Imports of standard modules --\n# -------------------------------\nfrom functools import lru_cache\nfrom typing import Any, Dict, List, Tuple\n\n# ----------------------------\n# Imports for other modules --\n# ----------------------------\nfrom . import jsonparser, util, version\nfrom .exception import IngestError\nfrom .http import DEFAULT_AUTH_PATH, Http, get_fqdn\nfrom .ingestconfig import IngestServiceConfig\n\n# ---------------------------------\n# Local non-exported definitions --\n# ---------------------------------\n\n\n_LOG = logging.getLogger(__name__)\n\n\nclass ReplicationClient:\n \"\"\"Client for the Qserv ingest/replication service.\n Use chunk metadata and connection to concurrent queue manager\n \"\"\"\n\n def __init__(\n self, repl_url: str, timeout_read_sec: int, timeout_write_sec: int, auth_path: str = DEFAULT_AUTH_PATH\n ) -> None:\n\n self.repl_url = util.trailing_slash(repl_url)\n self.http = Http(timeout_read_sec, timeout_write_sec, auth_path)\n self._check_version()\n self.index_url = urllib.parse.urljoin(self.repl_url, \"replication/sql/index\")\n\n def abort_all_transactions(self, database: str) -> None:\n \"\"\"Abort all started transactions for a given database.\"\"\"\n for transaction_id in self.get_transactions_inprogress(database):\n success = False\n self.close_transaction(database, transaction_id, success)\n _LOG.info(\"Abort transaction: %s\", transaction_id)\n\n def build_secondary_index(self, database: str) -> None:\n url = urllib.parse.urljoin(self.repl_url, \"ingest/index/secondary\")\n _LOG.info(\"Create secondary index\")\n payload = {\n \"version\": version.REPL_SERVICE_VERSION,\n \"database\": database,\n \"allow_for_published\": 1,\n \"local\": 1,\n \"rebuild\": 1,\n }\n self.http.post(url, payload)\n\n def close_transaction(self, database: str, transaction_id: int, success: bool) -> None:\n \"\"\"Close or abort a transaction.\"\"\"\n tmp_url = posixpath.join(\"ingest/trans/\", str(transaction_id))\n if success is True:\n tmp_url += \"?abort=0\"\n else:\n tmp_url += \"?abort=1\"\n url = urllib.parse.urljoin(self.repl_url, tmp_url)\n _LOG.debug(\"Attempt to close transaction (PUT %s)\", url)\n responseJson = self.http.put(url, payload=None, no_readtimeout=True)\n\n # TODO Check if there is only one transaction in responseJson in\n # order to remove 'database' parameter\n for trans in responseJson[\"databases\"][database][\"transactions\"]:\n _LOG.debug(\"Close transaction (id: %s state: %s)\", trans[\"id\"], trans[\"state\"])\n\n def _check_version(self) -> None:\n \"\"\"Check replication service version and exit if it is not\n the expected one\n \"\"\"\n url = urllib.parse.urljoin(self.repl_url, \"meta/version\")\n responseJson = self.http.get(url)\n if responseJson[\"version\"] != version.REPL_SERVICE_VERSION:\n _LOG.critical(\n \"Invalid replication server version (is %s, expected %s)\",\n responseJson[\"version\"],\n version.REPL_SERVICE_VERSION,\n )\n sys.exit(1)\n _LOG.info(\"Replication service version: v%s\", version.REPL_SERVICE_VERSION)\n\n def database_config(self, database: str, ingest_service_config: IngestServiceConfig) -> None:\n \"\"\"Set replication system configuration for a given database https://co\n nfluence.lsstcorp.org/display/DM/Ingest%3A+11.1.8.1.+Setting+configurat\n ion+parameters.\n\n Parameters\n ----------\n database: `str`\n Database name\n replication_config: `util.IngestServiceConfig`\n Configuration parameters for the database inside\n replication/ingest system\n\n \"\"\"\n json = {\n \"version\": version.REPL_SERVICE_VERSION,\n \"database\": database,\n \"CAINFO\": ingest_service_config.cainfo,\n \"SSL_VERIFYPEER\": ingest_service_config.ssl_verifypeer,\n }\n\n if ingest_service_config.async_proc_limit is not None:\n json[\"ASYNC_PROC_LIMIT\"] = ingest_service_config.async_proc_limit\n if ingest_service_config.async_proc_limit is not None:\n json[\"LOW_SPEED_LIMIT\"] = ingest_service_config.low_speed_limit\n if ingest_service_config.async_proc_limit is not None:\n json[\"LOW_SPEED_TIME\"] = ingest_service_config.low_speed_time\n\n url = urllib.parse.urljoin(self.repl_url, \"/ingest/config/\")\n _LOG.debug(\"Configure database inside replication system, url: %s, json: %s\", url, json)\n self.http.put(url, json)\n\n def database_publish(self, database: str) -> None:\n \"\"\"Publish a database inside replication system.\"\"\"\n path = \"/ingest/database/{}\".format(database)\n url = urllib.parse.urljoin(self.repl_url, path)\n _LOG.debug(\"Publish database: %s\", url)\n self.http.put(url, no_readtimeout=True)\n\n def database_register(self, json_db: Dict) -> None:\n \"\"\"Register a database inside replication system using\n data_url/
\"\n\t f\"Precipitation Readings
\"\n f\"/api/v1.0/precipitation
\"\n\t f\"List of Stations
\"\n f\"/api/v1.0/stations
\"\n\t f\"Temperature Observations (tobs)
\"\n f\"/api/v1.0/tobs
\"\n f\"Minimum, average, and maximum temperature for a given date.
\"\n f\"/api/v1.0/start (YYYY-MM-DD)
\"\n f\"Minimum, average, and maximum temperature for a given start to end date.
\"\n f\"/api/v1.0/start/end (YYYY-MM-DD)\"\n )\n\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n\n session = Session(engine)\n results = session.query(Measurement.date, Measurement.prcp).order_by(Measurement.date.asc()).all()\n session.close()\n\n measurement_date = [result[0] for result in results]\n measurement_prcp = [result[1] for result in results]\n precipitation_dict = dict(zip(measurement_date, measurement_prcp))\n\n return jsonify(precipitation_dict)\n\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n\n session = Session(engine)\n results = session.query(Measurement.station).all()\n session.close()\n\n measurement_stat = [result[0] for result in results]\n measurement_stat_unique = np.unique(measurement_stat).tolist()\n\n return jsonify(measurement_stat_unique)\n\n\n@app.route(\"/api/v1.0/tobs\")\ndef temp_obs():\n\n session = Session(engine)\n\n last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n last_date = last_date[0]\n last_date = dt.datetime.strptime(last_date, '%Y-%m-%d').date()\n year_ago = last_date - dt.timedelta(days=365)\n\n temps = session.query(Measurement.tobs).filter(Measurement.date >= year_ago).all()\n\n temp_list = []\n\n for i in temps:\n temp_list.append(i[0])\n\n return jsonify(temp_list)\n\n \n@app.route(\"/api/v1.0/Employee Added Successfully
\")\r\n\r\n elif request.method==\"GET\":\r\n return render(request,'add_emp.html')\r\n\r\n else:\r\n return HttpResponse(\"An error occur\")\r\n\r\ndef remove_emp(request,emp_id=0):\r\n if emp_id:\r\n try:\r\n emp_rem=Employee.objects.get(id=emp_id)\r\n \r\n emp_rem.delete()\r\n return HttpResponse(\"Employee Removed successfully\")\r\n except:\r\n return HttpResponse(\"Error\")\r\n emps=Employee.objects.all()\r\n context={\r\n \"emp\":emps\r\n }\r\n\r\n\r\n return render(request,'remove_emp.html',context)\r\n\r\ndef fil_emp(request):\r\n if request.method==\"POST\":\r\n name=request.POST.get(\"name\")\r\n dept=request.POST.get(\"dept\")\r\n role=request.POST.get(\"role\")\r\n\r\n emps=Employee.objects.all()\r\n\r\n if name:\r\n emps=emps.filter(Q(first_name__icontains = name) | Q(last_name__icontains=name))\r\n\r\n if dept:\r\n emps=emps.filter(Q(dept__name__icontains=dept))\r\n\r\n if role:\r\n emps=emps.filter(Q(role__name__icontains=role))\r\n\r\n context={\r\n \"emps\":emps\r\n }\r\n return render(request,\"view_emp.html\",context)\r\n elif request.method==\"GET\":\r\n return render(request,'fil_emp.html')\r\n\r\n# Create your views here.\r\n","repo_name":"Codingboat21/Office-Employee-management-system","sub_path":"office_emp_proj/office_emp_proj/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"13552691844","text":"# *******************************************************************************\n# **\n# ** Author: Michael Lomnitz (mrlomnitz@lbl.gov) \n# ** Python module to run word embedding (word2vec) using skipgram or continuos\n# ** bag of words (CBOW) models. Output is then plotted using SKlearn tSNE \n# ** for visualization.\n# **\n# *******************************************************************************\n# Load modules\nimport tensorflow as tf\nimport numpy as np\nimport random\nfrom matplotlib import pylab\nfrom sklearn.manifold import TSNE\n# Local modules\nimport Load_Text_Set as ld\nimport tf_Word2Vec as w2v\n# plotting amcro\ndef plot(embeddings, labels, name):\n assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'\n fig = pylab.figure(figsize=(15,15)) # in inches\n for i, label in enumerate(labels):\n x, y = embeddings[i,:]\n pylab.scatter(x, y)\n pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',\n ha='right', va='bottom')\n #pylab.show()\n fig.savefig('./'+name+'.pdf')\n\n# Model constants \nbatch_size = 128 # Training batch. Reduces overtraining and training time\nskip_window = 1 # How many words to consider left and right.\nnum_skips = 2 # How many times to reuse an input to generate a label.\n# Cosmntruct random validation sample from the loaded dataset. Limit ourselves\n# to a sample of words that have a low numeric ID, which by (i.e. frequent)\nvalid_size = 16 # Random set of words to evaluate similarity on.\nvalid_window = 100 # Only pick dev samples in the head of the distribution.\nvalid_examples = np.array(random.sample(range(valid_window), valid_size))\nvocabulary_size = 200000\n# Switch betweenskipgram and CBOW models\nuse_CBOW = True\n#\ngraph = tf.Graph()\nwords = ld.text_8(vocabulary_size)\n#\ndef run_embeddings():\n with graph.as_default(), tf.device('/cpu:0'):\n # Input data.\n if use_CBOW == False:\n train_dataset = tf.placeholder(tf.int32, shape=[batch_size])\n else: \n train_dataset = tf.placeholder(tf.int32, shape=[batch_size,num_skips])\n train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n valid_dataset = tf.constant(valid_examples, dtype=tf.int32)\n #\n embeddings = w2v.word_embedding(vocabulary_size, use_CBOW)\n optimizer,loss = embeddings.train(train_dataset, train_labels)\n \n num_steps = 100001\n\n with tf.Session(graph=graph) as session:\n tf.global_variables_initializer().run()\n print('Initialized')\n average_loss = 0\n for step in range(num_steps):\n if use_CBOW == False:\n batch_data, batch_labels = w2v.generate_batch(\n batch_size, num_skips, skip_window, words.data)\n else:\n batch_data, batch_labels = w2v.generate_batch_CBOW(\n batch_size, num_skips, skip_window, words.data)\n #\n feed_dict = {train_dataset : batch_data, train_labels : batch_labels}\n _, l = session.run([optimizer, loss], feed_dict=feed_dict)\n average_loss += l\n # The followign are just to keep track of the training and the performance\n if step % 2000 == 0:\n if step > 0:\n average_loss = average_loss / 2000\n # The average loss is an estimate of the loss over the last 2000 batches.\n print('Average loss at step %d: %f' % (step, average_loss))\n average_loss = 0\n # note that this is expensive (~20% slowdown if computed every 500 steps)\n if step % 10000 == 0:\n #sim = similarity.eval()\n sim = embeddings.similarity(valid_dataset)\n for i in range(valid_size):\n valid_word = words.reverse_dictionary[valid_examples[i]]\n top_k = 8 # number of nearest neighbors\n nearest = (-sim[i, :]).argsort()[1:top_k+1]\n log = 'Nearest to %s:' % valid_word\n for k in range(top_k):\n close_word = words.reverse_dictionary[nearest[k]]\n log = '%s %s,' % (log, close_word)\n print(log)\n final_embeddings = embeddings.normalized_embeddings.eval()\n return(final_embeddings)\n# plot output results\n","repo_name":"CDIPS-AI-2017/pensieve","sub_path":"Notebooks/word2vec/run_Word2Vec.py","file_name":"run_Word2Vec.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"41463529289","text":"import copy\n\n\nstart_time = 30\nstart_valve = 'AA'\n\n\ndef complete(valves):\n num_valves = len(valves)\n is_complete = False\n while not is_complete:\n is_complete = True\n for key, valve in valves.items():\n new_edges = {}\n for neighbor, cost in valve['edges'].items():\n if neighbor in new_edges:\n new_edges[neighbor] = min(cost, new_edges[neighbor])\n else:\n new_edges[neighbor] = cost\n for edge, added_cost in valves[neighbor]['edges'].items():\n if edge == key:\n continue\n if edge in new_edges:\n new_edges[edge] = min(cost + added_cost, new_edges[edge])\n else:\n new_edges[edge] = cost + added_cost\n valve['edges'] = new_edges\n if len(new_edges) < num_valves - 1:\n is_complete = False\n\n\ndef clean(valves, starter_costs):\n baddies = [name for name, valve in valves.items() if valve['rate'] == 0]\n for baddie in baddies:\n del valves[baddie]\n del starter_costs[baddie]\n for valve in valves.values():\n for baddie in baddies:\n del valve['edges'][baddie]\n\n\ndef find_starter_costs(valves):\n costs = copy.deepcopy(valves[start_valve]['edges'])\n costs[start_valve] = 0\n return costs\n\n\ndef score(valves, starter_costs, candidate):\n costs = starter_costs\n time = start_time\n score = 0\n for name in candidate:\n time -= costs[name] + 1\n if time <= 0:\n break\n score += time * valves[name]['rate']\n costs = valves[name]['edges']\n return score\n\n\ndef search(valves, time, costs, current=[]):\n yield current\n for name, cost in costs.items():\n if name in current:\n continue\n if time - cost - 1 > 0:\n candidates = search(valves, time - cost - 1, valves[name]['edges'], current + [name])\n if candidates is not None:\n for candidate in candidates:\n yield candidate\n\n\ndef solve(valves):\n complete(valves)\n starter_costs = find_starter_costs(valves)\n clean(valves, starter_costs)\n # example = ['DD', 'BB', 'JJ', 'HH', 'EE', 'CC']\n best_score = 0\n i = 0\n # for candidate in itertools.permutations(valves.keys()):\n for candidate in search(valves, start_time, starter_costs):\n i += 1\n value = score(valves, starter_costs, candidate)\n if value > best_score:\n best_score = value\n print(f'{i}: {best_score}')\n print(f'iterations: {i}')\n return best_score\n\n\ndef read(path):\n with open(path, 'r') as f:\n rows = [row.rstrip() for row in f.readlines()]\n nodes = {}\n for row in rows:\n parts = row.split(' ')\n name = parts[1]\n rate = int(parts[4][5:-1])\n edges = {edge.rstrip(','): 1 for edge in parts[9:]} \n nodes[name] = {\n 'name': name,\n 'rate': rate,\n 'edges': edges,\n }\n return nodes\n\n\ndef main(path, is_test):\n data = read(path)\n return solve(data)\n\n\ndef display(output):\n print('\\n')\n try:\n iterator = iter(output)\n except TypeError:\n print(output)\n pass\n else:\n for line in iterator:\n print(line)\n\n\nif __name__ == \"__main__\":\n is_test = False\n import os\n dirname = os.path.realpath(os.path.dirname(__file__))\n filename = 'test.txt' if is_test else 'input.txt'\n path = f'{dirname}/{filename}'\n import sys\n\n if (len(sys.argv) < 2):\n display(main(path, is_test=is_test))\n else:\n for f in sys.argv[1:]:\n display(main(f))\n","repo_name":"slovb/aoc-2022","sub_path":"Day16/first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"38386893043","text":"import numpy as np\n\ndef convert_to_np_array(dataset, split_name):\n \"\"\"\n Function that converts images and labels in TFRecords into separate NumPy arrays\n\n Args:\n dataset (int): The TFRecord containing both images and their associated image labels\n split_name (str): the data split the function is being invoked for\n\n Returns:\n x_cassava: NumPy array of images\n y_cassava: NumPy array of image labels\n \"\"\"\n\n #get the number of images in dataset\n num_images = len(dataset)\n\n #created empty vectors to populate\n #x_cassava = np.empty([num_images, img_size, img_size, 3], dtype='float32')\n y_cassava = np.empty(num_images, dtype='float32')\n\n #populate the above vectors\n counter = 0\n for image, label in dataset: \n #x_cassava[counter] = data[\"image\"]\n #y_cassava[counter] = data[\"label\"]\n #x_cassava[counter] = image\n y_cassava[counter] = label\n counter += 1\n\n if counter == num_images:\n print('All {} images and labels converted to NumPy arrays'.format(split_name))\n\n return y_cassava","repo_name":"liamcarew/cassava-leaf-disease-classification","sub_path":"image_pre_processing/utils/convert_to_np_array.py","file_name":"convert_to_np_array.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"27712878815","text":"import torch\nfrom diffusers import DiffusionPipeline\n\ndef genSingle(pipeline: DiffusionPipeline, prompt: str | None = None, width: int = 512, height: int = 512, samples: int = 50, negativePrompt: str | None = None):\n image = pipeline(prompt=prompt, negative_prompt=negativePrompt, width=width, height=height, num_inference_steps=samples).images[0]\n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n return image\n\ndef genMultiple(pipeline: DiffusionPipeline, prompt: str | None = None, negativePrompt: str | None = None, width: int = 512, height: int = 512, samples: int = 50, count: int = 10):\n images = []\n for i in range(count):\n images.append(genSingle(pipeline, prompt, width, height, samples, negativePrompt))\n return images","repo_name":"Cr0me1ve/easyStableDiffusionXL","sub_path":"scripts/runSD.py","file_name":"runSD.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"40358864649","text":"from PyQt6.QtWidgets import (\n QMainWindow,\n QLabel,\n QSpinBox,\n QPushButton,\n QTableWidget,\n)\nfrom project.form.constants import (\n WIDTH,\n HEIGHT,\n LEFT,\n)\nfrom project.form.base_object import Object\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setWindowTitle(\"Simulation: Discrete-event modeling\")\n self.setGeometry(350, 300, WIDTH, HEIGHT)\n\n self.obj: Object = Object()\n self.create_objects()\n\n def create_objects(self):\n labels: list[str] = ['Number of operators', 'Average customers', 'Service scale']\n for label in labels:\n self.obj.set_obj(\n object=QLabel(self),\n title=label,\n above=self.obj.indent,\n case=0,\n )\n\n self.obj.add_obj(\n self.obj.set_obj(\n object=QSpinBox(self),\n above=self.obj.indent,\n left=LEFT * 10,\n step=1,\n span=[0, 100000000],\n value=5,\n ),\n key='spinbox',\n )\n self.obj.increase_indent()\n self.obj.increase_indent()\n\n self.obj.add_obj(\n self.obj.set_obj(\n object=QPushButton(self),\n title='Start/Stop',\n above=self.obj.indent,\n left=LEFT * 3,\n ),\n key='button',\n )\n self.obj.add_obj(\n self.obj.set_obj(\n object=QTableWidget(),\n columns=4,\n title='Bank simulation',\n values=['event type', 'event time', 'queue', 'free operators'],\n width=WIDTH,\n ),\n key='table',\n )\n","repo_name":"BigBlackBob-93/Simulation--DiscreteEventModeling--Queue","sub_path":"project/form/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"2821603969","text":"# Starting with a clean slate\n\nfrom modal import Secret, Stub, Image, gpu, method\n\nARTFUSION_GITHUB_PATH = \"https://github.com/cadolphs/ArtFusion.git\"\nARTFUSION_PATH = \"/git/artfusion/\"\nMODEL_DIR = \"/models\"\nMODEL_NAME = \"artfusion_r12_step=317673.ckpt\"\nBASE_MODEL = \"lagerbaer/artfusion\"\nCKPT_PATH = f\"{MODEL_DIR}/{MODEL_NAME}\"\nCFG_PATH = f\"{ARTFUSION_PATH}/configs/kl16_content12.yaml\"\nDEVICE = \"cuda\"\n\nstub = Stub(\"art-fusion\")\n\n\ndef download_model_to_folder():\n from huggingface_hub import snapshot_download\n import os\n\n os.makedirs(MODEL_DIR, exist_ok=True)\n\n snapshot_download(\n BASE_MODEL,\n local_dir=MODEL_DIR,\n token=os.environ[\"HUGGINGFACE_TOKEN\"],\n )\n\n\ndef instantiate_model():\n \"\"\"Useful to pre-load the required weights\"\"\"\n import sys\n\n sys.path.append(ARTFUSION_PATH)\n from omegaconf import OmegaConf\n from main import instantiate_from_config\n\n config = OmegaConf.load(CFG_PATH)\n config.model.params.ckpt_path = CKPT_PATH\n config.model.params.first_stage_config.params.ckpt_path = None\n model = instantiate_from_config(config.model)\n\n\nimage = (\n Image.debian_slim()\n .apt_install(\"python3-opencv\")\n .pip_install(\n \"torch\",\n \"torchvision\",\n \"pytorch-lightning\",\n \"omegaconf\",\n \"einops\",\n \"transformers\",\n \"imageio\",\n \"imageio-ffmpeg\",\n \"hf-transfer~=0.1\",\n )\n .apt_install(\"git\")\n .run_commands(\n f\"cd / && mkdir -p {ARTFUSION_PATH} && cd {ARTFUSION_PATH} && git clone --depth 1 {ARTFUSION_GITHUB_PATH} .\",\n force_build=False,\n )\n .run_commands(f\"cd / && mkdir -p {MODEL_DIR}\")\n .run_function(\n download_model_to_folder, secret=Secret.from_name(\"my-huggingface-secret\")\n )\n .run_function(instantiate_model)\n)\n\n\ndef preprocess_image(image, size=(256, 256), max_size=256):\n import numpy as np\n import torch\n from einops import rearrange\n\n if not image.mode == \"RGB\":\n image = image.convert(\"RGB\")\n image.thumbnail((max_size, max_size))\n image = np.array(image).astype(np.uint8)\n image = (image / 127.5 - 1.0).astype(np.float32)\n image = rearrange(image, \"h w c -> c h w\")\n return torch.from_numpy(image)[None, :].to(DEVICE)\n\n\ndef tensor_to_rgb(x):\n import torch\n\n return torch.clamp((x + 1.0) / 2.0, min=0.0, max=1.0)\n\n\ndef convert_samples(samples):\n from einops import rearrange\n from PIL import Image\n import numpy as np\n\n if isinstance(samples, (list, tuple)):\n samples = torch.cat(samples, dim=0)\n\n samples = rearrange(samples[0, :], \"c h w -> h w c\").cpu().numpy() * 255.0\n samples = Image.fromarray(samples.astype(np.uint8))\n return samples\n\n\n@stub.cls(image=image, gpu=gpu.Any())\nclass StyleTransfer:\n def __enter__(self):\n from omegaconf import OmegaConf\n from pytorch_lightning import seed_everything\n import sys\n\n sys.path.append(ARTFUSION_PATH)\n from main import instantiate_from_config\n\n seed_everything(42)\n\n config = OmegaConf.load(CFG_PATH)\n config.model.params.ckpt_path = CKPT_PATH\n config.model.params.first_stage_config.params.ckpt_path = None\n model = instantiate_from_config(config.model)\n\n self.model = model.eval().to(DEVICE)\n\n def get_content_style_features(\n self, content_image, style_image, max_size=256, style_size=256\n ):\n import torch\n\n model = self.model\n style_image = preprocess_image(style_image, max_size=style_size)\n content_image = preprocess_image(content_image, max_size=max_size)\n\n with torch.no_grad(), model.ema_scope(\"Plotting\"):\n vgg_features = model.vgg(model.vgg_scaling_layer(style_image))\n c_style = model.get_style_features(vgg_features)\n null_style = c_style.clone()\n null_style[:] = model.null_style_vector.weight[0]\n\n content_encoder_posterior = model.encode_first_stage(content_image)\n content_encoder_posterior = model.get_first_stage_encoding(\n content_encoder_posterior\n )\n c_content = model.get_content_features(content_encoder_posterior)\n null_content = torch.zeros_like(c_content)\n\n c = {\"c1\": c_content, \"c2\": c_style}\n c_null_style = {\"c1\": c_content, \"c2\": null_style}\n c_null_content = {\"c1\": null_content, \"c2\": c_style}\n\n return c, c_null_style, c_null_content\n\n def style_transfer(\n self,\n content_image,\n style_image,\n content_s,\n style_s,\n ddim_steps,\n eta,\n max_size=None,\n style_size=None,\n ):\n import torch\n\n c, c_null_style, c_null_content = self.get_content_style_features(\n content_image, style_image, max_size=max_size, style_size=style_size\n )\n\n with torch.no_grad(), self.model.ema_scope(\"Plotting\"):\n samples = self.model.sample_log(\n cond=c,\n batch_size=1,\n x_T=torch.rand_like(c[\"c1\"]),\n ddim=True,\n ddim_steps=ddim_steps,\n eta=eta,\n unconditional_guidance_scale=content_s,\n unconditional_conditioning=c_null_content,\n unconditional_guidance_scale_2=style_s,\n unconditional_conditioning_2=c_null_style,\n )[0]\n\n x_samples = self.model.decode_first_stage(samples)\n x_samples = tensor_to_rgb(x_samples)\n\n return x_samples\n\n @method()\n def generate(\n self,\n content_bytes=None,\n style_bytes=None,\n content_strength=0.5,\n style_strength=1.0,\n max_size=256,\n style_size=256,\n ddim_steps=10,\n eta=0,\n ):\n from PIL import Image\n\n import io\n\n content_image = Image.open(io.BytesIO(content_bytes))\n style_image = Image.open(io.BytesIO(style_bytes))\n\n x_samples = self.style_transfer(\n content_image,\n style_image,\n content_s=content_strength,\n style_s=style_strength,\n max_size=max_size,\n style_size=style_size,\n ddim_steps=ddim_steps,\n eta=eta,\n )\n\n x_samples = convert_samples(x_samples)\n\n img_bytes = io.BytesIO()\n x_samples.save(img_bytes, format=\"PNG\")\n\n return img_bytes.getvalue()\n\n\n@stub.local_entrypoint()\ndef main(\n content_file_name: str,\n style_file_name: str,\n content_strength: float = 0.5,\n style_strength: float = 1.0,\n max_size: int = 512,\n style_size: int = 256,\n eta: float = 0,\n ddim_steps: int = 10,\n):\n import io\n\n with open(content_file_name, \"rb\") as f:\n content_bytes = io.BytesIO(f.read()).getvalue()\n with open(style_file_name, \"rb\") as f:\n style_bytes = io.BytesIO(f.read()).getvalue()\n\n image_bytes = StyleTransfer().generate.remote(\n content_bytes,\n style_bytes,\n content_strength=content_strength,\n style_strength=style_strength,\n max_size=max_size,\n style_size=style_size,\n eta=eta,\n ddim_steps=ddim_steps,\n )\n output_path = \"output.png\"\n with open(output_path, \"wb\") as f:\n f.write(image_bytes)\n","repo_name":"cadolphs/style-transfer","sub_path":"simple_script.py","file_name":"simple_script.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"6263741417","text":"from items import*\nimport random\n\nclass dice(clickable):\n def __init__(self,x,y,w,h,name, val ,backgroundColor = color(255)):\n super(dice, self).__init__(x,y,w,h,name,backgroundColor = backgroundColor)\n self.val=val\n \n def display(self): \n fill(255)\n if self.val == 1:\n self.diceOne()\n if self.val == 2:\n self.diceTwo()\n if self.val == 3:\n self.diceThree()\n if self.val == 4:\n self.diceFour()\n if self.val == 5:\n self.diceFive()\n if self.val == 6:\n self.diceSix()\n \n def onClick(self, *args):\n self.diceRoll()\n \n def onHover(self):\n pass\n \n def diceRoll(self):\n self.val = random.randint(1,6) \n \n def diceOne(self):\n fill(self.backgroundColor)\n rect (self.x,self.y,self.w,self.h,10,10,10,10)\n fill(10)\n ellipse(self.x + 0.5*self.w,self.y+0.5*self.h,0.2*self.w,0.2*self.h)\n \n def diceTwo(self):\n fill(self.backgroundColor)\n rect(self.x,self.y,self.w,self.h,10,10,10,10)\n fill(10)\n ellipse(self.x + 0.25 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n \n def diceThree(self):\n fill(self.backgroundColor)\n rect (self.x,self.y,self.w,self.h,10,10,10,10)\n fill(10)\n ellipse(self.x + 0.25 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.5*self.w,self.y+0.5*self.h,0.2*self.w,0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n \n def diceFour(self):\n fill(self.backgroundColor)\n rect (self.x,self.y,self.w,self.h,10,10,10,10)\n fill(10)\n ellipse(self.x + 0.25 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.25 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n \n \n def diceFive(self):\n fill(self.backgroundColor)\n rect (self.x,self.y,self.w,self.h,10,10,10,10)\n fill(10)\n ellipse(self.x + 0.25 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.25 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.5*self.w,self.y+0.5*self.h,0.2*self.w,0.2*self.h)\n \n \n def diceSix(self): \n fill(self.backgroundColor)\n rect (self.x,self.y,self.w,self.h,10,10,10,10)\n fill(10)\n ellipse(self.x + 0.25 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.25 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.25 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.75 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.25 * self.w, self.y + 0.5 * self.h, 0.2*self.w, 0.2*self.h)\n ellipse(self.x + 0.75 * self.w, self.y + 0.5 * self.h, 0.2*self.w, 0.2*self.h)\n \n def copy(self):\n return dice(self.x,self.y,self.w,self.h,self.name,self.val,self.backgroundColor)\n \nclass diceGroup(clickable): \n def __init__(self,x,y,w,h,name, *dice):\n super(diceGroup, self).__init__(x,y,w,h,name)\n self.dice=list()\n self._observers = []\n for d in dice: \n self.dice.append(d)\n \n def display(self):\n for d in self.dice:\n d.display()\n \n def onClick(self):\n for d in self.dice:\n d.onClick()\n \n def addDice(self,d):\n if isinstance(dice,d):\n self.dice.append(d)\n \n def bindTo(self,callback):\n self._observers.append(callback)\n \n\n#some secific items I made for the setup screen\nclass setupDice(dice):\n def __init__(self, x,y,w,h,name, val, backgroundColor = color(255)):\n super(setupDice, self).__init__(x,y,w,h,name, val,backgroundColor = backgroundColor)\n self.active = None\n \nclass setupDiceGroup(diceGroup):\n def __init__(self,x,y,w,h,name,game,*dice):\n super(setupDiceGroup,self).__init__(x,y,w,h,name,*dice)\n self.results = []\n self.amountActive = 2\n self.winningDice = 0\n self.game = game\n self.changeAmount(2)\n \n def onClick(self):\n self.winningDice = 0\n self.results = []\n for d in self.dice:\n if d.active:\n d.onClick()\n self.results.append(d.val)\n try: \n self.winningDice = self.results.index(max(self.results))\n except:\n self.winningDice = 0\n self.game._currentPlayer = self.game.setPlayer(self.game.players[self.winningDice])\n self.game.currentPlayerIndex = self.winningDice\n \n def changeAmount(self, amount):\n if amount == 2:\n self.amountActive = 2\n self.dice[0].active = True\n self.dice[1].active = True\n self.dice[2].active = False\n self.dice[3].active = False\n elif amount == 3:\n self.amountActive = 3\n self.dice[0].active = True\n self.dice[1].active = True\n self.dice[2].active = True\n self.dice[3].active = False\n else:\n self.amountActive = 4\n self.dice[0].active = True\n self.dice[1].active = True\n self.dice[2].active = True\n self.dice[3].active = True\n \n def display(self):\n for d in self.dice:\n if d.active:\n d.display()\n \nclass varDiceGroup(diceGroup):\n def __init__(self,x,y,w,h,name,parents,attrname,function,*dice):\n super(varDiceGroup,self).__init__(x,y,w,h,name,*dice)\n self.amount = 0\n self.parents = parents\n self.attrname = attrname\n for x in self.parents:\n x.bindTo(self.update)\n self.function = function\n self.sum = 0\n \n def update(self, value):\n self.amount = getattr(value,self.attrname)\n self.resetDice()\n \n def resetDice(self):\n self.dice = list()\n for x in range(self.amount):\n d = dice(self.x + 100*x,self.y,100,100,'',1)\n self.dice.append(d.copy())\n \n def onClick(self):\n self.sum = 0\n for d in self.dice:\n d.onClick()\n self.sum += d.val\n for callback in self._observers:\n callback(self) \n self.function(self.sum)\n \n \n \n \n\n \n \n \n","repo_name":"QuintenVerheij/digitalComponent","sub_path":"digitalComponent/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":7051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"30198586695","text":"from flask import Flask, render_template, jsonify, request\nfrom flask_api import status\nfrom flask_cors import CORS\nimport pickle\nimport numpy as np\nimport pandas as pd\n\n# Importing machine learning model\n\nimport spacy, nltk\nfrom model.movie_recommender import MovieRecommendation\nfrom sklearn.feature_extraction.text import CountVectorizer\nnlp = spacy.load('en_core_web_sm')\nstop_words = nlp.Defaults.stop_words\nps = nltk.PorterStemmer()\n\napp = Flask(__name__)\nMovieRecommendation()\nmovieRecommendation = pickle.load(open('./model/model.pkl','rb'))\nspam_classifier = pickle.load(open('./model/spam_classifier.pkl','rb'))\n\nCORS(app)\n\n@app.route('/api/get')\ndef get_data():\n return jsonify(posts)\n\n\n@app.route('/api/recommended-movie', methods=['POST', 'GET'])\ndef get_recommendation():\n movie = request.json['movie']\n movie_list = movieRecommendation.get_recommended_movies(movie)\n\n movie_list = dict(movie_list)\n if movie_list['success'] == True:\n return movie_list, status.HTTP_200_OK\n else:\n return movie_list, status.HTTP_500_INTERNAL_SERVER_ERROR\n\n\n@app.route('/api/email-classifier', methods=['POST', 'GET'])\ndef classify_email():\n message = request.json['message']\n\n corpus = pd.Series([message])\n corpus = corpus.apply(lambda x: ' '.join(ps.stem(x) for term in x.split() if not term in stop_words))\n\n cv = CountVectorizer()\n X = cv.fit_transform(corpus).toarray()\n \n print(X, 'sadasdasasdas')\n prediction = spam_classifier.predict(X)\n\n print(prediction, 'value predicted')\n\n \n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"VinayDagar/flask-ml","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"41474897370","text":"#!/usr/bin/env python3\n\nimport binascii\nimport serial\nimport struct\nimport time\nimport os\nimport sys\nfrom threading import Thread, Lock\n\nGPIOA = 0x00\nGPIOB = 0x01\n\nGPIO_INPUT = 0x00\nGPIO_OUTPUT = 0x10\nGPIO_MUX = 0x08\nGPIO_ANALOG = 0x03\n\nGPIO_PULL_NONE = 0x04\nGPIO_PULL_UP = 0x18\nGPIO_PULL_DOWN = 0x28\n\nCFG_GPIO_PIN = 0x1000\nCFG_DMA = 0x1001\nCFG_ADC = 0x1002\nTRIGGER_ADC = 0x1003\nREAD_ADC = 0x1004\nSET_GPIO_PIN = 0x1005\n\n\nclass Command:\n\n def __init__(self, cmd_code, args=[]):\n self.cmd_code = cmd_code\n self.args = [a for a in args if a is not None]\n\n def serialize(self):\n return struct.pack(\"I%s\"%(\"I\"*len(self.args),), self.cmd_code, *self.args)\n\n\nclass Client:\n\n def __init__(self):\n self.tty = serial.Serial(\"/dev/ttyACM0\", timeout=0.2)\n\n def write(self, data):\n self.tty.write(data)\n\n def read(self, count=8):\n return self.tty.read(count)\n\n def read2(self, count, timeout):\n data = b\"\"\n start = time.time()\n while (time.time()-start) < timeout and len(data) < count:\n data += self.read(count)\n return data\n\n def configure_dma(self):\n cmd = Command(CFG_DMA, [])\n self.write(cmd.serialize())\n cmd_code, status = struct.unpack(\"II\", self.read())\n if cmd_code != CFG_DMA or status != 0:\n sys.stderr.write(\"error! configure_dma failed!\")\n sys.stderr.write(cmd_code, status)\n\n def configure_adc(self):\n cmd = Command(CFG_ADC, [])\n self.write(cmd.serialize())\n d = self.read()\n cmd_code, status = struct.unpack(\"II\", d)\n if cmd_code != CFG_ADC or status != 0:\n sys.stderr.write(\"error! configure_adc failed!\")\n sys.stderr.write(cmd_code, status)\n\n def trigger_adc(self):\n cmd = Command(TRIGGER_ADC, [])\n self.write(cmd.serialize())\n d = self.read()\n cmd_code, status = struct.unpack(\"II\", d)\n if cmd_code != TRIGGER_ADC or status != 0:\n sys.stderr.write(\"error! trigger_adc failed!\")\n sys.stderr.write(cmd_code, status)\n\n def read_adc(self):\n with open(\"output.iq\", \"wb\") as f:\n cmd = Command(READ_ADC, [])\n self.write(cmd.serialize())\n while True:\n data = self.read2(3072, 2)\n yield(data)\n f.write(data)\n f.flush()\n\n\n def configure_gpio(self, group, pin, mode, value=None):\n cmd = Command(CFG_GPIO_PIN, [group, pin, mode, value])\n pld = cmd.serialize()\n self.write(pld)\n response = self.read()\n print(response)\n cmd_code, status = struct.unpack(\"II\", response)\n if cmd_code != CFG_GPIO_PIN or status != 0:\n print(\"error! configure_gpio failed!\", file=sys.stderr)\n print(cmd_code, status, file=sys.stderr)\n\nc = Client()\n\n# ADC Inputs\nc.configure_gpio(GPIOA, 6, GPIO_ANALOG)\nc.configure_gpio(GPIOA, 7, GPIO_ANALOG)\nc.configure_gpio(GPIOB, 0, GPIO_ANALOG)\nc.configure_gpio(GPIOB, 1, GPIO_ANALOG)\n\n# c.configure_gpio(GPIOB, 2, GPIO_OUTPUT, 0)\n# c.configure_gpio(GPIOA, 9, GPIO_OUTPUT, 1)\n# c.configure_gpio(GPIOA, 10, GPIO_OUTPUT, 1)\n\nc.configure_dma()\nc.configure_adc()\nc.trigger_adc()\n\nstart = time.time()\nsample_count = 0\nfor data in c.read_adc():\n\n # unpack IQ from SC12 -> SC16\n shorts_out = []\n while len(data) >= 3:\n I = (data[0]<<4) | (data[1]>>4)\n Q = ((data[1]&0xf)<<8) | data[2]\n data = data[3:]\n shorts_out.append(I)\n shorts_out.append(Q)\n\n # complex shorts -> stdout (to eg. baudline)\n sample_count += len(shorts_out)/2\n data_out = struct.pack(\"H\"*len(shorts_out), *shorts_out)\n sys.stdout.buffer.write(data_out)\n sys.stdout.flush()\n\n # print the sample rate once per second\n if (time.time()-start) >= 1.0:\n sys.stderr.buffer.write(b\"%d samples per second\\n\" % (sample_count/(time.time()-start)))\n sys.stderr.flush()\n sample_count = 0\n start = time.time()\n","repo_name":"marcnewlin/human-detector-detector","sub_path":"stream-iq.py","file_name":"stream-iq.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"}
+{"seq_id":"11617831484","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 26 10:27:40 2016\n\n@author: Dani\n\"\"\"\n\nimport os\nimport glob\nimport re\nimport sys\n\nfrom time import sleep\n\nfrom utils import retrCwd\n\nfrom importlib import import_module, reload, invalidate_caches\n\nfrom tempfile import gettempdir as gettemp\n\nfrom daemon import Daemon\n\nfrom ServiceLogger import ServiceLogger\n\nfrom services.ServiceException import LoggerException, ScheduleException, ScriptException\n\n\ncwd = retrCwd()\nos.chdir(os.path.dirname(cwd))\nsvcdir = os.path.join(cwd, \"services\")\nsys.path.append(svcdir)\n\n\nclass ServiceLauncherDaemon(Daemon):\n \n _svc_name_ = \"PySvcLauncher\"\n _svc_display_name_ = \"Lanzador de servicios python\"\n _svc_description_ = \"Servicio de gestión de ejecución de scripts de Python\"\n \n def __init__(self, *args, **kwargs):\n Daemon.__init__(self, *args, **kwargs)\n self.logger = ServiceLogger(\"servicelauncher.log\", \"servicelauncher\", 'ServiceLauncher')\n\n def log(self, message):\n self.logger.log(message)\n \n def run(self):\n instances = {}\n modules = {}\n while 1:\n\n \"\"\" Ok, here's the real money shot right here.\n [actual service code between rests] \"\"\"\n svcscripts = glob.glob(os.path.join(svcdir, \"*Svc.py\"))\n svcscripts = [re.split(r'[\\\\/]+', s)[-1] for s in svcscripts]\n\n for script in svcscripts:\n try:\n if script not in modules.keys():\n modules.update({script: import_module(script[:-3])})\n else:\n modules[script] = reload(modules[script])\n except Exception as x:\n self.log(\"%s:%s - Error: %s at %d\" %\n (self._svc_name_, script, str(x), sys.exc_info()[-1].tb_lineno))\n continue\n\n todel = []\n for script in [s for s in svcscripts if s not in instances.keys()]:\n try:\n aux_class = getattr(modules[script], script[:-6])\n instances.update({script: aux_class()})\n except Exception as x:\n self.log(\"%s:%s - Error: %s at %d\" %\n (self._svc_name_, script, str(x), sys.exc_info()[-1].tb_lineno))\n if script in instances.keys():\n todel.append(script) # Service will be forced to reload Script\n continue\n self.log('\"%s\" Added to Script list' % (script,))\n\n if len(todel) > 0:\n for script in todel:\n del instances[script]\n del todel\n invalidate_caches()\n\n for script in [s for s in instances.keys() if s not in svcscripts]:\n try:\n del instances[script]\n except Exception as x:\n self.log(\"%s:%s - Error: %s at %d\" %\n (self._svc_name_, script, str(x), sys.exc_info()[-1].tb_lineno))\n continue\n self.log('\"%s\" Removed from Script list' % (script,))\n\n todel = []\n for script in instances.keys():\n try:\n instances[script].run()\n except(ScriptException, LoggerException, ScheduleException) as x:\n self.log(str(x))\n todel.append(script) # Service will be forced to reload Script\n continue\n except Exception as x:\n self.log(\"%s:%s - Error: %s at %d\" %\n (self._svc_name_, script, str(x), sys.exc_info()[-1].tb_lineno))\n todel.append(script) # Service will be forced to reload Script\n continue\n\n if len(todel) > 0:\n for script in todel:\n del instances[script]\n del todel\n invalidate_caches()\n\n sleep(60)\n\n \"\"\" [actual service code between rests] \"\"\"\n\n \nif __name__ == '__main__':\n daemon = ServiceLauncherDaemon(os.path.join(gettemp(), 'daemon-example.pid'))\n if len(sys.argv) == 2:\n if 'start' == sys.argv[1]:\n daemon.start()\n elif 'stop' == sys.argv[1]:\n daemon.stop()\n elif 'restart' == sys.argv[1]:\n daemon.restart()\n else:\n print(\"Unknown command\")\n sys.exit(2)\n sys.exit(0)\n else:\n print(\"usage: %s start|stop|restart\" % (sys.argv[0],))\n sys.exit(2)\n\n","repo_name":"danielperezr88/unixpythonservicelauncher","sub_path":"ServiceLauncher.py","file_name":"ServiceLauncher.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"38046637629","text":"# -*- coding: utf-8 -*-\nimport itertools\n\nfrom scrapy import log\nfrom scrapy.selector import Selector\n\nfrom summaries.items import SummariesItem\n\nimport thread_float_bbs\n\n\nclass HimarinSpider(thread_float_bbs.ThreadFloatBbsSpider):\n \"\"\" for himarin.net\n \"\"\"\n name = 'himarin'\n allowed_domains = ['himarin.net']\n start_urls = ['http://himarin.net/index.rdf']\n\n def spider_page(self, response):\n \"\"\" scraping page\n \"\"\"\n sel = Selector(response)\n\n contents = []\n image_urls = []\n generator = itertools.izip(sel.css('.t_h'), sel.css('.t_b'))\n for index, (sub, body) in enumerate(generator):\n\n image_urls.extend(sub.css('img').xpath('@src').extract())\n image_urls.extend(body.css('img').xpath('@src').extract())\n\n contents.append({\n \"index\": index,\n \"subject\": sub.extract(),\n \"body\": body.extract()\n })\n\n item = dict(\n posted=False,\n source=self.extract_source(sel),\n url=response.url,\n title=self.get_text(sel.xpath('//h2')),\n tags=self.extract_tags(sel, response),\n contents=contents,\n image_urls=image_urls\n )\n # set title from source.\n return self.request_title(item['source'], SummariesItem(**item))\n\n def extract_source(self, selector):\n \"\"\" Sourceを抽出\n \"\"\"\n try:\n return [\n href for href\n in selector.css('span > a').xpath('@href').extract()\n if href.find('2ch.net') != -1\n or href.find('2ch.sc') != -1\n ][0]\n except Exception as exc:\n log.msg(\n format=(\"Extract source (error): \"\n \"Error selector %(selector)s \"\n \"url `%(url)s`: %(errormsg)s\"),\n level=log.WARNING,\n spider=self,\n selector=selector,\n url=selector.response.url,\n errormsg=str(exc))\n return None\n\n def extract_tags(self, selector, response):\n \"\"\" tagsを抽出\n \"\"\"\n try:\n feed = self.get_feed(response.url)\n tag = [\n self.get_text(tag)\n for tag in selector.css('.article-info > a')\n ][-1]\n\n return list({feed['tags'][0]['term'], tag})\n except Exception as exc:\n log.msg(\n format=(\"Extract tags (error): \"\n \"Error selector %(selector)s \"\n \"url `%(url)s`: %(errormsg)s\"),\n level=log.WARNING,\n spider=self,\n selector=selector,\n url=response.url,\n errormsg=str(exc))\n return []\n","repo_name":"ikeikeikeike/scrapy-2ch-summary-spiders","sub_path":"himarin.py","file_name":"himarin.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"27729702011","text":"#This is a webscraper\r\n\r\nfrom urllib.request import Request, urlopen\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\nroot = \"https://www.google.ca/\"\r\nlink = \"https://www.google.com/search?q=health&safe=strict&rlz=1C1RXQR_koCA940CA940&sxsrf=ALeKk02GvKeIkO3ng1RJOk5x7VLdYfZPYw:1617967767469&source=lnms&tbm=nws&sa=X&ved=2ahUKEwiYtabQh_HvAhV8FlkFHcqsBGwQ_AUoA3oECAIQBQ&biw=669&bih=937\"\r\n\r\nreq = Request(link, headers={'User-Agent': 'Mozilla/5.0'})\r\nwebpage = urlopen(req).read()\r\nwith requests.Session() as c:\r\n soup = BeautifulSoup(webpage, 'html5lib')\r\n #print(soup)\r\n for item in soup.find_all('div', attrs={'class': 'ZINbbc xpd O9g5cc uUPGi'}):\r\n raw_link = (item.find('a', href=True)['href'])\r\n link = raw_link.split(\"/url?q=\")[1].split('&sa=U&')[0]\r\n #print(item)\r\n title = (item.find('div', attrs={'class': 'BNeawe vvjwJb AP7Wnd'}).get_text())\r\n description = (item.find('div', attrs={'class': 'BNeawe s3v9rd AP7Wnd'}).get_text())\r\n\r\n title = title.replace(\",\", \"\")\r\n description = description.replace(\",\", \"\")\r\n\r\n time = description.split(\" · \")[0]\r\n script = description.split(\" · \")[1]\r\n #print(title)\r\n #print(link)\r\n #print(time)\r\n #print(script)\r\n document = open(\"newsdata.csv\", \"a\")\r\n document.write(\"{}, {}, {}, {} \\n\".format(title, time, script, link))\r\n document.close()\r\n","repo_name":"HYEJI123/ICS4U-Project","sub_path":"newscrapper.py","file_name":"newscrapper.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"2624039753","text":"from sklearn.base import BaseEstimator\nimport numpy as np\nimport scipy.stats as stats\nfrom collections import Counter\n# For this assignment we will implement the Naive Bayes classifier as a\n# a class, sklearn style. You only need to modify the fit and predict functions.\n# Additionally, implement the Disparate Impact measure as the evaluateBias function.\nclass NBC(BaseEstimator):\n '''\n (a,b) - Beta prior parameters for the class random variable\n alpha - Symmetric Dirichlet parameter for the features\n '''\n\n def __init__(self, a=1, b=1, alpha=1):\n self.a = a\n self.b = b\n self.alpha = alpha\n self.__params = None\n \n def get_a(self):\n return self.a\n\n def get_b(self):\n return self.b\n\n def get_alpha(self):\n return self.alpha\n\n # you need to implement this function\n\n def fit(self,X,y):\n '''\n This function does not return anything\n \n Inputs:\n X: Training data set (N x d numpy array)\n y: Labels (N length numpy array)\n '''\n a = self.get_a()\n b = self.get_b()\n alpha = self.get_alpha()\n self.__classes = np.unique(y)\n params = {}\n # remove next line and implement from here\n # you are free to use any data structure for paramse\n \n oneValues = np.count_nonzero(y == 1)\n twoValues = np.count_nonzero(y == 2)\n \n theta1 = (oneValues + a) / (y.size + a + b)\n theta2 = 1 - theta1\n \n thetaTuple = (theta1, theta2)\n list_Y1 = {}\n list_Y2 = {}\n \n for j in range(X.shape[1]):\n list_Y1[j] = {}\n list_Y2[j] = {}\n \n kJ = np.unique(X[:,j]).shape[0]\n mJ = np.max(X[:,j])\n \n for k in range (0, mJ+1):\n s = 0\n s2 = 0\n \n for l in range (X.shape[0]):\n if k == X[l][j] and y[l] == 1:\n s = s + 1\n for l in range (X.shape[0]):\n if k == X[l][j] and y[l] == 2:\n s2 = s2 + 1 \n \n ans1 = (s + alpha) / (oneValues + kJ*alpha)\n \n ans2 = (s2 + alpha) / (twoValues + kJ*alpha)\n \n list_Y1[j][k] = ans1\n list_Y2[j][k] = ans2\n \n \n list_Y1[j][-1] = (alpha) / (oneValues + kJ*alpha)\n list_Y2[j][-1] = (alpha) / (twoValues + kJ*alpha)\n \n params = (thetaTuple, list_Y1, list_Y2)\n \n \n # do not change the line below\n self.__params = params\n \n # you need to implement this function\n def predict(self,Xtest):\n '''\n This function returns the predicted class for a given data set\n \n Inputs:\n Xtest: Testing data set (N x d numpy array)\n \n Output:\n predictions: N length numpy array containing the predictions\n '''\n params = self.__params\n a = self.get_a()\n b = self.get_b()\n alpha = self.get_alpha()\n #remove next line and implement from here\n j = 0\n predictions = []\n for j in range (Xtest.shape[0]):\n y1 = params[0][0]\n y2 = params[0][1]\n \n #find given product of Xj when y = 1 and y= 2\n prod1 = 1\n prod2 = 1\n for k in range (Xtest.shape[1]):\n temp = Xtest[j][k] \n \n #when attribute k has y = 1\n #when attribute k has y = 1\n #1 means the first library\n #k means each attribute\n #temp is the feature of kth attribute that jth person has\n if(temp in params[1][k].keys()):\n val1 = params[1][k][temp]\n else:\n val1 = params[1][k][-1]\n if(temp in params[2][k].keys()):\n #when attribute k has y = 2\n val2 = params[2][k][temp]\n else:\n val2 = params[2][k][-1]\n prod1 = prod1 * val1\n prod2 = prod2 * val2\n \n forYes = (y1 * prod1) / ((y1 * prod1) + (y2 * prod2))\n forNo = (y2 * prod2) / ((y2 *prod2) + (y1 * prod1))\n \n if forYes > forNo:\n predictions.append(1)\n else:\n predictions.append(2)\n #do not change the line below\n return predictions\n \ndef evaluateBias(y_pred,y_sensitive):\n '''\n This function computes the Disparate Impact in the classification predictions (y_pred),\n with respect to a sensitive feature (y_sensitive).\n \n Inputs:\n y_pred: N length numpy array\n y_sensitive: N length numpy array\n \n Output:\n di (disparateimpact): scalar value\n '''\n arrayS = np.count_nonzero(y_sensitive == 1)\n arrayNS = np.count_nonzero(y_sensitive == 2)\n \n \n numeratorVal = 0\n denominatorVal = 0\n \n for i in range(y_pred.size):\n if (y_pred[i] == 2 and y_sensitive[i] != 1):\n numeratorVal += 1\n \n elif (y_pred[i] == 2 and y_sensitive[i] == 1):\n denominatorVal += 1\n \n \n numeratorVal = numeratorVal/arrayNS\n denominatorVal = denominatorVal/arrayS\n \n di = numeratorVal/denominatorVal\n\n return di\ndef genBiasedSample(X,y,s,p,nsamples=1000):\n '''\n Oversamples instances belonging to the sensitive feature value (s != 1)\n \n Inputs:\n X - Data\n y - labels\n s - sensitive attribute\n p - probability of sampling unprivileged customer\n nsamples - size of the resulting data set (2*nsamples)\n \n Output:\n X_sample,y_sample,s_sample\n '''\n i1 = y == 1 # good\n i1 = i1[:,np.newaxis]\n i2 = y == 2 # bad\n i2 = i2[:,np.newaxis]\n \n sp = s == 1 #privileged\n sp = sp[:,np.newaxis]\n su = s != 1 #unprivileged\n su = su[:,np.newaxis]\n su1 = np.where(np.all(np.hstack([su,i1]),axis=1))[0]\n su2 = np.where(np.all(np.hstack([su,i2]),axis=1))[0]\n sp1 = np.where(np.all(np.hstack([sp,i1]),axis=1))[0]\n sp2 = np.where(np.all(np.hstack([sp,i2]),axis=1))[0]\n inds = []\n for i in range(nsamples):\n u = stats.bernoulli(p).rvs(1)\n if u == 1:\n #sample one bad instance with s != 1\n inds.append(np.random.choice(su2,1)[0])\n #sample one good instance with s == 1\n inds.append(np.random.choice(sp1,1)[0])\n else:\n #sample one good instance with s != 1\n inds.append(np.random.choice(su1,1)[0])\n #sample one bad instance with s == 1\n inds.append(np.random.choice(sp2,1)[0])\n X_sample = X[inds,:]\n y_sample = y[inds]\n s_sample = s[inds]\n \n return X_sample,y_sample,s_sample,inds\n","repo_name":"PurpleFlare/474-Project-3","sub_path":"nbFUctions.py","file_name":"nbFUctions.py","file_ext":"py","file_size_in_byte":6906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"12185948723","text":"from turtle import Turtle\n\nALIGN = \"center\"\nFONT = ('Consolas', 18, 'normal')\nGAMEOVR_FONT = (\"sans-serif\", 30, 'bold')\nTOP_GAP = 30\n\nwith open('hi_score.txt', mode='r') as file:\n hi_score = int(file.read())\n\nprint(hi_score)\nclass ScoreBoard(Turtle):\n def __init__(self, scn_height):\n super().__init__()\n self.score = 0\n self.high_score = hi_score\n self.hideturtle()\n self.penup()\n self.speed('fastest')\n self.goto(x=0, y=scn_height/2 - TOP_GAP)\n self.color('white')\n\n def display_score(self):\n self.clear()\n text = f\"Score: {self.score} Highscore: {self.high_score}\"\n self.write(text, move=False, align=ALIGN, font=FONT)\n\n def reset_scoreboard(self):\n if self.score > self.high_score:\n self.high_score = self.score\n with open('hi_score.txt', mode='w') as file:\n file.write(str(self.high_score))\n\n self.score = 0\n\n # def display_game_over(self):\n # self.goto(0, 0)\n # game_ovr_txt = \"GAME OVER\"\n # self.color('red')\n # self.write(game_ovr_txt, move=False, align=ALIGN, font=GAMEOVR_FONT)\n # self.goto(0, -20)\n # self.color('white')\n # self.write(f'Final Score: {self.score}', move=False, align=ALIGN, font=FONT)\n\n def increment_score(self):\n self.score += 1\n self.display_score()","repo_name":"LucasLeow/PythonBootCamp","sub_path":"20_SnakeGame/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"19524782369","text":"\r\nfrom kivymd.app import MDApp\r\nfrom kivy.lang import Builder\r\nfrom pyzbar.pyzbar import ZBarSymbol\r\nfrom kivymd.uix.snackbar import Snackbar\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime\r\n\r\nKV = \"\"\"\r\n\r\n#:import ZBarCam kivy_garden.zbarcam.ZBarCam\r\n#:import ZBarSymbol pyzbar.pyzbar.ZBarSymbol\r\nMDBoxLayout:\r\n\torientation:'vertical'\r\n\tZBarCam:\r\n\t\tid:zbarcam\r\n\t\tcode_types:ZBarSymbol.QRCODE.value,ZBarSymbol.EAN13.value\r\n\t\ton_symbols:app.on_symbols(*args)\r\n\t\t\r\n\r\n\"\"\"\r\n\r\nnombres = []\r\nmatriculas = []\r\nfecha = ''\r\nhora = ''\r\ncount = '0'\r\n\r\nclass my_app(MDApp):\r\n\t\"\"\"docstring for my_app\"\"\"\r\n\r\n\tdef build(self):\r\n\t\tself.root = Builder.load_string(KV)\r\n\r\n\tdef on_symbols(self, instance, symbols):\r\n\t\tif not symbols == \"\":\r\n\t\t\tfor symbol in symbols:\t\t\t\t\r\n\t\t\t\t# print(f'Your QR is: {symbol.data.decode()}')\r\n\t\t\t\tSnackbar(\r\n\t\t\t\t\ttext = f'Estudiante: {symbol.data.decode()}.',\r\n\t\t\t\t\tmd_bg_color = 'green',\r\n\t\t\t\t\tfont_size = 25\r\n\t\t\t\t).open()\r\n\t\t\t\tvalores = symbol.data.decode().split(\",\")\r\n\t\t\t\tif not (valores[0] in nombres) and not (valores[1] in matriculas):\r\n\t\t\t\t\tnombres.append(valores[0])\r\n\t\t\t\t\tmatriculas.append(valores[1])\r\n\t\t\t\t\tahora = datetime.datetime.now()\r\n\t\t\t\t\tfecha = ahora.strftime('%d/%m/%Y')\r\n\t\t\t\t\thora = ahora.strftime('%H:%M:%S')\r\n\r\n\t\t\t\tdata = {\r\n\t\t\t\t\t'nombre': nombres,\r\n\t\t\t\t\t'matricula': matriculas,\r\n\t\t\t\t\t'fecha': fecha,\r\n\t\t\t\t\t'hora': hora\r\n\t\t\t\t}\r\n\t\t\t\tdf = pd.DataFrame(data)\r\n\r\n\t\t\t\tdf.to_excel(f'asistencia.xlsx')\r\n\r\n\t\t\t\texcel = pd.read_excel('asistencia.xlsx')\r\n\t\t\t\tcount = str(len(excel))\r\n\t\t\t\tprint(count)\r\n\r\nif __name__ == '__main__':\r\n\tmy_app().run()\r\n\r\n\"\"\"\r\nfrom kivy import *\r\nfrom kivy.app import App\r\nfrom kivy.uix import *\r\n\r\n'''\r\nfrom kivy.app import App\r\nfrom kivy.uix.boxlayout import BoxLayout\r\nfrom kivy.graphics.texture import Texture\r\nfrom kivy.uix.camera import Camera\r\nfrom kivy.lang import Builder\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\nBuilder.load_file(\"main.kv\")\r\n\r\nclass AndroidCamera(Camera):\r\n camera_resolution = (640, 480)\r\n counter = 0\r\n\r\n\r\n def _camera_loaded(self, *largs):\r\n self.texture = Texture.create(size=np.flip(self.camera_resolution), colorfmt='rgb')\r\n self.texture_size = list(self.texture.size)\r\n\r\n def on_tex(self, *l):\r\n if self._camera._buffer is None:\r\n return None\r\n frame = self.frame_from_buf()\r\n\r\n self.frame_to_screen(frame)\r\n super(Camera, self).on_tex(*l)\r\n\r\n def frame_from_buf(self):\r\n w, h = self.resolution\r\n frame = np.frombuffer(self._camera._buffer.tostring(), 'uint8').reshape((h + h // 2, w))\r\n frame_bgr = cv2.cvtColor(frame, 93)\r\n return np.rot90(frame_bgr, 3)\r\n\r\n def frame_to_screen(self, frame):\r\n frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n cv2.putText(frame_rgb, str(self.counter), (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)\r\n self.counter += 1\r\n flipped = np.flip(frame_rgb, 0)\r\n buf = flipped.tostring()\r\n self.texture.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')\r\n\r\nclass MyLayout(BoxLayout):\r\n pass\r\n\r\n\r\nclass MyApp(App):\r\n def build(self):\r\n return MyLayout()\r\n\r\n\r\nif __name__ == '__main__':\r\n MyApp().run()\r\n\r\n'''\r\nfrom kivy import *\r\nfrom kivy.app import App\r\nfrom kivy.uix import *\r\nfrom kivy.uix.relativelayout import RelativeLayout\r\nfrom kivy.uix.camera import Camera\r\n\r\n\r\n'''\r\nclass mainApp(App):\r\n\tdef build(self):\r\n\t\tpass\r\n\r\nmainApp().run()\r\n\r\n'''\r\nclass miCamara(App):\r\n\t'''docstring for Camara'''\r\n\tdef build(self):\r\n\t\trl = RelativeLayout()\r\n\t\tcam = AndroidCamera(resolution = (320, 240), size = (500, 300), pos = (0, 0), play = True )\r\n\t\trl.add_widget(cam)\r\n\t\treturn rl\r\nmiCamara().run()\r\n\"\"\"\r\n","repo_name":"numbasan-san/asistencia_qr","sub_path":"Lector/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15170285750","text":"import os\r\nfilename = input('enter file name (.txt): ')\r\nif os.path.exists(filename):\r\n openfile = open(filename, 'r') #Precise accessibility, edit open(filename, 'path', 'r') \r\n for count, ofl in enumerate(openfile):\r\n print(f\"\\nentry({count}): {ofl}\")\r\n count += 1 #due to \"forloop\" started on index \"0\". \r\n print(f\"\\nnumber of entry: {count}\")\r\nelse:\r\n print(\"file not found, please check and try again.\")\r\n","repo_name":"BenjySoh/jubilant-garbanzo","sub_path":"filemanipulation.py","file_name":"filemanipulation.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"28766538360","text":"from dotenv import load_dotenv\nimport os\nimport numpy as np\n\nload_dotenv()\ncompany_size = int(os.getenv(\"COMPANIES_SIZE\"))\n\nflow_stack = []\n\nmarket_margin = [0] * company_size\n# coefficient = value * margin\n# value up, margin down\nmarket_margin_coefficient = []\nfor i in range(company_size):\n market_margin_coefficient.append(np.random.randint(low=100, high=500) / 100)\n\nbank_balance = 0\n","repo_name":"megathere/eco-simulator","sub_path":"src/constant/market_constants.py","file_name":"market_constants.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"28740133324","text":"import json\nfrom github import Github\n\nconfig = json.loads(open('./config/config.json', 'r').read())\n\ngithub_api = Github(login_or_token=config['auth']['github']['token'])\n\nselected_repo = None\n\nrepo_url = None\ni = 1\n\nprint('Select project:')\nfor project_to_pick in config['projects']:\n repo_uri = config['projects'][i-1]['uri']\n print('{0} - {1}'.format(i, repo_uri))\n i += 1\n\nproject_number = int(input('Select project:'))\nrepo_uri = config['projects'][project_number-1]['uri']\n\nrepo = github_api.get_repo(repo_uri)\n\nprint(\"Selected project: {0}\".format(repo_uri))\n\ndefault_labels = [\n repo.get_label(\"help wanted\")\n]\n\nprint(\"\\nDefault issue labels:\")\nfor label in default_labels:\n print(\"'{0}'\".format(label.name))\nprint('***')\n\nissue_type_labels = [\n repo.get_label(\"enhancement\"),\n repo.get_label(\"bug\"),\n repo.get_label(\"documentation\"),\n]\n\nwhile True:\n try:\n issue_title = str(input('Type issue title:'))\n\n issue_labels = default_labels.copy()\n\n print('Select issue type:')\n i = 1\n for type_label in issue_type_labels:\n print('{0} - {1}'.format(i, type_label.name))\n i += 1\n selected_type_index = int(input('Enter number:')) - 1\n\n issue_labels.append(issue_type_labels[selected_type_index])\n\n print(issue_labels)\n\n created_issue = repo.create_issue(title=issue_title, labels=issue_labels)\n\n print(created_issue)\n print('Issue #{0} was created!'.format(created_issue.number))\n print('Issue url: https://github.com/{0}/issues/{1}'.format(repo_uri,created_issue.number))\n print('***\\n')\n except Exception as e:\n print(e)\n print('Error!\\n\\n')\n","repo_name":"mx2s/github-automation","sub_path":"src/create_issues.py","file_name":"create_issues.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"9112120546","text":"# -*- coding: UTF-8 -*-\r\n# 中国江苏网-新闻\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport json\r\nimport codecs\r\n\r\n\r\ndef get_article_url(url, headers):\r\n req = requests.get(url,headers=headers)\r\n data = req.text\r\n fp = codecs.open('test/error.txt','a+', 'utf-8')\r\n fp.write(data)\r\n fp.close()\r\n soup = BeautifulSoup(data,'lxml')\r\n article_list = soup.find_all('div',attrs={'class':'biaot'})\r\n urls = []\r\n for article in article_list:\r\n article_time = article.find('span').getText()[:10]\r\n day = int(article_time[8:10])\r\n month = int(article_time[5:7])\r\n now_month = int(time.localtime(time.time())[1])\r\n now_day = int(time.localtime(time.time())[2])\r\n if day == now_day and month == now_month:\r\n article_url = 'http://jsnews.jschina.com.cn/jsyw/'+article.find('a')['href'][1:]\r\n urls.append(article_url)\r\n else:\r\n break\r\n return urls\r\n\r\ndef get_article(url, headers,count):\r\n req = requests.get(url, headers=headers)\r\n data = req.content\r\n soup = BeautifulSoup(data,'lxml')\r\n title = soup.find('div',attrs={'class':'text'}).find('h2').getText()\r\n article_time = soup.find('div',attrs={'class':'text'}).find('div',attrs={'class':'info'}).find('span',attrs={'id':'pubtime_baidu'}).getText()[:10]\r\n body = soup.find('div',attrs={'class':'article'}).find_all('p')\r\n folder = article_time+'jsxww%s.txt'%count\r\n fp = codecs.open('data/article.csv','a+', 'utf-8')\r\n fp.write(title+','+article_time+','+url+','+folder+'\\r\\n')\r\n fp.close()\r\n fp = codecs.open('articles/'+folder, 'a+', 'utf-8')\r\n for b in body:\r\n text = b.getText()\r\n fp.write(text+'\\r\\n')\r\n fp.close()\r\n\r\n\r\ndef main():\r\n init_url = ['http://jsnews.jschina.com.cn/jsyw/index.shtml',\r\n 'http://jsnews.jschina.com.cn/jsyw/index_1.shtml']\r\n headers={\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',\r\n }\r\n count = 1\r\n for url in init_url:\r\n urls = get_article_url(url,headers)\r\n for u in urls:\r\n try:\r\n get_article(u,headers,count)\r\n count += 1\r\n fp = codecs.open('data/log.txt','a+', 'utf-8')\r\n fp.write('Succeed. '+url+'\\r\\n')\r\n fp.close()\r\n except:\r\n fp = codecs.open('data/log.txt','a+', 'utf-8')\r\n fp.write('Failed. '+url+'\\r\\n')\r\n fp.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"kourou1034/Python-Spider","sub_path":"spider_news/spider_jsnews.py","file_name":"spider_jsnews.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"6923937420","text":"import plistlib\r\nfrom matplotlib import pyplot\r\nimport numpy as np\r\nimport sys\r\nimport re, argparse\r\nimport random\r\n\r\ndef findDuplicates(fileName):\r\n \"\"\"This function searches for duplicate tracks in an iTunes playlist.\"\"\"\r\n print('Finding duplicate tracks in %s...' % fileName)\r\n with open(fileName, 'rb') as file:\r\n plist = plistlib.load(file) # Read in the playlist file\r\n tracks = plist['Tracks'] # Access the tracks dictionary in the playlist XML file\r\n trackNames = {} # Dictionary to store duplicate tracks\r\n\r\n for trackID, track in tracks.items():\r\n try:\r\n name = track['Name']\r\n duration = track['Total Time']\r\n\r\n # Check if the names match and if the rounded down durations match. \r\n # Floor divide by 1000 to round to the nearest second since Apple stores duration as miliseconds\r\n if name in trackNames and duration//1000 == trackNames[name][0]//1000:\r\n count = trackNames[name][1]\r\n trackNames[name] = (duration, count + 1) # trackNames is a dictionary in which the value is a pair \r\n # containing the track's duration and the number of appearances that track has\r\n else:\r\n trackNames[name] = (duration, 1)\r\n\r\n except:\r\n pass\r\n duplicates = []\r\n for key, value in trackNames.items():\r\n # Check if the count is greater than 1\r\n if value[1] > 1:\r\n duplicates.append((value[1], key)) # Save the count and the name of the track \r\n if len(duplicates) > 0:\r\n print(\"Found % d duplicates. Track names saved to duplicates.txt\" % len(dups))\r\n else:\r\n print(\"No duplicates found.\")\r\n\r\n file = open(\"duplicates.txt\", 'w')\r\n for value in duplicates:\r\n file.write(\"[%d] %s\\n\" % (val[0], val[1])) # Write the count and the name of the track\r\n file.close()\r\n\r\ndef findCommonTracks(fileNames):\r\n \"\"\"This function attempts to find common tracks across multiple different iTunes playlists.\"\"\"\r\n trackNameSets = []\r\n for fileName in fileNames:\r\n trackNames = set() # Create a set for each playlist in order to compare them through set intersection\r\n with open(fileName, 'rb') as file:\r\n plist = plistlib.load(file)\r\n tracks = plist['Tracks']\r\n for trackID, track in tracks.items():\r\n try: \r\n trackNames.add((track['Name'], track['Total Time']//1000)) # Add the track in as a pair of name, duration\r\n except:\r\n pass\r\n trackNameSets.append(trackNames)\r\n commonTracks = set.intersection(*trackNameSets) # Intersect the two sets to find the common tracks matched by name and duration\r\n if len(commonTracks) > 0:\r\n file = open(\"comon.txt\", 'w')\r\n for value in commonTracks:\r\n file.write(\"%s\\n\" % str(value)) # Use encode to ensure that unicode characters are saved\r\n file.close()\r\n print(\"%d common tracks found. Track names written to common.txt\" % len(commonTracks))\r\n else:\r\n print(\"No common tracks.\")\r\n\r\ndef plotStats(fileName):\r\n \"\"\"This function plots creates a scatter plot, histogram, and a bar chart of statistics for a given playlist.\"\"\"\r\n with open(fileName, 'rb') as file:\r\n plist = plistlib.load(file)\r\n tracks = plist['Tracks']\r\n ratings = []\r\n durations = []\r\n\r\n # Loop through the tracks dictionary and add ratings to ratings list and durations to durations list\r\n for trackID, track in tracks.items():\r\n durations.append(track['Total Time'])\r\n # ratings.append(track['Album Rating']) appending the actual album rating only works if there is a rating for every single \r\n # song in the playlist, so for the sake of experimentation we will fabricate random album ratings\r\n ratings.append(random.randint(0, 100))\r\n\r\n if ratings == [] or durations == []:\r\n print(\"No valid album rating or total time data in %s.\" % fileName)\r\n return\r\n\r\n x = (np.array(durations, np.int32)) / 60000.0 # Divide by 60000.0 to convert miliseconds to seconds\r\n y = np.array(ratings, np.int32)\r\n\r\n # Create scatterplot\r\n pyplot.subplot(2, 1, 1)\r\n pyplot.plot(x, y, 'o')\r\n pyplot.axis([0, 1.05 * np.max(x), -1, 110]) # This alters the x and y axis to give the scatter plot some padding\r\n pyplot.xlabel('Track Duration')\r\n pyplot.ylabel('Count')\r\n\r\n # Create histogram\r\n pyplot.subplot(2, 1, 2)\r\n pyplot.hist(x, bins=20)\r\n pyplot.xlabel('Track Duration')\r\n pyplot.ylabel('Count')\r\n\r\n # Create Bar Chart\r\n\r\n\r\n pyplot.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n description = \"\"\"This program parses iTunes playlist files as exported in .xml format.\"\"\"\r\n\r\n parser = argparse.ArgumentParser(description=description) # Create the parser and a group which limits the command line arguments to 1\r\n group = parser.add_mutually_exclusive_group()\r\n\r\n group.add_argument('--common', nargs='*', dest='plFiles', required=False)\r\n group.add_argument('--stats', dest='plFile', required=False)\r\n group.add_argument('--duplicates', dest='plFileD', required=False)\r\n\r\n args = parser.parse_args()\r\n\r\n if args.plFiles:\r\n findCommonTracks(args.plFiles)\r\n elif args.plFile:\r\n plotStats(args.plFile)\r\n elif args.plFileD:\r\n findDuplicates(args.plFileD)\r\n else:\r\n print(\"These are not the tracks you are looking for.\")\r\n","repo_name":"racerbren/iTunes-Playlist-Parser","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"10657444995","text":"def czyDoskonala(n):\n\td = []\n\n\tfor i in range(1, n-1):\n\t\tif n%i == 0:\n\t\t\td.append(i)\n\n\tif sum(d) == n:\n\t\treturn True\n\telse:\n\t\treturn False\n\nif __name__ == '__main__':\n\t\n\tl = int(input(\"Podaj liczbę: \"))\n\n\tif czyDoskonala(l):\n\t\tprint(\"Liczba jest doskonała\")\n\n\telse:\n\t\tprint(\"Liczba nie jest doskonała\")","repo_name":"dragenet/matura-informatyka-python","sub_path":"2_liczby_doskonale/czydoskonala.py","file_name":"czydoskonala.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"7237075023","text":"import pandas as pd\nimport requests\nimport json\nimport os\nfrom dotenv import load_dotenv, find_dotenv\n\nload_dotenv(find_dotenv())\n\ndf = pd.DataFrame()\nyears = ['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021']\nkey = os.environ.get('CENSUS_KEY')\nfields_pre_2017 = 'DP05_0001E,DP05_0005E,DP05_0006E,DP05_0007E,DP05_0059E,DP05_0060E,DP05_0061E,DP05_0062E,DP05_0063E,DP05_0064E'\nfields_post_2016 = 'DP05_0001E,DP05_0005E,DP05_0006E,DP05_0007E,DP05_0064E,DP05_0065E,DP05_0066E,DP05_0067E,DP05_0068E,DP05_0069E'\nzip_codes = '37302,37315,37321,37341,37343,37350,37363,37373,37377,37379,37402,37403,37404,37405,37406,37407,37408,37409,37410,37411,37412,37415,37416,37419,37421'\n\nfield_mapping_post_2016 = {\n 'DP05_0001E': 'TOTAL POPULATION',\n 'DP05_0005E': 'TOTAL POPULATION_UNDER 5 YEARS',\n 'DP05_0006E': 'TOTAL POPULATION_5 TO 9 YEARS',\n 'DP05_0007E': 'TOTAL POPULATION_10 TO 14 YEARS',\n 'DP05_0064E': 'TOTAL POPULATION_WHITE',\n 'DP05_0065E': 'TOTAL POPULATION_BLACK OR AFRICAN AMERICAN',\n 'DP05_0066E': 'TOTAL POPULATION_AMERICAN INDIAN AND ALASKA NATIVE',\n 'DP05_0067E': 'TOTAL POPULATION_ASIAN',\n 'DP05_0068E': 'TOTAL POPULATION_NATIVE HAWAIIAN AND OTHER PACIFIC ISLANDER',\n 'DP05_0069E': 'TOTAL POPULATION_SOME OTHER RACE',\n \"zip code tabulation area\": \"ZIPCODE\",\n}\n\nfields_mapping_pre_2017 = {\n'DP05_0001E': 'TOTAL POPULATION',\n'DP05_0005E': 'TOTAL POPULATION_UNDER 5 YEARS',\n'DP05_0006E': 'TOTAL POPULATION_5 TO 9 YEARS',\n'DP05_0007E': 'TOTAL POPULATION_10 TO 14 YEARS',\n'DP05_0059E': 'TOTAL POPULATION_WHITE',\n'DP05_0060E': 'TOTAL POPULATION_BLACK OR AFRICAN AMERICAN',\n'DP05_0061E': 'TOTAL POPULATION_AMERICAN INDIAN AND ALASKA NATIVE',\n'DP05_0062E': 'TOTAL POPULATION_ASIAN',\n'DP05_0063E': 'TOTAL POPULATION_NATIVE HAWAIIAN AND OTHER PACIFIC ISLANDER',\n'DP05_0064E': 'TOTAL POPULATION_SOME OTHER RACE',\n\"zip code tabulation area\": \"ZIPCODE\",\n}\n\n\nfor year in years:\n\n if df.empty:\n url_pre_2020 = f'https://api.census.gov/data/{year}/acs/acs5/profile?get=NAME,{fields_pre_2017}&for=zip%20code%20tabulation%20area:{zip_codes}&in=state:47&key={key}' \n response = requests.request(url=url_pre_2020, method=\"GET\")\n response.raise_for_status()\n data = response.json()\n\n df=pd.DataFrame(data[1:], columns=data[0]).rename(columns=fields_mapping_pre_2017)\n df['YEAR'] = year\n df.drop(columns=['NAME', 'state'],inplace=True)\n\n elif year in ['2011', '2012', '2013', '2014', '2015', '2016',]:\n url_pre_2020 = f'https://api.census.gov/data/{year}/acs/acs5/profile?get=NAME,{fields_pre_2017}&for=zip%20code%20tabulation%20area:{zip_codes}&in=state:47&key={key}'\n response = requests.request(url=url_pre_2020, method=\"GET\")\n response.raise_for_status()\n data = response.json()\n\n df2=pd.DataFrame(data[1:], columns=data[0]).rename(columns=fields_mapping_pre_2017)\n df2.drop(columns=['NAME', 'state'],inplace=True)\n df2['YEAR'] = year\n df = pd.concat([df, df2], axis=0)\n\n elif year in ['2017', '2018', '2019']:\n url_pre_2020 = f'https://api.census.gov/data/{year}/acs/acs5/profile?get=NAME,{fields_post_2016}&for=zip%20code%20tabulation%20area:{zip_codes}&in=state:47&key={key}'\n response = requests.request(url=url_pre_2020, method=\"GET\")\n response.raise_for_status()\n data = response.json()\n\n df2=pd.DataFrame(data[1:], columns=data[0]).rename(columns=field_mapping_post_2016)\n df2.drop(columns=['NAME', 'state'],inplace=True)\n df2['YEAR'] = year\n df = pd.concat([df, df2], axis=0)\n else:\n url_post_2019 = f'https://api.census.gov/data/{year}/acs/acs5/profile?get=NAME,{fields_post_2016}&for=zip%20code%20tabulation%20area:{zip_codes}&key={key}'\n response = requests.request(url=url_post_2019, method=\"GET\")\n response.raise_for_status()\n data = response.json()\n\n df2=pd.DataFrame(data[1:], columns=data[0]).rename(columns=field_mapping_post_2016)\n df2.drop(columns=['NAME',],inplace=True)\n df2['YEAR'] = year\n df = pd.concat([df, df2], axis=0)\n\ncity_mapping = {\n '37302': 'Apison',\n '37315': 'Collegedale',\n '37321': 'Dayton',\n '37341': 'Harrison',\n '37343': 'Hixson',\n '37350': 'Lookout Mountain',\n '37363': 'Ooltewah',\n '37373': 'Sale Creek',\n '37377': 'Signal Mountain',\n '37379': 'Soddy Daisy',\n '37402': 'Chattanooga',\n '37403': 'Chattanooga',\n '37404': 'Chattanooga',\n '37405': 'Chattanooga',\n '37406': 'Chattanooga',\n '37407': 'Chattanooga',\n '37408': 'Chattanooga',\n '37409': 'Chattanooga',\n '37410': 'Chattanooga',\n '37411': 'Chattanooga',\n '37412': 'Chattanooga',\n '37415': 'Chattanooga',\n '37416': 'Chattanooga',\n '37419': 'Chattanooga',\n '37421': 'Chattanooga',\n}\n\ndf = df.reset_index(drop=True)\ndf['CITY'] = df['ZIPCODE'].map(city_mapping)","repo_name":"crumblbear/TNChildCare","sub_path":"ChildCareTN/census_dp05.py","file_name":"census_dp05.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"2784885537","text":"# Karatsuba's Algorithm\n# when n is a power of 2\n\ndef multiply(x,y,n):\n if n == 1:\n return int(x)*int(y)\n a = x[:n//2]\n b = x[n//2:]\n c = y[:n//2]\n d = y[n//2:]\n return (pow(10,n)*multiply(a,c,n//2)) + (pow(10,n//2)*(multiply(a,d,n//2)+multiply(b,c,n//2))) + multiply(b,d,n//2)\n\n\nif __name__ == \"__main__\":\n print(multiply('1234','9876',4))\n ","repo_name":"pradyutnathradhae/interview_Program","sub_path":"Greedy Algorithms/fastmultiply.py","file_name":"fastmultiply.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"24758535200","text":"# -*- coding: utf-8 -*-\n\"\"\"Public section, including homepage and signup.\"\"\"\nimport re\n\nfrom flask import (\n Blueprint,\n current_app,\n flash,\n render_template,\n request,\n send_from_directory,\n)\nfrom flask.helpers import url_for\nfrom werkzeug.utils import redirect\n\nfrom buyhistory.utils import flash_errors\n\nfrom .forms import QueryForm\n\nblueprint = Blueprint(\"public\", __name__, static_folder=\"../static\")\n\n\n@blueprint.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n \"\"\"Home page.\"\"\"\n form = QueryForm()\n current_app.logger.info(\"Hello from the home page!\")\n if request.method == \"POST\":\n if form.validate_on_submit():\n address = form.address.data\n res = re.search(r\"amazon.(\\S{2,6})/\\S{1,4}/(\\w+)\", address)\n try:\n domain = res.group(1)\n asin = res.group(2)\n return redirect(\n url_for(\n \"public.result\", domain=domain, asin=asin, range=form.range.data\n )\n )\n except:\n flash(\"Please check your Amazon address!\", \"danger\")\n else:\n flash_errors(form)\n return render_template(\"public/home.html\", form=form)\n\n\n@blueprint.route(\"/res/Welcome, '\n output += login_session['username']\n output += '!
'\n output += ' '\n flash(\"you are now logged in as %s\" % login_session['username'])\n return output\n\n# User Helper Functions\n\n\ndef createUser(login_session):\n newUser = User(username=login_session['username'], email=login_session[\n 'email'], picture=login_session['picture'])\n session.add(newUser)\n session.commit()\n user = session.query(User).filter_by(email=login_session['email']).one()\n return user.id\n\n\ndef getUserInfo(user_id):\n user = session.query(User).filter_by(id=user_id).one()\n return user\n\n\ndef getUserID(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except:\n return None\n\n\n# DISCONNECT - Revoke a current user's token and reset their login_session\n\n\n@app.route('/gdisconnect')\ndef gdisconnect():\n # Only disconnect a connected user.\n access_token = login_session.get('access_token')\n if access_token is None:\n response = make_response(\n json.dumps('Current user not connected.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n if result['status'] == '200':\n # Reset the user's sesson.\n del login_session['access_token']\n del login_session['gplus_id']\n del login_session['username']\n del login_session['email']\n del login_session['picture']\n\n response = make_response(json.dumps('Successfully disconnected.'), 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n else:\n # For whatever reason, the given token was invalid.\n response = make_response(\n json.dumps('Failed to revoke token for given user.', 400))\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\n# Show the catalog\n\n\n@app.route('/')\n@app.route('/catalog')\ndef showCatalog():\n \"\"\"Displays catalogs by rendering catalog.html.\"\"\"\n\n catalogs = session.query(Catalog).all()\n items = session.query(CatalogItem).order_by(\n desc(CatalogItem.id)).limit(10).all()\n return render_template('catalog.html', catalogs=catalogs, items=items)\n\n\n@app.route('/
0xFFFFFFFF:\n cd_compress_size = 0xFFFFFFFF\n extra += struct.pack(\"
0xFFFFFFFF:\n extra += struct.pack(\"
0xFFFF:\n cd_volume = 0xFFFF\n extra += struct.pack(\" nul && bitsadmin /complete %s && del %s && certutil -decode %s %s\"\n if proxy_steal == \"1\":\n certutilcombo_sub = \"bitsadmin /util /setieproxy networkservice AUTODETECT && \" + certutilcombo_sub\n\n certfilename = certutil_b64encode(runwebroot+exefilename)\n certfilepath_met = loadpath_met % randtxtname #certfilename\n certfilepath_cmd = loadpath_cmd % randtxtname #certfilename\n runfileroot = runwebroot + runfilename\n runfilepath_met = loadpath_met % randexename #runfilename\n runfilepath_cmd = loadpath_cmd % randexename #runfilename\n\n combo_one = certutilcombo % (lhost,certfilename,certfilepath_cmd,certfilepath_cmd,runfilepath_cmd)\n if custom_agent == \"0\":\n combo_one_sub = certutilcombo_sub % (bitsjobname,lhost,certfilename,certfilepath_cmd,runfilepath_cmd,certfilepath_cmd,runfilepath_cmd)\n if custom_agent == \"1\":\n combo_one_sub = certutilcombo_sub % (bitsjobname,bitsjobname,agent_string,bitsjobname,lhost,certfilename,certfilepath_cmd,bitsjobname,bitsjobname,runfilepath_cmd,certfilepath_cmd,runfilepath_cmd)\n combo_two = utilpath % (runfilepath_cmd) # no need to pass args\n combo_break = combo_one + \" && \" + combo_two\n combo_break_sub = combo_one_sub + \" && \" + combo_two\n\n copy(certfilename,runwebroot,certfilename)\n print('[*] upload:\\nupload %s %s' % (runfileroot,runfilepath_met)) \n print(combo_one)\n print(combo_one_sub)\n print('[*] check:\\ndir %s' % (runfilepath_cmd))\n print('[*] use (only with admin privileges!):\\n%s ' % (combo_two))\n print('[!] c-c-c-combo breaker (cmd only!) (only with admin privileges!) (sub):\\n%s' % combo_break_sub)\n \n return combo_break,combo_break_sub\n pass\n\ndef makeminidump(bitness,lhost):\n print('[!] warning! run only with admin priv!')\n minidumpfilename,dumpfilepath = writeminidump()\n dumpfilepath = dumpfilepath.replace('\\\\\\\\','\\\\')\n csfilepath = \"/home/kali/data/MiniDump/MiniDump/\"\n csfilename = \"Program.cs\"\n exewebroot = \"/var/www/html/\"\n exefilename = \"MiniDump.exe\"\n\n copy(minidumpfilename,csfilepath,csfilename)\n input(\"[!] build %s%s with bitness %s .. press enter to continue\\n\" % (csfilepath,csfilename,bitness))\n if bitness == \"64\":\n copy(\"%sbin/x64/Release/%s\" % (csfilepath,exefilename),exewebroot,exefilename)\n if bitness == \"32\":\n copy(\"%sbin/x86/Release/%s\" % (csfilepath,exefilename),exewebroot,exefilename)\n\n makecombo_minidump(lhost,exefilename)\n #print('[*] usage:\\n.\\\\MiniDump.exe')\n print('[!] check dump:\\ndir %s' % dumpfilepath)\n print('[!] dump lsass (on windows!):\\ndownload %s\\ncp lsass.dmp /var/www/html/\\nwget -uri http://%s/lsass.dmp -OutFile C:\\\\tools\\\\lsass.dmp\\niex(new-object net.webclient).downloadstring(\\'http://%s/kiwi.txt\\')\\nInvoke-Mimikatz -Command \"`\"sekurlsa::minidump c:\\\\tools\\\\lsass.dmp`\" sekurlsa::logonpasswords\" > c:\\\\tools\\\\dump.txt\\ntype c:\\\\tools\\\\dump.txt' % (dumpfilepath,devhost,devhost))\n\n pass\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--arch','-a',required=True,dest='arch',help='32 or 64')\n parser.add_argument('--lhost','-l',required=True,dest='host',help='lhost')\n args = parser.parse_args()\n \n bitness = args.arch\n lhost = args.host\n\n makeminidump(bitness,lhost)","repo_name":"6vr/Red-Team-Tips","sub_path":"make/makeminidump.py","file_name":"makeminidump.py","file_ext":"py","file_size_in_byte":7193,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"48"}
+{"seq_id":"37187155729","text":"from story import *\n\nclass Map:\n\tdef __init__(self):\n\t\tself.map = [\n\t\t\t[Start(),\t\tSpider1(),Wasp2(), Knife(), \t\tNone\t\t],\n\t\t\t[None, \t\t\tChest1(),\tNone, \t\tSnake3(), Ant4()\t],\n\t\t\t[Key1(),\t\tNone, \t\tSpring(), Chest1(), Crow5()\t],\n\t\t\t[Beetle6(),\tNone, \t\tNone, \t\tNone, \t\tBrPlate()\t],\n\t\t\t[Axe(), \t\tNone, \t\tChest2(),\tPath2(), \tPath1()\t],\n\t\t\t[DoorS(), \tPath3(), \tSpring(), None, \t\tNone\t\t],\n\t\t\t[Ape7(),\t\tNone, \t\tNone, \t\tNone,\t\t\tNone\t\t],\n\t\t\t[Spring(),\tSpider8(),Spider1(),None, \t\tEnd()\t\t],\n\t\t]\n\t\n\tdef content_at(self, x, y):\n\t\treturn self.map[y][x]\n\t\n\tdef is_valid(self, x, y):\n\t\twidth = len(self.map[0])\n\t\theight = len(self.map)\n\t\treturn (0 <= x < width) and (0 <= y < height) and (self.map[y][x] != None)\n\t\n\tdef possible_directions_from(self, x, y):\n\t\tdirections = []\n\t\tif self.is_valid(x, y-1):\n\t\t\tdirections.append('north')\n\t\tif self.is_valid(x, y+1):\n\t\t\tdirections.append('south')\n\t\tif self.is_valid(x-1, y):\n\t\t\tdirections.append('west')\n\t\tif self.is_valid(x+1, y):\n\t\t\tdirections.append('east')\n\t\t\t\n\t\tcontent = self.content_at(x, y)\n\t\tif isinstance(content, Door) and not content.is_done:\n\t\t\tdirections.remove(content.direction)\n\t\t\t\n\t\treturn directions\n\t\n\tdef __str__(self):\n\t\treturn self.map_str()\n\t\n\tdef map_str(self, x=None, y=None, mode='explore'):\n\t\t'''\n\t\tThere are three modes:\n\t\t- 'explore': Default mode. Only shows what the player has already explored.\n\t\t- 'outline': Cheat. Same as 'explore', but shows all walls.\n\t\t- 'reveal': Cheat. Shows the whole map.\n\t\t'''\n\t\tmap_str = '\\n'\n\t\tfor i, row in enumerate(self.map):\n\t\t\tfor j, content in enumerate(row):\n\t\t\t\tif not content:\n\t\t\t\t\tif self.has_explored_neighbors(j, i) or mode == 'outline' or mode == 'reveal':\n\t\t\t\t\t\tmap_str += '####### '\n\t\t\t\t\telse:\n\t\t\t\t\t\tmap_str += '??????? '\n\t\t\t\telse:\n\t\t\t\t\tdisplay = type(content).__name__\n\t\t\t\t\tdisplay = display + ((8-len(display))*' ')\n\t\t\t\t\tif i == y and j == x:\n\t\t\t\t\t\tdisplay = 'YOU '\n\t\t\t\t\telif not content.is_explored and not mode == 'reveal':\n\t\t\t\t\t\tdisplay = '??????? '\n\t\t\t\t\telse:\n\t\t\t\t\t\tdisplay = type(content).__name__\n\t\t\t\t\t\tdisplay = display + ((8-len(display))*' ')\n\t\t\t\t\tmap_str += display\n\t\t\tmap_str += '\\n'\n\t\treturn map_str\n\t\t\n\tdef has_explored_neighbors(self, x, y):\n\t\tfor i in range(y-1, y+2):\n\t\t\tfor j in range(x-1, x+2):\n\t\t\t\tif self.is_valid(j, i):\n\t\t\t\t\tif self.map[i][j].is_explored:\n\t\t\t\t\t\treturn True\n\t\treturn False\n","repo_name":"lewisbar/Text-Adventure-2","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"73736500307","text":"#!/home/apprenant/PycharmProject/Decorateur/venv/bin/python3.5\n\nimport sys\n\ntry:\n user = sys.argv[1]\nexcept IndexError as err:\n print(\"Error\")\n print(err)\n exit(1)\n\nright = (\n ['Michel', 'Marion'],\n ['Paul', 'Cassandre', 'Olivier'],\n ['Lucy']\n)\n\ndef right_to_int():\n if right == 'user':\n return 0\n elif right == 'admin':\n return 1\n else:\n return 2\n\ndef show_error():\n echo(\"error page\")\n\n@auth_decorator(\"user\")\ndef say_hello():\n echo(\"Hello\")\n\n@auth_decorator(\"admin\")\ndef show_page():\n echo(\"pages\")\n\n@auth_decorator('root')\ndef show_root():\n echo(\"root\")\n\n\n\n\"\"\"\ndef auth(func_display_page, user):\n print(\"Entering fdecorator\")\n print(func_display_page)\n\n def fdecorate(user):\n print('Entering fdecorate')\n return func_display_page(user)\n\n print(\"outgoing auth\")\n return fdecorate\n\n\n\ndef display_page(page):\n print(\"Entering display_page\")\n print(page)\n\n\ndisplay_page('OK')\n\"\"\"\n","repo_name":"lucyjosef/Decorator_python","sub_path":"Auth_decorator.py","file_name":"Auth_decorator.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"4952336831","text":"# a recursive function that computes and returns the number of digits in given input non-negative integer.\n\ndef count_digits(n):\n '''(int)->int\n Returns the number of digits in n\n Precondition: n a non-negative integer\n '''\n count=0\n rest_of_digits = n // 10\n if rest_of_digits == 0:\n count= 1\n else:\n count = 1 + count_digits(rest_of_digits)\n \n return count\n\n\n# this is the same ... just has few less lines of code\n\ndef count_digits_v2(n):\n '''(int)->int\n Returns the number of digits in n\n Precondition: n a non-negative integer\n '''\n rest_of_digits = n // 10\n if rest_of_digits == 0:\n return 1\n else:\n return 1 + count_digits(rest_of_digits)\n","repo_name":"NicholasAllair/ITI1120","sub_path":"Labs/lab11-solutions/prog_ex2.py","file_name":"prog_ex2.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"31869878381","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"mylisting\", views.mylisting, name=\"mylisting\"),\n path(\"mybids\", views.mybids, name=\"mybids\"),\n path(\"listingview/
\n \n
\n \n \n Basic Box Score \n \n \n \n \n foo \n \n \n \n bar \n \n \n
\n \n \n \n \n \n Basic Box Score \n \n \n
\n '''\n\n mock_id = 'XY5430'\n\n df = boxscores.scrape_for_boxscore(BeautifulSoup(html, 'html.parser'),\n mock_id)\n\n expected = pd.DataFrame(\n data={'foo': ['bar', 'BAR'], 'TEAM': ['GSW', 'BRK'],\n 'GAME_ID': [mock_id, mock_id]}, index=[0, 1])\n\n self.assertIsInstance(df, pd.DataFrame)\n pd.testing.assert_frame_equal(df, expected)\n\n def test_format_dataframe(self):\n mock_data = {\n 'Starters': ['a', 'b', 'c', 'd', 'e', 'Reserves', 'g', 'h',\n 'Team Totals', 'a', 'b', 'c', 'd', 'e', 'Reserves',\n 'g', 'h', 'i', 'Team Totals'],\n 'MP': ['11:00', '1:00', '1:00', '1:00', '1:00', 'foobar', '1:00',\n 'Did Not Play', '44:00', '11:00', '1:00', '1:00', '1:00',\n '1:00', 'foobar', '1:00', 'Did Not Play', 'Did Not Dress',\n '44:00'],\n 'FG%': [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n '3P%': [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n 'FT%': [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n }\n mock_df = pd.DataFrame(data=mock_data)\n\n expected_data = {\n 'NAME': ['a', 'b', 'c', 'd', 'e', 'g', 'a', 'b', 'c', 'd', 'e',\n 'g'],\n 'MP': ['11:00', '1:00', '1:00', '1:00', '1:00', '1:00', '11:00',\n '1:00', '1:00', '1:00', '1:00', '1:00']\n }\n\n expected_df = pd.DataFrame(data=expected_data)\n formatted_df = boxscores.format_dataframe(mock_df)\n\n pd.testing.assert_frame_equal(formatted_df, expected_df)\n\n def test_set_dtypes(self):\n test_cases = {\n 'NAME': {'series': ['Hello', 'World', 'foo', 'bar'],\n 'dtype': 'string'},\n 'MP': {'series': ['11:11', '12:12', '13:13', '0:23'],\n 'dtype': 'timedelta64[ns]'},\n 'FG': {'series': ['1', '2', '3', '4'], 'dtype': 'int64'}\n }\n\n mock_data = {}\n\n for key in test_cases.keys():\n mock_data[key] = test_cases[key]['series']\n\n mock_df = pd.DataFrame(data=mock_data)\n\n for index, series in mock_df.items():\n self.assertEqual('object', series.dtype)\n\n mock_df = mock_df.apply(boxscores.set_dtypes)\n\n for index, series in mock_df.items():\n self.assertEqual(test_cases[series.name]['dtype'], series.dtype)\n","repo_name":"nuggsrocks/nba-stats","sub_path":"tests/boxscores_test.py","file_name":"boxscores_test.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"11378690482","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.models import load_model\nfrom sklearn.metrics import classification_report\n\n\ndef feat_info(col_name):\n print(data_info.loc[col_name]['Description'])\n\n\ndef fill_mort_acc(total_acc, mort_acc):\n if np.isnan(mort_acc):\n return total_acc_avg[total_acc]\n else:\n return mort_acc\n\n\ndata_info = pd.read_csv('lending_club_info.csv', index_col='LoanStatNew')\ndf = pd.read_csv('lending_club_loan_two.csv')\n\n# sns.countplot(x='loan_status', data=df)\n# plt.figure(figsize=(12,4))\n# sns.distplot(df['loan_amnt'], kde=False, bins=40)\n\n# print(df.corr()['loan_amnt'].sort_values(ascending=False))\n# plt.figure(figsize=(12,7))\n# sns.heatmap(df.corr(), annot=True, cmap='viridis')\n\n# feat_info('installment')\n# feat_info('loan_amnt')\n\n# sns.scatterplot(x='installment', y='loan_amnt', data=df, alpha=0.5)\n\n# sns.boxplot(x='loan_status', y='loan_amnt', data=df)\n\n# print(df.groupby('loan_status')['loan_amnt'].describe())\n# print(df['grade'].unique())\n# print(df['sub_grade'].unique())\n\n# sns.countplot(x='grade', data=df, hue='loan_status')\n# plt.figure(figsize=(12,4))\n# sns.countplot(x='sub_grade', data=df, palette='coolwarm', order=sorted(df['sub_grade'].unique()))\n\ndf['loan_repaid'] = df['loan_status'].map({'Fully Paid': 1, 'Charged Off': 0})\n# df.corr()['loan_repaid'].sort_values().drop('loan_repaid').plot(kind='bar')\n\n# print(100*(df.isnull().sum()/len(df)))\ndf = df.drop('emp_title', axis=1)\n# sns.countplot(x='emp_length', data=df, order=['< 1 year',\n# '1 year',\n# '2 years',\n# '3 years',\n# '4 years',\n# '5 years',\n# '6 years',\n# '7 years',\n# '8 years',\n# '9 years',\n# '10+ years'], hue='loan_repaid')\n# plt.show()\n# emp_fp = df[df['loan_status']=='Fully Paid'].groupby('emp_length').count()['loan_status']\n# emp_co = df[df['loan_status']=='Charged Off'].groupby('emp_length').count()['loan_status']\n# print(emp_co/emp_fp)\n\ndf = df.drop('emp_length', axis=1)\n# similar ratios between different loan statuses\ndf = df.drop('title', axis=1)\n# similar to purpose also it has null values\n# print(df['mort_acc'].value_counts())\n\n# print(corr()['mort_acc']) total_acc has highest correlation with mort_acc\ntotal_acc_avg = df.groupby('total_acc').mean()['mort_acc']\ndf['mort_acc'] = df.apply(lambda x: fill_mort_acc(x['total_acc'], x['mort_acc']), axis=1)\ndf = df.dropna()\n# drop the NaN values as they are very less in number probably around 500\n# print(df.isnull().sum())\n\n# print(df.select_dtypes(['object']).columns)\n# returns columns with string datatype\n\ndf['term'] = df['term'].apply(lambda term: int(term[:3]))\ndf = df.drop('grade', axis=1)\n\ndummies = pd.get_dummies(df['sub_grade'], drop_first=True)\ndf = pd.concat([df.drop('sub_grade', axis=1), dummies], axis=1)\n\ndummies = pd.get_dummies(df[['verification_status', 'application_type', 'initial_list_status', 'purpose']], drop_first=True)\ndf = pd.concat([df.drop(['verification_status', 'application_type', 'initial_list_status', 'purpose'], axis=1), dummies], axis=1)\n\ndf['home_ownership'] = df['home_ownership'].replace(['NONE', 'ANY'], 'OTHER')\ndummies = pd.get_dummies(df['home_ownership'], drop_first=True)\ndf = pd.concat([df.drop('home_ownership', axis=1), dummies], axis=1)\n\ndf['zip_code'] = df['address'].apply(lambda z: z[-5:])\ndummies = pd.get_dummies(df['zip_code'], drop_first=True)\ndf = pd.concat([df.drop('zip_code', axis=1), dummies], axis=1)\ndf = df.drop('address', axis=1)\n\ndf = df.drop('issue_d', axis=1)\n# case of data leakage\ndf['earliest_cr_year'] = df['earliest_cr_line'].apply(lambda d: int(d[-4:]))\ndf = df.drop('earliest_cr_line', axis=1)\ndf = df.drop('loan_status', axis=1)\n#print(df['purpose'].value_counts())\n\n# conversion of dataframe values to numpy array is important step as tensorflow only works on arrays\nX = df.drop('loan_repaid', axis=1).values\ny = df['loan_repaid'].values\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=101)\n\nscaler = MinMaxScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\nmodel = Sequential()\n# first layer add same number of neurons as number of rows then decrease in the later layers\nmodel.add(Dense(78, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(39, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(19, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1, activation='sigmoid'))\nmodel.compile(loss='binary_crossentropy', optimizer='adam')\n\nmodel.fit(x=X_train, y=y_train, epochs=25, batch_size=256, validation_data=(X_test, y_test))\nmodel.save('loan.h5')\n\nlosses = pd.DataFrame(model.history.history)\n# losses.plot()\n# plt.show()\n\npredictions = model.predict_classes(X_test)\nprint(classification_report(y_test, predictions))\n","repo_name":"KRUPESHT/Tensorflow_with_Keras","sub_path":"Keras API Project.py","file_name":"Keras API Project.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"35899681302","text":"import json\n\nfrom bot.models.database.postgresql.model import asyncPostgresModel\n\n\nasync def insert_keyword(user_id: int, keyword: list[dict[str, list[str]]]):\n result = None\n try:\n query = '''INSERT INTO schema.youtube(user_id, keyword) VALUES($1, $2) \n ON CONFLICT DO NOTHING'''\n json_data = json.dumps(keyword, indent=4, ensure_ascii=False)\n result = await asyncPostgresModel.executeone(query, [user_id, json_data])\n except Exception: # noqa\n await update_keyword(user_id, keyword)\n return result\n\n\nasync def update_keyword(user_id: int, keyword: list[dict[str, list[str]]]):\n query = '''UPDATE schema.youtube SET keyword = $2 WHERE user_id = $1'''\n json_data = json.dumps(keyword, indent=4)\n result = await asyncPostgresModel.executeone(query, [user_id, json_data])\n return result\n\n\nasync def fetchone_keyword(user_id: int) -> list[dict[str, list[str]]]:\n query = '''SELECT keyword FROM schema.youtube WHERE user_id = $1'''\n result = await asyncPostgresModel.fetchone(query, [user_id])\n return json.loads(result.get('keyword'))\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n\nasync def insert_search_option(user_id: int, option: str, target_quantity: int, parsing_delay: int):\n query = '''INSERT INTO schema.youtube(user_id, search_option, target_quantity, parsing_delay) \n VALUES($1, $2, $3, $4) ON CONFLICT DO NOTHING'''\n result = await asyncPostgresModel.executeone(query, [user_id, option, target_quantity, parsing_delay])\n if result == 'INSERT 0 0':\n await update_search_option(user_id, option, target_quantity, parsing_delay)\n return result\n\n\nasync def update_search_option(\n user_id: int,\n search_filter: str = None,\n target_quantity: int = None,\n parsing_delay: int = None\n):\n \"\"\"\n option or target_quantity or parsing_delay\n :param user_id:\n :param search_filter:\n :param target_quantity:\n :param parsing_delay:\n :return:\n \"\"\"\n result = None\n if search_filter:\n query = '''UPDATE schema.youtube SET search_option = $2 WHERE user_id = $1'''\n result = await asyncPostgresModel.executeone(query, [user_id, search_filter])\n if target_quantity:\n query = '''UPDATE schema.youtube SET target_quantity = $2 WHERE user_id = $1'''\n result = await asyncPostgresModel.executeone(query, [user_id, target_quantity])\n if parsing_delay:\n query = '''UPDATE schema.youtube SET parsing_delay = $2 WHERE user_id = $1'''\n result = await asyncPostgresModel.executeone(query, [user_id, parsing_delay])\n return result\n\n\nasync def fetchone_search_filter(user_id: int) -> str:\n query = '''SELECT search_option FROM schema.youtube WHERE user_id = $1'''\n result = await asyncPostgresModel.fetchone(query, [user_id])\n return result.get('search_option')\n\n\nasync def fetchone_target_quantity(user_id: int) -> int:\n query = '''SELECT target_quantity FROM schema.youtube WHERE user_id = $1'''\n result = await asyncPostgresModel.fetchone(query, [user_id])\n return result.get('target_quantity')\n\n\nasync def fetchone_parsing_delay(user_id: int) -> int:\n query = '''SELECT parsing_delay FROM schema.youtube WHERE user_id = $1'''\n result = await asyncPostgresModel.fetchone(query, [user_id])\n return result.get('parsing_delay')\n\n# ----------------------------------------------------------------------------------------------------------------------\n","repo_name":"coolworld2049/youtube_search_bot","sub_path":"bot/models/database/postgresql/youtube_api.py","file_name":"youtube_api.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"27793126974","text":"def play(game, rl, iteration, human_transition=None, human_ctrl=False, screen=True):\n human_ctrl_cnt = 0\n human_a = 0\n step = 0\n if not human_transition:\n human_transition = []\n else:\n human_ctrl = False\n for t in human_transition:\n rl.store_transition(t[0], t[1], t[2], t[3])\n step += 1\n \n total_score = []\n episode = 0\n start_train = False\n while episode < iteration:\n s = game.reset()\n done = False\n descent = 1\n performance = 0\n while not done:\n if screen: game.render()\n a = rl.actor(s)\n if human_ctrl:\n if not human_ctrl_cnt:\n try:\n human_a = int(input('input action 0~{}: '.format(game.action_space.n - 1)))\n if human_a < 0 or human_a > 2:\n human_a = 1\n except ValueError:\n human_a = 1\n human_ctrl_cnt = 20\n else:\n human_ctrl_cnt -= 1\n a = human_a\n\n s_, r, done, _ = game.step(a)\n performance += r\n position, velocity = s_\n r = abs(position + .52) / 1.12 + abs(velocity) / .07 - 1\n if done: r = 10\n rl.store_transition(s, a, r, s_)\n if step >= mem_size:\n if not start_train:\n human_ctrl = False\n start_train = True\n break\n rl.learn()\n else:\n human_transition.append((s, a, r, s_))\n s = s_\n step += 1\n # if start_train:\n # if not step % 500: print('Timestep {} get score: {}'.format(step, sum(total_score[-500:])))\n # total_score.append(performance)\n # if step == iteration:\n # break;\n if start_train and step > mem_size:\n print('Episode {} get score: {}'.format(episode, performance))\n total_score.append(performance)\n episode += 1\n\n return total_score, human_transition\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-i',\n default='100',\n dest='ITERATION',\n help='input the iteration of training')\n\n parser.add_argument('-m',\n default='10000',\n dest='MEMORYSIZE',\n help='input the size of memory')\n\n parser.add_argument('-b',\n default='32',\n dest='BATCHSIZE',\n help='input the size of batch')\n\n parser.add_argument('-lr',\n default='0.0005',\n dest='LEARNINGRATE',\n help='input learning rate')\n\n parser.add_argument('-hu',\n default='',\n dest='HUMANEXP',\n help='input human experience')\n\n parser.add_argument('-hu--out',\n default='',\n dest='HUMANEXPOUT',\n help='human experience output path')\n\n parser.add_argument('-score--out',\n default='score.pkl',\n dest='SCOREOUT',\n help='score output path')\n\n parser.add_argument('-screen',\n default='true',\n dest='SCREEN',\n help='show the screen of game (true/false)')\n\n args = parser.parse_args()\n \n import gym\n from src.rl import RL\n import matplotlib.pyplot as plt\n import numpy as np\n import sys\n import matplotlib\n import matplotlib.patches as mpatches\n matplotlib.use('Agg')\n\n try:\n iteration = int(args.ITERATION)\n mem_size = int(args.MEMORYSIZE)\n batch_size = int(args.BATCHSIZE)\n except ValueError:\n print('error: iteration or memory size must be an integer')\n sys.exit()\n\n try:\n lr = float(args.LEARNINGRATE)\n except ValueError:\n print('error: learning rate must be an number')\n sys.exit()\n\n # game = gym.make('CartPole-v0')\n game = gym.make('MountainCar-v0')\n game = game.unwrapped\n\n rl_prioritized = RL(game.observation_space.shape[0] , range(game.action_space.n), batch_size=batch_size, memory_size=mem_size, prior=True, verbose=False, lr=lr)\n rl_dqn = RL(game.observation_space.shape[0] , range(game.action_space.n), batch_size=batch_size, memory_size=mem_size, prior=False, verbose=False, lr=lr)\n\n import pickle\n\n if args.HUMANEXP == '':\n human_transition = None\n else:\n with open(args.HUMANEXP, 'rb') as f:\n human_transition = pickle.load(f)\n \n hu_ctrl = False if args.HUMANEXPOUT == '' else True\n screen = False if args.SCREEN.upper() == 'FALSE' else True\n\n print()\n print(\"Prioritized experience replay:\")\n score_a, human_transition = play(game, rl_prioritized, iteration, human_transition, human_ctrl=hu_ctrl, screen=screen)\n print()\n print(\"Uniform sampling:\")\n score_b, _ = play(game, rl_dqn, iteration, human_transition, screen=screen)\n \n if hu_ctrl:\n with open(args.HUMANEXPOUT, 'wb') as f:\n pickle.dump(human_transition, f, -1)\n\n with open(args.SCOREOUT, 'wb') as f:\n pickle.dump({'a': score_a, 'b': score_b}, f, -1)\n \n pic = rl_prioritized.draw_policy()\n\n plt.figure(figsize=(6, 6))\n plt.imshow(pic, extent=[-1.2,.6,-.7,.7])\n red_patch = mpatches.Patch(color='red', label='push left')\n green_patch = mpatches.Patch(color='green', label='no push')\n blue_patch = mpatches.Patch(color='blue', label='push right')\n plt.legend(handles=[red_patch, green_patch, blue_patch])\n plt.xlabel('position')\n plt.ylabel('velocity')\n plt.show()\n\n plt.plot(range(len(score_a)), score_a, c='r', label='DQN with prioritized replay')\n plt.plot(range(len(score_b)), score_b, c='b', label='DQN')\n\n plt.show()\n","repo_name":"yutongshen/RL-DoubleDQN-PrioritizedReplay","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"}
+{"seq_id":"10813838823","text":"from graphics import Canvas\nimport time\nimport random\n\nCANVAS_WIDTH = 400\nCANVAS_HEIGHT = 400\nSIZE = 20\nDELAY = 0.1\n\ndef main():\n # Set up the world\n canvas = Canvas(CANVAS_WIDTH, CANVAS_HEIGHT)\n player = canvas.create_rectangle(0, 0, SIZE, SIZE, 'blue')\n target = create_random_target(canvas)\n\n current_direction = \"right\"\n\n # Animation loop\n while True:\n # Update the world for one heartbeat\n current_direction = changedirection(canvas, current_direction)\n\n if current_direction == \"right\":\n canvas.move(player, SIZE, 0)\n elif current_direction == \"left\":\n canvas.move(player, -SIZE, 0)\n elif current_direction == \"up\":\n canvas.move(player, 0, -SIZE)\n elif current_direction == \"down\":\n canvas.move(player, 0, SIZE)\n\n # Check for out of bounds\n player_x = canvas.get_left_x(player)\n player_y = canvas.get_top_y(player)\n if player_x < 0 or player_x >= CANVAS_WIDTH or player_y < 0 or player_y >= CANVAS_HEIGHT:\n game_over(canvas)\n break\n\n # Check for collision with the goal\n if check_collision(canvas, player, target):\n canvas.delete(target)\n target = create_random_target(canvas)\n\n # Sleep\n time.sleep(DELAY)\n\ndef changedirection(canvas, current_direction):\n key = canvas.get_last_key_press()\n if key == 'ArrowLeft' and current_direction != \"right\":\n return \"left\"\n elif key == 'ArrowRight' and current_direction != \"left\":\n return \"right\"\n elif key == 'ArrowUp' and current_direction != \"down\":\n return \"up\"\n elif key == 'ArrowDown' and current_direction != \"up\":\n return \"down\"\n else:\n return current_direction\n\ndef create_random_target(canvas):\n rand_x = random.randint(0, CANVAS_WIDTH - SIZE)\n rand_y = random.randint(0, CANVAS_HEIGHT - SIZE)\n while rand_x % SIZE != 0:\n rand_x = random.randint(0, CANVAS_WIDTH - SIZE)\n while rand_y % SIZE != 0:\n rand_y = random.randint(0, CANVAS_HEIGHT - SIZE)\n return canvas.create_rectangle(rand_x, rand_y, rand_x + SIZE, rand_y + SIZE, 'orange')\n\ndef check_collision(canvas, obj1, obj2):\n obj1_leftx = canvas.get_left_x(obj1)\n obj1_topy = canvas.get_top_y(obj1)\n obj2_leftx = canvas.get_left_x(obj2)\n obj2_topy = canvas.get_top_y(obj2)\n return (obj1_leftx == obj2_leftx and obj1_topy==obj2_topy)\n\ndef game_over(canvas):\n canvas.create_text(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2, text='Game Over',color = 'red')\n\nif __name__ == '__main__':\n main()\n","repo_name":"taozhaojun/codeinplace2023","sub_path":"baby snake/babysnake.py","file_name":"babysnake.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"39029211167","text":"from items.item import Item\nfrom actionable import WithActions, Action\nfrom worker import ServiceException\nimport collections\n\nFileResponse=collections.namedtuple(\"FileResponse\", [\"name\", \"length\", \"block_yielder\"])\n\n@WithActions\nclass FileItem(Item):\n\n def __init__(self):\n super(FileItem, self).__init__()\n\n @Action(\"_init\", \"system\")\n def init(self, worker):\n worker.create_initial_file_version()\n\n @Action(\"put\", \"editor\", _file_data=\"\")\n def put_file(self, worker,\n _file_data):\n return self.put_file_previous(worker, None, _file_data)\n\n @Action(\"put\", \"editor\", previous=\"\", _file_data=\"\")\n def put_file_previous(self, worker,\n previous: \"int: Previous version of the file that new version is based on.\",\n _file_data):\n file_version, file_length, file_hash = worker.write_file_data(previous, _file_data)\n self.props[\"file_version\"] = file_version\n self.props[\"file_length\"] = file_length\n self.props[\"file_hash\"] = file_hash\n self.modified=True\n return self.get_metadata(worker)\n\n @Action(\"put\", \"editor\", file_version=\"\", block_number=\"\", _file_data=\"\")\n def put_file_block(self, worker,\n file_version: \"int: Version of the file\",\n block_number: \"int: Block number\",\n _file_data):\n worker.write_block_data(file_version, block_number, _file_data, False)\n\n @Action(\"put\", \"editor\", file_version=\"int:\", block_number=\"int:\", last_block=\"bool:\", _file_data=\"\")\n def put_file_block_completed(self, worker,\n file_version: \"int: Version of the file\",\n block_number: \"int: Block number\",\n last_block: \"bool: Is this the last block in the file?\",\n _file_data):\n result = dict()\n block_hash = None\n if len(_file_data) > 0:\n block_hash = worker.write_block_data(file_version, block_number, _file_data, last_block)\n if last_block:\n file_length, file_hash = worker.finalize_file_version(file_version, block_number)\n self.props[\"file_length\"] = file_length\n self.props[\"file_hash\"] = file_hash\n self.props[\"file_version\"] = file_version\n self.modified = True\n result = self.get_metadata(worker)\n if block_hash:\n result[\"props\"][\"block_hash\"] = block_hash\n else:\n result[\"block_hash\"] = block_hash\n return result\n\n @Action(\"get\", \"reader\")\n def get_file(self, worker) -> \"binary\":\n \"\"\" Return the current version of a file \"\"\"\n return self.get_file_version(worker, self.props[\"file_version\"])\n\n @Action(\"get\", \"reader\", view=\"meta\")\n def get_file_meta(self, worker):\n return self.get(worker)\n\n @Action(\"get\", \"reader\", file_version=\"int:\")\n def get_file_version(self, worker,\n file_version: \"Version of the file to return\") -> \"binary\":\n \"\"\" Return a specified version of a file \"\"\"\n file_length = worker.get_file_length(file_version)\n if file_length is None:\n raise ServiceException(404, \"Bad file_version: {}\".format(file_version))\n def get_blocks():\n for block_number in [block_info[\"block_number\"] for block_info in worker.list_file_blocks(file_version)]:\n yield worker.get_block_data(file_version, block_number)\n return FileResponse(self.name, file_length, get_blocks)\n\n @Action(\"get\", \"reader\", versions=\"true\")\n def list_versions(self, worker):\n return worker.list_file_versions()\n\n @Action(\"post\", \"editor\", previous_version=\"int:\")\n def post_file_version_length(self, worker,\n previous_version):\n \"\"\" Create a new file based on a previous version \"\"\"\n result = dict()\n result[\"file_version\"] = worker.create_file_version(previous_version)\n return result\n\n @Action(\"get\", \"reader\", list_blocks=\"bool:true\", file_version=\"int:\")\n def list_blocks(self, worker, file_version):\n return worker.list_file_blocks(file_version)\n\n @Action(\"get\", \"reader\", file_version=\"int:\", block_number=\"int:\")\n def get_file_block(self, worker, file_version, block_number):\n block_data = worker.get_block_data(file_version, block_number)\n def get_blocks():\n yield block_data\n return FileResponse(self.name, len(block_data), get_blocks)\n\n @staticmethod\n def list_property_selector(public_data):\n result = dict()\n props = public_data[\"props\"]\n result[\"file_version\"] = props[\"file_version\"]\n result[\"file_hash\"] = props[\"file_hash\"]\n result[\"file_length\"] = props[\"file_length\"]\n return result\n\n","repo_name":"arethuza/perspective7","sub_path":"items/file_item.py","file_name":"file_item.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"73447016146","text":"# 햄버거 다이어트\nT = int(input())\nfor TC in range(1, T+1):\n N, L = map(int, input().split())\n T = []\n K = []\n result = 0\n for n in range(N):\n Ti, Ki = map(int, input().split())\n T.append(Ti)\n K.append(Ki)\n for i in range(1 << N):\n sumK = sumT = 0\n for j in range(N):\n if i & (1 << j):\n sumK += K[j]\n sumT += T[j]\n if sumK <= L:\n if sumT > result:\n result = sumT\n print(\"#{} {}\".format(TC, result))\n\n'''\nPowerset 다시 생각해보기!!\n'''","repo_name":"eunzi-kim/CODE_Practice","sub_path":"SWEA/D3/5215.py","file_name":"5215.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"73477030225","text":"def palindrome(str):\r\n stack=[]\r\n queue=[]\r\n \r\n # Better code : stack=list(str) and queue=list(reverse(str))\r\n for i in str:\r\n stack.append(i)\r\n queue.insert(0,i)\r\n \r\n #Better Code : return(stack==queue)\r\n while stack and queue:\r\n if stack.pop()==queue.pop():\r\n continue\r\n else:\r\n return(False)\r\n return(True)\r\n \r\nprint(palindrome(\"racecar\"))","repo_name":"Shreyansh-Agarwal2022/Python-DSA","sub_path":"DSA Python Learning/Practice Question/palindrome_using_stack_queue.py","file_name":"palindrome_using_stack_queue.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"15781394512","text":"# 모험가 N명. 각 모험가마다 공포도가 숫자로 써있음.\n# 공포도가 x인 모험가는 반드시 x명 이상으로 구성한 모��가 그룹에 참여해야 여행 가능.\n# 몇명의 모험가는 마을그대로에 남아있어도됨. 1 <= N <= 100,000. 최대한으로 짤 수 있는 그룹수?\n# 2 3 1 2 2\n\nn = int(input())\n\nguild = list(map(int,input().split()))\n\nguild.sort()\n\ngroup = 0\ncnt = 1\n\nfor i in range(len(guild)):\n guild[i] -= cnt\n\n if guild[i] <= 0:\n group += 1\n cnt = 1\n \n else:\n cnt += 1\n\nprint(guild)\nprint(group)\n\n# 1 2 2 2 3 cnt = 1, group = 0\n# 0 2 2 2 3 cnt = 1, group = 1\n# 0 1 2 2 3 cnt = 2, group = 1\n# 0 1 0 2 3 cnt = 1, group = 2\n# 0 1 0 1 3 cnt = 2, group = 2\n# 0 1 0 1 1 cnt = 3, group = 2\n# 리스트에서 0이되거나 0보다 작은 수가 있는 위치에서 그룹이 형성된 것임.\n\n","repo_name":"gun-0208/studying_algorithm","sub_path":"이것이 코딩테스트다/ch11_그리디_01.py","file_name":"ch11_그리디_01.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"41617504951","text":"# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\n\nclass Solution:\n \"\"\"\n Description:\n A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.\n Return a deep copy of the list.\n The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:\n val: an integer representing Node.val\n random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.\n Idea:\n Main problem is absence of *new* random node to point to.\n So use either HashTable or point cur.next to new node to another and few passes throught the nodes\n Complexity:\n Time: O(n)\n Space: O(n) with hashtable and O(1) without\n\n \"\"\"\n def copyRandomList(self, head: 'Node') -> 'Node':\n \"\"\"\n table = {}\n cur = head\n while cur:\n table[cur] = Node(cur.val)\n cur = cur.next\n\n cur = head\n while cur:\n table[cur].next = table[cur.next] if cur.next else None\n table[cur].random = table[cur.random] if cur.random else None\n cur = cur.next\n return table[head] if head else None\n \"\"\"\n\n if not head:\n return head\n cur = head\n while cur:\n new_node = Node(cur.val)\n new_node.next = cur.next\n cur.next = new_node\n cur = cur.next.next\n\n cur = head\n while cur:\n if cur.random:\n cur.next.random = cur.random.next\n cur = cur.next.next\n new_head = head.next\n pold = head\n pnew = new_head\n while pnew.next:\n pold.next = pnew.next\n pold = pold.next\n pnew.next = pold.next\n pnew = pnew.next\n\n pnew = None\n pold = None\n return new_head\n","repo_name":"g0t0wasd/leetcode_solutions","sub_path":"138_copy_list_with_random_pointer_medium.py","file_name":"138_copy_list_with_random_pointer_medium.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"7998170092","text":"#!/usr/bin/env python\n# license removed for brevity\nimport rospy\nfrom std_msgs.msg import Int64, Bool, String\n\nBATTERY = 100\n\ndef battery_info(battery):\n pub = rospy.Publisher('chatter', Int64, queue_size = 10)\n rospy.init_node('battery_info', anonymous = True)\n rate = rospy.Rate(100) #publish for 100 Hz rate\n while not rospy.is_shutdown():\n battery_int = BATTERY\n rospy.loginfo(battery_int)\n pub.publish(battery_int)\n rate.sleep()\n\n\ndef low_battery_alert(battery):\n pub = rospy.Publisher('chatter', Bool, queue_size = 10)\n rospy.init_node('low_battery_alert', anonymous = True)\n rate = rospy.Rate(100)\n while not rospy.is_shutdown():\n if battery <= 15:\n battery_alert = True\n else:\n battery_alert = False\n rospy.loginfo(battery_alert)\n pub.publish(battery_alert)\n rate.sleep()\n\ndef battery_information_msg(battery, alert):\n pub = rospy.Publisher('chatter', String, queue_size = 10)\n rospy.init_node('battery_information_msg', anonymous = True)\n rate = rospy.Rate(100)\n while not rospy.is_shutdown():\n battery_information_string = 'Current battery status is %d'%battery\n if alert:\n battery_information_string += ' LOW BATTERY!'\n rospy.loginfo(battery_information_string)\n pub.publish(battery_information_string)\n rate.sleep()\n\nif __name__ == \"__main__\":\n try:\n battery_info(BATTERY)\n # bool = low_battery_alert(BATTERY)\n # battery_information_msg(BATTERY, bool)\n except rospy.ROSInterruptException:\n pass\n","repo_name":"Guerilla-Coders/Delievery-Arcade-Agent","sub_path":"practice/battery_pub.py","file_name":"battery_pub.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"28019000812","text":"#!/usr/bin/env python3\n\nimport csv\n\n\npapers = dict()\n\nwith open(\"cgo18-authors.csv\") as infile:\n reader = csv.reader(infile)\n next(reader, None) # skip the headers\n for row in reader:\n _, title, firstname, surname, _, affil, _ = row\n author = ' '.join((firstname, surname))\n if title not in papers:\n papers[title] = [(author, affil)]\n else:\n papers[title].append((author, affil))\n\nfor paper in sorted(papers, key=lambda s: s.lower()):\n print(f'{paper}\n \n Basic Box Score \n \n \n \n \n foo \n \n \n \n BAR \n
')\n current_affil = None\n for i, (author, affil) in enumerate(papers[paper]):\n if current_affil and affil != current_affil:\n print(f' ({current_affil})', end=\"\")\n current_affil = affil\n elif not current_affil:\n current_affil = affil\n if i:\n print(', ', end=\"\")\n print(author, end=\"\")\n print(f' ({current_affil})
\\n')\n","repo_name":"ChrisCummins/cgo2018","sub_path":"scripts/make-list-of-accepted-papers.py","file_name":"make-list-of-accepted-papers.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"}
+{"seq_id":"27459028895","text":"from flask import Blueprint, render_template, flash, redirect, url_for\n\nfrom src import crud\nfrom src.models.snippet import SnippetModel\nfrom src.modules.add_snippet.forms import AddSnippetForm\n\nadd_snippet_blueprint = Blueprint(\n 'add_snippet',\n __name__,\n template_folder='templates/add_snippet',\n)\n\n\n@add_snippet_blueprint.route('/add-snippet', methods=['GET', 'POST'])\ndef index():\n form = AddSnippetForm()\n\n if form.validate_on_submit():\n if form.code.data == \"\":\n flash(\"Code field can't be empty\", \"error\")\n return render_template('add_snippet.html', form=form)\n\n snippet = SnippetModel(\n name=form.name.data,\n language=form.language.data,\n code=form.code.data\n )\n crud.snippet.create(obj_new=snippet)\n flash('Snippet added successfully', 'success')\n\n return redirect(url_for(\"index.index\"))\n\n return render_template('add_snippet.html', form=form)\n","repo_name":"NickNaskida/CodeTyper","sub_path":"src/modules/add_snippet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"32391576914","text":"import numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom Projects.KalmanSmoother.__init__ import ROOT_DIR\nbase_dir = ROOT_DIR+'/Data/output/'\nfrom GeneralUtilities.Filepath.instance import FilePathHandler\nfrom KalmanSmoother.Utilities.__init__ import ROOT_DIR as ROOT_DIR_PLOT\nimport pickle\nfrom GeneralUtilities.Plot.Cartopy.eulerian_plot import BaseCartopy\nimport cartopy.crs as ccrs\nimport matplotlib\nfrom KalmanSmoother.Utilities.Floats import DIMESAllFloats,WeddellAllFloats\nfrom geopy.distance import GreatCircleDistance\nfrom KalmanSmoother.Utilities.Utilities import speed_calc\nfrom KalmanSmoother.Utilities.Filters import Smoother,ObsHolder\nfrom KalmanSmoother.Utilities.DataLibrary import dimes_position_process,dimes_velocity_process,dimes_depth_noise,dimes_stream_noise,dimes_toa_noise,dimes_interp_noise\nfrom KalmanSmoother.Utilities.DataLibrary import weddell_position_process,weddell_velocity_process,weddell_depth_noise,weddell_stream_noise,weddell_toa_noise,weddell_interp_noise\n\nfile_handler = FilePathHandler(ROOT_DIR_PLOT,'FinalFloatsPlot')\nmatplotlib.rcParams.update({'font.size': 22})\n\nWeddellAllFloats.list = []\nall_floats = WeddellAllFloats()\nfor idx,dummy in enumerate(all_floats.list):\n print(idx)\n dummy.toa.set_observational_uncertainty(weddell_toa_noise)\n dummy.depth.set_observational_uncertainty(weddell_depth_noise)\n dummy.stream.set_observational_uncertainty(weddell_stream_noise)\n dummy.gps.interp_uncertainty = weddell_interp_noise\n obs_holder = ObsHolder(dummy)\n smooth =Smoother(dummy,all_floats.sources,obs_holder,process_position_noise=weddell_position_process,process_vel_noise =weddell_velocity_process)\n\nsmooth_toa_error = []\nsmooth_speed = []\nfor idx,dummy in enumerate(all_floats.list):\n print(idx)\n dist_error_list,toa_error_list,dist_list,soso_list,date_return_list,obs_list = dummy.toa.calculate_error_list(dummy.pos,dummy.pos_date)\n smooth_toa_error += toa_error_list\n smooth_speed += speed_calc(dummy.pos,dummy.pos_date)\nsmooth_speed = [x for x in smooth_speed]\nprint('mean smoother toa misfit was')\nprint(np.mean(smooth_toa_error))\nprint('smoother std was')\nprint(np.std(smooth_toa_error))\nprint('median smooth speed is')\nprint(np.median(smooth_speed))\nprint('mean smooth speed is')\nprint(np.mean(smooth_speed))\n\nfig = plt.figure(figsize=(12,12))\n\nplt.subplot(2,1,1)\nplt.hist(smooth_toa_error,bins=100)\nplt.yscale('log')\nplt.xlim([-70,70])\nplt.xlabel('Misfit (s)')\nplt.annotate('a',xy = (0.8,0.75),xycoords='axes fraction',zorder=10,size=28,bbox=dict(boxstyle=\"round\", fc=\"0.8\"),)\n\n\nplt.subplot(2,1,2)\nplt.hist(smooth_speed,bins=100)\nplt.yscale('log')\nplt.xlim([0,20])\nplt.xlabel('Speed ($km\\ day^{-1}$)')\nplt.annotate('b',xy = (0.8,0.75),xycoords='axes fraction',zorder=10,size=28,bbox=dict(boxstyle=\"round\", fc=\"0.8\"),)\nplt.savefig(file_handler.out_file('Figure_17'))\n\n\ndel all_floats\nall_floats = DIMESAllFloats()\nfor idx,dummy in enumerate(all_floats.list):\n print(idx)\n dummy.toa.set_observational_uncertainty(dimes_toa_noise)\n dummy.stream.set_observational_uncertainty(dimes_stream_noise)\n dummy.depth.set_observational_uncertainty(dimes_depth_noise)\n obs_holder = ObsHolder(dummy)\n smooth =Smoother(dummy,all_floats.sources,obs_holder,process_position_noise=dimes_position_process,process_vel_noise =dimes_velocity_process)\ntrj_dist_error = []\ntrj_toa_error = []\ntrj_speed = []\nsmooth_dist_error = []\nsmooth_toa_error = []\nsmooth_speed = []\nfor idx,dummy in enumerate(all_floats.list):\n print(idx)\n dist_error_list,toa_error_list,dist_list,soso_list,date_return_list,obs_list = dummy.toa.calculate_error_list(dummy.trj_pos,dummy.trj_date)\n trj_dist_error += dist_error_list\n trj_toa_error += toa_error_list\n trj_speed += speed_calc(dummy.trj_pos,dummy.trj_date)\n dist_error_list,toa_error_list,dist_list,soso_list,date_return_list,obs_list = dummy.toa.calculate_error_list(dummy.pos,dummy.pos_date)\n smooth_dist_error += dist_error_list\n smooth_toa_error += toa_error_list\n smooth_speed += speed_calc(dummy.pos,dummy.pos_date)\ntrj_diff_list = []\nfor idx,dummy in enumerate(all_floats.list):\n for pos,date in zip(dummy.trj_pos,dummy.trj_date):\n try:\n idx = dummy.pos_date.index(date)\n trj_diff_list.append(GreatCircleDistance(pos,dummy.pos[idx]).km)\n except:\n continue\n\nprint('mean ARTOA toa misfit was')\nprint(np.mean(trj_toa_error))\nprint('ARTOA std was')\nprint(np.std(trj_toa_error))\nprint('mean smoother toa misfit was')\nprint(np.mean(smooth_toa_error))\nprint('smoother std was')\nprint(np.std(smooth_toa_error))\nprint('median trj diff is')\nprint(np.median(trj_diff_list))\nprint('mean trj diff is')\nprint(np.mean(trj_diff_list))\nprint('median smooth speed is')\nprint(np.median(smooth_speed))\nprint('mean smooth speed is')\nprint(np.mean(smooth_speed))\nprint('median trj speed is')\nprint(np.median(trj_speed))\nprint('mean trj speed is')\nprint(np.mean(trj_speed))\n\n\nplt.figure(figsize=(13,13))\nplt.subplot(3,1,1)\nbins = np.linspace(-30,30,200)\ntrj_n,dummy,dummy = plt.hist(trj_toa_error,bins=bins,color='b',label='ARTOA',alpha=0.3)\nkalman_n,dummy,dummy = plt.hist(smooth_toa_error,bins=bins,color='g',label='Smoother',alpha=0.3)\nplt.yscale('log')\nplt.legend()\nplt.xlabel('Misfit (seconds)', fontsize=22)\nplt.annotate('a', xy = (0.2,0.75),xycoords='axes fraction',zorder=10,size=32,bbox=dict(boxstyle=\"round\", fc=\"0.8\"),)\nplt.subplot(3,1,2)\nbins = np.linspace(0,300,40)\nplt.xlim([0,300])\nplt.hist(trj_diff_list,bins=bins)\nplt.yscale('log')\nplt.xlabel('Trajectory Difference (km)', fontsize=22)\nplt.annotate('b', xy = (0.2,0.75),xycoords='axes fraction',zorder=10,size=32,bbox=dict(boxstyle=\"round\", fc=\"0.8\"),) \nplt.subplot(3,1,3)\nbins = np.linspace(0,41,30)\nplt.hist(smooth_speed,bins=bins,color='g',label='Kalman',alpha=0.3)\nplt.hist(trj_speed,bins=bins,color='b',label='DIMES',alpha=0.3)\nplt.yscale('log')\nplt.annotate('c', xy = (0.8,0.7),xycoords='axes fraction',zorder=10,size=32,bbox=dict(boxstyle=\"round\", fc=\"0.8\"),) \nplt.xlim([0,35])\n# plt.yscale('log')\nplt.xlabel('Speed (km $day^{-1}$)', fontsize=22)\nplt.subplots_adjust(hspace=0.3)\nplt.savefig(file_handler.out_file('Figure_11'))\nplt.close()","repo_name":"Chamberpain/KalmanSmoother","sub_path":"Utilities/Plots/Figure_13_And_17.py","file_name":"Figure_13_And_17.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"73169876944","text":"import rasterio\nfrom builder import climate_db\nfrom psycopg2.extras import execute_values\nimport numpy\nimport geojson\nfrom rasterio.plot import show\nfrom pyproj import Transformer\n\nseasons = [\"winter\",\"spring\",\"summer\",\"autumn\",\"annual\"]\ndecades = [\"1980\",\"1990\",\"2000\",\"2010\",\"2020\",\n \"2030\",\"2040\",\"2050\",\"2060\",\"2070\"]\n\ndef nuke(db,table):\n data_cols={\n table: [[\"id\",\"serial primary key\"]]\n }\n\n # optimising for reading - store all the variables for each decade\n # together, this means it's a single select averaging them together\n # across primary key location ids\n for decade in decades:\n data_cols[table].append([\"tas_\"+decade,\"real\"])\n data_cols[table].append([\"tasmax_\"+decade,\"real\"])\n data_cols[table].append([\"tasmin_\"+decade,\"real\"])\n data_cols[table].append([\"sfcWind_\"+decade,\"real\"])\n data_cols[table].append([\"pr_\"+decade,\"real\"])\n data_cols[table].append([\"rsds_\"+decade,\"real\"])\n\n db.create_tables(data_cols)\n\ndef test_print(arr,w,h): \n for x in range(0,h,10):\n r = \"\"\n for y in range(0,w,10):\n v=arr[x][y]\n if v<-9999: r+=\" \"\n else: r+=str(int(v))\n print(r)\n\ndef print_check(t,start,end,skip):\n seasons = [\"winter\",\"spring\",\"summer\",\"autumn\"]\n print(int(t/4)+1980,seasons[t%4],int(start/4)+1980,int(end/4)+1980)\n \ndef avg_slice(start,end,skip,img):\n count=0\n total=0\n arr=numpy.zeros((img.height,img.width),numpy.float)\n for t in range(start,end,skip):\n print_check(t,start,end,skip)\n image = img.read(t+1)\n count+=1\n arr=arr+image\n arr/=count\n test_print(arr,img.width,img.height)\n return arr\n\ndef build_season_avg(img,season):\n return [avg_slice(season+d*40,season+(d+1)*40,4,img) for d in range(0,10)]\n\ndef build_avg(img):\n return [avg_slice(d*40,(d+1)*40,1,img) for d in range(0,10)]\n\ndef save_tiff(img,arr,table,rcp,variable,season,decade):\n with rasterio.Env():\n profile = img.profile\n profile.update(\n dtype=rasterio.float32,\n count=1,\n compress='lzw')\n\n fn = table+'_'+rcp+'_'+variable+'_'+seasons[season]+'_'+decades[decade]+'.tif'\n \n with rasterio.open(fn, 'w', **profile) as dst:\n dst.write(arr.astype(rasterio.float32), 1)\n\ndef save_averages(db,rcp,fn,table,variable):\n img = rasterio.open(fn)\n \n for decade in range(0,10):\n # winter/summer\n for season in [0,2]:\n print(rcp,variable)\n arr=avg_slice(season+decade*40,season+(decade+1)*40,4,img)\n save_tiff(img,arr,table,rcp,variable,season,decade);\n \n # annual\n for decade in range(0,10):\n print(rcp,variable)\n arr = avg_slice(decade*40,(decade+1)*40,1,img)\n save_tiff(img,arr,table,rcp,variable,4,decade);\n\n\ndef print_crs(fn):\n print(\"hello\")\n img = rasterio.open(fn)\n print(img.crs)\n\n \ndef load_grid(db,fn):\n img = rasterio.open(fn)\n\n print(img.crs)\n \n time_size = img.count\n x_size = img.width\n y_size = img.height\n\n data_cols = {\n \"chess_scape_grid\":\n [[\"id\",\"serial\"],\n [\"geom\",\"geometry(geometry, 4326)\"],\n [\"properties\",\"jsonb\"]],\n }\n\n db.create_tables(data_cols)\n\n transformer = Transformer.from_crs(img.crs, 4326) \n\n features = []\n # assumptions to check - coord is centre of pixel?\n for x in range(0,x_size):\n for y in range(0,y_size):\n\n pos = img.xy(y,x)\n \n a = transformer.transform(pos[0]-500,pos[1]-500)\n b = transformer.transform(pos[0]+500,pos[1]-500)\n c = transformer.transform(pos[0]+500,pos[1]+500)\n d = transformer.transform(pos[0]-500,pos[1]+500)\n\n # lat/lng = y/x\n features.append(geojson.Feature(id=x*y_size+y, geometry=geojson.Polygon([[\n (a[1],a[0]),(b[1],b[0]),(c[1],c[0]),(d[1],d[0])]],properties={})))\n print(\"loading grid \"+str(int((x/x_size)*100))+\"%\")\n \n db.import_geojson_feature(\"chess_scape_grid\",\"4326\",geojson.FeatureCollection(features))\n db.conn.commit()\n\n \ndef load_data(db,fn,table,decade,variable):\n img = rasterio.open(fn)\n\n vardec = variable+'_'+decade\n \n time_size = img.count\n x_size = img.width\n y_size = img.height\n\n print(\"updating: \"+table+\" \"+variable+\" decade:\"+decade)\n\n for y in range(0,y_size):\n values = img.read(1)[y]\n dat = []\n for x in range(0,x_size):\n value = values[x]\n grid_id = x*y_size+y\n if value > -9999:\n dat.append([grid_id,float(value)])\n\n\n q=f\"\"\"with new_values (id,{vardec}) as (values %s),\n upsert as ( update {table} m set {vardec} = nv.{vardec}\n from new_values nv\n where m.id = nv.id\n returning m.* )\n insert into {table} (id,{vardec})\n select id,{vardec}\n from new_values\n where not exists (select 1 from upsert up where up.id=new_values.id)\"\"\"\n \n #q=f\"insert into {table} (location,season,{variable}) values %s on conflict (location,season) do update set {variable} = excluded.{variable};\"\n execute_values(db.cur,q,dat)\n db.conn.commit()\n \ndef test_data(db,fn,table,variable):\n img = rasterio.open(fn)\n \n for x in range(0,img.height,10):\n r = \"\"\n for y in range(0,img.width,10):\n v=img.read(1)[x][y]\n if v>-9999: r+=\" \"\n else: r+=str(int(v))\n print(r)\n\ndef import_tiffs(db,path,rcp,variable):\n for season in [\"annual\",\"summer\",\"winter\"]:\n for decade in [\"1980\",\"1990\",\"2000\",\"2010\",\"2020\",\n \"2030\",\"2040\",\"2050\",\"2060\",\"2070\"]:\n fn = 'chess_scape_'+rcp+'_'+variable+'_'+season+'_'+decade+'.tif'\n load_data(db,path+fn,'chess_scape_'+rcp+'_'+season,decade,variable)\n\ndef import_grid(db,path,fn):\n load_grid(db,path+fn)\n \ndef create_averages(db,rcp,path,variable):\n fn = \"chess-scape_\"+rcp+\"_bias-correctedMEAN_\"+variable+\".tif\"\n save_averages(db,rcp,path+fn,\"chess_scape\",variable)\n\n","repo_name":"UniExeterRSE/LCAT","sub_path":"data/builder/tiff_loader.py","file_name":"tiff_loader.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"}
+{"seq_id":"42203838811","text":"from django.urls import path, include\n\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n path('', views.post_list, name=\"posts\"),\n # path('login',views.post_login,name=\"login\"),\n path('register', include('users.urls')),\n path('login', auth_views.LoginView.as_view(\n template_name='posts/login.html'), name='login'),\n path('logout', auth_views.LogoutView.as_view(\n template_name='posts/logout.html'), name='logout'),\n\n path('create', views.post_create, name=\"create\"),\n path('