index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
3,600
fb92912e1a752f3766f9439f75ca28379e23823f
REDIRECT_MAP = { '90':'19904201', '91':'19903329', '92':'19899125', '93':'19901043', '94':'19903192', '95':'19899788', '97':'19904423', '98':'19906163', '99':'19905540', '100':'19907871', '101':'19908147', '102':'19910103', '103':'19909980', '104':'19911813', ...
[ "REDIRECT_MAP = {\n '90':'19904201',\n '91':'19903329',\n '92':'19899125',\n '93':'19901043',\n '94':'19903192',\n '95':'19899788',\n '97':'19904423',\n '98':'19906163',\n '99':'19905540',\n '100':'19907871',\n '101':'19908147',\n '102':'19910103',\n '103':'19909980',\n '10...
false
3,601
f29d377e8a8fd6d2e156da665478d7a4c167f7d5
import gdalnumeric #Input File src = "../dati/islands/islands.tif" #Output tgt = "../dati/islands/islands_classified.jpg" srcArr = gdalnumeric.LoadFile(src) classes = gdalnumeric.numpy.histogram(srcArr,bins=2)[1] print classes #Color look-up table (LUT) - must be len(classes)+1. #Specified as R,G,B tuples lut = [[...
[ "import gdalnumeric\n\n#Input File\nsrc = \"../dati/islands/islands.tif\"\n\n#Output\ntgt = \"../dati/islands/islands_classified.jpg\"\n\nsrcArr = gdalnumeric.LoadFile(src)\n\nclasses = gdalnumeric.numpy.histogram(srcArr,bins=2)[1]\nprint classes\n\n#Color look-up table (LUT) - must be len(classes)+1.\n#Specified a...
true
3,602
2d4b0e7b430ffb5d236300079ded4b848e6c6485
print raw_input().count(raw_input())
[ "print raw_input().count(raw_input())" ]
true
3,603
d7653a205fb8203fed4009846780c63dd1bcb505
import csv import sys if len(sys.argv[1:]) == 5 : (name_pos, start_pos, length_pos, first_note_pos, second_note_pos) = [int(pos) for pos in sys.argv[1:]] elif len(sys.argv[1:]) == 4 : (name_pos, start_pos, length_pos, first_note_pos) = [int(pos) for pos in sys.argv[1:]] second_note_pos = None e...
[ "import csv\nimport sys\n\nif len(sys.argv[1:]) == 5 :\n (name_pos, start_pos, length_pos, \n first_note_pos, second_note_pos) = [int(pos) for pos in sys.argv[1:]]\nelif len(sys.argv[1:]) == 4 :\n (name_pos, start_pos, length_pos, \n first_note_pos) = [int(pos) for pos in sys.argv[1:]]\n second_not...
false
3,604
84f6336261e1c276f029822754842514715791df
from unittest import TestCase from spiral.spiral_matrix import SpiralMatrix class TestOutwardCounterClockwise(TestCase): def test_traverse_empty(self): matrix = [] actual = [i for i in SpiralMatrix(matrix, clockwise=False, inward=False)] self.assertEqual([], actual) def test_traverse_...
[ "from unittest import TestCase\nfrom spiral.spiral_matrix import SpiralMatrix\n\n\nclass TestOutwardCounterClockwise(TestCase):\n def test_traverse_empty(self):\n matrix = []\n actual = [i for i in SpiralMatrix(matrix, clockwise=False, inward=False)]\n self.assertEqual([], actual)\n\n def...
false
3,605
fc01c6fb812fe78ca04496494d68fcc90ae706f5
import numpy as np def shufflelists(lists): li = np.random.permutation(len(lists[0]) lo = [] for i in range(len(li)):
[ "import numpy as np\n\ndef shufflelists(lists):\n li = np.random.permutation(len(lists[0])\n lo = []\n for i in range(len(li)):\n \n" ]
true
3,606
9a7908212bf13565109cd4d9ab6de65909bc6910
# Copyright 2014 Charles Noneman # # 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 writin...
[ "# Copyright 2014 Charles Noneman\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agre...
false
3,607
78c8f953b924f3e664570b844bf736a788e9cfb7
from distutils.core import setup, Extension setup(name='supermodule', version='1.0', \ ext_modules=[Extension('supermodule', ['main.c'])])
[ "from distutils.core import setup, Extension\nsetup(name='supermodule', version='1.0', \\\n ext_modules=[Extension('supermodule', ['main.c'])])\n", "from distutils.core import setup, Extension\nsetup(name='supermodule', version='1.0', ext_modules=[Extension(\n 'supermodule', ['main.c'])])\n", "<import ...
false
3,608
88862d6bee5d83dd5f1c656a06a9dc46a5254b10
import math import operator as op Symbol = str Number = (int, float) Atom = (Symbol, Number) List = list Exp = (Atom, List) Env = dict def standard_env() -> Env: "An environment with some scheme standard procedures" env = Env() env.update(vars(math)) # sin, cos, sqrt, pi ... env.update({ ...
[ "import math\nimport operator as op\n\nSymbol = str\nNumber = (int, float)\nAtom = (Symbol, Number)\nList = list\nExp = (Atom, List)\nEnv = dict\n\ndef standard_env() -> Env:\n \"An environment with some scheme standard procedures\"\n env = Env()\n env.update(vars(math)) # sin, cos, sqrt, pi ...\...
false
3,609
18be97061c65185fcebf10c628e0e51bb08522cf
import torch import argparse from DialogGenerator import DialogGenerator from DialogDataset import DialogDataset from DialogDiscriminator import DialogDiscriminator from transformers import GPT2Tokenizer import os def prep_folder(args): """ Append to slash to filepath if needed, and generate folder if it doesn't e...
[ "import torch\nimport argparse\nfrom DialogGenerator import DialogGenerator\nfrom DialogDataset import DialogDataset\nfrom DialogDiscriminator import DialogDiscriminator\nfrom transformers import GPT2Tokenizer\nimport os\n\ndef prep_folder(args):\n \"\"\" Append to slash to filepath if needed, and generate folde...
false
3,610
68dcac07bbdb4dde983939be98ece127d963c254
"""Google Scraper Usage: web_scraper.py <search> <pages> <processes> web_scraper.py (-h | --help) Arguments: <search> String to be Searched <pages> Number of pages <processes> Number of parallel processes Options: -h, --help Show this screen. """ import re from functools impo...
[ "\"\"\"Google Scraper\n \nUsage:\n web_scraper.py <search> <pages> <processes>\n web_scraper.py (-h | --help)\n \nArguments:\n <search> String to be Searched\n <pages> Number of pages\n <processes> Number of parallel processes\n \nOptions:\n -h, --help Show this screen.\n \n\"\"\"\n\nim...
false
3,611
5db450424dc143443839e24801ece444d0d7e162
# Generated by Django 3.2 on 2021-06-28 04:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rrhh', '0014_alter_detallepermiso_fecha_permiso'), ] operations = [ migrations.AlterField( model_name='permiso', name=...
[ "# Generated by Django 3.2 on 2021-06-28 04:32\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rrhh', '0014_alter_detallepermiso_fecha_permiso'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='permiso',...
false
3,612
5b6ed75279b39a1dad1bf92535c4b129bb599350
class Solution: """ https://leetcode.com/problems/game-of-life/ 289. Game of Life Medium -------------------- According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." Given a ...
[ "class Solution:\n \"\"\"\n https://leetcode.com/problems/game-of-life/\n 289. Game of Life\n Medium\n --------------------\n According to the Wikipedia's article: \"The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970...
false
3,613
3cac7829cf0c07ddc704a25ec3c781c9510a8e0c
__version__ = '18.07.0'
[ "__version__ = '18.07.0'", "__version__ = '18.07.0'\n", "<assignment token>\n" ]
false
3,614
5efb8151375d705f3591921654f847e45b6927c9
""" You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the stri...
[ "\"\"\"\nYou are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.\n\nReturn true if it is possible to make both strings equal by performing at most one string swap on exactly one ...
false
3,615
efa06d929e76a255afd9923b5340252c291a325c
import sys from collections import defaultdict sys.setrecursionlimit(1200) def dfs(G, v, prev): t = [] s = 0 for x in G[v]: if x == prev: continue tmp = dfs(G, x, v) s += tmp[1] t.append(tmp[0] - tmp[1]) t.sort() t = t[:2] if len(t) < 2: return (s...
[ "import sys\nfrom collections import defaultdict\nsys.setrecursionlimit(1200)\n\ndef dfs(G, v, prev):\n t = []\n s = 0\n for x in G[v]:\n if x == prev: continue\n tmp = dfs(G, x, v)\n s += tmp[1]\n t.append(tmp[0] - tmp[1])\n t.sort()\n t = t[:2]\n if len(t) < 2...
true
3,616
2962ef1d7ecd4e8d472b9dc36664e4e8745391fd
from keras.preprocessing.text import text_to_word_sequence from keras.models import Sequential from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent, Embedding from keras.layers.recurrent import LSTM from keras.optimizers import Adam, RMSprop #from nltk import FreqDist import numpy as np ...
[ "from keras.preprocessing.text import text_to_word_sequence\nfrom keras.models import Sequential\nfrom keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent, Embedding\nfrom keras.layers.recurrent import LSTM\nfrom keras.optimizers import Adam, RMSprop\n#from nltk import FreqDist\nimport n...
false
3,617
be90447eb7c717ae0bae28fd7f10238be733648d
import json from tqdm import tqdm from topic.topic import get_topic_scores, get_topic_similarity user_weights = json.load(open('data/selected_user_weights.json', 'r', encoding='utf8')) reviews = json.load(open('data/business_reviews_test.json', 'r', encoding='utf8')) for business, business_reviews in reviews.items(...
[ "import json\n\nfrom tqdm import tqdm\n\nfrom topic.topic import get_topic_scores, get_topic_similarity\n\nuser_weights = json.load(open('data/selected_user_weights.json', 'r', encoding='utf8'))\nreviews = json.load(open('data/business_reviews_test.json', 'r', encoding='utf8'))\n\nfor business, business_reviews in ...
false
3,618
6add599035573842475c7f9155c5dbbea6c96a8a
from pyathena import connect from Config import config2 from Config import merchants def get_mapped_sku(sku): try: cursor = connect(aws_access_key_id=config2["aws_access_key_id"], aws_secret_access_key=config2["aws_secret_access_key"], s3_staging_dir=confi...
[ "from pyathena import connect\nfrom Config import config2\nfrom Config import merchants\n\n\ndef get_mapped_sku(sku):\n try:\n cursor = connect(aws_access_key_id=config2[\"aws_access_key_id\"],\n aws_secret_access_key=config2[\"aws_secret_access_key\"],\n s3...
false
3,619
71ffad81bcbc480dc0a750680bc72e1d5c48556a
# Generated by Django 2.1.5 on 2021-06-01 19:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('fotbal', '0008_auto_20210601_2109'), ] operations = [ migrations.RemoveField( model_name='komenty', name='jmeno', ),...
[ "# Generated by Django 2.1.5 on 2021-06-01 19:16\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('fotbal', '0008_auto_20210601_2109'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='komenty',\n name=...
false
3,620
b355bd5a519d65ea35d4e8d5e6a384424d79130a
# Write a class to hold player information, e.g. what room they are in # currently. class Player(): def __init__(self, name, location, items=[]): self.name = name self.location = location self.items = items # def try_direction(self, user_action): # attribute = user_action + '_...
[ "# Write a class to hold player information, e.g. what room they are in\n# currently.\n\n\nclass Player():\n def __init__(self, name, location, items=[]):\n self.name = name\n self.location = location\n self.items = items\n\n # def try_direction(self, user_action):\n # attribute = ...
false
3,621
259a4bb39496bdfc71d60edb4994d26351c6961d
class Patient(object): def __init__(self, id_number, name, bed_number, *allergies): self.id_number = id_number self.name = name self.allergies = allergies self.bed_number = bed_number class Hospital(object): def __init__(self, name, capacity): self.patients = [] ...
[ "class Patient(object):\r\n def __init__(self, id_number, name, bed_number, *allergies):\r\n self.id_number = id_number\r\n self.name = name\r\n self.allergies = allergies\r\n self.bed_number = bed_number\r\nclass Hospital(object):\r\n def __init__(self, name, capacity):\r\n ...
true
3,622
5c1d1eafb913822be9b6e46b15c6886f8bf3e2e1
from flask import Flask, json, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow import warnings app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:1234@localhost/escuela' app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False db = SQLAlche...
[ "from flask import Flask, json, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nimport warnings\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:1234@localhost/escuela'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False\n\...
false
3,623
7a41826f65f2f55b4c678df2ac06027df6ca50d4
__author__ = 'piotrek' import os import zipfile import tarfile from PyQt5 import QtWidgets from PyQt5 import QtGui from PyQt5 import QtCore from Widgets.list_view import ListView from Threads.PackThread import PackThread class CreateArchive(QtWidgets.QDialog): def __init__(self, model, index, path, parent=Non...
[ "__author__ = 'piotrek'\n\nimport os\nimport zipfile\nimport tarfile\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5 import QtGui\nfrom PyQt5 import QtCore\n\nfrom Widgets.list_view import ListView\nfrom Threads.PackThread import PackThread\n\n\nclass CreateArchive(QtWidgets.QDialog):\n\n def __init__(self, model, in...
false
3,624
4c59e5fab2469af3f40cafaac226a993f6628290
import json import tempfile import zipfile from contextlib import contextmanager from utils import ( codepipeline_lambda_handler, create_zip_file, get_artifact_s3_client, get_cloudformation_template, get_input_artifact_location, get_output_artifact_location, get_session, get_user_parame...
[ "import json\nimport tempfile\nimport zipfile\nfrom contextlib import contextmanager\n\nfrom utils import (\n codepipeline_lambda_handler,\n create_zip_file,\n get_artifact_s3_client,\n get_cloudformation_template,\n get_input_artifact_location,\n get_output_artifact_location,\n get_session,\n ...
false
3,625
4243c863827f1378c364171ca7d8fdabd42be22f
#!/usr/bin/env python #pylint: skip-file """ HostApi.py Copyright 2016 Cisco Systems 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...
[ "#!/usr/bin/env python\n#pylint: skip-file\n\"\"\"\nHostApi.py\n Copyright 2016 Cisco Systems\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.or...
false
3,626
35288c9ad4d3550003e3c2f9e9034f4bce1df830
# -*- coding: utf-8 -*- """ Created on Wed Jul 15 19:27:59 2020 @author: Dan """ import numpy as np def shift(v,i,j): if i <= j: return v store = v[i] for k in range(0, i-j-1): v[i-k] = v[i-k-1] v[j] = store return v def insertion(v): for i in range(1, len(v)): j = i ...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 15 19:27:59 2020\n\n@author: Dan\n\"\"\"\n\nimport numpy as np\n\ndef shift(v,i,j):\n if i <= j:\n return v\n store = v[i]\n for k in range(0, i-j-1):\n v[i-k] = v[i-k-1]\n v[j] = store\n return v\n\ndef insertion(v):\n for i in ra...
false
3,627
5068a78a1aa31a277b3b5854ddd1d8990d07b104
#roblem: Have the function PrimeTime(num) # take the num parameter being passed and return # the string true if the parameter is a prime number, \ # otherwise return the string false. # The range will be between 1 and 2^16. def PrimeTime(num): prime1 = (num-1)%6 prime2 = (num+1)%6 if prime1 * prime2 =...
[ "#roblem: Have the function PrimeTime(num) \n# take the num parameter being passed and return \n# the string true if the parameter is a prime number, \\\n# otherwise return the string false.\n# The range will be between 1 and 2^16.\n\ndef PrimeTime(num):\n\n prime1 = (num-1)%6\n prime2 = (num+1)%6\n\n if ...
false
3,628
bcbcb4ea3a3b8b5c11e9b107103418ae79a3921c
# Create your views here. from django.shortcuts import render_to_response, Http404, render from django.template import RequestContext from books.models import Book from django.http import HttpResponse, HttpResponseRedirect import urllib, urllib2 import json def incr_reads(request, book_id): if request.POST: ...
[ "# Create your views here.\nfrom django.shortcuts import render_to_response, Http404, render\nfrom django.template import RequestContext\nfrom books.models import Book\nfrom django.http import HttpResponse, HttpResponseRedirect\nimport urllib, urllib2\nimport json \n\ndef incr_reads(request, book_id):\n if reque...
false
3,629
1b3891565f776064cfcca02fb22ea65853f7e66f
from matplotlib import pyplot as plt # Function for testing # Maps x => x*x def calculate(x): return x * x inputs = [-0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5] outputs = [calculate(x) for x in inputs] plt.plot(inputs, outputs) plt.savefig("plot.png")
[ "from matplotlib import pyplot as plt\n\n# Function for testing\n# Maps x => x*x\ndef calculate(x):\n\treturn x * x\n\n\ninputs = [-0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5]\n\noutputs = [calculate(x) for x in inputs]\n\nplt.plot(inputs, outputs)\nplt.savefig(\"plot.png\")", "from matplotlib import...
false
3,630
3ccbafbdc84447438c194288b1409e332bb2b479
import cv2 as cv import numpy as np from servo import * from func import * #import threading #import dlib # import socket # import struct # import pickle def constrain(val, minv, maxv): return min(maxv, max(minv, val)) KP = 0.22 KI = 0 KD = 0.17 last = 0 integral = 0 # constants SIZE = (400, 300) RECT = np.flo...
[ "import cv2 as cv\nimport numpy as np\nfrom servo import *\nfrom func import *\n#import threading\n#import dlib\n# import socket\n# import struct\n# import pickle\n\n\ndef constrain(val, minv, maxv):\n return min(maxv, max(minv, val))\n\nKP = 0.22\nKI = 0\nKD = 0.17\nlast = 0\nintegral = 0\n\n# constants\nSIZE =...
false
3,631
98b0e42f3ed1a234f63c4d3aa76ceb9fce7c041d
from time import perf_counter_ns from anthony.utility.distance import compare, compare_info from icecream import ic start = perf_counter_ns() ic(compare("tranpsosed", "transposed")) print(f"Example Time: {(perf_counter_ns() - start)/1e+9} Seconds") ic(compare_info("momther", "mother"))
[ "from time import perf_counter_ns\n\nfrom anthony.utility.distance import compare, compare_info\nfrom icecream import ic\n\nstart = perf_counter_ns()\nic(compare(\"tranpsosed\", \"transposed\"))\nprint(f\"Example Time: {(perf_counter_ns() - start)/1e+9} Seconds\")\n\nic(compare_info(\"momther\", \"mother\"))\n", ...
false
3,632
2f5244c6144f5aafce29e5aba32bd7e3fc7ecf5b
# -*- coding: utf-8 -*- ''' * EAFS * Copyright (C) 2009-2011 Adam Etienne <eadam@lunasys.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation version 3. * * This program is distributed i...
[ "# -*- coding: utf-8 -*-\n'''\n * EAFS\n * Copyright (C) 2009-2011 Adam Etienne <eadam@lunasys.fr>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation version 3.\n *\n * This program is...
true
3,633
5580e5942370c925b759b09675306cdfbc7dd4f1
''' Created on 5 Mar 2010 @author: oppianmatt ''' # hook to find setup tools if not installed try: from ez_setup import use_setuptools use_setuptools() except ImportError: pass from setuptools import setup, find_packages setup( name = "django-defaultsite", version = "1.1", packages = find_pac...
[ "'''\nCreated on 5 Mar 2010\n\n@author: oppianmatt\n'''\n\n# hook to find setup tools if not installed\ntry:\n from ez_setup import use_setuptools\n use_setuptools()\nexcept ImportError:\n pass\n\nfrom setuptools import setup, find_packages\nsetup(\n name = \"django-defaultsite\",\n version = \"1.1\"...
false
3,634
856beaf3b9dad333d5b48c1be3a8ad917f8d020c
from flask import Blueprint, request, make_response from untils import restful, cacheuntil from untils.captcha import Captcha from exts import smsapi from .forms import SMSCaptchaForm from io import BytesIO bp = Blueprint('common', __name__, url_prefix='/c') # @bp.route('/sms_captcha/', methods=['post']) # def sms_c...
[ "from flask import Blueprint, request, make_response\nfrom untils import restful, cacheuntil\nfrom untils.captcha import Captcha\nfrom exts import smsapi\nfrom .forms import SMSCaptchaForm\nfrom io import BytesIO\n\nbp = Blueprint('common', __name__, url_prefix='/c')\n\n\n# @bp.route('/sms_captcha/', methods=['post...
false
3,635
05f77472625e902b66c4a97a4c640835826bd494
from functiona import * total = totalMarks(85,67,56,45,78) avg = average(total) grade = findGrade(avg) print(grade) print(total) print(avg)
[ "from functiona import *\n\ntotal = totalMarks(85,67,56,45,78)\n\navg = average(total)\n\ngrade = findGrade(avg)\n\nprint(grade)\nprint(total)\nprint(avg)", "from functiona import *\ntotal = totalMarks(85, 67, 56, 45, 78)\navg = average(total)\ngrade = findGrade(avg)\nprint(grade)\nprint(total)\nprint(avg)\n", ...
false
3,636
0f4bb65b93df997ca1a9b7945ebcec53a2f43822
"""This module will serve the api request.""" import json from bson.json_util import dumps from flask import abort, request, Response, jsonify from api import app, collection @app.route("/api/v1/users", methods=['POST']) def create_user(): """ Function to create new users. """ try: # Creat...
[ "\"\"\"This module will serve the api request.\"\"\"\n\nimport json\nfrom bson.json_util import dumps\nfrom flask import abort, request, Response, jsonify\nfrom api import app, collection\n\n\n@app.route(\"/api/v1/users\", methods=['POST'])\ndef create_user():\n \"\"\"\n Function to create new users.\n ...
false
3,637
6b6397fd18848ffa2ae9c0ec1443d20f2cbeb8b0
import math import pandas as pd from matplotlib import pyplot as plt tests = [ { "task": "listsort", "prompt": "examples", "length": 5, "shots": 0, "accuracy": 0.28, "trials": 50}, { "task": "listsort", "prompt": "examples", "length": 5, "shots": 1, "accuracy": 0.40, "trials": 50}, { "task": "listsort", "...
[ "import math\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\ntests = [\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 0, \"accuracy\": 0.28, \"trials\": 50},\n { \"task\": \"listsort\", \"prompt\": \"examples\", \"length\": 5, \"shots\": 1, \"accuracy\": 0.40, ...
false
3,638
46b1e5adbd956c35820d7d2b17628364388cdcd7
__author__ = 'tomer' import sqlite3 from random import randint import test_data def init_database(conn): c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS catalogs (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)''') c.execute('''CREATE TABLE IF NOT EXISTS products ...
[ "__author__ = 'tomer'\nimport sqlite3\nfrom random import randint\nimport test_data\n\ndef init_database(conn):\n c = conn.cursor()\n c.execute('''CREATE TABLE IF NOT EXISTS catalogs\n (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)''')\n c.execute('''CREATE TABLE IF NOT EXISTS pr...
false
3,639
ff3962d875da8e3f9e6c3178b1a8191ebb8a7b60
TABLE_NAME = 'active_module'
[ "TABLE_NAME = 'active_module'\n", "<assignment token>\n" ]
false
3,640
16a77c45a58e31c575511146dfceeaef0a2bc3a7
def get_partial_matched(n): pi = [0] * len(n) begin = 1 matched = 0 while begin + matched < len(n): if n[begin + matched] == n[matched]: matched += 1 pi[begin + matched - 1] = matched else: if matched == 0: begin += 1 else: ...
[ "def get_partial_matched(n):\n pi = [0] * len(n)\n begin = 1\n matched = 0\n while begin + matched < len(n):\n if n[begin + matched] == n[matched]:\n matched += 1\n pi[begin + matched - 1] = matched\n else:\n if matched == 0:\n begin += 1\n ...
false
3,641
33c4e0504425c5d22cefb9b4c798c3fd56a63771
#!/usr/bin/python import math def Main(): try: radius = float(input("Please enter the radius: ")) area = math.pi * radius**2 print("Area =", area) except: print("You did not enter a number") if __name__ == "__main__": Main()
[ "#!/usr/bin/python\nimport math\n\ndef Main():\n\ttry:\n\t\tradius = float(input(\"Please enter the radius: \"))\n\t\tarea = math.pi * radius**2\n\t\tprint(\"Area =\", area)\n\texcept:\n\t\tprint(\"You did not enter a number\")\n\nif __name__ == \"__main__\":\n\tMain()\n", "import math\n\n\ndef Main():\n try:\...
false
3,642
13a2814e8744c6c09906d790185ed44fc2b3f23e
import random import torch import numpy as np from torch.autograd import Variable class SupportSetManager(object): FIXED_FIRST = 0 RANDOM = 1 def __init__(self, datasets, config, sample_per_class): self.config = config (TEXT, LABEL, train, dev, test) = datasets[0] self.TEXT = TEXT ...
[ "import random\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\n\nclass SupportSetManager(object):\n FIXED_FIRST = 0\n RANDOM = 1\n def __init__(self, datasets, config, sample_per_class):\n self.config = config\n (TEXT, LABEL, train, dev, test) = datasets[0]\n se...
false
3,643
9f2a8e78aa2e3eab8f74847443dec9083603da39
import socket # Packet Sniffing # It's All Binary # Usage: python basic_sniffer.py # create the sniffer raw socket object sniffer = socket.socket(socket.AF_INET,socket.SOCK_RAW, socket.IPPROTO_ICMP) #bind it to localhost sniffer.bind(('0.0.0.0',0)) # make sure that the IP header is included sniffer.setsockopt(soc...
[ "import socket\n\n# Packet Sniffing\n# It's All Binary\n\n# Usage: python basic_sniffer.py \n\n# create the sniffer raw socket object\nsniffer = socket.socket(socket.AF_INET,socket.SOCK_RAW, socket.IPPROTO_ICMP)\n\n#bind it to localhost\nsniffer.bind(('0.0.0.0',0))\n\n# make sure that the IP header is included\nsni...
true
3,644
b10a50ce649650542d176a2f6fb8c35c500fbc38
from rest_framework import serializers from django.contrib.auth import password_validation from rest_framework.validators import UniqueValidator from .models import CustomUser, Role, Permission, ActionEntity from .utils import create_permission class ActionEntitySerializer(serializers.ModelSerializer): id = ser...
[ "from rest_framework import serializers\nfrom django.contrib.auth import password_validation\nfrom rest_framework.validators import UniqueValidator\n\nfrom .models import CustomUser, Role, Permission, ActionEntity\nfrom .utils import create_permission\n\nclass ActionEntitySerializer(serializers.ModelSerializer):\n...
false
3,645
919e1f8a4b021d75496f3bcff369261a09362a65
from typing import Callable, List, Optional import numpy as np import lab1.src.grad.grad_step_strategy as st import lab1.src.grad.stop_criteria as sc DEFAULT_EPSILON = 1e-9 DEFAULT_MAX_ITERATIONS = 1e5 def gradient_descent(f: Callable[[np.ndarray], float], f_grad: Callable[[np.ndarray], np.nda...
[ "from typing import Callable, List, Optional\nimport numpy as np\n\nimport lab1.src.grad.grad_step_strategy as st\nimport lab1.src.grad.stop_criteria as sc\n\n\nDEFAULT_EPSILON = 1e-9\nDEFAULT_MAX_ITERATIONS = 1e5\n\n\ndef gradient_descent(f: Callable[[np.ndarray], float],\n f_grad: Callable[[np...
false
3,646
8b583ee55df409020a605b467479236e610a2efe
from external.odds.betclic.api import get_odds # FDJ parsing is broken - their UI has been refactored with JS framework & # protected async JSON API usage (requires HEADERS) and more complex to isolate & group match odds # hence move to another betting website - which is still full html rendered
[ "from external.odds.betclic.api import get_odds\n\n# FDJ parsing is broken - their UI has been refactored with JS framework &\n# protected async JSON API usage (requires HEADERS) and more complex to isolate & group match odds\n# hence move to another betting website - which is still full html rendered\n", "from e...
false
3,647
0f266db39988cfce475380036f4f4f5b1a1fee1a
""" dansfunctions - various useful functions in python usage: >>import dansfunctions >>dansfunctions.fg # module of general mathematical, vector and string format functions >>dansfunctions.fp # module of matplotlib shortcuts >>dansfunctions.widgets # module of tkinter shortcuts Requirements: numpy Optional requirem...
[ "\"\"\"\ndansfunctions - various useful functions in python\nusage:\n>>import dansfunctions\n>>dansfunctions.fg # module of general mathematical, vector and string format functions\n>>dansfunctions.fp # module of matplotlib shortcuts\n>>dansfunctions.widgets # module of tkinter shortcuts\n\nRequirements: numpy\n...
false
3,648
7da274803de80f2864471d00c9d15aff1103372f
from nodes.Value import Value class Number(Value): def __init__(self, number: int): if abs(number) > 2 ** 31: raise SyntaxError(str(number) + ' number is out of range') self.number = number def __str__(self): return str(self.number)
[ "from nodes.Value import Value\n\n\nclass Number(Value):\n def __init__(self, number: int):\n if abs(number) > 2 ** 31:\n raise SyntaxError(str(number) + ' number is out of range')\n self.number = number\n\n def __str__(self):\n return str(self.number)\n", "from nodes.Value i...
false
3,649
99ecb927e22bc303dd9dffd2793887e7398dbb83
#Importacion de Dependencias Flask from flask import Blueprint,Flask, render_template, request,redirect,url_for,flash #modelado de basedato. from App import db # Importacion de modulo de ModeloCliente from App.Modulos.Proveedor.model import Proveedor #Inportacion de modulo de formularioCliente from App.Modulos.Proveedo...
[ "#Importacion de Dependencias Flask\nfrom flask import Blueprint,Flask, render_template, request,redirect,url_for,flash\n#modelado de basedato.\nfrom App import db\n# Importacion de modulo de ModeloCliente\nfrom App.Modulos.Proveedor.model import Proveedor\n#Inportacion de modulo de formularioCliente\nfrom App.Modu...
false
3,650
f29fa3d796d9d403d6bf62cb28f5009501c55545
"""You are given a string . Your task is to find out if the string contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.""" s = raw_input() print(any(i.isalnum()for i in s)) print(any(i.isalpha()for i in s)) print(any(i.isdigit()for i in s)) print(any(i.islow...
[ "\"\"\"You are given a string .\r\nYour task is to find out if the string contains:\r\nalphanumeric characters, alphabetical characters, digits,\r\nlowercase and uppercase characters.\"\"\"\r\n\r\ns = raw_input()\r\nprint(any(i.isalnum()for i in s))\r\nprint(any(i.isalpha()for i in s))\r\nprint(any(i.isdigit()for ...
false
3,651
3f655a12ac45c152215949d3d8bdb71147eeb849
from collections import deque def safeInsert(graph,left,right): if left not in graph: graph[left] = {} graph[left][right] = True if right not in graph: graph[right] = {} graph[right][left] = True def trace(graph,start,end): queue = deque([start]) pred = {start:None} while len(queue)>0: cur = queue.poplef...
[ "from collections import deque\n\ndef safeInsert(graph,left,right):\n\tif left not in graph:\n\t\tgraph[left] = {}\n\tgraph[left][right] = True\n\tif right not in graph:\n\t\tgraph[right] = {}\n\tgraph[right][left] = True\n\ndef trace(graph,start,end):\n\tqueue = deque([start])\n\tpred = {start:None}\n\twhile len(q...
true
3,652
6ef8a174dcce633b526ce7d6fdb6ceb11089b177
import sys def main(): lines = [line.strip() for line in sys.stdin.readlines()] h = lines.index("") w = len(lines[0].split()[0]) start = 0 grids = set() while start < len(lines): grid = tuple(x.split()[0] for x in lines[start:start + h]) if len(grid) == h: grids.add(grid) start += h + 1 ...
[ "import sys\n\ndef main():\n lines = [line.strip() for line in sys.stdin.readlines()]\n h = lines.index(\"\")\n w = len(lines[0].split()[0])\n start = 0\n grids = set()\n while start < len(lines):\n grid = tuple(x.split()[0] for x in lines[start:start + h])\n if len(grid) == h:\n grids.add(grid)\n ...
true
3,653
47c1746c2edfe4018decd59efbacc8be89a1f49e
from src.basepages.BreadCrumbTicketInfoBasePage import * class BreadCrumbHomeBasePage: def __init__(self): "" def gotoTicketInfoBasePage(self,ticketInfoPage): self.driver.get(ticketInfoPage) breadCrumbTicketInfoBasePage = BreadCrumbTicketInfoBasePage() breadCrumbTicketInfoBasePage.driver = self.driver r...
[ "\nfrom src.basepages.BreadCrumbTicketInfoBasePage import *\n\nclass BreadCrumbHomeBasePage:\n\tdef __init__(self):\n\t\t\"\"\n\n\tdef gotoTicketInfoBasePage(self,ticketInfoPage):\n\t\tself.driver.get(ticketInfoPage)\n\n\t\tbreadCrumbTicketInfoBasePage = BreadCrumbTicketInfoBasePage()\n\t\tbreadCrumbTicketInfoBaseP...
false
3,654
c447d1fe38a4af43de39e05d46dacbe88249d427
from quantopian.algorithm import order_optimal_portfolio from quantopian.algorithm import attach_pipeline, pipeline_output from quantopian.pipeline import Pipeline from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.factors import SimpleMovingAverage from quantopian.pipeline.filters im...
[ "from quantopian.algorithm import order_optimal_portfolio\nfrom quantopian.algorithm import attach_pipeline, pipeline_output\nfrom quantopian.pipeline import Pipeline\nfrom quantopian.pipeline.data.builtin import USEquityPricing\nfrom quantopian.pipeline.factors import SimpleMovingAverage\nfrom quantopian.pipeline....
false
3,655
dcfc6d76730ba3b33e64cc8f2c166f739bbde5ff
# This script created by Joseph Aaron Campbell - 10/2020 """ With Help from Agisoft Forum @: https://www.agisoft.com/forum/index.php?topic=12027.msg53791#msg53791 """ """ Set up Working Environment """ # import Metashape library module import Metashape # create a reference to the current project via Document...
[ "# This script created by Joseph Aaron Campbell - 10/2020\r\n\r\n\"\"\" With Help from Agisoft Forum @:\r\nhttps://www.agisoft.com/forum/index.php?topic=12027.msg53791#msg53791\r\n\"\"\"\r\n\r\n\"\"\" Set up Working Environment \"\"\"\r\n# import Metashape library module\r\nimport Metashape\r\n# create a reference ...
false
3,656
e651edcbe68264e3f25180b10dc8e9d5620ecd6b
import unittest import requests class TestAudiobookResponse(unittest.TestCase): def test_audiobook_can_insert(self): """ test that audiobook can be inserted into db """ data = { "audiotype": "Audiobook", "metadata": { "duration": 37477, "ti...
[ "import unittest\nimport requests\n\n\nclass TestAudiobookResponse(unittest.TestCase):\n\n def test_audiobook_can_insert(self):\n \"\"\" test that audiobook can be inserted into db \"\"\"\n\n data = {\n \"audiotype\": \"Audiobook\",\n \"metadata\": {\n \"duratio...
false
3,657
ed65d7e0de3fc792753e34b77254bccc8cee6d66
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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 appl...
[ "# coding=utf-8\n# Copyright 2022 The TensorFlow Datasets Authors.\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 ...
false
3,658
76c1929e901fce469661a299184765875d0eb53f
쫲𪪌𤣬㐭𤙵⃢姅幛𑄹馻돷軔ሠ𡺶ײַ𢊅𠞡鞿𭞎𦠟𦔻뜸𣦏蛫履뜟𢒰疅𗕢𨞧漷𫴫礴𬽣𨚒𠻚゚罉ꉷ🕸𡑁𩂱𑫌抿锃𫕊𦿮橖𓋊𧭠酞Ё햾𞄶𪳧蕱ꗍ𐊯𬏷먽𬻩뱩𗼾𠑧銋𝂥蘒굳뜀𬜀𮧛𡐔𭋇𭘡𬙒蕶믅𬂚𡟐剿𨸒ᄉ𮩨烘𮩽𭚱𗨦ﳇ큿턽쾘𩁻ꫲ𗨿蚀𨊍胗𗔑鼴𨵾㽡𩠌ݜ𪢭𩘼넴𤩭𬩽𢺤𫅬𧁏響𬶉喡𘨘뉵𨲊Ζ𥀐𩨇𠮢⏂𭖳𫓢𧛃𦥮単𦇭𮏨𬋪婓츏𪱔𭄿𦭺𣍵蹖🨞ޝ仂䱔讔ﭑ𨹟𐊁ﱥ𧅔𓇪뽼𗩢픛𖮌䮁ီ邾ࢠ㭨𣯇𩱵𥋭ѽ샑𭹓𫳃𧝽𥲇ᛲ𘁕粣𣑑ᒔ𣥕쯞⒋𩍥纝攂𨄷ͭ𧲵퍃氩𢐅𤵲뎋𥵘黴𤼩𬝉ⶌ𥬥𧺥浞🇴𑨲𠎆筬⌝༤쾘𤌲ы𡚎𑲙㽰𐛱𫛛�...
[ "쫲𪪌𤣬㐭𤙵⃢姅幛𑄹馻돷軔ሠ𡺶ײַ𢊅𠞡鞿𭞎𦠟𦔻뜸𣦏蛫履뜟𢒰疅𗕢𨞧漷𫴫礴𬽣𨚒𠻚゚罉ꉷ🕸𡑁𩂱𑫌抿锃𫕊𦿮橖𓋊𧭠酞Ё햾𞄶𪳧蕱ꗍ𐊯𬏷먽𬻩뱩𗼾𠑧銋𝂥蘒굳뜀𬜀𮧛𡐔𭋇𭘡𬙒蕶믅𬂚𡟐剿𨸒ᄉ𮩨烘𮩽𭚱𗨦ﳇ큿턽쾘𩁻ꫲ𗨿蚀𨊍胗𗔑鼴𨵾㽡𩠌ݜ𪢭𩘼넴𤩭𬩽𢺤𫅬𧁏響𬶉喡𘨘뉵𨲊Ζ𥀐𩨇𠮢⏂𭖳𫓢𧛃𦥮単𦇭𮏨𬋪婓츏𪱔𭄿𦭺𣍵蹖🨞ޝ仂䱔讔ﭑ𨹟𐊁ﱥ𧅔𓇪뽼𗩢픛𖮌䮁ီ邾ࢠ㭨𣯇𩱵𥋭ѽ샑𭹓𫳃𧝽𥲇ᛲ𘁕粣𣑑ᒔ𣥕쯞⒋𩍥纝攂𨄷ͭ𧲵퍃氩𢐅𤵲뎋𥵘黴𤼩𬝉ⶌ𥬥𧺥浞🇴𑨲𠎆筬⌝༤쾘𤌲ы𡚎𑲙㽰...
true
3,659
127bf47de554dd397d18c6a70616a2a4d93cae80
"""Sophie Tan's special AI.""" from typing import Sequence, Tuple from battleships import Player, ShotResult from random import randint class SophiesAI(Player): """Sophie Tan's Random Shot Magic.""" def ship_locations(self) -> Sequence[Tuple[int, int, int, bool]]: return [(2, 0, 0, True)] def d...
[ "\"\"\"Sophie Tan's special AI.\"\"\"\nfrom typing import Sequence, Tuple\n\nfrom battleships import Player, ShotResult\nfrom random import randint\n\n\nclass SophiesAI(Player):\n \"\"\"Sophie Tan's Random Shot Magic.\"\"\"\n\n def ship_locations(self) -> Sequence[Tuple[int, int, int, bool]]:\n return ...
false
3,660
22ffda3b2d84218af22bad7835689ec3d4959ab2
import numpy import yfinance as yf import pandas as pd import path import math pd.options.mode.chained_assignment = None # default='warn' all_tickers = ['2020.OL', 'ABG.OL', 'ADE.OL', 'AFG.OL', 'AKAST.OL', 'AKER.OL', 'AKBM.OL', ...
[ "import numpy\nimport yfinance as yf\nimport pandas as pd\nimport path\nimport math\npd.options.mode.chained_assignment = None # default='warn'\n\nall_tickers = ['2020.OL',\n 'ABG.OL',\n 'ADE.OL',\n 'AFG.OL',\n 'AKAST.OL',\n 'AKER.OL',\n ...
false
3,661
1cbc37655e28ab3082fc31baf119cb2bab96379b
def format_amount(a): return a.replace(",","").strip().replace("%","").replace("$","") def create_json(gdp, coords): # ------------ Split gdp data ------------ # line_list=gdp.split('\n') column_list = [x.split('\t') for x in line_list if x!=""] # ------------ Split coord data ------------ # line_list=coords.s...
[ "def format_amount(a):\n\treturn a.replace(\",\",\"\").strip().replace(\"%\",\"\").replace(\"$\",\"\")\n\ndef create_json(gdp, coords):\n\n\t# ------------ Split gdp data ------------ #\n\tline_list=gdp.split('\\n')\n\tcolumn_list = [x.split('\\t') for x in line_list if x!=\"\"]\n\n\t# ------------ Split coord data...
false
3,662
c8406db010a506b782030c5d3f84c319851e89d6
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('twitter', '0002_tweet'), ] operations = [ migrations.CreateModel( name='TwitterKeys', fields=[ ...
[ "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('twitter', '0002_tweet'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TwitterKeys',\n ...
false
3,663
0681ab83843187701ac72018b6078f5141bf22e0
import sys import os import tensorflow as tf import keras from cv2 import * from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from PIL import Image import numpy as np import pickle from sklearn.model_selection import train_test_split from keras.utils import np_utils from keras.layers ...
[ "import sys\nimport os\nimport tensorflow as tf\nimport keras\nfrom cv2 import *\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom PIL import Image\nimport numpy as np\nimport pickle\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils import np_utils\nf...
false
3,664
e3386b01bb0bdc7064a2e3e9f3edce8a3231721b
import json from faker import Faker import random fake = Faker() from faker.providers import date_time fake.add_provider(date_time) class Hour(object): def __init__(self): self.dayOfTheWeek = fake.day_of_week() self.openingTime = str(random.randint(1, 12)) + 'AM' self.closing...
[ "import json\r\nfrom faker import Faker\r\nimport random\r\n\r\nfake = Faker()\r\n\r\nfrom faker.providers import date_time\r\nfake.add_provider(date_time)\r\n\r\nclass Hour(object):\r\n def __init__(self):\r\n self.dayOfTheWeek = fake.day_of_week()\r\n self.openingTime = str(random.randint(1, 12))...
false
3,665
2d248ac1df1845bc5a2ee62a7171c1c47ca6d0ca
#!/usr/bin/env python3 import sys sys.path.insert(0, '../../common/python/') from primality import prime_factors """ phi(n) = n*sum_{p|n} (1 - 1/p) 1/phi(n) = (1/n)*sum_{p|n} p/(p - 1) n/phi(n) = sum_{p|n} p/(p - 1) """ def n_over_phi(n): top = 1 bot = 1 pfactors = prime_factors(n) for p, count i...
[ "#!/usr/bin/env python3\n\nimport sys\nsys.path.insert(0, '../../common/python/')\n\nfrom primality import prime_factors\n\n\"\"\"\nphi(n) = n*sum_{p|n} (1 - 1/p)\n1/phi(n) = (1/n)*sum_{p|n} p/(p - 1)\nn/phi(n) = sum_{p|n} p/(p - 1)\n\"\"\"\n\n\ndef n_over_phi(n):\n top = 1\n bot = 1\n\n pfactors = prime_f...
false
3,666
c6d61a0159073304309cd4b1534ed5aed666bab5
import os, glob, argparse, json, re from collections import defaultdict import numpy as np import pandas as pd from utils.CONSTANTS import output_dir, all_chromosomes, BINNED_CHRSZ, dataset_expts def extract_chrom_num(s): m = re.search('\d+', s) if m is None: return 24 else: return int(m.group(0)) de...
[ "import os, glob, argparse, json, re\nfrom collections import defaultdict\n\nimport numpy as np\nimport pandas as pd\n\nfrom utils.CONSTANTS import output_dir, all_chromosomes, BINNED_CHRSZ, dataset_expts\n\n\ndef extract_chrom_num(s):\n m = re.search('\\d+', s)\n if m is None:\n return 24\n else:\n return...
false
3,667
fcfec60a2302ee0c1385add053d4371040a2aff4
# Generated by Django 2.1.2 on 2018-10-19 22:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AlterField( model_name='mascota', name='descripcion', ...
[ "# Generated by Django 2.1.2 on 2018-10-19 22:13\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='mascota',\n name='descr...
false
3,668
355e3932c8bd9105e0c1ce9259e3b7416997523c
#!/usr/bin/env python # -*- coding: utf-8 -*- from operation import * import math class InsertWord(Operation): @classmethod def getValue(cls, t, h, w, b, arg=None): return math.log(arg["prob"]) * w[cls] @classmethod def getKBest(cls, t, h , args, w, b, k): valueList = [] for ...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom operation import *\nimport math\n\nclass InsertWord(Operation):\n\n @classmethod\n def getValue(cls, t, h, w, b, arg=None):\n return math.log(arg[\"prob\"]) * w[cls]\n\n @classmethod\n def getKBest(cls, t, h , args, w, b, k):\n valueL...
false
3,669
4daf029c4bc9f0726080bd67f37b1e77c9697d1c
''' Copyright (C) 2014 mdm marco[dot]masciola[at]gmail Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file d...
[ "'''\n Copyright (C) 2014 mdm \n marco[dot]masciola[at]gmail \n \nLicensed to the Apache Software Foundation (ASF) under one \nor more contributor license agreements. See the NOTIC...
true
3,670
19d5e9db142237d1cb2276ccaf083ca4a96109fc
from django.conf.urls import url from basket import views urlpatterns = [ url(r'^$', views.view_basket, name='basket'), url(r'^add/(?P<product_pk>\d+)$', views.add_to_basket, name='add_to_basket'), url(r'^remove/(?P<basketitem_pk>\d+)$', views.remove_from_basket, name='remove_from_basket'), ]
[ "from django.conf.urls import url\n\nfrom basket import views\n\n\nurlpatterns = [\n url(r'^$', views.view_basket, name='basket'),\n url(r'^add/(?P<product_pk>\\d+)$', views.add_to_basket, name='add_to_basket'),\n url(r'^remove/(?P<basketitem_pk>\\d+)$', views.remove_from_basket, name='remove_from_basket')...
false
3,671
71ff8e8a62a3b2731071ed7a039b51c150ebaca4
import os ,sys from scrapy.cmdline import execute sys.path.append(os.path.dirname(os.path.abspath(__file__))) execute('scrapy crawl laptop'.split())
[ "import os ,sys\nfrom scrapy.cmdline import execute\n\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\nexecute('scrapy crawl laptop'.split())\n", "import os, sys\nfrom scrapy.cmdline import execute\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\nexecute('scrapy crawl laptop'.split())\n"...
false
3,672
4ecf976a7d655efb5af427083ec1943cae6fe56d
class Restaurant(): """A restaurant model.""" def __init__(self, restaurant_name, cuisine_type): """Initialize name and type.""" self.name = restaurant_name self.type = cuisine_type def describe_restaurant(self): """Prints restaurant information.""" print("The restaurant's name is " + self.name.title())...
[ "class Restaurant():\n\t\"\"\"A restaurant model.\"\"\"\n\n\tdef __init__(self, restaurant_name, cuisine_type):\n\t\t\"\"\"Initialize name and type.\"\"\"\n\t\tself.name = restaurant_name\n\t\tself.type = cuisine_type\n\n\n\tdef describe_restaurant(self):\n\t\t\"\"\"Prints restaurant information.\"\"\"\n\t\tprint(\...
false
3,673
d4cdc4f1995eab7f01c970b43cb0a3c5ed4a2711
from golem import actions from projects.golem_gui.pages import common from projects.golem_gui.pages import api from projects.golem_gui.pages import test_builder_code description = 'Verify the user can edit test code and save it' tags = ['smoke'] def setup(data): common.access_golem(data.env.url, data.env.admi...
[ "from golem import actions\n\nfrom projects.golem_gui.pages import common\nfrom projects.golem_gui.pages import api\nfrom projects.golem_gui.pages import test_builder_code\n\n\ndescription = 'Verify the user can edit test code and save it'\n\ntags = ['smoke']\n\n\ndef setup(data):\n common.access_golem(data.env....
false
3,674
777c08876a2de803fc95de937d9e921044545ef8
from bs4 import BeautifulSoup import requests res = requests.get('http://quotes.toscrape.com/') #print(res.content) #proper ordered printing #print(res.text) #lxml -> parser library soup = BeautifulSoup(res.text , 'lxml') #print(soup) quote = soup.find_all('div',{'class' : 'quote'}) with open('Quotes.txt...
[ "from bs4 import BeautifulSoup\r\nimport requests\r\n\r\nres = requests.get('http://quotes.toscrape.com/')\r\n#print(res.content)\r\n#proper ordered printing\r\n#print(res.text)\r\n#lxml -> parser library\r\nsoup = BeautifulSoup(res.text , 'lxml')\r\n#print(soup)\r\n\r\nquote = soup.find_all('div',{'class' : 'quot...
false
3,675
851162e6c40a9f4f82a983a84fd0b4d6a6a57412
class Type(object): """Type of values.""" def __init__(self, jtype): self.jtype = jtype def __repr__(self): return self.jtype.toString() def __str__(self): return self.jtype.toPrettyString(False, False)
[ "\nclass Type(object):\n \"\"\"Type of values.\"\"\"\n \n def __init__(self, jtype):\n self.jtype = jtype\n\n def __repr__(self):\n return self.jtype.toString()\n\n def __str__(self):\n return self.jtype.toPrettyString(False, False)\n", "class Type(object):\n \"\"\"Type of v...
false
3,676
f1475d651c3b52611657a9767ad62796b55d8711
# obtain the dataset import pandas as pd titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt') #titanic.info() print(titanic.head()) # preprocessing x = titanic.drop(['row.names', 'name', 'survived'], axis=1) y = titanic['survived'] x['age'].fillna(x['age'].mean(),...
[ "# obtain the dataset\r\nimport pandas as pd\r\n\r\ntitanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')\r\n#titanic.info()\r\nprint(titanic.head())\r\n\r\n\r\n# preprocessing\r\nx = titanic.drop(['row.names', 'name', 'survived'], axis=1)\r\ny = titanic['survived']\r\n\r\nx['...
false
3,677
19bb3cd0c7862f39a78479d9a9703ebef198fc73
import math from Config import defaults as df from Utils.controls import sigmoid_decay def f1(phi, phi_o, d): """sinusoidally growing function between (phi_o-d) to phi_o""" return 1 - sigmoid_decay(phi, phi_o, d) def f2(phi, sigma): """normal distribution""" return math.exp(-phi ** 2 / sigma ** 2) ...
[ "import math\nfrom Config import defaults as df\nfrom Utils.controls import sigmoid_decay\n\n\ndef f1(phi, phi_o, d):\n \"\"\"sinusoidally growing function between (phi_o-d) to phi_o\"\"\"\n return 1 - sigmoid_decay(phi, phi_o, d)\n\n\ndef f2(phi, sigma):\n \"\"\"normal distribution\"\"\"\n return math....
false
3,678
e3a984294cad5830358df50fa00111017cbe226d
from django.urls import path from .views import MainView app_name = "bio" # app_name will help us do a reverse look-up latter. urlpatterns = [ path('get_mtx_data', MainView.as_view()), ]
[ "from django.urls import path\n\nfrom .views import MainView\n\napp_name = \"bio\"\n# app_name will help us do a reverse look-up latter.\nurlpatterns = [\n path('get_mtx_data', MainView.as_view()),\n]\n", "from django.urls import path\nfrom .views import MainView\napp_name = 'bio'\nurlpatterns = [path('get_mtx...
false
3,679
ebb4cf1ec2baa7bd0d29e3ae88b16e65cf76a88a
from flask import Flask, render_template, url_for, request, redirect, session, flash import os, json from usuarios import crearUsuario, comprobarUsuario from busqueda import filtrado from compra import procesarCompra, Dinero app = Flask(__name__) catalogo_data = json.loads(open(os.path.join(app.root_path,'json/catalo...
[ "from flask import Flask, render_template, url_for, request, redirect, session, flash\nimport os, json\nfrom usuarios import crearUsuario, comprobarUsuario\nfrom busqueda import filtrado\nfrom compra import procesarCompra, Dinero\n\napp = Flask(__name__)\n\ncatalogo_data = json.loads(open(os.path.join(app.root_path...
false
3,680
85974e48c7eafdf39379559820ed7f0bdc07fb7a
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Fri Apr 12 16:38:15 2013 @author: a92549 Fixes lack of / between tzvp and tzvpfit """ import sys def main(argv): for com in argv: with open(com, 'rb') as f: txt = f.read() if 'tzvp tzvpfit' in txt: parts = txt.spl...
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 12 16:38:15 2013\n\n@author: a92549\n\n\nFixes lack of / between tzvp and tzvpfit\n\n\"\"\"\n\nimport sys\n\ndef main(argv):\n for com in argv:\n with open(com, 'rb') as f:\n txt = f.read()\n if 'tzvp tzvpfit' in txt...
false
3,681
991fa5f9c83a1821e62f7baacbc56a4d31982312
a, b = map(int, input().split()) def mult(a, b): if a > 9 or b > 9 or a < 1 or b < 1: print(-1) else: print(a * b) mult(a,b)
[ "a, b = map(int, input().split())\n\n\ndef mult(a, b):\n if a > 9 or b > 9 or a < 1 or b < 1:\n print(-1)\n else:\n print(a * b)\n\nmult(a,b)", "a, b = map(int, input().split())\n\n\ndef mult(a, b):\n if a > 9 or b > 9 or a < 1 or b < 1:\n print(-1)\n else:\n print(a * b)\n...
false
3,682
193d48237b4b1e406eb565943cf01f0423449fca
# hw.shin@konantech.com #leekiljae@ogqcorp.com
[ "# hw.shin@konantech.com\n#leekiljae@ogqcorp.com", "" ]
false
3,683
1154fd3883dc8856e24127d56ce6a983308dc1aa
# -*- coding: utf-8 -*- __author__ = 'wxy' class ListProcess(object): def __init__(self, rsp, nickname): self.rsp = rsp self.nickname = nickname def get_friend_uin(self): try: for list in self.rsp['result']['info']: if list['nick'] == self.nickname: ...
[ "# -*- coding: utf-8 -*-\n__author__ = 'wxy'\n\nclass ListProcess(object):\n def __init__(self, rsp, nickname):\n self.rsp = rsp\n self.nickname = nickname\n\n def get_friend_uin(self):\n try:\n for list in self.rsp['result']['info']:\n if list['nick'] == self.ni...
true
3,684
3983f8dfb9c7b7e664af05857a0f6fe380154424
from django import forms from . import models class PhotoForm(forms.Form): image = forms.ImageField()
[ "from django import forms\nfrom . import models\n\n\nclass PhotoForm(forms.Form):\n image = forms.ImageField()\n\n", "from django import forms\nfrom . import models\n\n\nclass PhotoForm(forms.Form):\n image = forms.ImageField()\n", "<import token>\n\n\nclass PhotoForm(forms.Form):\n image = forms.Image...
false
3,685
d5d61b23dc14ffdfe7fe6f983164916863928eaf
from django.apps import AppConfig class AttendaceConfig(AppConfig): name = 'attendace'
[ "from django.apps import AppConfig\n\n\nclass AttendaceConfig(AppConfig):\n name = 'attendace'\n", "<import token>\n\n\nclass AttendaceConfig(AppConfig):\n name = 'attendace'\n", "<import token>\n\n\nclass AttendaceConfig(AppConfig):\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
3,686
5b7c04f23fb674191639e95dff8c530933379d67
""" Вам дана последовательность строк. В каждой строке замените все вхождения нескольких одинаковых букв на одну букву. Буквой считается символ из группы \w. Sample Input: attraction buzzzz Sample Output: atraction buz """ from sys import stdin import re for word in stdin: lst_in = word match = re.finditer(r...
[ "\"\"\"\nВам дана последовательность строк.\nВ каждой строке замените все вхождения нескольких одинаковых букв на одну букву.\nБуквой считается символ из группы \\w.\nSample Input:\n\nattraction\nbuzzzz\nSample Output:\n\natraction\nbuz\n\"\"\"\nfrom sys import stdin\nimport re\n\nfor word in stdin:\n lst_in = w...
false
3,687
a2292bc9cee57c5d4a7d36c66510ce4b4f3e20da
""" Simulator contains the tools needed to set up a multilayer antireflection coating simulation. Based on transfer matrix method outlined in Hou, H.S. 1974. """ # Author: Andrew Nadolski (with lots of help from previous work by Colin Merkel, # Steve Byrnes, and Aritoki Suzuki) # Filename: simulator.py impo...
[ "\"\"\"\nSimulator contains the tools needed to set up a multilayer antireflection\ncoating simulation.\n\nBased on transfer matrix method outlined in Hou, H.S. 1974.\n\"\"\"\n\n# Author: Andrew Nadolski (with lots of help from previous work by Colin Merkel,\n# Steve Byrnes, and Aritoki Suzuki)\n# Filename:...
false
3,688
a0dbb374f803cb05a35f823f54ef5f14eaf328b2
# coding: utf-8 """ login.py ~~~~~~~~ 木犀官网登陆API """ from flask import jsonify, request from . import api from muxiwebsite.models import User from muxiwebsite import db @api.route('/login/', methods=['POST']) def login(): email = request.get_json().get("email") pwd = request.get_json().get("pass...
[ "# coding: utf-8\n\n\"\"\"\n login.py\n ~~~~~~~~\n\n 木犀官网登陆API\n\n\"\"\"\n\nfrom flask import jsonify, request\nfrom . import api\nfrom muxiwebsite.models import User\nfrom muxiwebsite import db\n\n@api.route('/login/', methods=['POST'])\ndef login():\n email = request.get_json().get(\"email\")\n pwd...
false
3,689
3fa1736fd87448ec0da4649153521d0aba048ccf
from rest_framework import serializers from dailytasks.models import Tasks class TasksSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') class Meta: model = Tasks fields = ['id','created','title','description','status','user']
[ "from rest_framework import serializers\nfrom dailytasks.models import Tasks\n\n\nclass TasksSerializer(serializers.ModelSerializer):\n\n user = serializers.ReadOnlyField(source='user.username')\n\n class Meta:\n model = Tasks\n fields = ['id','created','title','description','status','user']\n ...
false
3,690
c036e6a0a9f06b08ee3eb43655dd833b46fd1e76
from .factories import *
[ "\nfrom .factories import *", "from .factories import *\n", "<import token>\n" ]
false
3,691
4892d4f364b03b53b1ad6f4c2177bbe2898edbda
#!/usr/bin/env python import os import sys import numpy as np from sklearn.metrics import roc_curve, auc def confusion_matrix(Or, Tr, thres): tpos = np.sum((Or >= thres) * (Tr == 1)) tneg = np.sum((Or < thres) * (Tr == 0)) fpos = np.sum((Or >= thres) * (Tr == 0)) fneg = np.sum((Or < thres) * (Tr == 1...
[ "#!/usr/bin/env python\nimport os\nimport sys\n\nimport numpy as np\nfrom sklearn.metrics import roc_curve, auc\n\n\ndef confusion_matrix(Or, Tr, thres):\n tpos = np.sum((Or >= thres) * (Tr == 1))\n tneg = np.sum((Or < thres) * (Tr == 0))\n fpos = np.sum((Or >= thres) * (Tr == 0))\n fneg = np.sum((Or < ...
false
3,692
51cb750082ce93b6d14fe3aa40711836d493129c
""" Proyecto SA^3 Autor: Mario Lopez Luis Aviles Joaquin V Fecha: Octubre del 2012 versión: 1 """ #Manejo de temlates en el HTML import jinja2 from jinja2 import Environment, PackageLoader import os import cgi import datetime import urllib # for hashing import hashlib...
[ "\"\"\"\r\nProyecto SA^3\r\nAutor: \tMario Lopez\r\n Luis Aviles\r\n\t\tJoaquin V\r\nFecha: Octubre del 2012\r\nversión: 1\r\n\"\"\"\r\n\r\n#Manejo de temlates en el HTML\r\nimport jinja2 \r\nfrom jinja2 import Environment, PackageLoader\r\n\r\nimport os\r\nimport cgi\r\nimport datetime\r...
true
3,693
5cd9d4fe9889c4d53b50d86fa78ae84d0c242536
import tensorflow as tf import random from tqdm import tqdm import spacy import ujson as json from collections import Counter import numpy as np import os.path nlp = spacy.blank("en") def word_tokenize(sent): doc = nlp(sent) return [token.text for token in doc] def convert_idx(text, tokens): current = ...
[ "import tensorflow as tf\nimport random\nfrom tqdm import tqdm\nimport spacy\nimport ujson as json\nfrom collections import Counter\nimport numpy as np\nimport os.path\n\nnlp = spacy.blank(\"en\")\n\n\ndef word_tokenize(sent):\n doc = nlp(sent)\n return [token.text for token in doc]\n\n\ndef convert_idx(text,...
false
3,694
f10e20d5c409930d697c36d1897ebcb648511e27
from typing import List from fastapi import Depends, APIRouter from sqlalchemy.orm import Session from attendance.database import get_db from attendance import schemas from attendance.models import User from attendance import crud from attendance.dependency import get_current_user router = APIRouter() #BASE_SALARY #...
[ "from typing import List\n\nfrom fastapi import Depends, APIRouter\nfrom sqlalchemy.orm import Session\n\nfrom attendance.database import get_db\nfrom attendance import schemas\nfrom attendance.models import User\nfrom attendance import crud\nfrom attendance.dependency import get_current_user\n\nrouter = APIRouter(...
false
3,695
e93d5461a2604d3b8015489397c68e16d1cb222e
from manim import * class SlidingDoorIllustration(Scene): def construct(self): waiting_room = Rectangle(color=BLUE, stroke_width=8) waiting_room.shift(LEFT + DOWN) workspace = Rectangle(color=BLUE, stroke_width=8) workspace.next_to(waiting_room, RIGHT + UP, buff=0) workspac...
[ "from manim import *\n\n\nclass SlidingDoorIllustration(Scene):\n def construct(self):\n waiting_room = Rectangle(color=BLUE, stroke_width=8)\n waiting_room.shift(LEFT + DOWN)\n workspace = Rectangle(color=BLUE, stroke_width=8)\n workspace.next_to(waiting_room, RIGHT + UP, buff=0)\n ...
false
3,696
cbad5d6f381e788a2f064aac0a5d468f40b39c93
import os, subprocess os.environ['FLASK_APP'] = "app/app.py" os.environ['FLASK_DEBUG'] = "1" # for LSTM instead: https://storage.googleapis.com/jacobdanovitch/twtc/lstm.tar.gz # Will have to change app.py to accept only attention_weights subprocess.call('./serve_model.sh') subprocess.call(['flask', 'run'])
[ "import os, subprocess\n\nos.environ['FLASK_APP'] = \"app/app.py\"\nos.environ['FLASK_DEBUG'] = \"1\"\n\n# for LSTM instead: https://storage.googleapis.com/jacobdanovitch/twtc/lstm.tar.gz\n# Will have to change app.py to accept only attention_weights\n\n\nsubprocess.call('./serve_model.sh')\nsubprocess.call(['flask...
false
3,697
51cdb41836415c08609ee6a6bcc3adbaf2533da4
""" USERS MODEL """ from www import app import mongoengine import datetime class User(mongoengine.Document): username = mongoengine.StringField(required=True) password = mongoengine.StringField(required=True) email = mongoengine.StringField(required=True) active_hash = mongoengine.StringField(re...
[ "\"\"\"\n USERS MODEL\n\"\"\"\n\nfrom www import app\nimport mongoengine\nimport datetime\n\n\nclass User(mongoengine.Document):\n username = mongoengine.StringField(required=True)\n password = mongoengine.StringField(required=True)\n email = mongoengine.StringField(required=True)\n\n active_hash = m...
false
3,698
3d1e6be71f92910cdc9eb2bf60ea7f8f1187f706
''' This script will do auto-check in/out for ZMM100 fingerprint access control device by ZKSoftware. At my office, the manager uses an application to load data from the fingerprint device. After he loads data, log in device's database is cleared. So in my case, I write this script to automate checking in/out everyday...
[ "'''\nThis script will do auto-check in/out for ZMM100 fingerprint access control\ndevice by ZKSoftware.\n\nAt my office, the manager uses an application to load data from the\nfingerprint device. After he loads data, log in device's database is cleared.\nSo in my case, I write this script to automate checking in/o...
false
3,699
10fda09f47c292cb3dc901f42d38ead7757460f5
import json import requests import boto3 import uuid import time profile_name = 'mine' region = 'us-west-2' session = boto3.Session(profile_name=profile_name) api = session.client('apigateway', region_name=region) cf = session.client('cloudformation', region_name=region) def get_key(name_of_key): print('Discover...
[ "import json\nimport requests\nimport boto3\nimport uuid\nimport time\n\nprofile_name = 'mine'\nregion = 'us-west-2'\nsession = boto3.Session(profile_name=profile_name)\napi = session.client('apigateway', region_name=region)\ncf = session.client('cloudformation', region_name=region)\n\n\ndef get_key(name_of_key):\n...
false