index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
8,000
5e86e97281b9d18a06efc62b20f5399611e3510d
from enum import Enum EXIT_CODES = [ "SUCCESS", "BUILD_FAILURE", "PARSING_FAILURE", "COMMAND_LINE_ERROR", "TESTS_FAILED", "PARTIAL_ANALYSIS_FAILURE", "NO_TESTS_FOUND", "RUN_FAILURE", "ANALYSIS_FAILURE", "INTERRUPTED", "LOCK_HEL...
[ "from enum import Enum\n\nEXIT_CODES = [\n \"SUCCESS\", \n \"BUILD_FAILURE\", \n \"PARSING_FAILURE\", \n \"COMMAND_LINE_ERROR\", \n \"TESTS_FAILED\",\n \"PARTIAL_ANALYSIS_FAILURE\",\n \"NO_TESTS_FOUND\",\n \"RUN_FAILURE\",\n \"ANALYSIS_FAILURE\",\n ...
false
8,001
603cce951dd0f78ef3ca9dce587042b3b7f6b449
"""" You are given a tree-like data structure represented as nested dictionaries. Implement a function collect_leaves that accepts a tree and returns a list of all its leaves. A leaf is a bottom-most node in a tree. Implement a kind of unit tests via assert operator. """ from typing import Union def collect...
[ "\"\"\"\"\r\nYou are given a tree-like data structure represented as nested dictionaries.\r\nImplement a function collect_leaves that accepts a tree and returns a list of all its leaves. A leaf is a bottom-most node in a tree.\r\n\r\nImplement a kind of unit tests via assert operator.\r\n\"\"\"\r\nfrom typing impor...
false
8,002
593d3221e34c0eef51228082d767d8516ec93ca2
y_true = [7, 3, 3, 4, 9, 9, 2, 5, 0, 0, 6, 3, 1, 6, 8, 7, 9, 7, 4, 2, 0, 1, 4, 1, 7, 7, 5, 0, 8, 0, 1, 7, 4, 2, 2, 4, 9, 3, 1, 7, 1, 2, 1, 7, 5, 9, 9, 4, 8, 5, 7, 2, 7, 5, 5, 6, 6, 1, 2, 6, 6, 5, 3, 2, 3, 8, 8, 8, 8, 5, 3, 4, 3, 2, 8, 1, 9, 0, 6, 8, 6, 1, 1, 1, 5, 4, 8, 8, 5, 5, 8, 6, 4, 4, 6, 9, 8, 1, 5, 5] y_pred_p...
[ "\ny_true = [7, 3,\n3,\n4,\n9,\n9,\n2,\n5,\n0,\n0,\n6,\n3,\n1,\n6,\n8,\n7,\n9,\n7,\n4,\n2,\n0,\n1,\n4,\n1,\n7,\n7,\n5,\n0,\n8,\n0,\n1,\n7,\n4,\n2,\n2,\n4,\n9,\n3,\n1,\n7,\n1,\n2,\n1,\n7,\n5,\n9,\n9,\n4,\n8,\n5,\n7,\n2,\n7,\n5,\n5,\n6,\n6,\n1,\n2,\n6,\n6,\n5,\n3,\n2,\n3,\n8,\n8,\n8,\n8,\n5,\n3,\n4,\n3,\n2,\n8,\n1,\n...
false
8,003
f218f47acfb078877645de26c64e57f92dbcd953
import utilities import sys if __name__ == "__main__": print('I am main!') else: print(__name__) for i in range(0,6): print(i) mylist = [12, 13, 14, 13, 12] print(mylist) #Enter iterations to run [0-5] #value = -1 value = 3 while (value not in range(0,6)): try: value =...
[ "import utilities\r\nimport sys\r\n\r\nif __name__ == \"__main__\":\r\n print('I am main!')\r\nelse:\r\n print(__name__)\r\n\r\nfor i in range(0,6):\r\n print(i)\r\n \r\nmylist = [12, 13, 14, 13, 12]\r\nprint(mylist)\r\n\r\n#Enter iterations to run [0-5]\r\n#value = -1\r\nvalue = 3\r\nwhile (value not i...
false
8,004
25ee13314c7cf828b8805d9f483bd5ee12073228
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .BLWecc import ( curve, setCurve, getPublicKey, getPrivateKey, getAddress as getAddressByCode, pub2add as getAddressByPublicKey, sign, verifyTx as verify, )
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom .BLWecc import (\ncurve,\nsetCurve,\ngetPublicKey,\ngetPrivateKey,\ngetAddress as getAddressByCode, \npub2add as getAddressByPublicKey,\nsign,\nverifyTx as verify,\n)\n\n\n", "from __future__ impo...
false
8,005
46f3d3681343d96889ddb073f17ff7f225486f35
my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1] new_list = list(filter(lambda x: x != 0, my_list)) try: new = list(map(lambda x: 2 / x, new_list)) except ZeroDivisionError: pass print(new) # def devis(n, list): # new_list = [] # for i, m_list in enumerate(list): # try: # new_list.a...
[ "my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1]\nnew_list = list(filter(lambda x: x != 0, my_list))\n\ntry:\n new = list(map(lambda x: 2 / x, new_list))\nexcept ZeroDivisionError:\n pass\n\nprint(new)\n\n\n\n\n\n# def devis(n, list):\n# new_list = []\n# for i, m_list in enumerate(list):\n# try:\n#...
false
8,006
8eb08fa497ccf3ddc8f4d2b886c9e5a9bdb2e052
#!/usr/bin/python import socket, os, datetime, time, re, sys import numpy as np import matplotlib.pyplot as plt from baseband import vdif import astropy.units as u from scipy.signal import resample_poly import matplotlib.patches as patches def fbcmd(message): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM...
[ "#!/usr/bin/python\nimport socket, os, datetime, time, re, sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom baseband import vdif\nimport astropy.units as u\nfrom scipy.signal import resample_poly\nimport matplotlib.patches as patches\n\ndef fbcmd(message):\n sock = socket.socket(socket.AF_INET, soc...
false
8,007
9dfbf14a2005aad87be82e5e482c6b0347f32f2c
# Generated by Django 3.2.9 on 2021-11-10 13:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('settings', '0003_auto_20210814_2246'), ] operations = [ migrations.AlterField( model_name='building', name='id', ...
[ "# Generated by Django 3.2.9 on 2021-11-10 13:36\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('settings', '0003_auto_20210814_2246'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='building',\n ...
false
8,008
1825b365032a224ed56a1814d7f6457e2add8fdd
import csv with open('healthviolations.csv', 'w') as fp: with open('Restaurant_Inspections.csv', 'rb') as csvfile: reader = csv.reader(csvfile) header = next(reader, None) writer = csv.writer(fp, delimiter=',') writer.writerow([header[0], "violation"]) for row in reader: if (row[20] != '')...
[ "import csv\n\nwith open('healthviolations.csv', 'w') as fp:\n\n with open('Restaurant_Inspections.csv', 'rb') as csvfile:\n reader = csv.reader(csvfile)\n header = next(reader, None)\n writer = csv.writer(fp, delimiter=',')\n writer.writerow([header[0], \"violation\"])\n for row in reader:\n i...
false
8,009
7789e54acc02fe0277ff80ce14efbcdc4ee6e7f1
import gym import random import numpy as np import statistics from collections import Counter import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression #setup the Cartpole environment env = gym.make("CartPole-v0") env.reset() #----------Expl...
[ "import gym\nimport random \nimport numpy as np\nimport statistics\nfrom collections import Counter\n\nimport tflearn\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\n\n#setup the Cartpole environment\nenv = gym.make(\"CartPole-v0\")\nenv.reset(...
false
8,010
3e7df9a733c94b89d22d10883844c438444d5e2c
from __future__ import unicode_literals from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver PROFILE_PIC_PATH = 'users/profile_pic' class Profile(models.Model): user = models.OneToOneField(User, on_delete=mod...
[ "from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth.models import User\nfrom django.dispatch import receiver\n\nPROFILE_PIC_PATH = 'users/profile_pic'\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(Use...
false
8,011
746971cd6c5bf65268e89303c8f4ce98a56eb111
#!/usr/bin/env python2 # -*- coding: utf8 -*- from __future__ import print_function, division, absolute_import from flask.ext.login import current_user from . import cert_record_process as record_process_base from walis.thirdparty import thrift_client, thirdparty_svc from walis.exception.util import raise_user_exc f...
[ "#!/usr/bin/env python2\n# -*- coding: utf8 -*-\n\nfrom __future__ import print_function, division, absolute_import\n\nfrom flask.ext.login import current_user\n\nfrom . import cert_record_process as record_process_base\nfrom walis.thirdparty import thrift_client, thirdparty_svc\nfrom walis.exception.util import ra...
false
8,012
99b5ac74da95dff399c31d58e19bac65e538a34b
def main(): ' main entry point for module execution\n ' argument_spec = dict(src=dict(type='path'), replace_src=dict(), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', '...
[ "def main():\n ' main entry point for module execution\\n '\n argument_spec = dict(src=dict(type='path'), replace_src=dict(), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'e...
false
8,013
841743d4e9d683827962d83a77a87c6432842add
import tkinter as tk from functools import partial from numpy import random from base import NinePalaceGame class SingleMode(NinePalaceGame): player1 = player = 'O' player2 = computer = 'X' def __init__(self): self.create_choose_one_window() super().__init__() self.main_game_wind...
[ "import tkinter as tk\nfrom functools import partial\nfrom numpy import random\nfrom base import NinePalaceGame\n\n\nclass SingleMode(NinePalaceGame):\n player1 = player = 'O'\n player2 = computer = 'X'\n\n def __init__(self):\n self.create_choose_one_window()\n super().__init__()\n\n ...
false
8,014
c04c38d78144b6f5d3e5af4ebe9ce430e882a367
import numpy as np def get_train_batches(data_dir='/home/yunhan/batchified'): """ return a list or generator of (large) ndarrays, in order to efficiently utilize GPU """ # todo: read in data that is preoprocessed # Use batch 1 - 52 as train (60%), 53 - 71 as validation (20%), 72 - 89 a...
[ "import numpy as np\n\n\ndef get_train_batches(data_dir='/home/yunhan/batchified'):\n \"\"\"\n return a list or generator of (large) ndarrays,\n in order to efficiently utilize GPU\n \"\"\"\n # todo: read in data that is preoprocessed\n # Use batch 1 - 52 as train (60%), 53 - 71 as validat...
false
8,015
fe82a46a7965b27729ff5bd61c1059416c96cae7
print("""Hello world""") print("Hello again") print('Hello again')
[ "print(\"\"\"Hello world\"\"\")\nprint(\"Hello again\")\nprint('Hello again')", "print('Hello world')\nprint('Hello again')\nprint('Hello again')\n", "<code token>\n" ]
false
8,016
108c8bbb4d3dbc6b7f32e084b13009296b3c5a80
import serial import time def main(): # '/dev/tty****' is your port ID con=serial.Serial('/dev/tty****', 9600) print('connected.') while 1: str=con.readline() # byte code print (str.strip().decode('utf-8')) # decoded string if __name__ == '__main__': main()
[ "import serial\nimport time\n\ndef main():\n # '/dev/tty****' is your port ID\n con=serial.Serial('/dev/tty****', 9600)\n print('connected.')\n while 1:\n str=con.readline() # byte code\n print (str.strip().decode('utf-8')) # decoded string\n\nif __name__ == '__main__':\n main()\n", "...
false
8,017
62ca95a871c16191fb8f56213646e8173f400630
import streamlit as st st.write('hi')
[ "import streamlit as st\n\nst.write('hi')", "import streamlit as st\nst.write('hi')\n", "<import token>\nst.write('hi')\n", "<import token>\n<code token>\n" ]
false
8,018
a1c5d86a3f042d9e5ba522726191c8aeb9b738ed
import os from dataclasses import dataclass from dotenv import load_dotenv from fastapi.security import OAuth2PasswordBearer from passlib.context import CryptContext load_dotenv() @dataclass class Settings: SECRET_KEY = os.getenv("SECRET_KEY", "mysecret") ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES ...
[ "import os\nfrom dataclasses import dataclass\n\nfrom dotenv import load_dotenv\nfrom fastapi.security import OAuth2PasswordBearer\nfrom passlib.context import CryptContext\n\nload_dotenv()\n\n\n@dataclass\nclass Settings:\n SECRET_KEY = os.getenv(\"SECRET_KEY\", \"mysecret\")\n ALGORITHM = \"HS256\"\n ACC...
false
8,019
8cfab525ab3a86dd6964475d5621fdc7c6413e38
"""Secret Garden tests.""" from secret_garden import Decoder, SecretGarden import random filename = "pr08_example_data.txt" key = "Fat Chocobo" d = Decoder(filename, key) s = SecretGarden(filename, key) def test_read_from_file(): """ Test of function of reading data from file. :return: """ readi...
[ "\"\"\"Secret Garden tests.\"\"\"\nfrom secret_garden import Decoder, SecretGarden\nimport random\n\nfilename = \"pr08_example_data.txt\"\nkey = \"Fat Chocobo\"\nd = Decoder(filename, key)\ns = SecretGarden(filename, key)\n\n\ndef test_read_from_file():\n \"\"\"\n Test of function of reading data from file.\n...
false
8,020
2a3f9c4518df337cfc5e4b1816e7b2b4af62c101
#!/usr/bin/env python3 import unittest import solution class TestMethods(unittest.TestCase): def LinkedListFromArray(self, values): if len(values) > 0: headNode = solution.ListNode(values[0], None) tailPtr = headNode if len(values) > 1: for value in val...
[ "#!/usr/bin/env python3\n\nimport unittest\nimport solution\n\nclass TestMethods(unittest.TestCase):\n def LinkedListFromArray(self, values):\n if len(values) > 0:\n headNode = solution.ListNode(values[0], None)\n tailPtr = headNode\n\n if len(values) > 1:\n ...
false
8,021
3f4b05a1d0c4c2a2b085a0265bafbf89b5635e31
import pandas as pd import statistics import csv df = pd.read_csv("height-weight.csv") heightlist = df["Height(Inches)"].to_list() weightlist = df["Weight(Pounds)"].to_list() heightmean = statistics.mean(heightlist) heightmedian = statistics.median(heightlist) heightmode = statistics.mode(heightlist) heigh...
[ "import pandas as pd\r\nimport statistics\r\nimport csv\r\n\r\ndf = pd.read_csv(\"height-weight.csv\")\r\nheightlist = df[\"Height(Inches)\"].to_list()\r\nweightlist = df[\"Weight(Pounds)\"].to_list()\r\n\r\nheightmean = statistics.mean(heightlist)\r\nheightmedian = statistics.median(heightlist)\r\nheightmode = sta...
false
8,022
b137fc40a5b2dec63c7abb6953664a969f5c126f
def equals(left, right, tol=0.001): """ Tests equality of left and right Rosalind allows for a default [absolute] error of 0.001 in decimal answers unless otherwise stated. """ try: left = left.strip() right = right.strip() except AttributeError: pass try: ...
[ "def equals(left, right, tol=0.001):\n \"\"\"\n Tests equality of left and right\n\n Rosalind allows for a default [absolute] error of 0.001 in decimal\n answers unless otherwise stated.\n \"\"\"\n try:\n left = left.strip()\n right = right.strip()\n except AttributeError:\n ...
false
8,023
11e9d25c30c8c9945cfa3c234ffa1aab98d1869e
from math import gcd from random import randint, choice task = """6. Реализовать алгоритм построения ПСП методом Фиббоначи с запаздываниями. Обосновать выбор коэффициентов алгоритма. Для начального заполнения использовать стандартную линейную конгруэнтную ПСП с выбранным периодом. Реализовать возможность для пользоват...
[ "from math import gcd\nfrom random import randint, choice\n\ntask = \"\"\"6. Реализовать алгоритм построения ПСП методом Фиббоначи с\nзапаздываниями. Обосновать выбор коэффициентов алгоритма. Для\nначального заполнения использовать стандартную линейную конгруэнтную\nПСП с выбранным периодом. Реализовать возможность...
false
8,024
fbfc1749252cf8cbd9f8f72df268284d3e05d6dc
def regexp_engine(pattern, letter): return pattern in ('', '.', letter) def match_regexp(pattern, substring): if not pattern: # pattern is empty always True return True if substring: # if string is not empty try the regexp engine if regexp_engine(pattern[0], substring[0]): # if reg and ...
[ "def regexp_engine(pattern, letter):\n return pattern in ('', '.', letter)\n\n\ndef match_regexp(pattern, substring):\n if not pattern: # pattern is empty always True\n return True\n if substring: # if string is not empty try the regexp engine\n if regexp_engine(pattern[0], substring[0]): ...
false
8,025
46a3c3777d90976c7d39772d2e94430506d3acd7
""" Day 2 """ with open('input.txt', 'r') as f: lines = f.read() lines = lines.split('\n')[:-1] lines = [l.split(' ') for l in lines] valid = 0 new_valid = 0 for cur_pw in lines: letter = cur_pw[1].strip(':') amount = cur_pw[2].count(letter) rule = cur_pw[0].split('-') rule = [int(r) for r in ru...
[ "\"\"\"\nDay 2\n\"\"\"\n\nwith open('input.txt', 'r') as f:\n lines = f.read()\n\nlines = lines.split('\\n')[:-1]\nlines = [l.split(' ') for l in lines]\n\nvalid = 0\nnew_valid = 0\nfor cur_pw in lines:\n\n letter = cur_pw[1].strip(':')\n amount = cur_pw[2].count(letter)\n rule = cur_pw[0].split('-')\n ...
false
8,026
fc89fdf17f887ea398be5b36d4d6f0444d64b3e0
"""script for subpixel experiment (not tested) """ import numpy as np from tqdm import tqdm import logging from pathlib import Path import paddle import paddle.optimizer import paddle.io from utils.loader import dataLoader from utils.loader import modelLoader from utils.loader import pretrainedLoader from utils.tools...
[ "\"\"\"script for subpixel experiment (not tested)\n\"\"\"\nimport numpy as np\nfrom tqdm import tqdm\nimport logging\nfrom pathlib import Path\n\nimport paddle\nimport paddle.optimizer\nimport paddle.io\n\nfrom utils.loader import dataLoader\nfrom utils.loader import modelLoader\nfrom utils.loader import pretraine...
false
8,027
d4b9403366a16dfbb12a2161a996e641b3a785a5
# __author__: Stanley # date: 2018/10/22 class Foo: def __init__(self, name, age): self.name = name self.age = age def __getitem__(self, item): return item + 10 def __setitem__(self, key, value): print(key, value) def __delitem__(self, key): print(key) obj =...
[ "# __author__: Stanley\n# date: 2018/10/22\n\nclass Foo:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def __getitem__(self, item):\n return item + 10\n\n def __setitem__(self, key, value):\n print(key, value)\n\n def __delitem__(self, key):\n ...
false
8,028
779e7cd05edfd74c8e60eaf5ce8443aea5fdaaef
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """ # @Time : 20-6-9 上午11:47 # @Author : zhufa # @Software: PyCharm """ """ tensorflow version must below 1.15 """ import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", ...
[ "#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\n\"\"\"\n# @Time : 20-6-9 上午11:47\n\n# @Author : zhufa\n\n# @Software: PyCharm\n\"\"\"\n\"\"\"\ntensorflow version must below 1.15\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_...
true
8,029
1221394dfb97cbbfb00b412f60d4df521acc1262
# MODULES import sys sys.path.append('~/Documents/Project_3/REPO') from scipy import * from scipy import linalg import cPickle as pickle import ConfigParser import TobySpectralMethods as tsm config = ConfigParser.RawConfigParser() fp = open('config.cfg') config.readfp(fp) N = config.getint('General', 'N') M = config....
[ "\n# MODULES\nimport sys\nsys.path.append('~/Documents/Project_3/REPO')\nfrom scipy import *\nfrom scipy import linalg\nimport cPickle as pickle\nimport ConfigParser\nimport TobySpectralMethods as tsm\n\nconfig = ConfigParser.RawConfigParser()\nfp = open('config.cfg')\nconfig.readfp(fp)\nN = config.getint('General'...
true
8,030
177401f25471cf1cbd32dd0770acdc12bf271361
import os from NeuralEmulator.Configurators.NormalLeakSourceConfigurator import NormalLeakSourceConfigurator from NeuralEmulator.Configurators.OZNeuronConfigurator import OZNeuronConfigurator from NeuralEmulator.Configurators.PulseSynapseConfigurator import PulseSynapseConfigurator from NeuralEmulator.NormalLeakS...
[ "import os\r\n\r\nfrom NeuralEmulator.Configurators.NormalLeakSourceConfigurator import NormalLeakSourceConfigurator\r\nfrom NeuralEmulator.Configurators.OZNeuronConfigurator import OZNeuronConfigurator\r\nfrom NeuralEmulator.Configurators.PulseSynapseConfigurator import PulseSynapseConfigurator\r\nfrom NeuralEmula...
false
8,031
c2d6e4286e1b9d6dc852bde994da60d353e03e5c
from youtube_transcript_api import YouTubeTranscriptApi transcript_list = YouTubeTranscriptApi.list_transcripts('i8pOulVUz0A') transcript = transcript_list.find_transcript(['en']) transcript = transcript.fetch() with open("transcript.txt", 'w') as f: for line in transcript: f.write(line['text']+ '\n')
[ "from youtube_transcript_api import YouTubeTranscriptApi\n\ntranscript_list = YouTubeTranscriptApi.list_transcripts('i8pOulVUz0A')\ntranscript = transcript_list.find_transcript(['en'])\ntranscript = transcript.fetch()\n\nwith open(\"transcript.txt\", 'w') as f:\n for line in transcript:\n f.write(line['te...
false
8,032
18c4c1e1ee0df835895397488b270a47b1620c30
with open('dwarfs.txt') as fh: i = 1 for line in fh: print("[%d] %s" % (i, line)) i += 1
[ "with open('dwarfs.txt') as fh:\n i = 1\n for line in fh:\n print(\"[%d] %s\" % (i, line))\n i += 1\n\t\t", "with open('dwarfs.txt') as fh:\n i = 1\n for line in fh:\n print('[%d] %s' % (i, line))\n i += 1\n", "<code token>\n" ]
false
8,033
08b57c00beb8dfedfee1bc032b8c281d7a151931
# Copyright (C) 2010 Google Inc. All rights reserved. # Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
[ "# Copyright (C) 2010 Google Inc. All rights reserved.\n# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistrib...
false
8,034
40e2b695d8aaaa82cb90694b85d12061b4e6eca8
import matplotlib.pyplot as plt x_int = list(range(1, 5001)) y_int = [i**3 for i in x_int] plt.scatter(x_int, y_int, c=y_int, cmap=plt.cm.Blues, s=40) plt.show()
[ "import matplotlib.pyplot as plt\n\nx_int = list(range(1, 5001))\ny_int = [i**3 for i in x_int]\n\nplt.scatter(x_int, y_int, c=y_int, cmap=plt.cm.Blues, s=40)\nplt.show()\n\n", "import matplotlib.pyplot as plt\nx_int = list(range(1, 5001))\ny_int = [(i ** 3) for i in x_int]\nplt.scatter(x_int, y_int, c=y_int, cma...
false
8,035
8d48b5b831edb62b2d9624bc23cae45d390fd224
# pylint: disable=C0103, C0413, E1101, W0611 """Covid Catcher Backend""" import os from os.path import join, dirname import json import requests import flask from flask import request import flask_sqlalchemy import flask_socketio from dotenv import load_dotenv from covid import get_covid_stats_by_state from covid impor...
[ "# pylint: disable=C0103, C0413, E1101, W0611\n\"\"\"Covid Catcher Backend\"\"\"\nimport os\nfrom os.path import join, dirname\nimport json\nimport requests\nimport flask\nfrom flask import request\nimport flask_sqlalchemy\nimport flask_socketio\nfrom dotenv import load_dotenv\nfrom covid import get_covid_stats_by_...
false
8,036
092242cdb231e09ccf3dd4dccfb6d786c3e4aad2
from django.db import models # Create your models here. class GameGenre(models.Model): genreName = models.CharField(max_length=100) genreDescription = models.CharField(max_length=300) def __str__(self): return "%s" % (self.genreName) class Game(models.Model): gameName = models.CharField(...
[ "from django.db import models\n\n# Create your models here.\n\n\nclass GameGenre(models.Model):\n\n genreName = models.CharField(max_length=100)\n genreDescription = models.CharField(max_length=300)\n\n def __str__(self):\n return \"%s\" % (self.genreName)\n\n\nclass Game(models.Model):\n\n gameN...
false
8,037
9e314cdf4ef09ecf4a4b43358ae32f76c40aaea8
import os import redis import requests import lxml.html ads_api_url = "http://adslabs.org/adsabs/api/search/" ads_html_url = "http://labs.adsabs.harvard.edu/adsabs/abs/" rdb = redis.Redis() def get_dev_key(): # Credit: Andy Casey ads_dev_key_filename = os.path.abspath( os.path.expanduser("~/.ads/dev...
[ "import os\nimport redis\nimport requests\nimport lxml.html\n\nads_api_url = \"http://adslabs.org/adsabs/api/search/\"\nads_html_url = \"http://labs.adsabs.harvard.edu/adsabs/abs/\"\n\nrdb = redis.Redis()\n\n\ndef get_dev_key():\n # Credit: Andy Casey\n ads_dev_key_filename = os.path.abspath(\n os.path...
false
8,038
92bcfff733e5f305ad1276ceb39a72a8f0fcb214
import argparse import tensorboardX as tb import torch as th import torch.nn.functional as F import torch.optim as optim import torch.utils.data as D import data import mlp import resnet import utils parser = argparse.ArgumentParser() parser.add_argument('--bst', nargs='+', type=int, help='Batch Size for Training') pa...
[ "import argparse\nimport tensorboardX as tb\nimport torch as th\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data as D\nimport data\nimport mlp\nimport resnet\nimport utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--bst', nargs='+', type=int, help='Batch Size ...
false
8,039
88390f411af90d494284617ef8f5fb0e9bb8890e
def memo(fn): cache = {} missed = object() def query(*args): result = cache.get(args, missed) if result is missed: result = cache[args] = fn(*args) return result return query @memo def cal_edit_distance(ori, tar): def edit_tuple(old, distance, path): r...
[ "def memo(fn):\n cache = {}\n missed = object()\n\n def query(*args):\n result = cache.get(args, missed)\n if result is missed:\n result = cache[args] = fn(*args)\n return result\n\n return query\n\n\n@memo\ndef cal_edit_distance(ori, tar):\n def edit_tuple(old, distan...
false
8,040
e6efd2de5f92d66f1b734a2173fc8681af3c4cc8
def myswap(a, b): temp = a a = b b = temp if a < b: print(a, b) else: print(b, a) a, b = map(int,input().split()) myswap(a,b)
[ "def myswap(a, b):\n temp = a\n a = b\n b = temp\n if a < b:\n print(a, b)\n else:\n print(b, a)\n\na, b = map(int,input().split())\n\nmyswap(a,b)", "def myswap(a, b):\n temp = a\n a = b\n b = temp\n if a < b:\n print(a, b)\n else:\n print(b, a)\n\n\na, b ...
false
8,041
ba85f3c8a9e40f30076c13487a97567f7bc646dc
import numpy as np from scipy import stats a = np.random.normal(25.0, 5.0, 10000) b = np.random.normal(26.0, 5.0, 10000) print(stats.ttest_ind(a, b)) # bad change, with a ery low chance of randomness b = np.random.normal(25.0, 5.0, 10000) print(stats.ttest_ind(a, b)) # no change, outcome is likely random
[ "import numpy as np\r\nfrom scipy import stats\r\n\r\na = np.random.normal(25.0, 5.0, 10000)\r\nb = np.random.normal(26.0, 5.0, 10000)\r\n\r\nprint(stats.ttest_ind(a, b)) # bad change, with a ery low chance of randomness\r\n\r\nb = np.random.normal(25.0, 5.0, 10000)\r\nprint(stats.ttest_ind(a, b)) # no change, outc...
false
8,042
2ec8b9a92f8dd42faf99f0cd569ebf356e12c1d6
'''It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' import common import itertools def digits(x): return set(int(d) for d in str(x)) commo...
[ "'''It can be seen that the number, 125874, and its double, 251748, contain\nexactly the same digits, but in a different order.\n\nFind the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain\nthe same digits.\n'''\n\nimport common\nimport itertools\n\ndef digits(x):\n return set(int(d) for d i...
false
8,043
b3758e42b52bb50d806832c6a3a76ae0537266de
'''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest Created 27 Aug 20 @author: rik@electronicArtifacts.com ''' from collections import defaultdict import csv import datetime import json import random import re import requests import sys import time import urllib import re PRRDateFm...
[ "'''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest\n\nCreated 27 Aug 20\n\n@author: rik@electronicArtifacts.com\n'''\n\nfrom collections import defaultdict\nimport csv\nimport datetime\nimport json\nimport random\nimport re\nimport requests\nimport sys\nimport time\nimport urllib\n...
false
8,044
63bd8a15dd489844968f46c4b0ffe157d567537a
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import pwd import sys from string import ascii_letters, digits from ConfigParser import SafeConfigParser # copied from utils, avoid circular reference fun :) def mk_boolean(value): if...
[ "\n# Make coding more python3-ish\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport os\nimport pwd\nimport sys\n\nfrom string import ascii_letters, digits\nfrom ConfigParser import SafeConfigParser\n\n# copied from utils, avoid circular reference fun :)\ndef mk_bool...
false
8,045
647258ee5f2f6f1cb8118bcf146b8959c65b70cd
import numpy as n, pylab as p from scipy import stats as st a=st.norm(0,1) b=st.norm(0.1,1) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN=n.abs(avals-bvals).max() a=st.norm(0,1) b=st.norm(0,1.2) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN2=n.abs(avals-bvals...
[ "import numpy as n, pylab as p\nfrom scipy import stats as st\na=st.norm(0,1)\nb=st.norm(0.1,1)\ndomain=n.linspace(-4,4,10000)\navals=a.cdf(domain)\nbvals=b.cdf(domain)\ndiffN=n.abs(avals-bvals).max()\n\na=st.norm(0,1)\nb=st.norm(0,1.2)\ndomain=n.linspace(-4,4,10000)\navals=a.cdf(domain)\nbvals=b.cdf(domain)\ndiffN...
false
8,046
94540561ba29d2fc1766dac7b199e0cbbbeecdfc
# name: Ali # date: 7/12/2016 # description: uses openweathermap.org's api to get weather data about # the city that is inputted # unbreakable? = idk import json import urllib2 from collections import OrderedDict from pprint import pprint api_key = "&APPID=507e30d896f751513350c41899382d89" city_name_url = "http://api....
[ "# name: Ali\n# date: 7/12/2016\n# description: uses openweathermap.org's api to get weather data about\n# the city that is inputted\n\n# unbreakable? = idk\nimport json\nimport urllib2\nfrom collections import OrderedDict\nfrom pprint import pprint\napi_key = \"&APPID=507e30d896f751513350c41899382d89\"\ncity_name_...
true
8,047
f633496f1a7cd562fd41d697a2e26831ceaef479
__all__ = ["loading"] from . import loading
[ "__all__ = [\"loading\"]\n\nfrom . import loading\n", "__all__ = ['loading']\nfrom . import loading\n", "__all__ = ['loading']\n<import token>\n", "<assignment token>\n<import token>\n" ]
false
8,048
d8df9a9f95a1d4a9aa34987ec1244cc6c0c7c610
# Generated by Django 2.0.3 on 2018-03-24 07:53 import django.core.files.storage from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('printers', '0001_initial'), ('devices', '0002_url'), ] operations = [ migration...
[ "# Generated by Django 2.0.3 on 2018-03-24 07:53\n\nimport django.core.files.storage\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('printers', '0001_initial'),\n ('devices', '0002_url'),\n ]\n\n operations =...
false
8,049
0ad71f02e37f2744036b134c33e037a724fd38a6
import numpy as np import matplotlib.pyplot as plt from PIL import Image import cv2 import openslide class QualityPatch(): def __init__(self, original_img_path,label_img_path,patch_level,patch_size): """ parameter: original_img_path(str): the source of image label_img_path(s...
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport cv2\nimport openslide\n\nclass QualityPatch():\n def __init__(self, original_img_path,label_img_path,patch_level,patch_size):\n \"\"\"\n parameter:\n original_img_path(str): the source of image\n ...
false
8,050
d520f9d681125937fbd9dff316bdc5f922f25ff3
"""Seed file to make sample data for pets db.""" from models import db, User, Feedback from app import app # Create all tables db.drop_all() db.create_all() # If table isn't empty, empty it User.query.delete() Feedback.query.delete() # Add users and posts john = User(username="John",password="123",email="24",first...
[ "\"\"\"Seed file to make sample data for pets db.\"\"\"\n\nfrom models import db, User, Feedback\nfrom app import app\n\n# Create all tables\ndb.drop_all()\ndb.create_all()\n\n# If table isn't empty, empty it\nUser.query.delete()\nFeedback.query.delete()\n\n\n# Add users and posts\njohn = User(username=\"John\",pas...
false
8,051
83815acb0520c1f8186b0b5c69f8597b1b6a552a
#! /usr/bin/env python from game_calc import * def game(screen, clock): running = True time = 0 WHITE = (255,255,255) BLUE = (0,0,205) upper_border = pygame.Rect(12,44,1000,20) right_border = pygame.Rect(992,60,20,648) left_border = pygame.Rect(12,60,20,648) down_border = pygame.Rect(12...
[ "#! /usr/bin/env python\nfrom game_calc import *\n\ndef game(screen, clock):\n running = True\n time = 0\n WHITE = (255,255,255)\n BLUE = (0,0,205)\n upper_border = pygame.Rect(12,44,1000,20)\n right_border = pygame.Rect(992,60,20,648)\n left_border = pygame.Rect(12,60,20,648)\n down_border ...
false
8,052
346df9706dc222f43a77928964cd54e7d999a585
import discord class Leveling: __slots__ = ( 'sid', 'channelID', 'message', 'noxpchannelIDs', 'noxproleID', 'remove', 'bot', 'roles') sid: int channelID: int message: str noxpchannelIDs: list[int] noxproleID: int remove: bool roles: list[list] def __init__(self, bot, sid,...
[ "import discord\n\n\nclass Leveling:\n __slots__ = (\n 'sid', 'channelID', 'message', 'noxpchannelIDs', 'noxproleID', 'remove', 'bot', 'roles')\n\n sid: int\n channelID: int\n message: str\n noxpchannelIDs: list[int]\n noxproleID: int\n remove: bool\n roles: list[list]\n\n def __in...
false
8,053
14807568af046594644095a2682e0eba4f445b26
# Write a function that receives a string as a parameter and returns a dictionary in which the keys are the characters in the character string and the values are the number of occurrences of that character in the given text. # Example: For string "Ana has apples." given as a parameter the function will return the dicti...
[ "# Write a function that receives a string as a parameter and returns a dictionary in which the keys are the characters in the character string and the values are the number of occurrences of that character in the given text.\n# Example: For string \"Ana has apples.\" given as a parameter the function will return t...
false
8,054
2fabb03f0f6b0b297245354782e650380509424b
y = 10 x = 'Тишь да гладь' print(f'Текст:{x}') print(f'Число:{y}') a1 = input('Введите первое число: ') a2 = input('Введите второе число: ') b1 = input('Введите первую строку: ') b2 = input('Введите вторую строку: ') print(f'Вы ввели числа: {a1}/{a2}') print(f'Вы ввели строки: {b1} / {b2}')
[ "y = 10\nx = 'Тишь да гладь'\nprint(f'Текст:{x}')\nprint(f'Число:{y}')\na1 = input('Введите первое число: ')\na2 = input('Введите второе число: ')\nb1 = input('Введите первую строку: ')\nb2 = input('Введите вторую строку: ')\nprint(f'Вы ввели числа: {a1}/{a2}')\nprint(f'Вы ввели строки: {b1} / {b2}')\n", "<assign...
false
8,055
d67842c05af9241dbe7e038a9b2dc4223ee7ef4d
# You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n). # In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] # (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the...
[ "# You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n).\n\n# In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] \n# (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the element...
false
8,056
a91d42764fa14111afca4551edd6c889903ed9bd
# Generated by Django 2.1.3 on 2019-01-06 06:53 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
[ "# Generated by Django 2.1.3 on 2019-01-06 06:53\n\nimport django.db.models.deletion\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL...
false
8,057
2d72f063362aaefdc236e1240020c71bacaf51cf
num = 15850 base = 16 # Primera división residuo = num % base cociente = num // base bit1 = str(residuo) bit1 = bit1.replace("10","a") bit1 = bit1.replace("11","b") bit1 = bit1.replace("12","c") bit1 = bit1.replace("13","d") bit1 = bit1.replace("14","e") bit1 = bit1.replace("15","f") # Segunda división residuo = co...
[ "num = 15850\nbase = 16\n\n# Primera división\nresiduo = num % base\ncociente = num // base\nbit1 = str(residuo)\n\nbit1 = bit1.replace(\"10\",\"a\")\nbit1 = bit1.replace(\"11\",\"b\")\nbit1 = bit1.replace(\"12\",\"c\")\nbit1 = bit1.replace(\"13\",\"d\")\nbit1 = bit1.replace(\"14\",\"e\")\nbit1 = bit1.replace(\"15\...
false
8,058
30df17d636c33d2824aad7d7ef6aae7db83615ec
# Copyright 2021 Google LLC. All Rights Reserved. # # 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 a...
[ "# Copyright 2021 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by appl...
false
8,059
aace7bc6684f4a9cec2f8fe270b5123a375780af
from string import maketrans def to_rna(str): strtrans = maketrans('ACGT', 'UGCA') return str.translate(strtrans)
[ "from string import maketrans\ndef to_rna(str):\n\tstrtrans = maketrans('ACGT', 'UGCA')\n\treturn str.translate(strtrans)\n", "from string import maketrans\n\n\ndef to_rna(str):\n strtrans = maketrans('ACGT', 'UGCA')\n return str.translate(strtrans)\n", "<import token>\n\n\ndef to_rna(str):\n strtrans ...
false
8,060
753e062940e0580d7d33c88c1165977142dcd202
#!/usr/bin/env python3 def main(): A1, A2, A3 = map(int, input().split()) A=A1+A2+A3 if A >=22: ans='bust' else: ans='win' print(ans) if __name__ == "__main__": main()
[ "#!/usr/bin/env python3\n\ndef main():\n A1, A2, A3 = map(int, input().split())\n A=A1+A2+A3\n if A >=22:\n ans='bust'\n else:\n ans='win'\n print(ans)\n \nif __name__ == \"__main__\":\n main()\n", "def main():\n A1, A2, A3 = map(int, input().split())\n A = A1 + A2 + A3\n ...
false
8,061
23a7aa6b9a98bfd4fd43fea1ecfa26cb44969804
from qcg.appscheduler.errors import * class Node: def __init__(self, name=None, totalCores=0, used=0): self.__name = name self.__totalCores = totalCores self.__usedCores = used self.resources = None def __getName(self): return self.__name def __getTotalCores(self)...
[ "from qcg.appscheduler.errors import *\n\n\nclass Node:\n def __init__(self, name=None, totalCores=0, used=0):\n self.__name = name\n self.__totalCores = totalCores\n self.__usedCores = used\n self.resources = None\n\n def __getName(self):\n return self.__name\n\n def __g...
false
8,062
bca0baaffefed6917939614defadf9960ffa4727
class Solution: # @param num, a list of integer # @return an integer def rob(self, num): n = len(num) if n == 0: return 0 if(n == 1): return num[0] f = [0] * n f[0] = num[0] f[1] = max(num[0],num[1]) for i in xrange(2,n): ...
[ "class Solution:\n # @param num, a list of integer\n # @return an integer\n def rob(self, num):\n n = len(num)\n if n == 0:\n return 0\n if(n == 1):\n return num[0]\n f = [0] * n\n f[0] = num[0]\n f[1] = max(num[0],num[1])\n for i in xr...
false
8,063
a21c132ba9f24ff2c695bf66cae074705025d6b1
#-*- coding: utf-8 -*- # Copyright (C) 2011 by # Jordi Torrents <jtorrents@milnou.net> # Aric Hagberg <hagberg@lanl.gov> # All rights reserved. # BSD license. import itertools import networkx as nx __author__ = """\n""".join(['Jordi Torrents <jtorrents@milnou.net>', 'Aric Hagb...
[ "#-*- coding: utf-8 -*-\n# Copyright (C) 2011 by\n# Jordi Torrents <jtorrents@milnou.net>\n# Aric Hagberg <hagberg@lanl.gov>\n# All rights reserved.\n# BSD license.\nimport itertools\nimport networkx as nx\n__author__ = \"\"\"\\n\"\"\".join(['Jordi Torrents <jtorrents@milnou.net>',\n ...
false
8,064
63cce356b792949b90b215e0a5826f7b33d2d375
# System import import os # Docutils import from docutils import nodes from docutils.parsers.rst.directives.admonitions import BaseAdmonition from docutils.statemachine import ViewList # Add node class link_to_block(nodes.Admonition, nodes.Element): """ Node for inserting a link to button.""" pass # Add di...
[ "# System import\nimport os\n\n# Docutils import\nfrom docutils import nodes\nfrom docutils.parsers.rst.directives.admonitions import BaseAdmonition\nfrom docutils.statemachine import ViewList\n\n\n# Add node\nclass link_to_block(nodes.Admonition, nodes.Element):\n \"\"\" Node for inserting a link to button.\"\"...
false
8,065
638842cda666100ce197437cb354f66de77eb328
from distutils.core import setup setup( name="zuknuft", version="0.1", author="riotbib", author_email="riotbib@github", scripts=["zukunft.py"], install_requires=[ 'bottle', ], )
[ "from distutils.core import setup\n\nsetup(\n name=\"zuknuft\",\n version=\"0.1\",\n author=\"riotbib\",\n author_email=\"riotbib@github\",\n scripts=[\"zukunft.py\"],\n install_requires=[\n 'bottle',\n ],\n)\n", "from distutils.core import setup\nsetup(n...
false
8,066
0bbc8aa77436193ab47c0fe8cf0d7c6dffcfe097
from marko.parser import Parser # type: ignore from marko.block import Heading, Paragraph, CodeBlock, List # type: ignore from marko.inline import CodeSpan # type: ignore from langcreator.common import Generators, InputOutputGenerator, tag_regex, get_tags, builtin_generators import collections import re def parse(...
[ "from marko.parser import Parser # type: ignore\nfrom marko.block import Heading, Paragraph, CodeBlock, List # type: ignore\nfrom marko.inline import CodeSpan # type: ignore\nfrom langcreator.common import Generators, InputOutputGenerator, tag_regex, get_tags, builtin_generators\nimport collections\nimport re\n\...
false
8,067
a33abd253288140f8051aced1d0ed1e41b2fc786
from flask import Blueprint application_vue_demo = Blueprint('application_vue_demo', __name__) from. import views
[ "from flask import Blueprint\napplication_vue_demo = Blueprint('application_vue_demo', __name__)\n\nfrom. import views\n", "from flask import Blueprint\napplication_vue_demo = Blueprint('application_vue_demo', __name__)\nfrom . import views\n", "<import token>\napplication_vue_demo = Blueprint('application_vue_...
false
8,068
3c6ef57501e01da79f894b36726a93a3a5e0a8f6
# RUSH HOUR m = int(input('Enter number of males:')) f = int(input('Enter number of females:')) if m%20 == 0: m2 = m//20 c = 20 else: m2 = m//20+1 c = m%20 f2 = f - 10*m2 if f2 <= 0 or f2-(20-c) <=0: print('Number of trains needed: '+str(m2)) else: print('Number of trains ...
[ "# RUSH HOUR\r\nm = int(input('Enter number of males:'))\r\nf = int(input('Enter number of females:'))\r\n\r\n\r\nif m%20 == 0:\r\n m2 = m//20\r\n c = 20\r\nelse:\r\n m2 = m//20+1\r\n c = m%20\r\n\r\n\r\nf2 = f - 10*m2\r\n\r\nif f2 <= 0 or f2-(20-c) <=0:\r\n print('Number of trains needed: '+str(m2))...
false
8,069
c716f43dbe62f662c60653f09be946a27c3fff66
import Adafruit_BBIO.GPIO as GPIO from pydrs import SerialDRS import time import sys sys.dont_write_bytecode = True class SyncRecv: def __init__(self): self._comport = '/dev/ttyUSB0' self._baudrate = '115200' self._epwm_sync_pin = 'GPIO2_23' # Input in BBB perspective ...
[ "import Adafruit_BBIO.GPIO as GPIO\nfrom pydrs import SerialDRS\nimport time\nimport sys\n\nsys.dont_write_bytecode = True\n\nclass SyncRecv:\n\n def __init__(self):\n self._comport = '/dev/ttyUSB0'\n self._baudrate = '115200'\n self._epwm_sync_pin = 'GPIO2_23' # Input in BBB p...
false
8,070
3e8fa71c4e23348c6f00fe97729b5717bb6245a1
''' held-karp.py Implementation of the Bellman-Held-Karp Algorithm to exactly solve TSPs, requiring no external dependencies. Includes a purely recursive implementation, as well as both top-down and bottom-up dynamic programming approaches. ''' import sys def held_karp_recursive(distance_matrix): ''' Soluti...
[ "'''\nheld-karp.py\n\nImplementation of the Bellman-Held-Karp Algorithm to exactly solve TSPs,\nrequiring no external dependencies.\n\nIncludes a purely recursive implementation, as well as both top-down and\nbottom-up dynamic programming approaches.\n'''\nimport sys\n\n\ndef held_karp_recursive(distance_matrix):\n...
false
8,071
9d4559a363c4fd6f9a22dc493a7aaa0a22386c21
import pandas as pd from pymongo import MongoClient import numpy as np mongo_client = MongoClient('localhost', 27018) mongo_db = mongo_client['ProjetoIN242'] mongo_collection = mongo_db['contadorpessoas'] query = mongo_collection.find({}) df = pd.DataFrame.from_records(query) df_filtro = df[['Entrada','Dia', 'Quant...
[ "import pandas as pd\nfrom pymongo import MongoClient\nimport numpy as np\n\nmongo_client = MongoClient('localhost', 27018)\nmongo_db = mongo_client['ProjetoIN242']\nmongo_collection = mongo_db['contadorpessoas']\n\nquery = mongo_collection.find({})\n\ndf = pd.DataFrame.from_records(query)\n\ndf_filtro = df[['Entra...
false
8,072
5cd573f2b7f91a8b20e96deb1004c0ef7fc62398
from funct import read_excel import requests import unittest import HTMLTestReportCN class v2exapi(unittest.TestCase): def test_node_api(self): url = "https://www.v2ex.com/api/nodes/show.json" #querystring = {"name":"php"} a=read_excel("xx.xlsx",0,0) for node_name in a: #fo...
[ "from funct import read_excel\nimport requests\nimport unittest\nimport HTMLTestReportCN\nclass v2exapi(unittest.TestCase):\n def test_node_api(self):\n url = \"https://www.v2ex.com/api/nodes/show.json\"\n\n #querystring = {\"name\":\"php\"}\n a=read_excel(\"xx.xlsx\",0,0)\n for node...
false
8,073
e14c7eb11c06d6de5c2f9f8adfb8b742fcb432e1
#!/usr/bin/env python """ haxor Unofficial Python wrapper for official Hacker News API @author avinash sajjanshetty @email hi@avi.im """ from __future__ import absolute_import from __future__ import unicode_literals import datetime import json import sys import requests from .settings import supported_api_versions...
[ "#!/usr/bin/env python\n\n\"\"\"\nhaxor\nUnofficial Python wrapper for official Hacker News API\n\n@author avinash sajjanshetty\n@email hi@avi.im\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nimport datetime\nimport json\nimport sys\n\nimport requests\n\nfrom .settings ...
false
8,074
02230b44568808757fe45fd18d28881d9bc3e410
#!/usr/bin/env python # encoding: utf-8 import tweepy #https://github.com/tweepy/tweepy import csv import scraperwiki import json #Twitter API credentials - these need adding consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" def get_all_tweets(screen_name): #Twitter only allows access to a ...
[ "#!/usr/bin/env python\n# encoding: utf-8\n\nimport tweepy #https://github.com/tweepy/tweepy\nimport csv\nimport scraperwiki\nimport json\n\n#Twitter API credentials - these need adding\nconsumer_key = \"\"\nconsumer_secret = \"\"\naccess_key = \"\"\naccess_secret = \"\"\n\n\ndef get_all_tweets(screen_name):\n\t#Tw...
true
8,075
c81889cf4d87933b562aa4618bc5185a8d213107
#! /usr/bin/env python import os import re from codecs import open from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) def get_changelog(): with open(os.path.join(here, 'CHANGELOG'), encoding='utf-8') as f: text = f.read() header_matches = list(re.finditer...
[ "#! /usr/bin/env python\n\nimport os\nimport re\n\nfrom codecs import open\n\nfrom setuptools import find_packages, setup\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef get_changelog():\n with open(os.path.join(here, 'CHANGELOG'), encoding='utf-8') as f:\n text = f.read()\n header_matche...
false
8,076
e4ff6d689a7da5b16786fd59d6a4707b9b6e3e7d
import os error_msg = '''The default transformer cannot handle slashes (subdirectories); try another transformer in vlermv.transformers.''' def to_path(key): if isinstance(key, tuple): if len(key) == 1: key = key[0] else: raise ValueError(error_msg) if '/' in key or '\...
[ "import os\n\nerror_msg = '''The default transformer cannot handle slashes (subdirectories);\ntry another transformer in vlermv.transformers.'''\n\ndef to_path(key):\n if isinstance(key, tuple):\n if len(key) == 1:\n key = key[0]\n else:\n raise ValueError(error_msg)\n\n if...
false
8,077
be63e8e6e98c9afed66cae033a7f41f1be1561a8
#!/usr/bin/python3 import tkinter from PIL import Image, ImageTk import requests from io import BytesIO from threading import Timer rootWindow = tkinter.Tk() # the following makes the program full-screen RWidth = rootWindow.winfo_screenwidth() RHeight = rootWindow.winfo_screenheight() # rootWindow.overrideredirect(...
[ "#!/usr/bin/python3\n\nimport tkinter\nfrom PIL import Image, ImageTk\nimport requests\nfrom io import BytesIO\nfrom threading import Timer\n\n\nrootWindow = tkinter.Tk()\n\n# the following makes the program full-screen\nRWidth = rootWindow.winfo_screenwidth()\nRHeight = rootWindow.winfo_screenheight()\n#\nrootWind...
false
8,078
0ef03ed455938bd2001581986c38104bfac395ce
# leetcode 836 # determine if two rectangles overlap # input is two lists [x1,y1,x2,y2] coordinates # where x1,y1 are coordinates of bottom left corner # and x2,y2 are coordinates of top right corner def overlap_rect(rec1, rec2): """Determine if rectangles overlap.""" # true if rec2 is left of rec1 a = rec...
[ "# leetcode 836\n# determine if two rectangles overlap\n# input is two lists [x1,y1,x2,y2] coordinates\n# where x1,y1 are coordinates of bottom left corner\n# and x2,y2 are coordinates of top right corner\n\ndef overlap_rect(rec1, rec2):\n \"\"\"Determine if rectangles overlap.\"\"\"\n # true if rec2 is left ...
false
8,079
bf9e83591f737caec3060b72d86d56faec9bb23b
# 5. Усовершенствовать программу «Банковский депозит». Третьим аргументом в функцию должна # передаваться фиксированная ежемесячная сумма пополнения вклада. Необходимо в главной # функции реализовать вложенную функцию подсчета процентов для пополняемой суммы. # Примем, что клиент вносит средства в последний день каж...
[ "# 5. Усовершенствовать программу «Банковский депозит». Третьим аргументом в функцию должна\r\n# передаваться фиксированная ежемесячная сумма пополнения вклада. Необходимо в главной\r\n# функции реализовать вложенную функцию подсчета процентов для пополняемой суммы.\r\n# Примем, что клиент вносит средства в последн...
false
8,080
59b2d0ff3296c9d9a76b8b69a784d5a0c46128be
''' XFA/XDP DOM in Javascript This file is part of the phoneyPDF Framework This module provides methods for transforming both PDF objects and XML (xfa/xdp) into a single structure of linked objects in javascript. The idea is that any *DOM interation will play out in javascript land, where the DOMs are created and main...
[ "'''\nXFA/XDP DOM in Javascript\nThis file is part of the phoneyPDF Framework\n\nThis module provides methods for transforming both PDF objects and XML (xfa/xdp) into a single structure of linked objects\nin javascript. The idea is that any *DOM interation will play out in javascript land, where the DOMs are create...
true
8,081
9d772d5500593583907b65bc2c81490e61375e8b
class TimeInterval(object): def __init__(self, start_time, end_time): self.start_time = start_time self.end_time = end_time
[ "class TimeInterval(object):\n def __init__(self, start_time, end_time):\n self.start_time = start_time\n self.end_time = end_time\n", "class TimeInterval(object):\n\n def __init__(self, start_time, end_time):\n self.start_time = start_time\n self.end_time = end_time\n", "class...
false
8,082
9bb15842b39c7fd3e6f6c0048a51c2b2112ddb94
from django.db import models from django.contrib.auth.models import User from django.utils.encoding import smart_unicode from django.core.validators import MinValueValidator from django.utils import timezone from concurrency.fields import IntegerVersionField class ProductCategory(models.Model): name = models.Char...
[ "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.encoding import smart_unicode\nfrom django.core.validators import MinValueValidator\nfrom django.utils import timezone\nfrom concurrency.fields import IntegerVersionField\n\n\nclass ProductCategory(models.Model):\n name...
false
8,083
592f29f08637e511bd7d49a3b58f69b700721d89
def alt(h, dt): t=0 while True: t=t+1 a=(-6)*(t**4)+ h*(t**3)+2*(t**2)+t if a<=0: print('The balloon first touches ground at hour:') print(t) break elif t==dt: print('The balloon does not touch ground in the given tim...
[ "def alt(h, dt):\n t=0\n while True:\n t=t+1\n a=(-6)*(t**4)+ h*(t**3)+2*(t**2)+t\n \n if a<=0:\n print('The balloon first touches ground at hour:')\n print(t)\n break\n elif t==dt:\n print('The balloon does not touch ground ...
false
8,084
312a95c9514722157653365104d8cd0ada760ce8
"""URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based ...
[ "\"\"\"URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name...
false
8,085
fdae984f7cf5e1c20dee197d3f2518a0c7c38bdc
from time import sleep from uuid import uuid1 from pprint import pprint from shutil import copy2 from multiprocessing import Process, Queue, Pool, Manager from ad_grabber_classes import * from adregex import * from pygraph.classes.digraph import digraph import os import json import jsonpickle import subprocess import ...
[ "from time import sleep\nfrom uuid import uuid1\nfrom pprint import pprint\nfrom shutil import copy2\nfrom multiprocessing import Process, Queue, Pool, Manager\nfrom ad_grabber_classes import *\nfrom adregex import *\nfrom pygraph.classes.digraph import digraph\n\nimport os\nimport json\nimport jsonpickle\nimport s...
false
8,086
cf5062c999c6c29f103428c247d8d1a4550f9d75
file = open('thegazelle.wordpress.2016-06-22.xml', 'r') text = file.read() authors = [] start = text.find("<wp:author_display_name>") length = len("<wp:author_display_name>") end = text.find("</wp:author_display_name") authors.append(text[start+length+len("<![CDATA["):end-len("]]>")]) while text.find("<wp:author_displa...
[ "file = open('thegazelle.wordpress.2016-06-22.xml', 'r')\ntext = file.read()\nauthors = []\nstart = text.find(\"<wp:author_display_name>\")\nlength = len(\"<wp:author_display_name>\")\nend = text.find(\"</wp:author_display_name\")\nauthors.append(text[start+length+len(\"<![CDATA[\"):end-len(\"]]>\")])\nwhile text.f...
false
8,087
7d173b0571c20dc8fcae884451e8f69ba3a05763
from __future__ import print_function import os import re import xml.etree.ElementTree as ET def read_vivado_report(hls_dir, full_report=False): if not os.path.exists(hls_dir): print('Path {} does not exist. Exiting.'.format(hls_dir)) return prj_dir = None top_func_name = None if os.p...
[ "from __future__ import print_function\nimport os\nimport re\nimport xml.etree.ElementTree as ET\n\ndef read_vivado_report(hls_dir, full_report=False):\n if not os.path.exists(hls_dir):\n print('Path {} does not exist. Exiting.'.format(hls_dir))\n return\n\n prj_dir = None\n top_func_name = N...
false
8,088
c7c405535b2ca656d4d5f18013e3e2fdef70efea
""" 1. Если в строке больше символов в нижнем регистре - вывести все в нижнем, если больше в верхнем - вывести все в верхнем, если поровну - вывести в противоположных регистрах. 2. Если в строке каждое слово начинается с заглавной буквы, тогда добавить в начало строки 'done. '. И...
[ "\"\"\"\n 1. Если в строке больше символов в нижнем регистре - вывести все в нижнем,\n если больше в верхнем - вывести все в верхнем,\n если поровну - вывести в противоположных регистрах.\n 2. Если в строке каждое слово начинается с заглавной буквы, тогда\n добавить в начало строки 'done....
false
8,089
d726e468a9df26f1bcb8a016812b87fad7b41aa8
from brie.config import ldap_config from brie.model.ldap import * from brie.lib.log_helper import BrieLogging import datetime import smtplib class Residences: @staticmethod def get_dn_by_name(user_session, name): result = user_session.ldap_bind.search_first(ldap_config.liste_residence_dn, "(cn=" +...
[ "from brie.config import ldap_config\nfrom brie.model.ldap import *\nfrom brie.lib.log_helper import BrieLogging\nimport datetime\nimport smtplib\n\nclass Residences:\n \n @staticmethod\n def get_dn_by_name(user_session, name):\n result = user_session.ldap_bind.search_first(ldap_config.liste_residen...
false
8,090
3752b68e151379c57e1494715a45172607f4aead
# file = open('suifeng.txt') # # text = file.read() # # print(text) # # file.close() # with open('suifeng.txt') as f: # print(f.read()) newList=[] for i in range(11): newList.append(i*2) print(newList) newList2=[i*2 for i in range(11)] print(newList2) list = ["小米","王银龙","王思"] emptyList=[] for name in list...
[ "# file = open('suifeng.txt')\n# # text = file.read()\n# # print(text)\n# # file.close()\n\n# with open('suifeng.txt') as f:\n# print(f.read())\n\n\nnewList=[]\nfor i in range(11):\n newList.append(i*2)\nprint(newList)\n\nnewList2=[i*2 for i in range(11)]\nprint(newList2)\n\n\nlist = [\"小米\",\"王银龙\",\"王思\"]\...
false
8,091
ca551d8e55ebb15a03077af5695782c6d72ff2fd
"""Command line interface to the OSF These functions implement the functionality of the command-line interface. """ from __future__ import print_function from functools import wraps import getpass import os import sys from six.moves import configparser from six.moves import input from tqdm import tqdm from .api im...
[ "\"\"\"Command line interface to the OSF\n\nThese functions implement the functionality of the command-line interface.\n\"\"\"\nfrom __future__ import print_function\n\nfrom functools import wraps\nimport getpass\nimport os\nimport sys\n\nfrom six.moves import configparser\nfrom six.moves import input\n\nfrom tqdm ...
false
8,092
3f20438b0dd2ae8de470e5456dbb764eabf69645
import types import qt cfg = qt.cfgman cfg.remove_cfg('protocols') cfg.remove_cfg('samples') cfg.remove_cfg('setup') cfg.add_cfg('protocols') cfg.add_cfg('samples') cfg.add_cfg('setup') cfg['samples']['current'] = 'hans-sil13' cfg['protocols']['current'] = 'hans-sil13-default' print 'updating msmt params for {}'.for...
[ "import types\nimport qt\ncfg = qt.cfgman\n\ncfg.remove_cfg('protocols')\ncfg.remove_cfg('samples')\ncfg.remove_cfg('setup')\ncfg.add_cfg('protocols')\ncfg.add_cfg('samples')\ncfg.add_cfg('setup')\n\ncfg['samples']['current'] = 'hans-sil13'\ncfg['protocols']['current'] = 'hans-sil13-default'\n\nprint 'updating msmt...
true
8,093
e239c2089fc6d4ab646c490b6e3de8953cec5634
from typing import Sequence, Union, Tuple import kdtree from colour import Color AnsiCodeType = Union[str, int, Tuple[int, int, int]] class ColorPoint(object): def __init__(self, source: Color, target: Color, ansi: AnsiCodeType) -> None: """ Map source color to target color, st...
[ "from typing import Sequence, Union, Tuple\n\nimport kdtree\n\nfrom colour import Color\n\nAnsiCodeType = Union[str, int, Tuple[int, int, int]]\n\n\nclass ColorPoint(object):\n def __init__(self, source: Color, target: Color,\n ansi: AnsiCodeType) -> None:\n \"\"\"\n Map source colo...
false
8,094
e57109f1c5c2e1468ef1cf9f10fba743633ca150
from discord.ext import commands, tasks from discord.utils import get import discord import re import json import time import random import asyncio import os import datetime from live_ticker_scrape import wrangle_data from tokens import dev, dev1, es, nas, dow, us10y, dollar, vix, btc, eth, silver , link es_bot = d...
[ "from discord.ext import commands, tasks\nfrom discord.utils import get\nimport discord\nimport re\nimport json \nimport time \nimport random\nimport asyncio\nimport os\nimport datetime\n\nfrom live_ticker_scrape import wrangle_data\nfrom tokens import dev, dev1, es, nas, dow, us10y, dollar, vix, btc, eth, silver ,...
false
8,095
4ce1e802831f09e503d18fd287cb35400986e3c8
#! /usr/bin/env python # -*- coding: utf-8 -*- # auther : xiaojinsong(61627515@qq.com) parts = ['Is', 'Chicago', 'Not', 'Chicago?'] data = ['ACME', 50, 91.1] print(' '.join(parts)) def generate_str(): print(','.join(str(d) for d in data)) def sample(): yield 'Is' yield 'Chicago' yield 'Not' yi...
[ "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# auther : xiaojinsong(61627515@qq.com)\n\n\nparts = ['Is', 'Chicago', 'Not', 'Chicago?']\ndata = ['ACME', 50, 91.1]\nprint(' '.join(parts))\n\n\ndef generate_str():\n print(','.join(str(d) for d in data))\n\n\ndef sample():\n yield 'Is'\n yield 'Chicago'\n...
false
8,096
8439972b4458ba66d98f6a80a82a35576df472a4
from channels.routing import route from .consumers import message_consumer channel_routing = [ route("slack.rtm.message", message_consumer) ]
[ "from channels.routing import route\nfrom .consumers import message_consumer\n\nchannel_routing = [\n route(\"slack.rtm.message\", message_consumer)\n]", "from channels.routing import route\nfrom .consumers import message_consumer\nchannel_routing = [route('slack.rtm.message', message_consumer)]\n", "<import...
false
8,097
11e9e4dd5c9c6158fed40080d4cc221f28a0eba0
#!/usr/bin/python import sys import os class ParseError(Exception): pass def remove_inline_comments(text): ret = [] in_comment_block = False p = 0 while True: if (op := text.find('/*', p)) > 0: in_comment_block = True if op != p: ret.append(text[p...
[ "#!/usr/bin/python\n\nimport sys\nimport os\n\n\nclass ParseError(Exception):\n pass\n\n\ndef remove_inline_comments(text):\n ret = []\n in_comment_block = False\n p = 0\n while True:\n if (op := text.find('/*', p)) > 0:\n in_comment_block = True\n if op != p:\n ...
false
8,098
5f4abc7e9397034737ee214b0d0aae39ebf1548b
#!/usr/bin/env python # pylama:ignore=E221,E251 from setuptools import find_packages, setup setup( name = 'coding_exercises', version = '1.0', description = 'Coding Exercises in Python', author = 'Gustavo Gama', author_email = 'gustavo.gama@gmail.com', url = 'https...
[ "#!/usr/bin/env python\n# pylama:ignore=E221,E251\n\nfrom setuptools import find_packages, setup\n\nsetup(\n name = 'coding_exercises',\n version = '1.0',\n description = 'Coding Exercises in Python',\n author = 'Gustavo Gama',\n author_email = 'gustavo.gama@gmail.com',\n url ...
false
8,099
3f92bf194058c97a40cd5728cfc7c9d1be6b2548
import os import sys import time from collections import deque import pickle import random import string from tensorflow.python.framework.errors import InvalidArgumentError from baselines.ddpg.ddpg import DDPG import baselines.common.tf_util as U from baselines.ddpg import prosthetics_env from baselines import logger...
[ "import os\nimport sys\nimport time\nfrom collections import deque\nimport pickle\nimport random\nimport string\nfrom tensorflow.python.framework.errors import InvalidArgumentError\n\nfrom baselines.ddpg.ddpg import DDPG\nimport baselines.common.tf_util as U\nfrom baselines.ddpg import prosthetics_env\n\nfrom basel...
false