code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
primos = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] # números entre (8 - 26) e (44 - 44) intervalo = list(range(8, 27)) + list(range(49, 50)) is_magic = [] for n in primos: quadrado = n ** 2 if quadrado in intervalo: is_magic.append(quadrado) print(len(is_magic)) # 3
normal
{ "blob_id": "b7f443521e165f327aae9ff5d7bbb7b8462abeb5", "index": 2890, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor n in primos:\n quadrado = n ** 2\n if quadrado in intervalo:\n is_magic.append(quadrado)\nprint(len(is_magic))\n", "step-3": "primos = [2, 3, 5, 7, 11, 13, 17, 19, 23, ...
[ 0, 1, 2, 3 ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Cesar Sinchiguano <cesarsinchiguano@hotmail.es> # # Distributed under terms of the BSD license. """ """ import numpy as np from open3d import * def main(): print("Load a ply point cloud, print it, and render it") pcd = read_...
normal
{ "blob_id": "30e8e269cf6500ab804566a85c9b96b3ef9bda36", "index": 4143, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n print('Load a ply point cloud, print it, and render it')\n pcd = read_point_cloud('11.ply')\n \"\"\" read_point_cloud reads a point cloud from a file.\n ...
[ 0, 1, 2, 3, 4 ]
target = [] with open('IntegerArray.txt', 'r') as f: target = f.readlines() for x in range(len(target)): target[x] = int(target[x]) def f(A): if len(A) == 1: return 0 else: rightStart = len(A) // 2 leftArray = A[0:rightStart] righArray = A[rightStart:] B, b = co...
normal
{ "blob_id": "b5611c668a40e1735c92d6d00867885023ad713f", "index": 248, "step-1": "<mask token>\n\n\ndef f(A):\n if len(A) == 1:\n return 0\n else:\n rightStart = len(A) // 2\n leftArray = A[0:rightStart]\n righArray = A[rightStart:]\n B, b = count_and_sort(leftArray)\n ...
[ 2, 3, 4, 5 ]
# Name: CreateDatabase.py # Description: Connects to a point in time in the geodatabase in # PostgreSQL using database authentication. # Import system modules import arcpy import os arcpy.env.workspace="Database Connections" if arcpy.Exists ("Prueba6.sde")==False: arcpy.CreateDatabaseConnection_m...
normal
{ "blob_id": "6e98dfd758700c57ddbb17624472ce2c23cbee6a", "index": 2036, "step-1": "# Name: CreateDatabase.py\n# Description: Connects to a point in time in the geodatabase in\n# PostgreSQL using database authentication.\n\n# Import system modules\nimport arcpy\nimport os\n\n\n\n\narcpy.env.workspace=...
[ 0 ]
import sys sys.stdin = open('retire.txt', 'r') def counseling(pay, row): global max_sum if row == N - 1: if arr[row][0] == 1: pay += arr[row][1] max_sum = max(pay, max_sum) return if row == N: max_sum = max(pay, max_sum) return if row > N - 1: ...
normal
{ "blob_id": "9db2377f15aaf28373959dad88c6ec7b6dacffd2", "index": 9512, "step-1": "<mask token>\n\n\ndef counseling(pay, row):\n global max_sum\n if row == N - 1:\n if arr[row][0] == 1:\n pay += arr[row][1]\n max_sum = max(pay, max_sum)\n return\n if row == N:\n max...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/python import argparse import contextlib import os.path import shutil import subprocess import sys import tempfile from Bio import SeqIO BOOTSTRAP_MODES = 'a', # Some utilities @contextlib.contextmanager def sequences_in_format(sequences, fmt='fasta', **kwargs): with tempfile.NamedTemporaryFile(**kwa...
normal
{ "blob_id": "28532fe798b6a764bec7ea511ba9e66a1d096b6f", "index": 9364, "step-1": "#!/usr/bin/python\n\nimport argparse\nimport contextlib\nimport os.path\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\nfrom Bio import SeqIO\n\nBOOTSTRAP_MODES = 'a',\n\n# Some utilities\n@contextlib.contextmanag...
[ 0 ]
from output.models.sun_data.ctype.content_type.content_type00401m.content_type00401m_xsd.content_type00401m import ( A1, A, ) __all__ = [ "A1", "A", ]
normal
{ "blob_id": "846a42a997539a45576d3ecbe0bd290e00b55935", "index": 3258, "step-1": "<mask token>\n", "step-2": "<mask token>\n__all__ = ['A1', 'A']\n", "step-3": "from output.models.sun_data.ctype.content_type.content_type00401m.content_type00401m_xsd.content_type00401m import A1, A\n__all__ = ['A1', 'A']\n", ...
[ 0, 1, 2, 3 ]
import math # type defining of the variable and playing with variables. a = 5.0 print(id(a)) a = 10 print("hello.....") print(type(a)) print(id(a)) # locating addresses... b = [5, 6, 7] print(id(b)) b.append(10) print(id(b)) # Strings... name = input("Enter Your Name:: ") # iNPUTTING AS NAME pri...
normal
{ "blob_id": "95b75395cafc6ba9f75ecf48157421e37ced2518", "index": 815, "step-1": "<mask token>\n\n\ndef rows(**ro):\n print(ro)\n\n\n<mask token>\n", "step-2": "<mask token>\nprint(id(a))\n<mask token>\nprint('hello.....')\nprint(type(a))\nprint(id(a))\n<mask token>\nprint(id(b))\nb.append(10)\nprint(id(b))\...
[ 1, 3, 4, 5, 6 ]
import cv2 import glob import numpy as np import csv import matplotlib.pyplot as plt from pydarknet import Detector,Image """ Calculates the average precision based on the precision and recall values, which are essentially the output of getPrecisionRecall Returns the 101pt interpolation curve and a single av...
normal
{ "blob_id": "f8a31cdf5f55b5aed33a407d2c008ba9b969d655", "index": 9493, "step-1": "<mask token>\n\n\ndef getIntersection(a, b):\n intersection = [0, 0, 0, 0]\n if b[0] <= a[0] and a[0] <= b[2]:\n intersection[0] = a[0]\n elif a[0] <= b[0] and b[0] <= a[2]:\n intersection[0] = b[0]\n else...
[ 3, 5, 6, 7, 8 ]
import datetime now = datetime.datetime.now() print(now.year, now.month, now.day, now.hour, now.minute, now.second)
normal
{ "blob_id": "3af91de0b25f575ec9d981d7711c710a7e9695e4", "index": 6819, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(now.year, now.month, now.day, now.hour, now.minute, now.second)\n", "step-3": "<mask token>\nnow = datetime.datetime.now()\nprint(now.year, now.month, now.day, now.hour, now.minut...
[ 0, 1, 2, 3 ]
#Creating function def name_of_function(): ''' Docstring explains function. ''' return "Hello" #use return instead of print since return can be stored as a variable. #Simple example def dog_check(mystring): if 'dog' in mystring.lower(): return True else: return False #This is a beginner mo...
normal
{ "blob_id": "1deb070dd91c01190b70fa678add31ecb82f34fa", "index": 3404, "step-1": "def name_of_function():\n \"\"\"\n Docstring explains function.\n \"\"\"\n return 'Hello'\n\n\ndef dog_check(mystring):\n if 'dog' in mystring.lower():\n return True\n else:\n return False\n\n\n<mask tok...
[ 5, 6, 7, 8, 9 ]
import argparse import sys import subprocess import getpass # Process arguments parser = argparse.ArgumentParser(description='Setup a new apache virtual host on an Ubuntu system. Only tested on versions 18.04 and 20.04') parser.add_argument('domain_name', metavar='D', type=str, nargs='+', help='domain name to give to ...
normal
{ "blob_id": "a8e67ddbb741af6a9ff7540fef8c21468321ede0", "index": 7996, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.add_argument('domain_name', metavar='D', type=str, nargs='+', help=\n 'domain name to give to virtual host. multiple domains can be specified at once'\n )\n<mask token>\nprin...
[ 0, 1, 2, 3, 4 ]
import numpy from scipy.optimize import OptimizeResult from logging import getLogger logger = getLogger(__name__) def minimize_neldermead(func, x0, args=(), callback=None, maxiter=None, maxfev=None, disp=False, return_all=False, initial_simplex=None, ...
normal
{ "blob_id": "35921b081e8e8c4da2b16afc20b27b636e9a6676", "index": 4761, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef minimize_neldermead(func, x0, args=(), callback=None, maxiter=None,\n maxfev=None, disp=False, return_all=False, initial_simplex=None, xatol=\n 0.0001, fatol=0.0001, **unkno...
[ 0, 1, 2, 3, 4 ]
from typing import Any, Callable, Generator, List, Optional import pytest from _pytest import nodes from _pytest.config import hookimpl from _pytest.python import Function, PyCollector # type: ignore from hypothesis.errors import InvalidArgument # pylint: disable=ungrouped-imports from .._hypothesis import create_t...
normal
{ "blob_id": "2060f0af351c1487f8aa45943dbaa050f4291c58", "index": 7791, "step-1": "<mask token>\n\n\nclass SchemathesisCase(PyCollector):\n <mask token>\n\n def _get_test_name(self, endpoint: Endpoint) ->str:\n return f'{self.name}[{endpoint.method}:{endpoint.path}]'\n\n def _gen_items(self, endpo...
[ 4, 6, 7, 8, 9 ]
from data.dataframe_sequence_multi import DataFrameSequenceMulti from metrics import Metrics from models.models_ts_multi import lstm_model_multi import threading import sys from keras import optimizers from data.data_helper import plot_history epochs = 100 start = 6 end = 18 res = [] sets = [] min_vals = [] min_loss ...
normal
{ "blob_id": "af903feda57e4ace0c7f909abbeb86bb9a7e4d8c", "index": 1806, "step-1": "<mask token>\n\n\ndef run_final_test_days():\n sqs = [5]\n cams = [1]\n permutations = [(True, True, True)]\n permutations_names = ['all data perez']\n for pidx, p in enumerate(permutations):\n for s in sqs:\n...
[ 3, 5, 7, 8, 9 ]
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf tf.__version__ import glob import imageio import matplotlib.pyplot as plt import numpy as np import os import PIL from tensorflow.keras import layers import time import pathlib from IPython import display ###---...
normal
{ "blob_id": "e007e2d32fa799e7658813f36911616f7bf58b48", "index": 3972, "step-1": "<mask token>\n\n\ndef preprocess_image(image):\n image = tf.image.decode_jpeg(image, channels=3)\n image = tf.image.resize(image, [280, 280])\n image /= 255.0\n return image\n\n\n<mask token>\n\n\ndef make_generator_mod...
[ 8, 10, 12, 13, 14 ]
class Book: """Class that defines book model.""" def __init__(self, title, authors, pub_year): self.title = title self.authors = authors self.pub_year = pub_year
normal
{ "blob_id": "14345a8c4e20d84dfc87476d890f59530a8f4d96", "index": 7237, "step-1": "<mask token>\n", "step-2": "class Book:\n <mask token>\n <mask token>\n", "step-3": "class Book:\n <mask token>\n\n def __init__(self, title, authors, pub_year):\n self.title = title\n self.authors = a...
[ 0, 1, 2, 3 ]
import unittest import hospital.employee.nurse as n class TestNurse(unittest.TestCase): @classmethod def setUpClass(cls): print('Start testing nurse') def setUp(self): self.n1 = n.Nurse('Tess',18,"5436890982",3200,25) self.n2 = n.Nurse('Melissa',40,"8920953924",9000,5) def...
normal
{ "blob_id": "f24075ea70851ce95bb6b3cd87b6417f8141d546", "index": 9112, "step-1": "<mask token>\n\n\nclass TestNurse(unittest.TestCase):\n <mask token>\n\n def setUp(self):\n self.n1 = n.Nurse('Tess', 18, '5436890982', 3200, 25)\n self.n2 = n.Nurse('Melissa', 40, '8920953924', 9000, 5)\n <m...
[ 7, 8, 9, 11, 13 ]
from django.contrib import admin from lesson.models import ProgrammingEnvironment, Language, Lesson, LessonHint # list_display - Show these fields for each model on the Admin site # search_fields - Allow searching in these fields # Register models for the Admin site class ProgrammingEnvironmentAdmin(admin.ModelAdmin)...
normal
{ "blob_id": "2500c3562819e4e85ce3cbc30e0ddf1b8437e0a2", "index": 6448, "step-1": "<mask token>\n\n\nclass LanguageAdmin(admin.ModelAdmin):\n <mask token>\n list_display = 'language_name', 'description', 'environment'\n filter_horizontal = ()\n list_filter = ()\n fieldsets = ()\n\n\nclass LessonAdm...
[ 8, 9, 12, 14, 15 ]
from datetime import datetime import struct BEACON_LENGTH = 84 EPS_LENGTH = 20 COM_LENGTH = 10 # reverse engineered ADCS1_LENGTH = 7 ADCS2_LENGTH = 6 AIS_LENGTH = 20 class EPS(object): def __init__(self, eps_data): if len(eps_data) != EPS_LENGTH: raise InputException(len(eps_data), EPS_LENGTH...
normal
{ "blob_id": "505689803c8f4490619ab1a7579fde1e2c18c538", "index": 5532, "step-1": "<mask token>\n\n\nclass ADCS2(object):\n\n def __init__(self, adcs2_data):\n self.gyro = tuple(struct.unpack('>hhh', adcs2_data))\n <mask token>\n\n\nclass AIS(object):\n\n def __init__(self, ais_data):\n sel...
[ 8, 10, 19, 20, 21 ]
"""SamsungTV Encrypted.""" import aiohttp from aioresponses import aioresponses import pytest from yarl import URL from samsungtvws.encrypted.authenticator import SamsungTVEncryptedWSAsyncAuthenticator @pytest.mark.asyncio async def test_authenticator(aioresponse: aioresponses) -> None: with open("tests/fixtures...
normal
{ "blob_id": "e1448e62020f87e315d219be97d9af84607441df", "index": 9104, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@pytest.mark.asyncio\nasync def test_authenticator(aioresponse: aioresponses) ->None:\n with open('tests/fixtures/auth_pin_status.xml') as file:\n aioresponse.get('http://1....
[ 0, 1, 2, 3 ]
# -*- coding:UTF-8 -*- from __future__ import print_function import logging import numpy as np from optparse import OptionParser import sys from time import time import matplotlib.pyplot as plt import os from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from skl...
normal
{ "blob_id": "84a516e924252d897be7444e11acfecd66474090", "index": 1177, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open(forbidpath, 'rb') as f:\n for line in f:\n word = line.strip()\n forbidkword[word] = 0\n<mask token>\nwith open(inputpath, 'rb') as f:\n for line in f:\n ...
[ 0, 1, 2, 3, 4 ]
import numpy as np er = ['why','who','how','where','which','what','when','was','were','did','do','does','is','are','many','much'] qst = [] txt = None ans = None fnd = [] def chek_qst(qst): global er for h in er: for i in qst: if i == h: qst.remove(i) # qst ...
normal
{ "blob_id": "d30129248f5245560ee0d3ee786e118427e169d7", "index": 4616, "step-1": "<mask token>\n\n\ndef search_word(qst):\n global txt\n for h in qst:\n temp = []\n for n, l in enumerate(txt):\n if [n for i, j in enumerate(l) if h in j] != []:\n temp.append(n)\n ...
[ 3, 6, 7, 8, 9 ]
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.utils import timezone from timesheets.models import TimeSheet from channels import Group class ProjectTS(models.Model): class Meta: ...
normal
{ "blob_id": "df39a97db25f03aca8ebd501283fd6a7c486db8c", "index": 1243, "step-1": "<mask token>\n\n\nclass ProjectTSEntry(models.Model):\n description = models.CharField(max_length=150, default='')\n project_time_sheet = models.ForeignKey(ProjectTS, related_name=\n 'project_time_sheet')\n project_...
[ 3, 4, 5, 6, 7 ]
from __future__ import absolute_import, unicode_literals from django.db import DataError, IntegrityError, connection import pytest from .models import Page pytestmark = pytest.mark.django_db MYSQL_REASON = 'MySQL parses check constraints but are ignored by all engines' def test_match(): Page.objects.create(u...
normal
{ "blob_id": "96065e7e61b63f915561f117d71092e4bfb9a5da", "index": 1149, "step-1": "<mask token>\n\n\n@pytest.mark.skipif('connection.vendor == \"mysql\"', reason=MYSQL_REASON)\ndef test_invalid_regex():\n exception = IntegrityError if connection.vendor == 'sqlite' else DataError\n with pytest.raises(excepti...
[ 1, 3, 4, 5, 7 ]
import requests import urllib.request from utilities.read_write_utilities import read_set,write_to_csv import time from bs4 import BeautifulSoup import pickledb import json import glob import csv drugs = read_set('/Users/sandeep.dey/Downloads/2020-02-06_scrape/drugs') print(drugs) output_records = [] # fields = ["equ...
normal
{ "blob_id": "e7f511b97f316157a768203afe9f36ea834ebb6c", "index": 5493, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(drugs)\n<mask token>\nfor drug in drugs:\n with open('/Users/sandeep.dey/Downloads/2020-02-06_scrape/%s' % drug\n ) as json_file:\n for record in json.load(json_fil...
[ 0, 1, 2, 3, 4 ]
import ccxt import json import time from baglanti import mysql_baglan import datetime import requests from urllib.parse import urljoin import sys db = mysql_baglan("bingo") cursor = db.cursor() cursor.execute('SET NAMES utf8;') cursor.execute('SET CHARACTER SET utf8;') cursor.execute('SET character_set_co...
normal
{ "blob_id": "1d29ce58ca626155d626216fbbd70d7b241efa25", "index": 6363, "step-1": "<mask token>\n", "step-2": "<mask token>\ncursor.execute('SET NAMES utf8;')\ncursor.execute('SET CHARACTER SET utf8;')\ncursor.execute('SET character_set_connection=utf8;')\n<mask token>\ncursor.execute(sql)\n<mask token>\nfor ro...
[ 0, 1, 2, 3, 4 ]
from app.routes import home from .home import bp as home from .dashboard import bp as dashboard
normal
{ "blob_id": "358a4948ac1f60e0966328cebf401777042c3d0e", "index": 5239, "step-1": "<mask token>\n", "step-2": "from app.routes import home\nfrom .home import bp as home\nfrom .dashboard import bp as dashboard\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
# encoding=utf-8 from lib.calculate_time import tic,toc import scipy as sp import numpy as np from lib.make_A import make_A from lib.make_distance import make_distance from lib.lambda_sum_smallest import lambda_sum_smallest from lib.fiedler import fiedler from lib.make_al import make_al import math from lib.newmatrix i...
normal
{ "blob_id": "77d545d1a4fc5f96ae19f654a32ab75707434d46", "index": 7614, "step-1": "# encoding=utf-8\nfrom lib.calculate_time import tic,toc\nimport scipy as sp\nimport numpy as np\nfrom lib.make_A import make_A\nfrom lib.make_distance import make_distance\nfrom lib.lambda_sum_smallest import lambda_sum_smallest\n...
[ 0 ]
def prime_sieve(n): if n==2: return [2] elif n<2: return [] s=range(3,n+1,2) mroot = n ** 0.5 half=(n+1)/2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)/2 s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i+3 return [2]+[x for x in s if x] ps = prime_sieve(1000000) def get_primes_upto(n): ...
normal
{ "blob_id": "5771f49ad5254588f1683a8d45aa81ce472bb562", "index": 30, "step-1": "\ndef prime_sieve(n): \n\tif n==2: return [2]\n\telif n<2: return []\n\ts=range(3,n+1,2)\n\tmroot = n ** 0.5\n\thalf=(n+1)/2-1\n\ti=0\n\tm=3\n\twhile m <= mroot:\n\t\tif s[i]:\n\t\t\tj=(m*m-3)/2\n\t\t\ts[j]=0\n\t\t\twhile j<half:\n\t...
[ 0 ]
import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import pandas as pd import time from urllib.request import Request import requests import json import re import sys def compare(mystring): def usd_to_ngn(): print("Getting USD to NGN Rate") r...
normal
{ "blob_id": "d96038a715406388b4de4611391dee18fc559d5a", "index": 2693, "step-1": "<mask token>\n\n\ndef compare(mystring):\n\n def usd_to_ngn():\n print('Getting USD to NGN Rate')\n req = requests.get(\n 'http://free.currconv.com/api/v7/convert?q=USD_NGN&apiKey=5029a99b396929294f63'\n...
[ 1, 2, 3, 4, 5 ]
import configure import connectify import userlog import dirlog import time def getUser(sock): try: userinfo = userlog.getInfo() except: userinfo = configure.init(sock) userinfo = userinfo.split('^')[0] # print userinfo return userinfo if __name__=="__main__": sock = connectify.createCon() userinfo = get...
normal
{ "blob_id": "2ca1b603b18316bc1d970b5e32389e10e4b532e2", "index": 1071, "step-1": "import configure\nimport connectify\nimport userlog\nimport dirlog\nimport time\n\n\ndef getUser(sock):\n\ttry:\n\t\tuserinfo = userlog.getInfo()\n\texcept:\t\n\t\tuserinfo = configure.init(sock)\n\tuserinfo = userinfo.split('^')[0...
[ 0 ]
# coding=utf-8 # Copyright 2019 SK T-Brain 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 applicable law or...
normal
{ "blob_id": "b6e4214ace89165f6cfde9f2b97fcee8be81f2ed", "index": 4301, "step-1": "<mask token>\n\n\ndef get_onnx_kobert_model(cachedir='.cache'):\n \"\"\"Get KoBERT ONNX file path after downloading\"\"\"\n onnx_kobert = {'url':\n 's3://skt-lsl-nlp-model/KoBERT/models/kobert.onnx1.8.0.onnx',\n ...
[ 1, 2, 3, 4, 5 ]
# The error measures used in this project # # Rooth Mean Squared Error # Mean Absolute Error # # ! Both calculated after descaling the output of the system first import numpy as np def RMSE(min_y, max_y, yhat, y): # first scale output and target back to # original scale, to prevent scale bias yhat = descale(yhat,...
normal
{ "blob_id": "4fd4c9cf3bdb73a003ce860bf2ee0ccab01f0009", "index": 4646, "step-1": "<mask token>\n\n\ndef RMSE(min_y, max_y, yhat, y):\n yhat = descale(yhat, min_y, max_y)\n y = descale(y, min_y, max_y)\n return np.mean(np.power(np.subtract(yhat, y), 2))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n...
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- elements = str(input("Type the elements of list: ")).split() elements = list(map(float,elements)) times = int(input("How many times you wish shift to right: ")) for _ in range(times): removed = elements.pop() elements.insert(0,removed) print(elements)
normal
{ "blob_id": "307bb7461a729ba979f6a862fe7c292c42f96ce6", "index": 1164, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor _ in range(times):\n removed = elements.pop()\n elements.insert(0, removed)\nprint(elements)\n", "step-3": "elements = str(input('Type the elements of list: ')).split()\neleme...
[ 0, 1, 2, 3 ]
# encoding:utf-8 import tensorflow as tf import p182.py as p182 # 创建文件列表,并通过文件列表创建输入文件队列。在调用输入数据处理流程前,需要 # 统一所有原始数据的格式并将它们存储到TFRcord文件中。下面给出的文件列表应该包含所 # 有提供训练数据的TFRcord文件 files = tf.train.match_filenames_once("/home/shenxj/tf-work/datasets/file_pattern-*") filename_queue = tf.train.string_input_producer(files, shuffle=...
normal
{ "blob_id": "1685a2c49bea14e6fcaffb03634f6875f8fa1049", "index": 3726, "step-1": "<mask token>\n", "step-2": "<mask token>\ndecoded_image.set_shape([height, width, channels])\n<mask token>\nwith tf.Session() as sess:\n tf.initialize_all_variables().run()\n coord = tf.train.Coordinator()\n threads = tf...
[ 0, 1, 2, 3, 4 ]
# -*- coding:utf-8 -*- #随机森林调参 #RandomizedSearchCV 随机最佳 #GridSearchCV 地毯式最佳 import pandas as pd features = pd.read_csv('data/temps_extended.csv') features = pd.get_dummies(features) labels = features['actual'] features = features.drop('actual', axis = 1) feature_list = list(features.columns) import numpy as np...
normal
{ "blob_id": "de4e14a4fa8520c1aae60805084224337dd9620c", "index": 9009, "step-1": "<mask token>\n\n\ndef evaluate(model, test_features, test_labels):\n predictions = model.predict(test_features)\n errors = abs(predictions - test_labels)\n mape = 100 * np.mean(errors / test_labels)\n accuracy = 100 - m...
[ 1, 2, 3, 4, 5 ]
from celery.task.schedules import crontab from celery.decorators import periodic_task from celery.utils.log import get_task_logger from bbapp.scripts.getScores import doScoresScrape, fixScores logger = get_task_logger(__name__) @periodic_task( run_every=(crontab(minute='*/10')), name="scrape_espn_feed", ...
normal
{ "blob_id": "a9a067ee3b176d2f2ca558b69ce2bc598bb31d22", "index": 4501, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@periodic_task(run_every=crontab(minute='*/10'), name='scrape_espn_feed',\n ignore_result=True)\ndef scrape_espn_feed():\n \"\"\"\n Saves latest image from Flickr\n \"\"\"...
[ 0, 1, 2, 3, 4 ]
import random # library to create window in the terminal import curses # initialized curses by returning a window object stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) curses.curs_set(0) height, width = stdscr.getmaxyx() # create a new window of a given size window = cur...
normal
{ "blob_id": "153d37b58a10847aae1fa7dbec4c7576c3d97fb2", "index": 3407, "step-1": "<mask token>\n", "step-2": "<mask token>\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(True)\ncurses.curs_set(0)\n<mask token>\nwindow.keypad(1)\nwindow.timeout(100)\n<mask token>\nwindow.addch(int(food[0]), int(food[1]), curs...
[ 0, 1, 2, 3, 4 ]
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...
normal
{ "blob_id": "919e1f8a4b021d75496f3bcff369261a09362a65", "index": 3645, "step-1": "<mask token>\n\n\ndef gradient_descent(f: Callable[[np.ndarray], float], f_grad: Callable[[np\n .ndarray], np.ndarray], start: np.ndarray, step_strategy: st.\n StepStrategy, stop_criteria: sc.StopCriteria, eps_strategy: float...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # # Copyright (c) 2020 PanXu, Inc. All Rights Reserved # """ 测试 label index decoder Authors: PanXu Date: 2020/07/05 15:10:00 """ import pytest import torch from easytext.tests import ASSERT from easytext.data import LabelVocabulary from easytext.modules import Cond...
normal
{ "blob_id": "f64138ee5a64f09deb72b47b86bd7795acddad4d", "index": 9980, "step-1": "<mask token>\n\n\nclass CRFData:\n \"\"\"\n 测试用的 crf 数据\n \"\"\"\n\n def __init__(self):\n bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]\n self.label_vocabulary = LabelVocabulary(labels=bio_labels, padd...
[ 3, 5, 6, 7, 8 ]
def parse(filename): t1, t2 = open(filename).read().strip().split("\n\n") return tuple(map(lambda x: list(map(int, x.split("\n")[1:])), [t1, t2])) def score(deck): res = 0 for i in range(len(deck)): res += deck[i] * (len(deck)-i) return res def solution1(deck1, deck2): while len(deck1) > 0 and len(deck2) > 0:...
normal
{ "blob_id": "508d016161131481ace41f3d3bda005423125fe5", "index": 5635, "step-1": "def parse(filename):\n t1, t2 = open(filename).read().strip().split('\\n\\n')\n return tuple(map(lambda x: list(map(int, x.split('\\n')[1:])), [t1, t2]))\n\n\ndef score(deck):\n res = 0\n for i in range(len(deck)):\n ...
[ 4, 5, 6, 8, 9 ]
#!/usr/bin/python3.8 # -*- coding: utf-8 -*- __version__ = "0.2.2" __author__ = 'Anton Vanke <f@hpu.edu.cn>' class Gobang: """ 五子棋 ===== 一个简单的五子棋类, 可以在控制台下五子棋. 提供以下函数 : new(): 新局 printcb(): 打印棋盘 player(): 获取当前应落子 ID (轮走方) sortstep(): 处理总步表 loadstep(): 将 step 步表...
normal
{ "blob_id": "e0394bfed51cd0af9bca06867e9b556b226f37d1", "index": 1720, "step-1": "<mask token>\n\n\nclass Gobang:\n <mask token>\n <mask token>\n\n def new(self):\n \"\"\"新局\"\"\"\n self.__init__()\n\n def printcb(self):\n \"\"\"打印棋盘\"\"\"\n print('\\x1b[7;32;40m+ ', end...
[ 8, 11, 14, 15, 16 ]
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'])
normal
{ "blob_id": "cbad5d6f381e788a2f064aac0a5d468f40b39c93", "index": 3696, "step-1": "<mask token>\n", "step-2": "<mask token>\nsubprocess.call('./serve_model.sh')\nsubprocess.call(['flask', 'run'])\n", "step-3": "<mask token>\nos.environ['FLASK_APP'] = 'app/app.py'\nos.environ['FLASK_DEBUG'] = '1'\nsubprocess.c...
[ 0, 1, 2, 3, 4 ]
from django.contrib import admin # from .models import Product, Client from .models import Board admin.site.register(Board) # admin.site.register(Product) # # admin.site.register(Price) # admin.site.register(Client) # # Register your models here.
normal
{ "blob_id": "ea323a8398ceff8496e7f8d0f365d50f3115e954", "index": 5228, "step-1": "<mask token>\n", "step-2": "<mask token>\nadmin.site.register(Board)\n", "step-3": "from django.contrib import admin\nfrom .models import Board\nadmin.site.register(Board)\n", "step-4": "from django.contrib import admin\n# fr...
[ 0, 1, 2, 3 ]
from django.contrib import admin from django.urls import path from petsApp import views urlpatterns = [ path('user/<int:id>/', views.getUser), path('user/addImage/', views.addImage), path('user/getImage/<int:id>/', views.getImage), path('user/signup/', views.signUp), path('user/login/', views.logI...
normal
{ "blob_id": "2458b8169029b3af501b650d548925770b0da74e", "index": 6656, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('user/<int:id>/', views.getUser), path('user/addImage/',\n views.addImage), path('user/getImage/<int:id>/', views.getImage), path(\n 'user/signup/', views.signUp...
[ 0, 1, 2, 3 ]
from numpy import * from numpy.linalg import* preco = array(eval(input("Alimentos: "))) alimento = array([[ 2, 1 ,4 ], [1 , 2 , 0], [2 , 3 , 2 ]]) r = dot(inv(alimento),preco.T) # print("estafilococo: ", round(r[0] , 1)) print("salmonela: ", round(r[1], 1)) print("coli: ", round(r[2], 1)) if r[0] ...
normal
{ "blob_id": "0f3e12f35cc29a71be5b8e6d367908e31c200c38", "index": 3896, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('estafilococo: ', round(r[0], 1))\nprint('salmonela: ', round(r[1], 1))\nprint('coli: ', round(r[2], 1))\nif r[0] == min(r):\n print('estafilococo')\nelif r[1] == min(r):\n pr...
[ 0, 1, 2, 3, 4 ]
import sys import os import numpy as np import math sys.path.append("../") from sir.improveagent import * import numpy as np import numpy.linalg as la import matplotlib.pyplot as plt #from sklearn.neighbors import BallTree from scipy.spatial import KDTree from scipy.spatial import cKDTree from scipy.spatial.distance im...
normal
{ "blob_id": "92317996f884befd646138cd3a3dc3f8345679f4", "index": 2122, "step-1": "<mask token>\n\n\ndef run_Simulation2(k, N=100, T=10, start=1, p=0.5, q=0.08, startcenter=\n False, startcorner=False):\n \"\"\"\n run the simulation for the pop\n \"\"\"\n recover = [0]\n infect = [start]\n su...
[ 3, 4, 5, 6, 7 ]
import logging import argparse import getpass import errno import re import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import dns.resolver class Mail(object): def __init__(self, recipient=None, sender=None, subject=None, body=None): self.recipient = recipi...
normal
{ "blob_id": "3a678f9b5274f008a510a23b2358fe2a506c3221", "index": 4061, "step-1": "<mask token>\n\n\nclass Mail(object):\n <mask token>\n <mask token>\n\n @property\n def message(self):\n m = MIMEMultipart('alternative')\n m['Subject'] = self.subject\n m['From'] = self.sender\n ...
[ 5, 6, 7, 8, 11 ]
import json import jieba import util from pypinyin import pinyin, Style class Song: def __init__(self, songName, artistName, lyric): self.songName = songName self.artistName = artistName self.lyric = lyric self.phrasePinyinDict = util.lyricToPinYi(self.lyric) def getSongName(se...
normal
{ "blob_id": "fa3cec0781b9ca5c1d99a7500748104d7cdce631", "index": 130, "step-1": "<mask token>\n\n\nclass Song:\n\n def __init__(self, songName, artistName, lyric):\n self.songName = songName\n self.artistName = artistName\n self.lyric = lyric\n self.phrasePinyinDict = util.lyricToP...
[ 6, 7, 8, 9, 10 ]
import discord from discord.ext import commands import datetime from discord.utils import get from discord import User class Sinner(commands.Converter): async def convert(self, ctx, argument): argument = await commands.MemberConverter().convert(ctx, argument) permission = argument.guild_permissions...
normal
{ "blob_id": "16cd89a43a1985276bd14d85ad8ddb990c4d82c3", "index": 6136, "step-1": "<mask token>\n\n\nclass Redeemed(commands.Converter):\n\n async def convert(self, ctx, argument):\n argument = await commands.MemberConverter().convert(ctx, argument)\n muted = discord.utils.get(ctx.guild.roles, na...
[ 4, 5, 7, 8, 9 ]
# https://py.checkio.org/blog/design-patterns-part-1/ class ImageOpener(object): @staticmethod def open(filename): raise NotImplementedError() class PNGImageOpener(ImageOpener): @staticmethod def open(filename): print('PNG: open with Paint') class JPEGImageOpener(ImageOpener): @...
normal
{ "blob_id": "c199b2f87b7a4ac820001dab13f24fdd287a1575", "index": 3507, "step-1": "<mask token>\n\n\nclass UnknownImageOpener(ImageOpener):\n\n @staticmethod\n def open(filename):\n print(\"You don't hame program for %s extension\" % filename.split(\n '.')[-1].upper())\n\n\nclass Image(obj...
[ 5, 6, 12, 13, 15 ]
from tkinter import * import mathcalc as c root= Tk() root.title("CALCULATOR") ent=Entry(root,width=35) ent.grid(row=0,column=0,columnspan=3,padx=10,pady=10) #ent.grid(row=0,column=0) ch='' num=ent.get() def clicked(num): current=ent.get() ent.delete(0,END) ent.insert(0,str(current)+str(num)) def click...
normal
{ "blob_id": "bdd9ebfa9a2f14d57efd527ca88032bfb0160a5e", "index": 7504, "step-1": "<mask token>\n\n\ndef clicked(num):\n current = ent.get()\n ent.delete(0, END)\n ent.insert(0, str(current) + str(num))\n\n\ndef click_clear():\n ent.delete(0, END)\n\n\ndef add():\n global ch\n ch = '+'\n clic...
[ 7, 8, 9, 10, 11 ]
import datetime import time import boto3 from botocore.config import Config # FinSpace class with Spark bindings class SparkFinSpace(FinSpace): import pyspark def __init__( self, spark: pyspark.sql.session.SparkSession = None, config = Config(retries = {'max_attempts': 0, 'mode': 'sta...
normal
{ "blob_id": "4f4af4caf81397542e9cd94c50b54303e2f81881", "index": 3926, "step-1": "<mask token>\n\n\nclass SparkFinSpace(FinSpace):\n import pyspark\n <mask token>\n\n def upload_dataframe(self, data_frame: pyspark.sql.dataframe.DataFrame):\n resp = self.client.get_user_ingestion_info()\n u...
[ 3, 5, 6, 7, 8 ]
from layers import TrueSkillFactorGraph from math import e, sqrt from numerics import atLeast, _Vector, _DiagonalMatrix, Matrix from objects import SkillCalculator, SupportedOptions, argumentNotNone, \ getPartialPlayPercentage, sortByRank class FactorGraphTrueSkillCalculator(SkillCalculator): def __init__(self): s...
normal
{ "blob_id": "009be282e45d191eb8f4d7d2986a2f182d64c1dd", "index": 2935, "step-1": "<mask token>\n\n\nclass FactorGraphTrueSkillCalculator(SkillCalculator):\n\n def __init__(self):\n super(FactorGraphTrueSkillCalculator, self).__init__(\n SupportedOptions.PARTIAL_PLAY | SupportedOptions.PARTIA...
[ 6, 7, 8, 9, 10 ]
# getting a sample of data to parse for the keys of the players import requests import xml.etree.ElementTree as ET currentPlayerInfoUrl="http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=1&LeagueID=00&Season=2015-16" r=requests.get(currentPlayerInfoUrl) if r.status_code == requests.codes.ok: with open(...
normal
{ "blob_id": "68f8b301d86659f9d76de443b0afe93fd7f7e8c2", "index": 6588, "step-1": "<mask token>\n", "step-2": "<mask token>\nif r.status_code == requests.codes.ok:\n with open('currentPlayerDump.json', 'w') as f:\n for line in r.text:\n f.write(line)\n", "step-3": "<mask token>\ncurrentPl...
[ 0, 1, 2, 3, 4 ]
""" Authentication views. login() Flask view to log a user in. """ import functools from typing import Any, Callable, cast, Dict from flask import Blueprint, make_response, request, session from werkzeug.security import check_password_hash as _check_password_hash from .accesscontrol import PERMISSIONS from .api...
normal
{ "blob_id": "2d36ae916ad257615016ed6c0bc67e506ee313c9", "index": 1528, "step-1": "<mask token>\n\n\n@bp.route('/login', methods=('POST',))\ndef login() ->Any:\n \"\"\"Flask view for logging a user in.\"\"\"\n user_dict = UserSchema().load(request.json, partial=('id',\n 'qualifications') + PERMISSION...
[ 4, 6, 7, 8, 9 ]
import numpy as np import cv2 def optical_flow_from_video(): cap = cv2.VideoCapture("/home/ubuntu/data1.5TB/异常dataset/Avenue_dataset/training_videos/01.avi") # 设置 ShiTomasi 角点检测的参数 feature_params = dict(maxCorners=100, qualityLevel=0.3, minDistance=7, blockSize=7) # 设置 lucas kanade 光流场的参数 # maxLe...
normal
{ "blob_id": "ae0547aa1af2d4dd73bb60154574e64e74107a58", "index": 4062, "step-1": "<mask token>\n\n\ndef optical_flow_from_video():\n cap = cv2.VideoCapture(\n '/home/ubuntu/data1.5TB/异常dataset/Avenue_dataset/training_videos/01.avi'\n )\n feature_params = dict(maxCorners=100, qualityLevel=0.3,...
[ 5, 6, 7, 8, 10 ]
import media import fresh_tomatoes toy_story = media.Movie("Toy Story", "A story of a boy and his toys that come to life", '<p><a href="https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg"><img src="https://upload.wikimedia.org/wikipedia/en/1/13/To...
normal
{ "blob_id": "e2f6e6e872f95471ebbc8b25bde08247fe8f7e61", "index": 8829, "step-1": "<mask token>\n", "step-2": "<mask token>\nfresh_tomatoes.open_movies_page(movies)\n", "step-3": "<mask token>\ntoy_story = media.Movie('Toy Story',\n 'A story of a boy and his toys that come to life',\n '<p><a href=\"http...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding:utf-8 -*- school = "Old boy" def chang_name(name): global school #声明全局变量 school = "Mage Linux" print("Before change:", name, school) name = 'Stack Cong' age = 33 print("After change:", name) print("School:", school) name = "Stack" chang_name(name) print(na...
normal
{ "blob_id": "a9531fb020428e573d189c377652692e301ea4d3", "index": 3026, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef chang_name(name):\n global school\n school = 'Mage Linux'\n print('Before change:', name, school)\n name = 'Stack Cong'\n age = 33\n print('After change:', name)...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python import sys import random def has_duplicates(list) : """Returns True if there are duplicate in list, false otherwise""" copy = list[:] copy.sort() for item in range(len(list)-1): if copy[item] == copy[item + 1]: return True; return False; def gen_birthdays(n): """returns a list ...
normal
{ "blob_id": "e34e1e220c6d0fe2dc3d42caaefb04b178cdd120", "index": 3768, "step-1": "#!/usr/bin/python\nimport sys\nimport random\n\ndef has_duplicates(list) :\n \"\"\"Returns True if there are duplicate in list, false otherwise\"\"\"\n copy = list[:]\n copy.sort()\n for item in range(len(list)-1):\n if copy...
[ 0 ]
# Head start. # ask me for this solution: 6cb9ce6024b5fd41aebb86ccd40d8080 # this line is not needed, just for better output: from pprint import pprint # just remove the top line def count_or_add_trigrams(trigram, trigrams_so_far): ''' Takes a trigram, and a list of previously seen trigrams and ...
normal
{ "blob_id": "753cc532e4d049bacff33c97de4d80bb9ab8ece8", "index": 2655, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef count_or_add_trigrams(trigram, trigrams_so_far):\n \"\"\"\n Takes a trigram, and a list of previously seen trigrams\n and yields the same list with all discovered and cou...
[ 0, 2, 3, 4, 5 ]
# coding: utf-8 # # Configuration # In[1]: CONNECTION_STRING = "mongodb://localhost:27017" DATABASE_NAME = "off" COLLECTION_NAME = "products" # # MongDB connection # In[2]: from pymongo import MongoClient from bson.code import Code import plotly, pymongo plotly.offline.init_notebook_mode() from plotly.graph_obj...
normal
{ "blob_id": "2ecd234753fabbca2829dc86db2f740e371e4ea7", "index": 6499, "step-1": "\n# coding: utf-8\n\n# # Configuration\n\n# In[1]:\n\nCONNECTION_STRING = \"mongodb://localhost:27017\"\nDATABASE_NAME = \"off\"\nCOLLECTION_NAME = \"products\"\n\n\n# # MongDB connection\n\n# In[2]:\n\nfrom pymongo import MongoCli...
[ 0 ]
import torch import torch.nn as nn import torch.nn.functional as F # Const. low-rank version class xCNNlow(torch.nn.Module): def __init__(self, channels, filters, kernel_size, padding=0, stride=1, groups=1, rank=1, bias=True): super(xCNNlow, self).__init__() self.filters = filters self.time...
normal
{ "blob_id": "f714c7006f50379cc7508a13d710d902d38d2d1f", "index": 425, "step-1": "<mask token>\n\n\nclass xCNNlow(torch.nn.Module):\n\n def __init__(self, channels, filters, kernel_size, padding=0, stride=1,\n groups=1, rank=1, bias=True):\n super(xCNNlow, self).__init__()\n self.filters =...
[ 2, 3, 4, 5, 6 ]
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data import numpy as np def weight_init(layers): for layer in layers: if isinstance(layer, nn.BatchNorm1d): layer.weight.data.fill_(1) layer.bias.data.zero_() elif isinstance(layer, nn.Lin...
normal
{ "blob_id": "2c2b075f9ea9e8d6559e44ad09d3e7767c48205e", "index": 6772, "step-1": "<mask token>\n\n\nclass LR(nn.Module):\n <mask token>\n <mask token>\n\n\nclass RNN(nn.Module):\n\n def __init__(self, feature_nums, hidden_dims, bi_lstm, out_dims=1):\n super(RNN, self).__init__()\n self.fea...
[ 7, 9, 10, 11, 12 ]
# _*_ coding: utf-8 _*_ from service import service_logger from service.TaskService import TaskService class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data...
normal
{ "blob_id": "0ac14b023c51bfd1cf99bd2d991baa30a671e066", "index": 9994, "step-1": "<mask token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\...
[ 3, 4, 5, 6, 7 ]
import unittest import numpy import set_solver class TestSets(unittest.TestCase): def test_is_set(self): """Test set validator (Exercise 3a).""" cards = numpy.array([[1, 1, 1, 2, 0], [0, 1, 2, 2, 2], [0, 1, 2, 2, 2], [0, 1, 2, 2, 2]]) self.assertTrue(set_solver.is_set(cards, [...
normal
{ "blob_id": "6065fae2a11f6b525ef10346e297505ec9d4e9d5", "index": 8550, "step-1": "<mask token>\n\n\nclass TestSets(unittest.TestCase):\n\n def test_is_set(self):\n \"\"\"Test set validator (Exercise 3a).\"\"\"\n cards = numpy.array([[1, 1, 1, 2, 0], [0, 1, 2, 2, 2], [0, 1, 2, 2,\n 2],...
[ 2, 3, 4, 5 ]
# Generated by Django 3.1.6 on 2021-04-22 07:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0004_project_is_featured'), ] operations = [ migrations.AlterField( model_name='project', name='pin_id',...
normal
{ "blob_id": "24ed29dfaaf7ce508b2d80740bad1304b291c596", "index": 8466, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('projects', ...
[ 0, 1, 2, 3, 4 ]
import random import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import fetch_mldata from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, LabelBinarizer from ann.act import relu, softmax_with_xentropy from ann.loss import xentropy_with_softmax fr...
normal
{ "blob_id": "2f6e5ed4e2d52190551dec2ac18441b8355699b5", "index": 7096, "step-1": "<mask token>\n\n\ndef plot(ax, ls_batch, ls_dev, its, title):\n ax.plot(range(len(ls_batch)), ls_batch, label='Batch')\n ax.plot(range(len(ls_dev)), ls_dev, label='Dev')\n ax.text(0.3, 0.93, 'Batch: {:.3f}'.format(ls_batch...
[ 1, 2, 3, 4, 5 ]
import pandas as pd import folium ctx = '../data/' json = ctx + 'us-states.json' csv = ctx + 'US_Unemployment_Oct2012.csv' data = pd.read_csv(csv) m = folium.Map(location=[37, -102], zoom_start=5) m.choropleth(geo_data=json, name='choropleth', data=data, columns=['State', 'Unemployment'], Key_on='feature.id', fill_...
normal
{ "blob_id": "382cb55a6b849f0240276d8f45746e995b16d714", "index": 4455, "step-1": "<mask token>\n", "step-2": "<mask token>\nm.choropleth(geo_data=json, name='choropleth', data=data, columns=['State',\n 'Unemployment'], Key_on='feature.id', fill_color='YlGn', fill_opacity=\n 0.7, line_opacity=0.2, legend_...
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- # Copyright 2017 Objectif Libre # # 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 ...
normal
{ "blob_id": "0ea67ac97ec8e7f287a2430c67f8f7d841d8b646", "index": 813, "step-1": "<mask token>\n\n\nclass TestSummary(base.BaseTestCase):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestSummary(base.BaseTestCase):\n\n def setUp(self):\n super(TestSummary, self).setUp()\n...
[ 1, 2, 3, 4, 5 ]
import numpy as np from sklearn import model_selection from iterstrat.ml_stratifiers import MultilabelStratifiedKFold """ - binary cross-validate - multi-class cross-validate - multi-label cross-validate - holdout - regression """ class CrossValidate(object): def __init__(self, df, target_cols...
normal
{ "blob_id": "0dad1937df39c012f7991c3897f27964bed1d5a0", "index": 1533, "step-1": "<mask token>\n\n\nclass CrossValidate(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass CrossValidate(object):\n\n def __init__(self, df, target_cols, problem_type, num_folds=3, shuffle=\n ...
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-12 20:48 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0010_auto_20170512_2248'), ] o...
normal
{ "blob_id": "438efbaf35401a29ea5408fee3b49b85f237760e", "index": 1089, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('home', '001...
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('examen', '0002_auto_20161122_1836'), ] operations = [ migrations.RemoveField( model_name='actuacionventa', ...
normal
{ "blob_id": "5acbd6002c5e3cfac942d52b788f18c6afa92da2", "index": 7028, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('examen', '0...
[ 0, 1, 2, 3, 4 ]
import requests from app.main.model.location import Location from app.main.util.db_util import save_changes key = 'a544aecdde85a1f52a56292f77ecde6e' def save_location(ip_addr): try: existing_location = Location.query.filter_by(ip=ip_addr).first() if existing_location: location_data = e...
normal
{ "blob_id": "eb8aec947cc1eeeb56b3884286b46ec7468dcc23", "index": 9035, "step-1": "<mask token>\n\n\ndef save_location(ip_addr):\n try:\n existing_location = Location.query.filter_by(ip=ip_addr).first()\n if existing_location:\n location_data = existing_location.location\n else:...
[ 1, 2, 3, 4 ]
class _ProtectedClass: pass class MyClass: pass class OtherClass(MyClass): pass def _protected_fun() -> MyClass: return variable # noqa: F821 def my_fun() -> MyClass: return variable # noqa: F821 def my_fun2() -> MyClass: return variable # noqa: F821 variable: MyClass variable_wit...
normal
{ "blob_id": "b5949b40d731178bdbab776af8877921dcdfbf15", "index": 3215, "step-1": "class _ProtectedClass:\n pass\n\n\nclass MyClass:\n pass\n\n\nclass OtherClass(MyClass):\n pass\n\n\ndef _protected_fun() ->MyClass:\n return variable\n\n\n<mask token>\n\n\ndef my_fun2() ->MyClass:\n return variable...
[ 5, 6, 7, 8, 9 ]
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.shtiker.CogPageGlobals COG_QUOTAS = ((30, 25, 20, 15, 10, 5, 2, 1), (45, 40, 35, 30, 25, 20, 15, 10)) COG_UNSEEN = 1 COG_BATTLED = 2 COG_DEFEATED = 3 COG_COMPLETE1 = 4 COG_COMPLETE2 = 5
normal
{ "blob_id": "fdb680f12dfb4b29f25cfe4f7af80469dc4294cf", "index": 2437, "step-1": "<mask token>\n", "step-2": "COG_QUOTAS = (30, 25, 20, 15, 10, 5, 2, 1), (45, 40, 35, 30, 25, 20, 15, 10)\nCOG_UNSEEN = 1\nCOG_BATTLED = 2\nCOG_DEFEATED = 3\nCOG_COMPLETE1 = 4\nCOG_COMPLETE2 = 5\n", "step-3": "# Fuck you Disyer....
[ 0, 1, 2 ]
from math import sqrt def prime_generator(n): pp=[2,3] for i in range(3,n): i+=2 count=0 for ps in pp: if ps>(sqrt(i)+1): break if i%ps==0: count+=1 break if count==0: pp.append(i) return pp ...
normal
{ "blob_id": "cfa064611a4aa16638bd649c68d64872b9fac1ff", "index": 4647, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef prime_generator(n):\n pp = [2, 3]\n for i in range(3, n):\n i += 2\n count = 0\n for ps in pp:\n if ps > sqrt(i) + 1:\n break\...
[ 0, 1, 2, 3 ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that a...
normal
{ "blob_id": "332c530d221c9441d6ff3646f8e9226dc78067f9", "index": 2902, "step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n\n def change(self, amount: int, coins: List[int]) ->int:\n coins = sorted(coins, reverse=True)\n\n...
[ 1, 2, 4, 5, 6 ]
import random print(random.choice(['python', 'c++', 'java'])) print(random.choice((1.1, -5, 6, 4, 7)))
normal
{ "blob_id": "44f18d7e7713073c27fec38f0b847803eceefbc9", "index": 2687, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(random.choice(['python', 'c++', 'java']))\nprint(random.choice((1.1, -5, 6, 4, 7)))\n", "step-3": "import random\nprint(random.choice(['python', 'c++', 'java']))\nprint(random.cho...
[ 0, 1, 2 ]
import numpy as np import pandas as pd from pathlib import Path import matplotlib as mpl from matplotlib import pyplot as plt plt.style.use('seaborn-muted') #from IPython import get_ipython from IPython.display import HTML, Markdown import air_cargo_problems as acp problems = ['Air Cargo Problem 1', '...
normal
{ "blob_id": "cd49230be3c418853aa2986ed727204e51a6b6ae", "index": 3794, "step-1": "<mask token>\n\n\ndef get_results_df(fname, problem):\n \"\"\"Process csv into dataframe.\n \"\"\"\n t = '\\t'\n val_cols = ['Actions', 'Expansions', 'GoalTests', 'NewNodes',\n 'PlanLength', 'ElapsedSeconds']\n ...
[ 6, 12, 14, 16, 17 ]
""" Simple neural network using pytorch """ import torch import torch.nn as nn # Prepare the data # X represents the amount of hours studied and how much time students spent sleeping X = torch.tensor(([2, 9], [1, 5], [3, 6]), dtype=torch.float) # 3 X 2 tensor # y represent grades. y = torch.tensor(([92], [100], [89]...
normal
{ "blob_id": "2d5e7c57f58f189e8d0c7d703c1672ea3586e4ac", "index": 6771, "step-1": "<mask token>\n\n\nclass Neural_Network(nn.Module):\n <mask token>\n\n def __init__(self, input_size=2, output_size=1, hidden_size=3):\n super(Neural_Network, self).__init__()\n self.input_size = input_size\n ...
[ 9, 10, 12, 13, 14 ]
#!/usr/bin python import socket import json import threading import sys from db_util import DBUtil from cryptoLib import AesCtr,Hmac class Client(threading.Thread): def __init__(self, (client_conn, client_addr), sema): threading.Thread.__init__(self) self.client_conn = client_conn self.client_addr = client_ad...
normal
{ "blob_id": "1338d6578a94338c6e75acc025ddddd14097ee10", "index": 2044, "step-1": "#!/usr/bin python\n\nimport socket\nimport json\nimport threading\nimport sys\nfrom db_util import DBUtil\nfrom cryptoLib import AesCtr,Hmac\n\n\nclass Client(threading.Thread):\n\tdef __init__(self, (client_conn, client_addr), sem...
[ 0 ]
#!/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...
normal
{ "blob_id": "5f4abc7e9397034737ee214b0d0aae39ebf1548b", "index": 8098, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name='coding_exercises', version='1.0', description=\n 'Coding Exercises in Python', author='Gustavo Gama', author_email=\n 'gustavo.gama@gmail.com', url='https://gama.igenesi...
[ 0, 1, 2, 3 ]
import urllib.request import json def kind(): data={} with open("dataset.json", "r") as read_file: data = json.load(read_file) return data["kind"] def items(): data={} with open("dataset.json", "r") as read_file: data = json.load(read_file) return data["items"] #Can add a bunc...
normal
{ "blob_id": "630480e9458491a26ea9060bd36541a0d5805a11", "index": 647, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef kind():\n data = {}\n with open('dataset.json', 'r') as read_file:\n data = json.load(read_file)\n return data['kind']\n\n\n<mask token>\n", "step-3": "<mask toke...
[ 0, 1, 2, 3, 4 ]
"""Helpers for FormatCBFMiniPilatus...""" from __future__ import annotations import calendar import time def get_pilatus_timestamp(timestamp_string): if "." in timestamp_string: timestamp, milliseconds = timestamp_string.split(".") else: timestamp = timestamp_string milliseconds = "...
normal
{ "blob_id": "21526dabe8456c599e4409228fa69ffd0d672c5b", "index": 4689, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_pilatus_timestamp(timestamp_string):\n if '.' in timestamp_string:\n timestamp, milliseconds = timestamp_string.split('.')\n else:\n timestamp = timestamp_...
[ 0, 1, 2, 3 ]
''' Handprint module for handling credentials. Authors ------- Michael Hucka <mhucka@caltech.edu> -- Caltech Library Copyright --------- Copyright (c) 2018-2022 by the California Institute of Technology. This code is open-source software released under a 3-clause BSD license. Please see the file "LICENSE" for mor...
normal
{ "blob_id": "7e29220752b4a52be34cdf0c734695d1052d0414", "index": 9309, "step-1": "<mask token>\n", "step-2": "<mask token>\nfrom .base import Credentials\nfrom .amazon_auth import AmazonCredentials\nfrom .google_auth import GoogleCredentials\nfrom .microsoft_auth import MicrosoftCredentials\n", "step-3": "''...
[ 0, 1, 2 ]
''' 3、 编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n ''' def f(n): if n%2==0: sum=0 for x in range(2,n+1,2): sum+=1/x print(sum) if n%2!=0: sum=0 for x in range(1,n+1,2): sum+=1/x print(sum)
normal
{ "blob_id": "69cf28d32e6543271a0855d61a76808b03c06891", "index": 4805, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef f(n):\n if n % 2 == 0:\n sum = 0\n for x in range(2, n + 1, 2):\n sum += 1 / x\n print(sum)\n if n % 2 != 0:\n sum = 0\n for x ...
[ 0, 1, 2 ]
# coding: utf-8 # 02. 「パトカー」+「タクシー」=「パタトクカシーー」 # 「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ. s1 = "パトカー" s2 = "タクシー" ans = "" for c1, c2 in zip(s1, s2): ans += c1 + c2 print(ans) #パタトクカシーー
normal
{ "blob_id": "4d7e30714ae209e1d09d895dadf7a19928fe253f", "index": 6623, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor c1, c2 in zip(s1, s2):\n ans += c1 + c2\nprint(ans)\n", "step-3": "s1 = 'パトカー'\ns2 = 'タクシー'\nans = ''\nfor c1, c2 in zip(s1, s2):\n ans += c1 + c2\nprint(ans)\n", "step-4": ...
[ 0, 1, 2, 3 ]
from __future__ import division, print_function, absolute_import import numbers import warnings from abc import ABCMeta, abstractmethod import numpy as np from .base import check_frame from skutil.base import overrides from sklearn.externals import six from sklearn.base import _pprint from sklearn.utils.fixes import si...
normal
{ "blob_id": "c59707ba07c1659d94684c54cdd7bb2658cba935", "index": 6, "step-1": "<mask token>\n\n\nclass H2OShuffleSplit(H2OBaseShuffleSplit):\n <mask token>\n\n def _iter_indices(self, frame, y=None):\n \"\"\"Iterate the indices.\n\n Parameters\n ----------\n\n frame : H2OFrame\n...
[ 21, 29, 40, 43, 47 ]
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import numpy.random as nr import math import os from datetime import datetime from sklearn.linear_model import LinearRegression, SGDRegressor import sys import time import imp from sklearn.ensemble import ExtraTreesRegressor fr...
normal
{ "blob_id": "ee49ce63951721458cb98b370285d04231bb2c20", "index": 7438, "step-1": "<mask token>\n\n\nclass predict(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def trainExtraTreeRegressor(self):\n self.__tree_reg.fit(self.train_...
[ 4, 8, 14, 17, 18 ]
import torch from torch import nn from torch.nn import functional as F from models.blocks import UnetConv3, MultiAttentionBlock, UnetGridGatingSignal3, UnetUp3_CT, UnetDsv3 class AttentionGatedUnet3D(nn.Module): """ Attention Gated Unet for 3D semantic segmentation. Args: config: Mus...
normal
{ "blob_id": "55a392d63838cbef027f9cf525999c41416e3575", "index": 3875, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass AttentionGatedUnet3D(nn.Module):\n <mask token>\n\n def __init__(self, config):\n super(AttentionGatedUnet3D, self).__init__()\n assert hasattr(config, 'num_...
[ 0, 3, 4, 5, 6 ]
#!/usr/bin/env python3 from pexpect import pxssh import time s = pxssh.pxssh() ip = "" #replace ip address username= "" #replace username password= "" #replace password s.login (ip, username, password) print ("SSH session login successful") s.sendline ('application stop') s.prompt() # match the prompt print("S...
normal
{ "blob_id": "dd9574ea08beb9bc5f1413afd63c751fd42cba67", "index": 6406, "step-1": "<mask token>\n", "step-2": "<mask token>\ns.login(ip, username, password)\nprint('SSH session login successful')\ns.sendline('application stop')\ns.prompt()\nprint('Stopping the app')\nprint(\"\"\"\nStarting the app\"\"\")\ns.sen...
[ 0, 1, 2, 3, 4 ]
import time class Block: def __init__(self, index, transactions, previous_hash, nonce=0): self.index = index self.transaction = transactions self.timestamp = time.time() self.previous_hash = previous_hash self.nonce = nonce self.hash = None
normal
{ "blob_id": "43a23958b8c8779e3292f0f523a37b6d712fdbac", "index": 4448, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Block:\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Block:\n\n def __init__(self, index, transactions, previous_hash, nonce=0):\n self.index = index\n ...
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- import sys import yaml def add_sub_path(yaml_path): file = open(yaml_path, "r", encoding="utf-8") file_data = file.read() file.close() data = yaml.safe_load(file_data) for p, p_info in data.get("paths", {}).items(): for method, m_info in p_info.items(): ...
normal
{ "blob_id": "bbd50c40bc0897fe7a93f277bcfdcba3ba6d6f2a", "index": 1531, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef add_sub_path(yaml_path):\n file = open(yaml_path, 'r', encoding='utf-8')\n file_data = file.read()\n file.close()\n data = yaml.safe_load(file_data)\n for p, p_info...
[ 0, 1, 2, 3, 4 ]
""" Crie um programa onde o usuario possa digitar sete valores numericos e cadastre-os em uma lisa unicaque mantenha separados os valores pares e impares. No final, mostre os valores ares e impares em ordem crescente """ n = [[],[]] for c in range(0,7): num = int(input(f'Digite o {c+1} valor: ')) res = num % ...
normal
{ "blob_id": "72bbbe78db746febc9a36a676e0fa2d97bf5e81e", "index": 8849, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor c in range(0, 7):\n num = int(input(f'Digite o {c + 1} valor: '))\n res = num % 2\n if res == 0:\n n[0].append(num)\n else:\n n[1].append(num)\nn[0].sort()\n...
[ 0, 1, 2, 3 ]
import datetime import discord def getTeams(reign, uprising, hunters, fuel, mayhem, gladiators, charge, outlaws, spark, spitfire, excelsior, eternal, fusion, dynasty, shock, dragons, defiant, valiant, titans, justice) : teamList = discord.Embed( title="Overwatch League Teams", description="2021 Sea...
normal
{ "blob_id": "9a02e09cbfe2c9b6ebb9d20ba6cea639871f0838", "index": 7647, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef getTeams(reign, uprising, hunters, fuel, mayhem, gladiators, charge,\n outlaws, spark, spitfire, excelsior, eternal, fusion, dynasty, shock,\n dragons, defiant, valiant, tit...
[ 0, 1, 2, 3 ]
from mesa.visualization.modules import CanvasGrid from mesa.visualization.ModularVisualization import ModularServer from mesa.visualization.modules import ChartModule from mesa.batchrunner import BatchRunner from agentPortrayal import agent_portrayal import metrics from matplotlib import pyplot as plt from Architecture...
normal
{ "blob_id": "57b51ea36e9e2a095cf7e9646db2cc400cc72b83", "index": 1082, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n dir_path = os.path.dirname(os.path.realpath(__file__))\n if runBatch:\n fixed_params = {'width': 60, 'height': 60, 'splitSize': 1,\n '...
[ 0, 1, 2, 3, 4 ]
import tensorflow as tf import numpy as np import time import os from sklearn.metrics import roc_curve import matplotlib.pyplot as plt from src.model import get_args from src.funcs import linear from src.youtubeface import load_ytf_data from src.lfw import load_lfw_data from src.facescrub import load_fs_data from src...
normal
{ "blob_id": "459dd9302f7100ad02119cc94b735b19287f21e5", "index": 5956, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n total_iteration = 300000\n m = 512\n q = 32\n lam = 0.01\n beta = 1.0\n margin = 0.5\n s = ...
[ 0, 1, 2, 3 ]
# 심사문제 22 # 표준 입력으로 정수 두 개가 입력됩니다(첫 번째 입력 값의 범위는 1~20, 두 번째 입력 값의 범위는 10~30이며 첫 번째 입력 값은 두 번째 입력 값보다 항상 작습니다). # 첫 번째 정수부터 두 번째 정수까지를 지수로 하는 2의 거듭제곱 리스트를 출력하는 프로그램을 만드세요 # (input에서 안내 문자열은 출력하지 않아야 합니다). 단, 리스트의 두 번째 요소와 뒤에서 두 번째 요소는 삭제한 뒤 출력하세요. 출력 결과는 리스트 형태라야 합니다. start, stop = list(map(int, input().split())) 1 10 ...
normal
{ "blob_id": "1f8040776a55d6fe52b64c714d4003469460e454", "index": 7186, "step-1": "# 심사문제 22\n# 표준 입력으로 정수 두 개가 입력됩니다(첫 번째 입력 값의 범위는 1~20, 두 번째 입력 값의 범위는 10~30이며 첫 번째 입력 값은 두 번째 입력 값보다 항상 작습니다).\n# 첫 번째 정수부터 두 번째 정수까지를 지수로 하는 2의 거듭제곱 리스트를 출력하는 프로그램을 만드세요\n# (input에서 안내 문자열은 출력하지 않아야 합니다). 단, 리스트의 두 번째 요소와 뒤에서 두 번...
[ 0 ]