index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
99,900
6ecbe2d74c2996b804b3102329f59e9e32d278c9
SPARSE = 'Sparse_word' PADDING = 'Padding' TRUE = 'true' FALSE = 'false' DISEASE = 'disease' CHEMICAL = 'chemical' GENE = 'gene' E1_B = 'entity1begin' E1_E = 'entity1end' E2_B = 'entity2begin' E2_E = 'entity2end'
[ "SPARSE = 'Sparse_word'\nPADDING = 'Padding'\n\nTRUE = 'true'\nFALSE = 'false'\n\nDISEASE = 'disease'\nCHEMICAL = 'chemical'\nGENE = 'gene'\n\nE1_B = 'entity1begin'\nE1_E = 'entity1end'\nE2_B = 'entity2begin'\nE2_E = 'entity2end'", "SPARSE = 'Sparse_word'\nPADDING = 'Padding'\nTRUE = 'true'\nFALSE = 'false'\nDISE...
false
99,901
8d3b4bd3b34dd168634cf24443244c33962291f8
from . import db from app.models.permiso_usuario_horario import Permiso_usuario_horario from sqlalchemy import * from app.models.grupo import Grupo class Grupo_alumno_horario(db.Model): __tablename__ = 'grupo_alumno_horario' grupo = db.relationship(Grupo,backref = __tablename__,lazy=True) usuario_horario =...
[ "from . import db\nfrom app.models.permiso_usuario_horario import Permiso_usuario_horario \nfrom sqlalchemy import *\nfrom app.models.grupo import Grupo\nclass Grupo_alumno_horario(db.Model):\n __tablename__ = 'grupo_alumno_horario'\n grupo = db.relationship(Grupo,backref = __tablename__,lazy=True)\n usuar...
false
99,902
979cfa17af2711f9389ee86eb4c1f8ac75086811
import random import datetime while True: question = input('Ask a question: ') # .split() b = {"what" and "time": ["The time of the day is:", datetime.datetime.now().time()], "name": ["My name is Precious!"], "love": ["Yes, I love you", "No, I don't love you", "What is love?", "Love is wick...
[ "import random\nimport datetime\n\nwhile True:\n question = input('Ask a question: ') # .split()\n b = {\"what\" and \"time\": [\"The time of the day is:\", datetime.datetime.now().time()],\n \"name\": [\"My name is Precious!\"],\n \"love\": [\"Yes, I love you\", \"No, I don't love you\", \"...
false
99,903
d5ac3b91b25ed4d6e1f1722e936513848eef3641
import block # block (bytes) as an integer def getWords(block): words = [0,0,0,0] remainder = block for i in range(4): word = remainder % (16 ** 4) # insert into array starting from low order bits words[3-i] = word remainder //= (16 ** 4) return words # xor each 4 word...
[ "import block \n\n# block (bytes) as an integer\ndef getWords(block):\n words = [0,0,0,0]\n remainder = block\n for i in range(4):\n word = remainder % (16 ** 4)\n # insert into array starting from low order bits\n words[3-i] = word\n remainder //= (16 ** 4)\n return words\n\...
false
99,904
03c4404901c23acadf0f12ac800fb5492ce7abbe
import os """ Constant parameters """ UCR_DIR = '../../dataset/UCR_TS_Archive_2015' """ classifiers """ from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import LinearSVC StandardClassifierDic = { 'LR': LogisticRegression(), 'LSVC': Linear...
[ "import os\n\n\"\"\" Constant parameters\n\"\"\"\nUCR_DIR = '../../dataset/UCR_TS_Archive_2015'\n\n\n\"\"\" classifiers\n\"\"\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import LinearSVC\nStandardClassifierDic = {\n 'LR': LogisticRe...
false
99,905
8cf6968582b9e0d0dfb124adfeaf78f9262618a2
#! /usr/bin/python # Single 6 faced dice import random print("Welcome to Dice Simulator. Press 'Enter' to start.") Enter = input() while Enter == "": x = random.randint(1,6) print(x) if x == 6: print ("Roll Again. Press 'Enter'") Enter = input() if Enter == "": x = random...
[ "#! /usr/bin/python\n# Single 6 faced dice\nimport random\nprint(\"Welcome to Dice Simulator. Press 'Enter' to start.\")\nEnter = input()\nwhile Enter == \"\":\n x = random.randint(1,6)\n print(x)\n if x == 6:\n print (\"Roll Again. Press 'Enter'\")\n Enter = input()\n if Enter == \"\"...
false
99,906
c5ac9cb72b76168a706dc43f27806985d59bbb31
import errno import os import re import sass import shutil from cssmin import cssmin from jsmin import jsmin from src.lib.util.injection import * from src.lib.util.logger import * from src.lib.util.settings import * class Renderer: def __init__(self): settings = Settings.get_instance() cwd = os.g...
[ "import errno\nimport os\nimport re\nimport sass\nimport shutil\nfrom cssmin import cssmin\nfrom jsmin import jsmin\nfrom src.lib.util.injection import *\nfrom src.lib.util.logger import *\nfrom src.lib.util.settings import *\n\n\nclass Renderer:\n\n def __init__(self):\n settings = Settings.get_instance(...
false
99,907
4712e515d3ec32bbf8ba2b506cada78cbd553fd8
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ http://selenium-python.readthedocs.io https://realpython.com/blog/python/modern-web-automation-with-python-and-selenium/ dokumentace s příklady: https://media.readthedocs.org/pdf/selenium-python/latest/selenium-python.pdf """ from selenium.webdriver import Firef...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nhttp://selenium-python.readthedocs.io\nhttps://realpython.com/blog/python/modern-web-automation-with-python-and-selenium/\n\ndokumentace s příklady:\nhttps://media.readthedocs.org/pdf/selenium-python/latest/selenium-python.pdf\n \n\"\"\"\n\nfrom selenium....
false
99,908
920e987d7aefd02603b5d96c8e593a3c80547733
#!/usr/bin/env python3 """ Non-interactive tests for installer. pytest files should start from `test_` """ import cluster_dev as installer # pylint: disable=unused-import # noqa: WPS110, F401 # Example usage: def func(test_param): """Test something.""" return test_param + 1 def test_func(): """Functi...
[ "#!/usr/bin/env python3\n\"\"\"\nNon-interactive tests for installer.\n\npytest files should start from `test_`\n\"\"\"\nimport cluster_dev as installer # pylint: disable=unused-import # noqa: WPS110, F401\n\n# Example usage:\n\n\ndef func(test_param):\n \"\"\"Test something.\"\"\"\n return test_param + 1\n\...
false
99,909
9638d2d2cc9f4777aeccfd237cae8bb14253c6b4
#censor >> "this **** is wack ****" text = "this hack is wack hack" word = "hack" def censor(text, word): Z = [] for g in text.split(): if g != word: Z.append(g) elif g == word: P = "" for x in g: x = "*" P += x Z.ap...
[ "#censor >> \"this **** is wack ****\"\n\ntext = \"this hack is wack hack\"\nword = \"hack\"\n\ndef censor(text, word):\n Z = []\n for g in text.split():\n if g != word:\n Z.append(g)\n elif g == word:\n P = \"\"\n for x in g:\n x = \"*\"\n ...
false
99,910
5a8e34748e48e532036899ebea1d6c2506f8d4b7
import copy import random D = list(map(int, input().split())) q = int(input()) for x in range(q): y, z = map(int, input().split()) while True: r = random.randint(0,3) if r == 0: Dt = copy.copy(D) temp = Dt[0] Dt[0] = Dt[4] Dt[4] = Dt[5] ...
[ "import copy\nimport random\n\nD = list(map(int, input().split()))\nq = int(input())\n\nfor x in range(q):\n y, z = map(int, input().split())\n while True:\n r = random.randint(0,3)\n if r == 0:\n Dt = copy.copy(D)\n temp = Dt[0]\n Dt[0] = Dt[4]\n Dt[4...
false
99,911
32a73965fd70a27f68a4884a2e3738e15a5dfd05
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `pyriskadjust` package.""" import unittest import json from pyriskadjust.models import model_2018_v22 class TestPyriskadjust(unittest.TestCase): """Tests for `pyriskadjust` package.""" def setUp(self): """Set up test fixtures, if any.""" ...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Tests for `pyriskadjust` package.\"\"\"\n\n\nimport unittest\nimport json\nfrom pyriskadjust.models import model_2018_v22\n\n\nclass TestPyriskadjust(unittest.TestCase):\n \"\"\"Tests for `pyriskadjust` package.\"\"\"\n\n def setUp(self):\n \"\"\...
false
99,912
4c3fb19a90ebabbed4fc3193b38fec720eb27dc9
# # [222] Count Complete Tree Nodes # # https://leetcode.com/problems/count-complete-tree-nodes # # Medium (27.30%) # Total Accepted: # Total Submissions: # Testcase Example: '[]' # # Given a complete binary tree, count the number of nodes. # # Definition of a complete binary tree from Wikipedia: # ...
[ "#\r\n# [222] Count Complete Tree Nodes\r\n#\r\n# https://leetcode.com/problems/count-complete-tree-nodes\r\n#\r\n# Medium (27.30%)\r\n# Total Accepted: \r\n# Total Submissions: \r\n# Testcase Example: '[]'\r\n#\r\n# Given a complete binary tree, count the number of nodes.\r\n# \r\n# Definition of a complete bi...
false
99,913
a4aad2760de34fde725a59a148e85b86f5e6e673
import numpy as np from numpy import * from numpy.linalg import inv import MahalanobisDistance from os import listdir """rawdata has n rows ## Create arr_groupvariance to store variance of each group of 5 rows (has n/5 rows)""" arr_rawdata = genfromtxt('../../Raw Data/Truncated-Horizontal.csv', ...
[ "import numpy as np\nfrom numpy import *\nfrom numpy.linalg import inv\nimport MahalanobisDistance\nfrom os import listdir\n\n\"\"\"rawdata has n rows\n## Create arr_groupvariance to store variance of each group of 5 rows (has n/5 rows)\"\"\"\n\narr_rawdata = genfromtxt('../../Raw Data/Truncated-Horizontal.csv',\n ...
false
99,914
9cd6b07d724922d9d6568483fd5cbc5a0d0c886a
import ftplib import os
[ "import ftplib\nimport os\n\n", "import ftplib\nimport os\n", "<import token>\n" ]
false
99,915
5dac538485abb64388974ba3201084a779d5e9cf
# Adaptar o programa desenvolvido acima para que ela calcule o percentual dos valores positivos e # negativos em relação ao total de valores fornecidos. positivos, negativos = 0, 0 total = 1 num = int(input("Informe um número: ")) while (num != 0): if num > 0: positivos += 1 if num < 0: negativ...
[ "# Adaptar o programa desenvolvido acima para que ela calcule o percentual dos valores positivos e\n# negativos em relação ao total de valores fornecidos.\n\npositivos, negativos = 0, 0\ntotal = 1\nnum = int(input(\"Informe um número: \"))\nwhile (num != 0):\n if num > 0:\n positivos += 1\n if num < 0:...
false
99,916
2f6e85ef5154e92e270adda5b92ff5e51cf0e22f
# -*- coding: utf-8 -*- # 震惊小伙伴的单行代码(Python篇) # 1、让列表中的每个元素都乘以2 print map(lambda x: x * 2, range(1, 11)) # 2、求列表中的所有元素之和 print sum(range(1, 1001)) # 3、判断一个字符串中是否存在某些词 wordlist = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." print map(lambd...
[ "# -*- coding: utf-8 -*-\n\n# 震惊小伙伴的单行代码(Python篇)\n\n# 1、让列表中的每个元素都乘以2\n\nprint map(lambda x: x * 2, range(1, 11))\n\n# 2、求列表中的所有元素之和\n\nprint sum(range(1, 1001))\n\n# 3、判断一个字符串中是否存在某些词\n\nwordlist = [\"scala\", \"akka\", \"play framework\", \"sbt\", \"typesafe\"]\ntweet = \"This is an example tweet talking about s...
true
99,917
9af1005a865196e45664e7a353e33c32f4814e6c
#! /usr/bin/env python2 # # This file is part of khmer, http://github.com/ged-lab/khmer`, and is # Copyright (C) Michigan State University, 2009-2014. It is licensed under # the three-clause BSD license; see doc/LICENSE.txt. # Contact: khmer-project@idyll.org # Author Sherine Awad import sys, getopt import glob from co...
[ "#! /usr/bin/env python2\n#\n# This file is part of khmer, http://github.com/ged-lab/khmer`, and is\n# Copyright (C) Michigan State University, 2009-2014. It is licensed under\n# the three-clause BSD license; see doc/LICENSE.txt.\n# Contact: khmer-project@idyll.org\n# Author Sherine Awad\nimport sys, getopt\nimport...
true
99,918
09d50bcb40089bd2213279b156c77943653d631b
""" Collection of models. """
[ "\"\"\"\nCollection of models.\n\"\"\"", "<docstring token>\n" ]
false
99,919
1a1a1c2de774ae8c79004824678fabd5b2029a01
# Write a Python function that takes a list of words and returns the length of the longest one #!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 l=['cnxvjxnlkxnlxc','kjgnfxkjvkfjnvklxnv','xkjvbfkjbvjkxznvkjxcnvkjzcxnvjzxcnv','jfvjcgcb','ggg'] max_s=l[0] for i in l: if len(max_s) < len(i): ma...
[ "# Write a Python function that takes a list of words and returns the length of the longest one\n#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6\nl=['cnxvjxnlkxnlxc','kjgnfxkjvkfjnvklxnv','xkjvbfkjbvjkxznvkjxcnvkjzcxnvjzxcnv','jfvjcgcb','ggg']\nmax_s=l[0]\nfor i in l:\n if len(max_s) < len(i):\...
false
99,920
28d4cf5fd4193fbf8a2ccc5484fd5ac7bd7bfc1f
from abc import ABCMeta, abstractmethod from conformal_predictors.validation import NotCalibratedError from conformal_predictors.nc_measures import NCMeasure import numpy as np from decimal import * class ConformalPredictor: """ Abstract class that represents the Conformal Predictors and defines their bas...
[ "from abc import ABCMeta, abstractmethod\nfrom conformal_predictors.validation import NotCalibratedError\nfrom conformal_predictors.nc_measures import NCMeasure\nimport numpy as np\nfrom decimal import *\n\n\nclass ConformalPredictor:\n \"\"\"\n Abstract class that represents the Conformal Predictors and defi...
false
99,921
855c58fd502af172bbc95e2a111edbba4f715368
import numpy as np import re import nltk from sklearn.datasets import load_files nltk.download('stopwords' ) import pickle from nltk.corpus import stopwords movie_data = load_files("data/review_polarity/txt_sentoken") X, y = movie_data.data, movie_data.target print(type(X)) documents = [] from nltk.stem impor...
[ "import numpy as np \nimport re \nimport nltk\nfrom sklearn.datasets import load_files \nnltk.download('stopwords' )\nimport pickle \nfrom nltk.corpus import stopwords \n\n\nmovie_data = load_files(\"data/review_polarity/txt_sentoken\")\nX, y = movie_data.data, movie_data.target\n\nprint(type(X))\n\ndocuments = []\...
false
99,922
48b91572a5d492e416042d0ea9800775a6257682
"""This is the class for the light powerup.""" import random import pygame import os from .entity import Entity DIRECTORY = os.path.abspath(os.getcwd()) POWERUP_DIR = DIRECTORY+"/players_images/powerups/flash.png" POWERUPSIZE = 20 class Flash(Entity): """get the size""" def __init__(self, name): Ent...
[ "\"\"\"This is the class for the light powerup.\"\"\"\nimport random\nimport pygame\nimport os\nfrom .entity import Entity\n\n\nDIRECTORY = os.path.abspath(os.getcwd())\nPOWERUP_DIR = DIRECTORY+\"/players_images/powerups/flash.png\"\n\nPOWERUPSIZE = 20\n\nclass Flash(Entity):\n \"\"\"get the size\"\"\"\n def ...
false
99,923
3e9df2ef61ea6d62d1e7508de18431b8f05023e6
#tokenizing and covertint to lower-case import nltk.tokenize raw = open("E:\\dataset.txt").read() raw = raw.lower() docs = nltk.tokenize.sent_tokenize(raw) docs = docs[0].split('\n') #pre-processing punctuations from string import punctuation as punc for d in docs: for ch in d: if ch in punc: d...
[ "#tokenizing and covertint to lower-case\nimport nltk.tokenize\nraw = open(\"E:\\\\dataset.txt\").read()\nraw = raw.lower()\ndocs = nltk.tokenize.sent_tokenize(raw)\ndocs = docs[0].split('\\n')\n\n#pre-processing punctuations\nfrom string import punctuation as punc\nfor d in docs:\n for ch in d:\n if ch i...
false
99,924
ddf5d72696f6e1c5e40685902336c88167dfc065
def solution(tickets): tck = dict() for t1, t2 in tickets: if t1 in tck.keys(): tck[t1].append(t2) else: tck[t1] = [t2] for k in tck.keys(): tck[k].sort() st = ['ICN'] res = [] while st: top = st[-1] ...
[ "def solution(tickets): \n tck = dict()\n \n for t1, t2 in tickets:\n if t1 in tck.keys():\n tck[t1].append(t2)\n else:\n tck[t1] = [t2]\n \n for k in tck.keys():\n tck[k].sort()\n \n st = ['ICN']\n res = []\n \n while st:\n top = st...
false
99,925
3e2838efdd4efa8a6b5ac227504030fa64388877
import keras from keras.models import Sequential from keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout import cv2 import numpy as np model2 = Sequential() model2.add(Conv2D(filters = 16,kernel_size=2,padding='same',activation='relu',input_shape=(100,100,3))) model2.add(MaxPooling2D(pool_size=2)) model2.ad...
[ "import keras\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout\nimport cv2\nimport numpy as np\n\nmodel2 = Sequential()\nmodel2.add(Conv2D(filters = 16,kernel_size=2,padding='same',activation='relu',input_shape=(100,100,3)))\nmodel2.add(MaxPooling2D(pool_size=...
false
99,926
f7407cf768d072a19b7086a40f29a633c5a6fe6c
import sqlite3 #function for creating table to store user def make_user(): conn = sqlite3.connect("app.db") cur = conn.cursor() sql = 'CREATE TABLE IF NOT EXISTS user(Email TEXT, Name TEXT, Password TEXT)' cur.execute(sql) conn.commit() #function to insert values into user table def insert(table...
[ "import sqlite3\n\n#function for creating table to store user\ndef make_user():\n conn = sqlite3.connect(\"app.db\")\n cur = conn.cursor()\n\n sql = 'CREATE TABLE IF NOT EXISTS user(Email TEXT, Name TEXT, Password TEXT)'\n cur.execute(sql)\n conn.commit()\n\n#function to insert values into user table...
false
99,927
28f11c9882baa46236557fa8d18e38805c3a9546
def part_1(): bag_rules = {} direct_bags = set([]) for line in open("input.txt"): # Using :-1 instead of rstrip as it is faster line = line[:-1] splitln = line.split(' bags contain ') bag_type = splitln[0] rules = {} for bag_rule in splitln[1].split(', '): ...
[ "\n\ndef part_1():\n bag_rules = {}\n direct_bags = set([])\n for line in open(\"input.txt\"):\n # Using :-1 instead of rstrip as it is faster\n line = line[:-1]\n splitln = line.split(' bags contain ')\n bag_type = splitln[0]\n rules = {}\n for bag_rule in splitln...
false
99,928
40f53e254466550f08cf627a46b5c247fabe1901
# using `value_counts` result = df['Position'].value_counts() display(Markdown("Using `value_counts`:")) display(result) # using `groupby` result = df.groupby(['Position'])['Position'].count() display(Markdown("Using `groupby`:")) display(result) # using `pivot_table` # NOTE: This is not the correct way to get the re...
[ "# using `value_counts`\nresult = df['Position'].value_counts()\ndisplay(Markdown(\"Using `value_counts`:\"))\ndisplay(result)\n\n# using `groupby`\nresult = df.groupby(['Position'])['Position'].count()\ndisplay(Markdown(\"Using `groupby`:\"))\ndisplay(result)\n\n# using `pivot_table`\n# NOTE: This is not the corre...
false
99,929
9e087bb6d6705bb8ed469ffaa6434279fb0e6f59
# 오답 import sys sys.stdin=open('input.txt','r') # 수정 본 실행시간 반으로 줄어듬 for t in range(1,int(input())+1): n, k = map(int,input().split());cnt=0 L=[*map(int,input().split())];q=[(0,-1)] while q: a,b=q.pop() for id,v in enumerate(L): if id>b: a+=v if a>...
[ "# 오답\nimport sys\nsys.stdin=open('input.txt','r')\n\n# 수정 본 실행시간 반으로 줄어듬\nfor t in range(1,int(input())+1):\n n, k = map(int,input().split());cnt=0\n L=[*map(int,input().split())];q=[(0,-1)]\n while q:\n a,b=q.pop()\n for id,v in enumerate(L):\n if id>b:\n a+=v\n ...
false
99,930
72926b4c8bff521c7247bccdb71ed130917b250e
#!/usr/bin/env python # coding:utf-8 """ @Version: V1.0 @Author: willson @License: Apache Licence @Contact: willson.wu@goertek.com @Site: goertek.com @Software: PyCharm @File: __init__.py.py @Time: 19-1-26 上午9:48 """ from flask_security.utils import encrypt_password from myApp import app, store_datastore from myApp.m...
[ "#!/usr/bin/env python\n# coding:utf-8\n\"\"\"\n@Version: V1.0\n@Author: willson\n@License: Apache Licence\n@Contact: willson.wu@goertek.com\n@Site: goertek.com\n@Software: PyCharm\n@File: __init__.py.py\n@Time: 19-1-26 上午9:48\n\"\"\"\n\nfrom flask_security.utils import encrypt_password\n\nfrom myApp import app, st...
false
99,931
a6b3c1423b21c66a94297434a968a8e91d0307bf
nome = input('Digite seu nome completo: ').strip() print(nome.upper()) print(nome.lower()) print(len(nome.replace(' ', ''))) nome_separado = nome.split() print(len(nome_separado[0])) print(nome_separado[0], nome_separado[len(nome_separado) - 1]) # EXTRA - Imprimindo Primeiro e Ultimo Nome
[ "nome = input('Digite seu nome completo: ').strip()\n\nprint(nome.upper())\nprint(nome.lower())\nprint(len(nome.replace(' ', '')))\n\nnome_separado = nome.split()\n\nprint(len(nome_separado[0]))\n\nprint(nome_separado[0], nome_separado[len(nome_separado) - 1]) # EXTRA - Imprimindo Primeiro e Ultimo Nome", "nome =...
false
99,932
72a96a4c7c6e745aaf52f3c3bb32e6a19c5a79d0
# coding=utf-8 """Plot Tools.""" import matplotlib.pyplot as plt from sklearn.metrics import auc, roc_curve import numpy as np def plot_roc_curve(y_true, y_pred_prob, show_threshold=False, **params): """ A function plot Roc AUC. Parameters: y_true: Array ...
[ "# coding=utf-8\n\"\"\"Plot Tools.\"\"\"\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import auc, roc_curve\nimport numpy as np\n\n\ndef plot_roc_curve(y_true, y_pred_prob, show_threshold=False, **params):\n \"\"\"\n A function plot Roc AUC.\n Parameters:\n ...
false
99,933
152867d01dd1309a9472762c4e421a2ff7c7105e
# # @lc app=leetcode id=935 lang=python3 # # [935] Knight Dialer # # @lc code=start # TAGS: Dynamic Programming import sys sys.setrecursionlimit(5010) class Solution: # 2800 ms, 24.18%. Time and Space: O(N). Recursion with memoization def knightDialer(self, n: int) -> int: future_moves = {1: [6, 8], 2...
[ "#\n# @lc app=leetcode id=935 lang=python3\n#\n# [935] Knight Dialer\n#\n\n# @lc code=start\n# TAGS: Dynamic Programming\nimport sys\nsys.setrecursionlimit(5010)\nclass Solution:\n\n # 2800 ms, 24.18%. Time and Space: O(N). Recursion with memoization\n def knightDialer(self, n: int) -> int:\n future_mo...
false
99,934
bc6a79ed2d6197db15cc9d34198313b3f24e681b
from __future__ import annotations import os from xml.etree import ElementTree from cloudshell.layer_one.core.helper.xml_helper import XMLHelper from cloudshell.layer_one.core.response.command_response import CommandResponse ElementTree.register_namespace( "", "http://schemas.qualisystems.com/ResourceManagement/...
[ "from __future__ import annotations\n\nimport os\nfrom xml.etree import ElementTree\n\nfrom cloudshell.layer_one.core.helper.xml_helper import XMLHelper\nfrom cloudshell.layer_one.core.response.command_response import CommandResponse\n\nElementTree.register_namespace(\n \"\", \"http://schemas.qualisystems.com/Re...
false
99,935
71ddbe711aeabf84ecf9c32197ac4e17b21ddba4
from django.contrib import admin from . models import csv_data from . models import temp_ssdata # Register your models here. admin.site.register(csv_data) admin.site.register(temp_ssdata)
[ "from django.contrib import admin\nfrom . models import csv_data\nfrom . models import temp_ssdata\n# Register your models here.\n\nadmin.site.register(csv_data)\nadmin.site.register(temp_ssdata)", "from django.contrib import admin\nfrom .models import csv_data\nfrom .models import temp_ssdata\nadmin.site.registe...
false
99,936
0892d2bd363ae7a15e05aab651e5310ccb23362a
import numpy as np import pandas as pd from scipy import stats from util.caching import cache_today # FIXME: There are more exact significance tests with more resolving power for our # cases, e.g. Barnard's or Boschloo's tests. def binomial_pv(counts=None, frequencies=None, table=None, chi_min=10, **kwargs): if ...
[ "import numpy as np\nimport pandas as pd\nfrom scipy import stats\n\nfrom util.caching import cache_today\n\n\n# FIXME: There are more exact significance tests with more resolving power for our\n# cases, e.g. Barnard's or Boschloo's tests.\ndef binomial_pv(counts=None, frequencies=None, table=None, chi_min=10, **kw...
false
99,937
662cb7300294342a812a13cf2132502ee45aad7c
import sys, os from lxml import objectify usage = """ Usage is: py admx2oma.py <your.admx> <ADMX-OMA-URI> <ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file Take care, the OMA-URI is case sensitive. <your.admx> : The admx file you ingested """ def run(): if len(s...
[ "import sys, os\nfrom lxml import objectify\n\nusage = \"\"\"\nUsage is:\npy admx2oma.py <your.admx> <ADMX-OMA-URI>\n<ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file\n Take care, the OMA-URI is case sensitive.\n<your.admx> : The admx file you ingested\n\n\"\"\"\n\n...
false
99,938
082d740bfa2ed2fcb4fba11d6f269a715abd1354
# -*- coding: utf-8 -*- import sys import os import re import time """ Python Nagios extensions """ __author__ = "Drew Stinnett" __copyright__ = "Copyright 2008, Drew Stinnett" __credits__ = ["Drew Stinnett", "Pall Sigurdsson"] __license__ = "GPL" __version__ = "0.4" __maintainer__ = "Pall Sigurdsson" __email__ = "p...
[ "# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport re\nimport time\n\n\"\"\"\nPython Nagios extensions\n\"\"\"\n\n__author__ = \"Drew Stinnett\"\n__copyright__ = \"Copyright 2008, Drew Stinnett\"\n__credits__ = [\"Drew Stinnett\", \"Pall Sigurdsson\"]\n__license__ = \"GPL\"\n__version__ = \"0.4\"\n__maintain...
true
99,939
88215fda2071e16e59da7f27e603ebff1a9fe7d5
from http import HTTPStatus from peewee import DoesNotExist, IntegrityError from playhouse.shortcuts import dict_to_model, model_to_dict from api.helpers import add_extra_info_to_dict, to_utc_datetime from api.models import DataSource, DataSourceToken, User class UserService(): def get_user_by_id(self, user_id:...
[ "from http import HTTPStatus\n\nfrom peewee import DoesNotExist, IntegrityError\nfrom playhouse.shortcuts import dict_to_model, model_to_dict\n\nfrom api.helpers import add_extra_info_to_dict, to_utc_datetime\nfrom api.models import DataSource, DataSourceToken, User\n\n\nclass UserService():\n def get_user_by_id...
false
99,940
416fe1a39b6acd1cfc63b9be8932965ec9792a9d
#Makes dataset for tensorflow (possibility, might not do it) def NNDataSet(num_testers,mispercievedSeq, mispercievedRan): AOIfile=open("AOIMetricsSequential.csv","r") #AOIfileR=open("AOIMetricsRandom.csv","r") file = open("NN_SVMData/EmotionDataSequentialAll.csv","w") fileP = open("NN_SVMData/EmotionDataSequential...
[ "#Makes dataset for tensorflow (possibility, might not do it)\n\ndef NNDataSet(num_testers,mispercievedSeq, mispercievedRan):\n\tAOIfile=open(\"AOIMetricsSequential.csv\",\"r\")\n\t#AOIfileR=open(\"AOIMetricsRandom.csv\",\"r\")\n\tfile = open(\"NN_SVMData/EmotionDataSequentialAll.csv\",\"w\")\n\tfileP = open(\"NN_S...
false
99,941
2ce0664d4e0f8860873e7d894279ce767377328e
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from flask import Blueprint, url_for, render_template, request, abort, flash, session, redirect from web.wxtranstypes.utils import utils_show_transtypes mod = Blueprint('wxtranstypes', __name__, url_prefix='/wxtranstypes') @mod.route('/show_transtypes', metho...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\nfrom flask import Blueprint, url_for, render_template, request, abort, flash, session, redirect\nfrom web.wxtranstypes.utils import utils_show_transtypes\n\nmod = Blueprint('wxtranstypes', __name__, url_prefix='/wxtranstypes')\n\n\n@mod.route('/show_tran...
false
99,942
38fde5ecf1bf15d737e1a886c5dca0c1893fc149
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if ...
[ "# This is an auto-generated Django model module.\n# You'll have to do the following manually to clean this up:\n# * Rearrange models' order\n# * Make sure each model has one field with primary_key=True\n# * Make sure each ForeignKey has `on_delete` set to the desired behavior.\n# * Remove `managed = False`...
false
99,943
1fd18338067e28ab48a9a83f5ced26e69a1d58b1
# -*-coding: utf-8-*- ; -*-Python-*- # Copyright © 2022-2023 Tom Fontaine # Title: colors.py # Date: 25-Apr-2022 colors = {'CSI': chr(27) + '[', 'CSI24': chr(27) + '[38;5;', 'NORMAL': '0', 'BOLD': '1', 'BLACK': '30', 'RED': '31', 'GR...
[ "# -*-coding: utf-8-*- ; -*-Python-*-\n\n# Copyright © 2022-2023 Tom Fontaine\n\n# Title: colors.py\n# Date: 25-Apr-2022\n\n\ncolors = {'CSI': chr(27) + '[',\n 'CSI24': chr(27) + '[38;5;',\n\n 'NORMAL': '0',\n 'BOLD': '1',\n\n 'BLACK': '30',\n 'RED': ...
false
99,944
b36f307d81187eb662470628aa84f86295a91297
__copyright__ = """ This file is part of stellar-py, Stellar Python Client. Copyright 2018 CSIRO Data61 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apach...
[ "__copyright__ = \"\"\"\n\n This file is part of stellar-py, Stellar Python Client.\n\n Copyright 2018 CSIRO Data61\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n ...
false
99,945
5058f568f278e7e87e07d0523d58293fdc1e1ddc
def add(x, y): return x + y def minus(x, y): return x - y def multiple(x, y): return x * y def divide(x, y): if y == 0: print("error!") return else: return x / y
[ "def add(x, y):\n\treturn x + y\n\ndef minus(x, y):\n\treturn x - y\n\ndef multiple(x, y):\n\treturn x * y\n\ndef divide(x, y):\n\tif y == 0:\n\t\tprint(\"error!\")\n\t\treturn\n\telse:\n\t\treturn x / y", "def add(x, y):\n return x + y\n\n\ndef minus(x, y):\n return x - y\n\n\ndef multiple(x, y):\n retu...
false
99,946
926f55a6fc19dcf95339aae1e16f5d10cbd977ac
import math from abc import ABCMeta, abstractmethod from collections import Iterable # from __future__ import annotations ''' This whole thing is a bit much... To make the assignment interesting I decided to practice object hierarchies and inheritance, and potentially generate some code I could reuse later with Katis...
[ "import math\nfrom abc import ABCMeta, abstractmethod\nfrom collections import Iterable\n\n# from __future__ import annotations\n\n'''\nThis whole thing is a bit much...\nTo make the assignment interesting I decided to practice object hierarchies and inheritance,\nand potentially generate some code I could reuse la...
false
99,947
ded367d0159f7c1a72f7adea7494f61ae658b1cf
import json def load_information(key): f = open('doc\print_info.json',) data = json.load(f) if key: data = [x for x in data if x['modelo'] == key or x['ip'] == key or x['nombre'] == key or x['sise'] == key ] f.close() return data
[ "import json\n\ndef load_information(key):\n f = open('doc\\print_info.json',)\n data = json.load(f)\n \n if key:\n data = [x for x in data if x['modelo'] == key or x['ip'] == key or x['nombre'] == key or x['sise'] == key ]\n f.close()\n return data", "import json\n\n\ndef load_information...
false
99,948
1210c4d499c02cf9861b97261033b2d12f2c78d7
#!/usr/bin/env python3 import csv, json from sys import argv try: filename = argv[1] except IndexError: print("No input given") exit() try: f = open(filename, 'r') blockdata = csv.reader(f, delimiter=',') timestamp = [] height = [] nonce = [] diff = [] for row in blockdata: ...
[ "#!/usr/bin/env python3\n\nimport csv, json\nfrom sys import argv\n\ntry:\n filename = argv[1]\nexcept IndexError:\n print(\"No input given\")\n exit()\n\ntry:\n f = open(filename, 'r')\n blockdata = csv.reader(f, delimiter=',')\n\n timestamp = []\n height = []\n nonce = []\n diff = []\n\...
false
99,949
840acc471ea55a84186b25ca07ddcf7c006a60a9
#!/usr/bin/python from __future__ import print_function import dbus import sys import time import gobject from dbus.mainloop.glib import DBusGMainLoop WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1" WPAS_DBUS_INTERFACE = "fi.w1.wpa_supplicant1" WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1" WPAS_DBUS_INTERFACES_INTERFACE = "...
[ "#!/usr/bin/python\n\nfrom __future__ import print_function\nimport dbus\nimport sys\nimport time\nimport gobject\nfrom dbus.mainloop.glib import DBusGMainLoop\n\nWPAS_DBUS_SERVICE = \"fi.w1.wpa_supplicant1\"\nWPAS_DBUS_INTERFACE = \"fi.w1.wpa_supplicant1\"\nWPAS_DBUS_OPATH = \"/fi/w1/wpa_supplicant1\"\nWPAS_DBUS_I...
true
99,950
d1434f8fdd0b75ff8a13226f18b60b5281a4ebca
n,m= map(int,input().split()) from collections import Counter arr = list(map(int,input().split())) d = Counter(arr) flag = 0 for i in range(n): temp = m - arr[i] if d[temp]: if arr[i]==temp and d[temp]==1: continue print("YES") flag = 1 break if flag==0: pr...
[ "n,m= map(int,input().split())\nfrom collections import Counter\narr = list(map(int,input().split()))\nd = Counter(arr)\n\n\nflag = 0\nfor i in range(n):\n temp = m - arr[i]\n if d[temp]:\n if arr[i]==temp and d[temp]==1:\n continue\n print(\"YES\")\n flag = 1\n break\ni...
false
99,951
9921f7fe70280babd2fd29783676d605356081ba
from socket import AF_INET, socket, SOCK_STREAM s = socket(AF_INET, SOCK_STREAM) s.connect(('localhost', 8888)) msg = 'Привет, сервер!' s.send(msg.encode('utf-8')) data = s.recv(4096) print(data.decode('utf-8')) s.close() # print(tame_data.decode('utf-8'))
[ "from socket import AF_INET, socket, SOCK_STREAM\n\ns = socket(AF_INET, SOCK_STREAM)\ns.connect(('localhost', 8888))\n\nmsg = 'Привет, сервер!'\ns.send(msg.encode('utf-8'))\ndata = s.recv(4096)\nprint(data.decode('utf-8'))\ns.close()\n\n# print(tame_data.decode('utf-8'))", "from socket import AF_INET, socket, SOC...
false
99,952
31ac9e6651e11458654adebc13e85b45bde2c54a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 12 12:16:58 2019 @author: vladgriguta Downloads the spectra of the objects in a multi-threading manner, allowing for fast download of data. """ import os NUM_CPUS = 2 # defaults to all available def get_address_lists(n_lists,file='../download_ur...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 12 12:16:58 2019\n\n@author: vladgriguta\n\nDownloads the spectra of the objects in a multi-threading manner, allowing\nfor fast download of data.\n\n\"\"\"\nimport os\nNUM_CPUS = 2 # defaults to all available\n\ndef get_address_lists(n_l...
false
99,953
a2455fb96660a919f5b4987e501c3064e431222a
#! python3 #bullet adder -adds bullets before lines import pyperclip pyperclip.copy('hello dear\n what\n') text = pyperclip.paste() #seperate lines lines = text.split('\n') for i in range(len(lines)): lines[i] = '*'+lines[i] text = '\n'.join(lines) pyperclip.copy(text)
[ "#! python3\r\n#bullet adder -adds bullets before lines\r\n\r\nimport pyperclip\r\npyperclip.copy('hello dear\\n what\\n')\r\n\t\r\ntext = pyperclip.paste()\r\n\r\n#seperate lines \r\nlines = text.split('\\n')\r\nfor i in range(len(lines)):\r\n\tlines[i] = '*'+lines[i]\r\ntext = '\\n'.join(lines)\r\npyperclip.copy(...
false
99,954
9e73be09c9861d7ba881c2fbcca7f25da2f55c32
import tensorflow.keras from PIL import Image import numpy as np np.set_printoptions(suppress=True) model = tensorflow.keras.models.load_model('keras_model.h5') data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) image = Image.open(r'15.jpeg') image = image.resize((224, 224)) image_array = np.asarray(image)...
[ "import tensorflow.keras\nfrom PIL import Image\nimport numpy as np\n\nnp.set_printoptions(suppress=True)\n\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\n\n\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\nimage = Image.open(r'15.jpeg')\nimage = image.resize((224, 224))\nimage_array = ...
false
99,955
4fcbdf96cfe5016835eb3c2443211a5070821279
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ class HrExpenseAdvanceLine(models.Model): _name = "hr.expense.advance.line" _description = "Expense Advance Line" name = fields.Char(string="Description", required=True) advance_id = fields.Many2one(string="Advance Reference", ...
[ "# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\n\nclass HrExpenseAdvanceLine(models.Model):\n _name = \"hr.expense.advance.line\"\n _description = \"Expense Advance Line\"\n\n name = fields.Char(string=\"Description\",\n required=True)\n advance_id = fields.Many2one(string=\"...
false
99,956
39f02872715e2a7cfd7779b83e80a0ffdbd6b3c8
# Copyright 2020 Red Hat, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
[ "# Copyright 2020 Red Hat, Inc.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to...
false
99,957
dff58769b0084bf6f2da86ec47ed0ac6c336bf15
import numpy as np def find_rank(arr): a = np.array(arr) r = np.array(a.argsort().argsort(), dtype=float) f = a==a for i in xrange(len(a)): if not f[i]: continue s = a == a[i] ls = np.sum(s) if ls > 1: tr = np.sum(r[s]) r[s] = float(t...
[ "import numpy as np\n\ndef find_rank(arr):\n a = np.array(arr)\n r = np.array(a.argsort().argsort(), dtype=float)\n f = a==a\n for i in xrange(len(a)):\n if not f[i]: \n continue\n s = a == a[i]\n ls = np.sum(s)\n if ls > 1:\n tr = np.sum(r[s])\n ...
true
99,958
cdb44b7ac0fb0d4e24786741de3ccb3440aff67e
from django.db import models from djongo import models as djongo_models class CourseScore(models.Model): course_name = models.CharField(max_length=4) student_name = models.CharField(max_length=16) score = models.IntegerField() # the manager for postgres objects = models.Manager() # the djong...
[ "from django.db import models\nfrom djongo import models as djongo_models\n\n\nclass CourseScore(models.Model):\n\n course_name = models.CharField(max_length=4)\n student_name = models.CharField(max_length=16)\n score = models.IntegerField()\n\n # the manager for postgres\n objects = models.Manager()...
false
99,959
679181c622282ca8b33b2217fd94336431b9d23a
def left_child(root): return root * 2 + 1 def right_child(root): return root * 2 + 2 def parent(child): return (child - 1)// 2 def shift_down(a, start, end): root = start while True: child = left_child(root) if child > end: return swap = root if a[s...
[ "def left_child(root):\n return root * 2 + 1\n\n\ndef right_child(root):\n return root * 2 + 2\n\n\ndef parent(child):\n return (child - 1)// 2\n\n\ndef shift_down(a, start, end):\n root = start\n\n while True:\n child = left_child(root)\n if child > end:\n return\n sw...
false
99,960
9a24790d67d5a53c540fafa734240354fb7a684e
import pandas as pd import numpy as np import matplotlib.pyplot as plt from efficient_apriori import apriori # header=None,不将第一行作为head dataset = pd.read_csv('./Market_Basket_Optimisation.csv', header = None) # shape为(7501,20) print(dataset.shape) # 将数据存放到transactions中 transactions = [] for i in range(0, ...
[ "import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom efficient_apriori import apriori\r\n\r\n# header=None,不将第一行作为head\r\ndataset = pd.read_csv('./Market_Basket_Optimisation.csv', header = None) \r\n# shape为(7501,20)\r\nprint(dataset.shape)\r\n\r\n# 将数据存放到transactions中\r\ntransactio...
false
99,961
13f7e99aedb4b5a049a53f68738d5447f9ca63c2
import pprint import os import sqlite3 from td.client import TDClient from datetime import datetime pp = pprint.PrettyPrinter() conn = sqlite3.connect(os.environ.get('DB_NAME')) # Create a new session, credentials path is required. TDSession = TDClient( client_id=os.environ.get('CLIENT_ID'), redirect_uri='htt...
[ "import pprint\nimport os\nimport sqlite3\nfrom td.client import TDClient\nfrom datetime import datetime\n\npp = pprint.PrettyPrinter()\nconn = sqlite3.connect(os.environ.get('DB_NAME'))\n\n# Create a new session, credentials path is required.\nTDSession = TDClient(\n client_id=os.environ.get('CLIENT_ID'),\n ...
false
99,962
940f3a3a5c7936bf4e7e429e3c3088d09a64f6dd
# coding=utf-8 import requests from bs4 import BeautifulSoup url = "http://www.mysoal.com/moments/9JjqHTN2OEvnFeXZO4uUGT8LLOx4I-xJZOlQeYp6Cs0" page = requests.get(url).text soup = BeautifulSoup(page,"lxml") tayara_listing = soup.find("div", class_="moment") tayara_item = tayara_listing.find_all("div", class_="moment...
[ "# coding=utf-8\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"http://www.mysoal.com/moments/9JjqHTN2OEvnFeXZO4uUGT8LLOx4I-xJZOlQeYp6Cs0\"\npage = requests.get(url).text\nsoup = BeautifulSoup(page,\"lxml\")\n\ntayara_listing = soup.find(\"div\", class_=\"moment\")\ntayara_item = tayara_listing.find_all...
false
99,963
4df299857e9abc20bc162ef283ae3679251ed32d
reddit_categories = ['hot', 'new', 'controversial', 'rising', 'top'] async def get_subreddit_json(session, subreddit, category): return await get_json(session, 'https://www.reddit.com/r/' + subreddit + '/' + category + '/.json') async def get_json(session, url): async with session.get(url) as resp: re...
[ "reddit_categories = ['hot', 'new', 'controversial', 'rising', 'top']\n\nasync def get_subreddit_json(session, subreddit, category):\n return await get_json(session, 'https://www.reddit.com/r/' + subreddit + '/' + category + '/.json')\n\nasync def get_json(session, url):\n async with session.get(url) as resp:...
false
99,964
b015a5d7a956c836722b262426b7a89bcce907e2
import sys import requests import json from requests import Request, Session from requests.auth import HTTPBasicAuth import argparse from SwarmClient import Swarm from JiraClient import Jira import Config if __name__ == '__main__': swarm = Swarm() jira = Jira() parser = argparse.ArgumentParser( epilog="WA...
[ "import sys\nimport requests\nimport json\nfrom requests import Request, Session\nfrom requests.auth import HTTPBasicAuth\nimport argparse\nfrom SwarmClient import Swarm\nfrom JiraClient import Jira\nimport Config\n\n\nif __name__ == '__main__':\n swarm = Swarm()\n jira = Jira()\n parser = argparse.Argumen...
true
99,965
b6051496357dabc0ede873ceebb4054ff46e4d3d
from django.conf.urls import url from user.views import login, login_validate, join_page, about urlpatterns = [ url(r'^login/$', login), url(r'^login/validate/$', login_validate), url(r'^join/$', join_page), url(r'^about/$', about), ]
[ "from django.conf.urls import url\r\n\r\nfrom user.views import login, login_validate, join_page, about\r\n\r\nurlpatterns = [\r\n url(r'^login/$', login),\r\n url(r'^login/validate/$', login_validate),\r\n url(r'^join/$', join_page),\r\n url(r'^about/$', about),\r\n]", "from django.conf.urls import u...
false
99,966
19110b2767433c84dfab6ba28892923b00e99776
import tensorflow as tf from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional ,Dropout from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import A...
[ "import tensorflow as tf\n\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.layers import Embedding, LSTM, Dense, Bidirectional ,Dropout\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimize...
false
99,967
810fc5480d25b8f00fd47a7215f87e017848077e
# the square root function using Newton’s method. In this case, Newton’s method is to approximate sqrt(x) by picking a starting point z and then repeating: # z_next = z - ((z*z - x) / (2 * z)) # Author: Adrian Sypos # Date: 23/09/2017 import math x = 20.0 z_next = lambda z: (z - ((z*z - x) / (2 * z))) current = 1.0...
[ "# the square root function using Newton’s method. In this case, Newton’s method is to approximate sqrt(x) by picking a starting point z and then repeating:\n# z_next = z - ((z*z - x) / (2 * z))\n# Author: Adrian Sypos\n# Date: 23/09/2017\n\nimport math\n\nx = 20.0\n\nz_next = lambda z: (z - ((z*z - x) / (2 * z)))\...
false
99,968
a270c3749a4fda58bd1f8624fdd2f75d8e4cbdd0
from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torch.autograd import Variable import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time i...
[ "from __future__ import print_function, division\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.autograd import Variable\nimport numpy as np\nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt...
false
99,969
a452badb12abe9b1df7bf66963285c6aa93f0dbd
# -*- coding: utf-8 -*- """ Created on Mon Sep 5 17:09:33 2022 @author: Santi Extrae multiples espectros adquiridos en Bruker Avance II """ # import nmrglue as ng import matplotlib.pyplot as plt import numpy as np import scipy.integrate from Datos import * from Espectro import autophase from scipy.stats import linr...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 5 17:09:33 2022\n\n@author: Santi\n\nExtrae multiples espectros adquiridos en Bruker Avance II\n\"\"\"\n\n# import nmrglue as ng\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.integrate\nfrom Datos import *\nfrom Espectro import autophase\nfr...
false
99,970
7913ca2d7d428c4b4851e7ad52ccfc578e1a5f65
# -*- coding: utf-8 -*- """ Created on Tue Feb 28 16:06:17 2023 @author: Gilles.DELBECQ """ import sys, struct, math, os, time import numpy as np import matplotlib.pyplot as plt import scipy.signal as sp def read_data(filename): """Reads Intan Technologies RHD2000 data file generated by evaluation board GUI. ...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 28 16:06:17 2023\n\n@author: Gilles.DELBECQ\n\"\"\"\n\nimport sys, struct, math, os, time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport scipy.signal as sp\n\n\ndef read_data(filename):\n \"\"\"Reads Intan Technologies RHD2000 data file generat...
false
99,971
cd6b1c8c1dae53c95f77b4af60fd401ff6c71285
import numpy as np import base64 import cv2 import os class LSB: # to get object's format, size, data def get_object_info(self, file, itype): try: file_format = os.path.splitext(file)[-1].lower() size = os.path.getsize(file) name = os.path.basename(file) ...
[ "import numpy as np\nimport base64\nimport cv2\nimport os\n\nclass LSB:\n # to get object's format, size, data \n def get_object_info(self, file, itype):\n try:\n file_format = os.path.splitext(file)[-1].lower()\n size = os.path.getsize(file)\n name = os.path.basename(f...
false
99,972
260c40c7fd9ebff889f88d9a3f6e3c6d183d4cb4
from bootstrap import db from um import models # Contact 1 u1 = models.Contact('Contact 1', 'user1@example.com') db.session.add(u1) db.session.commit() # Contact 1 properties p = models.Property('first_name', 'Peter', u1.id) p1 = models.Property('last_name', 'Wanowan', u1.id) p2 = models.Property('email', 'peter.wano...
[ "from bootstrap import db\nfrom um import models\n\n# Contact 1\nu1 = models.Contact('Contact 1', 'user1@example.com')\ndb.session.add(u1)\ndb.session.commit()\n\n# Contact 1 properties\np = models.Property('first_name', 'Peter', u1.id)\np1 = models.Property('last_name', 'Wanowan', u1.id)\np2 = models.Property('ema...
false
99,973
8cdf2354dead12b292b47a12663748c0c1c09351
#!/usr/bin/env python # -*- coding: utf-8 -*- __all__ = ['NameSpace', 'ns'] from .utils import UnicodeDict class NameSpace(dict): @classmethod def instance(cls): if not hasattr(cls, "_instance"): cls._instance = cls() return cls._instance def __getattr__(self, key): ...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__all__ = ['NameSpace', 'ns']\n\nfrom .utils import UnicodeDict\n\n\nclass NameSpace(dict):\n @classmethod\n def instance(cls):\n if not hasattr(cls, \"_instance\"):\n cls._instance = cls()\n return cls._instance\n\n def __getattr_...
false
99,974
758f6328f197e4fbcbf52ac5c91ed68c3e8fc112
# class first_class: # age = 10 # name = 'gilbert' # p1 = first_class() # print(p1.name) # class meth: # def __init__(self, name='gilbert', age=25): # self.name = name # self.age = age # def get_name(self): # print(f'hello {self.name} your age is {self.age}') # p1 = meth('...
[ "# class first_class:\n# age = 10\n# name = 'gilbert'\n# p1 = first_class()\n# print(p1.name)\n\n# class meth:\n# def __init__(self, name='gilbert', age=25):\n# self.name = name\n# self.age = age\n \n# def get_name(self):\n# print(f'hello {self.name} your age is {self.age}...
false
99,975
83e2fe37bdc51475c914af611b671b6995efe890
# 手机号规则 REGEX_MOBILE = "^1[3578]\d{9}$|^147\d{8}$|^176\d{8}$" # 代拿费 AGENCY_FEE = 2.0 #退货服务费 SERVER_FEE = 2.0 # 首重件数 2 FIRST_WEIGHT = 2 # 发件人姓名 sender_name = "" # 发件人手机 sender_phone = "" # 发件人地址 sender_address = ""
[ "# 手机号规则\nREGEX_MOBILE = \"^1[3578]\\d{9}$|^147\\d{8}$|^176\\d{8}$\"\n\n# 代拿费\nAGENCY_FEE = 2.0\n#退货服务费\nSERVER_FEE = 2.0\n\n# 首重件数 2\nFIRST_WEIGHT = 2\n\n# 发件人姓名\nsender_name = \"\"\n\n# 发件人手机\nsender_phone = \"\"\n\n# 发件人地址\n\nsender_address = \"\"\n", "REGEX_MOBILE = '^1[3578]\\\\d{9}$|^147\\\\d{8}$|^176\\\\d{...
false
99,976
afab7a1a1d16c3af1bbdb8cf3a9e4c9c91f95cdb
#!/usr/bin/env python import socket import struct class KongsbergEM: def __init__(self,port=16112): self.insock = socket.socket(type=socket.SOCK_DGRAM) self.insock.bind(('',port)) def getPacket(self): data,addr = self.insock.recvfrom(10000) start,dgram_type = struct.unpack('<B...
[ "#!/usr/bin/env python\n\nimport socket\nimport struct\n\nclass KongsbergEM:\n def __init__(self,port=16112):\n self.insock = socket.socket(type=socket.SOCK_DGRAM)\n self.insock.bind(('',port))\n\n def getPacket(self):\n data,addr = self.insock.recvfrom(10000)\n start,dgram_type = ...
true
99,977
3c08cca562db78861ec754eb2b7caae4c8ed1eed
import os from google.cloud import storage from google.cloud.storage import Bucket def connect_to_bucket(bucket_name: str) -> Bucket: """ @param bucket_name: name of the bucket of the save location @return: bucket object provided by GCP """ storage_client = storage.Client(project='your-project-na...
[ "import os\n\nfrom google.cloud import storage\nfrom google.cloud.storage import Bucket\n\n\ndef connect_to_bucket(bucket_name: str) -> Bucket:\n \"\"\"\n @param bucket_name: name of the bucket of the save location\n @return: bucket object provided by GCP\n \"\"\"\n storage_client = storage.Client(pr...
false
99,978
1e8adf8bc9b96b3e32cd95ca0a739125c72dc17e
import unittest class TestAbs(unittest.TestCase): def test_abs1(self): self.assertEqual(abs(-42), 42, "Should be absolute value of a number") def test_abs2(self): self.assertEqual(abs(-15), 15, "Should be absolute value of a number") def test_abs3(self): self.assertEqual(abs(-8),...
[ "import unittest\n\n\nclass TestAbs(unittest.TestCase):\n def test_abs1(self):\n self.assertEqual(abs(-42), 42, \"Should be absolute value of a number\")\n\n def test_abs2(self):\n self.assertEqual(abs(-15), 15, \"Should be absolute value of a number\")\n\n def test_abs3(self):\n self....
false
99,979
8975603a891221ec894f5616bfb377a4f87fb13a
from flask import Flask from config import Configuration from routes import myMainRouter app = Flask(__name__) app.config.from_object(Configuration) app.register_blueprint(myMainRouter.bp)
[ "from flask import Flask\nfrom config import Configuration\nfrom routes import myMainRouter\n\napp = Flask(__name__)\napp.config.from_object(Configuration)\napp.register_blueprint(myMainRouter.bp)\n", "from flask import Flask\nfrom config import Configuration\nfrom routes import myMainRouter\napp = Flask(__name__...
false
99,980
214a6862dc0b1d7822a34ad1c8a1b0381f8f7c6b
import os from motor import MotorClient from tornado.options import define, options from tornado.web import Application from app.api.urls import urls def is_debug(): try: debug = os.environ['DEBUG'] return debug.lower() in ("true", "t", "1") except KeyError: return False def load_c...
[ "import os\n\nfrom motor import MotorClient\nfrom tornado.options import define, options\nfrom tornado.web import Application\n\nfrom app.api.urls import urls\n\n\ndef is_debug():\n try:\n debug = os.environ['DEBUG']\n return debug.lower() in (\"true\", \"t\", \"1\")\n except KeyError:\n ...
false
99,981
f66069ad599747f10ba260f0062d271cf2c0d5a4
from __future__ import print_function for col in range(8): for row in range(col): for left in range(col - row): print (' ', end='') print('#')
[ "from __future__ import print_function\n\nfor col in range(8):\n for row in range(col):\n for left in range(col - row):\n print (' ', end='')\n print('#')\n", "from __future__ import print_function\nfor col in range(8):\n for row in range(col):\n for left in range(col - row):...
false
99,982
62f85ea9566ba2ebacb3dddcb746bb287ad8b54d
import torch def to_categorical(in_content, num_classes=None): if num_classes is None: num_classes = int(in_content.max()) + 1 shape = in_content.shape[0], num_classes, *in_content.shape[2:] temp = torch.zeros(shape).transpose(0, 1) for i in range(num_classes): temp[i, (...
[ "import torch\n\n\ndef to_categorical(in_content, num_classes=None):\n if num_classes is None:\n num_classes = int(in_content.max()) + 1\n \n shape = in_content.shape[0], num_classes, *in_content.shape[2:]\n \n temp = torch.zeros(shape).transpose(0, 1)\n \n for i in range(num_classes):\n...
false
99,983
dc72077499ff0254bca3244a8a5cef8d72016ef8
from .pulsesms import PulseCrypt, PulseSMSAPI
[ "from .pulsesms import PulseCrypt, PulseSMSAPI\n", "<import token>\n" ]
false
99,984
ee7c3dbe415b89a834f9023426e9a6dd026f1021
import json import requests with open('config.json') as config_file: es_config = json.load(config_file) def saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField="timestamp", verify=True): chart_json = json.loads(altairChart.to_json()) chart_json['data']['url'] = { "%context%": Tru...
[ "import json\nimport requests\n\nwith open('config.json') as config_file:\n es_config = json.load(config_file)\n\n\ndef saveVegaLiteVis(index, visName, altairChart, resultSize=100, timeField=\"timestamp\", verify=True):\n chart_json = json.loads(altairChart.to_json())\n chart_json['data']['url'] = {\n ...
false
99,985
398200b8e922a026827c981e4f14b16bea7eb366
from django.urls import include, path from . import views urlpatterns = [ path('',include("lenus_app.urls")), path("signup/",views.signup,name="signup" ), path("logout/",views.logout_request,name="logout" ), path("login/",views.user_login,name="login" ), path("profile/",views.profile,name="profile"...
[ "from django.urls import include, path\nfrom . import views\n\nurlpatterns = [\n path('',include(\"lenus_app.urls\")),\n path(\"signup/\",views.signup,name=\"signup\" ),\n path(\"logout/\",views.logout_request,name=\"logout\" ),\n path(\"login/\",views.user_login,name=\"login\" ),\n path(\"profile/\"...
false
99,986
04c6a30f1065d5ca42507121d89d73b73d846bc5
""" Module: DMS Project Wide Context Processors Project: Adlibre DMS Copyright: Adlibre Pty Ltd 2012 License: See LICENSE for license information """ import os from django.conf import settings from core.models import CoreConfiguration def theme_template_base(context): """ Returns Global Theme Base Template """ ...
[ "\"\"\"\nModule: DMS Project Wide Context Processors\nProject: Adlibre DMS\nCopyright: Adlibre Pty Ltd 2012\nLicense: See LICENSE for license information\n\"\"\"\n\nimport os\n\nfrom django.conf import settings\nfrom core.models import CoreConfiguration\n\ndef theme_template_base(context):\n \"\"\" Returns Globa...
false
99,987
cb6d64a8495022b4962c51eae9bef5adf47dc6fa
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 29 12:44:18 2021 @author: tai """ ''' Evaluate Object Detection Model: 1. Get all bounding box prediction on our test set Table: Image_name Confidence_value TP_or_FP image1 0.3 FP image3 2. Sort by descendi...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 29 12:44:18 2021\n\n@author: tai\n\"\"\"\n\n'''\nEvaluate Object Detection Model:\n1. Get all bounding box prediction on our test set\nTable:\n Image_name Confidence_value TP_or_FP\n image1 0.3 FP\n image3...
false
99,988
32d715dbe1764e86f9d5c2bee93bbbda2ec3515f
import pulumi_aws as aws import pulumi import os import mimetypes config = pulumi.Config() site_dir = config.get("site") bucket = aws.s3.Bucket(resource_name="pulumi-demo", bucket="pulumi-demo", tags={ "Owner": "pulumi-demo", ...
[ "import pulumi_aws as aws\nimport pulumi\nimport os\nimport mimetypes\n\nconfig = pulumi.Config()\nsite_dir = config.get(\"site\")\n\nbucket = aws.s3.Bucket(resource_name=\"pulumi-demo\",\n bucket=\"pulumi-demo\",\n tags={\n \"Owner\": \"pulumi-d...
false
99,989
0b67714bf9b60e63e48586ac2a1e50468a918752
import pprint import re from collections import defaultdict __author__ = 'ronanbrady2' # Prints all street suffixes, e.g. Lane, Avenue, to allow audit analysis def printAllStreetSuffixes(db): pipeline = [ { "$group" : { "_id" : "$address.street" , "coun...
[ "import pprint\nimport re\nfrom collections import defaultdict\n\n__author__ = 'ronanbrady2'\n\n# Prints all street suffixes, e.g. Lane, Avenue, to allow audit analysis\ndef printAllStreetSuffixes(db):\n pipeline = [\n { \"$group\" : {\n \"_id\" : \"$address.street\" ,\n ...
false
99,990
9a75c2b9fed227b660a688bd3adf5b837e85af9e
class node(): def __init__(self): self.child = [None]*26 self.flag = False class trie(): def __init__(self): self.root = node() def gethash(self, key): return ord(key)-ord("a") def add(self, key): nex = self.root for char in list(key): index = self.gethash(char) #if index is none, create new n...
[ "class node():\n\tdef __init__(self):\n\t\tself.child = [None]*26\n\t\tself.flag = False\n\nclass trie():\n\tdef __init__(self):\n\t\tself.root = node()\n\t\n\tdef gethash(self, key):\n\t\treturn ord(key)-ord(\"a\")\n\n\tdef add(self, key):\n\t\tnex = self.root\n\t\tfor char in list(key):\n\t\t\tindex = self.gethas...
false
99,991
07191eaf858d411c733666dea85de3400d32ca6d
taille = int(input("Saisir la taille du triangle: ")) for i in range (taille,0,-1): print("*"*i)
[ "taille = int(input(\"Saisir la taille du triangle: \"))\r\nfor i in range (taille,0,-1):\r\n print(\"*\"*i)\r\n ", "taille = int(input('Saisir la taille du triangle: '))\nfor i in range(taille, 0, -1):\n print('*' * i)\n", "<assignment token>\nfor i in range(taille, 0, -1):\n print('*' * i)\n", "<as...
false
99,992
edcf3b16203c006e5bd9382593a8584de26114d5
import common import edify_generator def AddAssertions(info): edify = info.script for i in xrange(len(edify.script)): if ");" in edify.script[i] and ("ro.product.device" in edify.script[i] or "ro.build.product" in edify.script[i]): edify.script[i] = edify.script[i].replace(");", ' || getpro...
[ "import common\nimport edify_generator\n\ndef AddAssertions(info):\n edify = info.script\n for i in xrange(len(edify.script)):\n if \");\" in edify.script[i] and (\"ro.product.device\" in edify.script[i] or \"ro.build.product\" in edify.script[i]):\n edify.script[i] = edify.script[i].replace...
false
99,993
4d5f8cb419277b87cad42a09632e81d63367fdcb
"""Using datetime to make an app that will ask us math questions and time our answers. """ from quiz import Quiz # create class to keep track of quiz scores over time? def main(): while True: quiz_prompt = input('Do you want a math quiz? y/n') if quiz_prompt.lower()[0] == 'y': quiz...
[ "\"\"\"Using datetime to make an app that will ask us math questions\nand time our answers.\n\"\"\"\nfrom quiz import Quiz\n \n \n# create class to keep track of quiz scores over time?\ndef main():\n while True:\n quiz_prompt = input('Do you want a math quiz? y/n')\n if quiz_prompt.lower()[0] == ...
false
99,994
c3b34cf17b04a9611e348363537371ead6cefe2a
# koomar is a simple IRC bot written for fun. # Grab your updates from: http://github.com/anandkunal/koomar/ # Peep the IRC RFC: http://www.irchelp.org/irchelp/rfc/rfc.html import datetime import random import socket import re import time import lib from lib import Message, flatten server = "irc.freenode.net" channe...
[ "# koomar is a simple IRC bot written for fun.\n# Grab your updates from: http://github.com/anandkunal/koomar/\n# Peep the IRC RFC: http://www.irchelp.org/irchelp/rfc/rfc.html\n\nimport datetime\nimport random\nimport socket\nimport re\nimport time\n\nimport lib\nfrom lib import Message, flatten\n\nserver = \"irc.f...
false
99,995
c11fd5bcba3242216a26bba364888ca95160da35
# -*- coding: utf-8 -*- # encoding=utf8 import sys from flask import Flask, render_template, request, redirect, url_for, session import sqlite3 import datetime import os import random import re ##burasi hacky. py3 de gerekmiyor ve bu da onerilmiyor reload(sys) sys.setdefaultencoding('utf8') app = Fl...
[ "# -*- coding: utf-8 -*-\r\n# encoding=utf8 \r\nimport sys\r\nfrom flask import Flask, render_template, request, redirect, url_for, session\r\nimport sqlite3\r\nimport datetime\r\nimport os\r\nimport random\r\nimport re\r\n\r\n##burasi hacky. py3 de gerekmiyor ve bu da onerilmiyor\r\nreload(sys) \r\nsys.setdefaul...
true
99,996
eca1c5bec2249f529d878c3b9768c4611ccb1e64
from selenium import webdriver import requests from selenium.webdriver.common.keys import Keys import time from bs4 import BeautifulSoup import urlparse, random import argparse,os key = "badoo.com" driver = webdriver.PhantomJS() driver.set_window_size(1280,800) driver.get('https://badoo.com/') Main_win...
[ "from selenium import webdriver\r\nimport requests\r\nfrom selenium.webdriver.common.keys import Keys\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport urlparse, random\r\nimport argparse,os\r\nkey = \"badoo.com\"\r\ndriver = webdriver.PhantomJS()\r\n\r\ndriver.set_window_size(1280,800)\r\ndriver.get('https...
true
99,997
0a03e7274a1d30e2b4f509d3cab8d600eda1cf0f
def process_dict(my_dict): for key, value in my_dict.items(): if key.startswith("melon"): print(sorted(value)) process_dict({"elon": [3, 1, 2], "melon": 4})
[ "def process_dict(my_dict):\n for key, value in my_dict.items():\n if key.startswith(\"melon\"):\n print(sorted(value))\n\n\nprocess_dict({\"elon\": [3, 1, 2], \"melon\": 4})\n", "def process_dict(my_dict):\n for key, value in my_dict.items():\n if key.startswith('melon'):\n ...
false
99,998
455799a224a29da1b46ae3727166c3b65d08225e
# -*- coding: utf-8 -*- # BSD 3-Clause License # # Copyright (c) 2017 xxxx # All rights reserved. # Copyright 2021 Huawei Technologies Co., Ltd # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of so...
[ "# -*- coding: utf-8 -*-\n# BSD 3-Clause License\n#\n# Copyright (c) 2017 xxxx\n# All rights reserved.\n# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redist...
false
99,999
ab30a233e125889b97c957820961dc8c749c0b0e
# RECURSION def fact(n): result = 1 if n > 1: for f in range(2, n+1): result *= f return result def factorial(n): if n <= 1: return 1 else: return n * factorial(n-1) def fib(n): if n < 2: return n else: return fib(n-1) + fib(n-2) def ...
[ "# RECURSION\n\ndef fact(n):\n result = 1\n if n > 1:\n for f in range(2, n+1):\n result *= f\n return result\n\n\ndef factorial(n):\n if n <= 1:\n return 1\n else:\n return n * factorial(n-1)\n\ndef fib(n):\n if n < 2:\n return n\n else:\n return f...
false