code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
import re class Markdown: __formattedFile = [] __analyzing = [] def __processSingleLine(self, line): if(self.__isHeading(line)): self.__process("p") self.__analyzing.append(re.sub("(#{1,6})", "", line).strip()) self.__process("h" + str(len(re.split("\s", line)[0]))) elif(self.__isH...
normal
{ "blob_id": "13e3337cf9e573b8906fe914a830a8e895af20ba", "index": 3983, "step-1": "<mask token>\n\n\nclass Markdown:\n <mask token>\n <mask token>\n\n def __processSingleLine(self, line):\n if self.__isHeading(line):\n self.__process('p')\n self.__analyzing.append(re.sub('(#{...
[ 9, 10, 11, 12, 13 ]
import drawSvg import noise import random import math import numpy as np sizex = 950 sizey = 500 noisescale = 400 persistence = 0.5 lacunarity = 2 seed = random.randint(0, 100) actorsnum = 1000 stepsnum = 50 steplenght = 2 noisemap = np.zeros((sizex, sizey)) for i in range(sizex): for j in range(sizey): noi...
normal
{ "blob_id": "68c9944c788b9976660384e5d1cd0a736c4cd0e6", "index": 3826, "step-1": "<mask token>\n\n\nclass Actor:\n\n def __init__(self):\n self.x = random.random() * sizex\n self.y = random.random() * sizey\n self.xn = self.x\n self.yn = self.y\n\n def step(self):\n t = g...
[ 3, 4, 6, 7 ]
import os from typing import List from pypinyin import pinyin, lazy_pinyin # map vowel-number combination to unicode toneMap = { "d": ['ā', 'ē', 'ī', 'ō', 'ū', 'ǜ'], "f": ['á', 'é', 'í', 'ó', 'ú', 'ǘ'], "j": ['ǎ', 'ě', 'ǐ', 'ǒ', 'ǔ', 'ǚ'], "k": ['à', 'è', 'ì', 'ò', 'ù', 'ǜ'], } weightMap = {} def g...
normal
{ "blob_id": "e50c1ef7368aabf53bc0cfd45e19101fa1519a1f", "index": 6245, "step-1": "<mask token>\n\n\ndef getWeightMap():\n with open(os.path.join(os.path.dirname(__file__),\n '../cells/cubor-base.dict.yaml'), 'r', encoding='utf8') as base:\n _lines = base.readlines()\n for wunit in _lines:...
[ 4, 5, 7, 8, 9 ]
from django.shortcuts import render from django.http import HttpResponse # # Create your views here. # def Login_Form(request): # return render(request, 'Login.html')
normal
{ "blob_id": "ee161ff66a6fc651a03f725427c3731bdf4243eb", "index": 6906, "step-1": "<mask token>\n", "step-2": "from django.shortcuts import render\nfrom django.http import HttpResponse\n", "step-3": "from django.shortcuts import render\r\nfrom django.http import HttpResponse\r\n\r\n\r\n\r\n# # Create your vie...
[ 0, 1, 2 ]
# 문제 설명 # 길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다. a와 b의 내적을 return 하도록 solution 함수를 완성해주세요. # 이때, a와 b의 내적은 a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] 입니다. (n은 a, b의 길이) # 제한사항 # a, b의 길이는 1 이상 1,000 이하입니다. # a, b의 모든 수는 -1,000 이상 1,000 이하입니다. # 입출력 예 # a b result # [1,2,3,4] [-3,-1,0,2] 3 # [-1,0,1] [1,0,-1] -2 # 입출력...
normal
{ "blob_id": "5b8322761975ebec76d1dccd0290c0fb1da404e5", "index": 5999, "step-1": "<mask token>\n\n\ndef solution2(a, b):\n answer = [(a[i] * b[i]) for i in range(len(a))]\n return sum(answer)\n\n\n<mask token>\n\n\ndef solution5(a, b):\n answer = sum([(i * j) for i, j in zip(a, b)])\n return answer\n...
[ 2, 3, 4, 5, 6 ]
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name = "keputils", version = "0.2.1", description = "Basic module for interaction with KOI and Kepler-stellar tables.", long_description = readme(), author = "Timothy D. Morton", author_email...
normal
{ "blob_id": "6da828a797efac7c37723db96a2682e960c317b5", "index": 1007, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef readme():\n with open('README.rst') as f:\n return f.read()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef readme():\n with open('README.rst') as f:\n ...
[ 0, 1, 2, 3, 4 ]
""" Array.diff Our goal in this kata is to implement a difference function, which subtracts one list from another and returns the result. It should remove all values from list a, which are present in list b keeping their order. """ from unittest import TestCase def list_diff(a, b): return [x for x in a if x n...
normal
{ "blob_id": "76526bdff7418997ac90f761936abccbb3468499", "index": 6513, "step-1": "<mask token>\n\n\nclass TestListDiff(TestCase):\n <mask token>\n\n def test_two(self):\n assert list_diff([1, 2, 2, 2, 3], [2]) == [1, 3]\n <mask token>\n\n\n<mask token>\n\n\nclass TestDiffLR(TestCase):\n\n def ...
[ 6, 8, 9, 10, 12 ]
""" This program takes information about students and their coursework and calculates their final grades based on the weight of each course factor """ def read_file(string_object): """ Opens and reads through a file, returning none if it isnt found """ try: return open(string_object,"r") except Fil...
normal
{ "blob_id": "d8af8e36bd00fbfc966ef1c4dd0c6385cbb019ee", "index": 2064, "step-1": "<mask token>\n\n\ndef read_file(string_object):\n \"\"\" Opens and reads through a file, returning none if it isnt found \"\"\"\n try:\n return open(string_object, 'r')\n except FileNotFoundError:\n return No...
[ 4, 5, 6, 8, 10 ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-26 05:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Discou...
normal
{ "blob_id": "957db647500433fd73723fdeb3933037ba0641b1", "index": 1527, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T...
[ 0, 1, 2, 3, 4 ]
#! import os import sys #get current working directory cwd = os.getcwd() ovjtools = os.getenv('OVJ_TOOLS') javaBinDir = os.path.join(ovjtools, 'java', 'bin') # get the envirionment env = Environment(ENV = {'JAVA_HOME' : javaBinDir, 'PATH' : javaBinDir + ':' + os.environ['PATH']}) env.Execut...
normal
{ "blob_id": "549d7368d49cf2f4d2c6e83e300f31db981b62bd", "index": 6285, "step-1": "<mask token>\n", "step-2": "<mask token>\nenv.Execute('cd vjunit && make -f makevjunit')\nenv.Execute('cd VJQA/src && make -f makexmlcheck')\nExecute('rm -rf ovj_qa')\n<mask token>\nif not os.path.exists(path):\n os.makedirs(p...
[ 0, 1, 2, 3, 4 ]
#Matthew Shrago #implementation of bisection search. import math low = 0 high = 100 ans = int((high + low)/2) print "Please think of a number between 0 and 100!" while ans != 'c': #print high, low print "Is your secret number " + str(ans) + "?", number = raw_input("Enter 'h' to indicate the guess is too hi...
normal
{ "blob_id": "39abda1dd8b35889405db1b3971917d2a34180e3", "index": 6428, "step-1": "#Matthew Shrago\n#implementation of bisection search.\nimport math\nlow = 0\nhigh = 100\nans = int((high + low)/2)\n\nprint \"Please think of a number between 0 and 100!\"\nwhile ans != 'c':\n #print high, low\n print \"Is yo...
[ 0 ]
'''给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。 数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'。输入: 示例: letters = ["c", "f", "j"] target = "a" 输出: "c" ''' class Solution(object): def nextGreatestLetter(self, letters, target): """ :type letters: List[str] ...
normal
{ "blob_id": "9cb3d8bc7af0061047136d57abfe68cbb5ae0cd7", "index": 3344, "step-1": "<mask token>\n\n\nclass SolutionBest(object):\n <mask token>\n", "step-2": "<mask token>\n\n\nclass SolutionBest(object):\n\n def nextGreatestLetter(self, letters, target):\n \"\"\"\n :type letters: List[str]\...
[ 1, 2, 3, 4, 5 ]
casosteste = int(input()) for testes in range(casosteste): num_instru = int(input()) lista = [] for intru in range(num_instru): p = input().upper() if p == 'LEFT': lista.append(-1) elif p == 'RIGHT': lista.append(+1) elif p.startswith('SAME AS'): ...
normal
{ "blob_id": "a14a6c015ed3063015973b5376a1351a70808dc0", "index": 8420, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor testes in range(casosteste):\n num_instru = int(input())\n lista = []\n for intru in range(num_instru):\n p = input().upper()\n if p == 'LEFT':\n lis...
[ 0, 1, 2 ]
#time:2020-11-28 import xlrd #读取库 def get_teacherData(): excelDir = r'../data/松勤-教管系统接口测试用例-v1.4.xls' workBook = xlrd.open_workbook(excelDir, formatting_info=True) # 保存原样---样式 # 2-操作对应的用例表 workSheet = workBook.sheet_by_name('3-老师模块') # 通过表名获取 dataList = [] for cnt in range(1, 2): # 到第四行 ...
normal
{ "blob_id": "d7dee3311e202ae50172077940fc625f1cc6836d", "index": 1429, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_teacherData():\n excelDir = '../data/松勤-教管系统接口测试用例-v1.4.xls'\n workBook = xlrd.open_workbook(excelDir, formatting_info=True)\n workSheet = workBook.sheet_by_name('3-老...
[ 0, 1, 2, 3, 4 ]
from __future__ import division from __future__ import print_function import numpy import tables as PT import scipy.io import sys, math import tables.flavor from flydra_analysis.analysis.save_as_flydra_hdf5 import save_as_flydra_hdf5 tables.flavor.restrict_flavors(keep=["numpy"]) def main(): filename = sys.argv[...
normal
{ "blob_id": "b20bf203a89ed73cc65db50fdbef897667fe390f", "index": 2804, "step-1": "<mask token>\n\n\ndef main():\n filename = sys.argv[1]\n do_it(filename=filename)\n\n\ndef get_valid_userblock_size(min):\n result = 2 ** int(math.ceil(math.log(min, 2)))\n if result < 512:\n result = 512\n re...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- from LibTools.filesystem import Carpeta from slaves import SentinelSat import settings if __name__ == '__main__': carpeta = Carpeta(settings.folder_sat) sentinela = SentinelSat(carpeta) sentinela.start_Monitoring()
normal
{ "blob_id": "9e3f4484542c2629d636fcb4166584ba52bebe21", "index": 2196, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n carpeta = Carpeta(settings.folder_sat)\n sentinela = SentinelSat(carpeta)\n sentinela.start_Monitoring()\n", "step-3": "from LibTools.filesystem im...
[ 0, 1, 2, 3 ]
from django.db import models class ScggjyList(models.Model): title = models.CharField(max_length=255) pubData = models.CharField(db_column='pubData', max_length=255) detailLink = models.CharField(db_column='detailLink', max_length=255) detailTitle = models.CharField(db_column='detailTitle', max_length...
normal
{ "blob_id": "951fafe9f1b9a3273f30d101831d1e59e26fe85d", "index": 1535, "step-1": "<mask token>\n\n\nclass ZakerNewsTab(models.Model):\n code = models.IntegerField(blank=True, null=True)\n tabName = models.CharField(db_column='tabName', max_length=20, blank=\n True, null=True)\n\n\n class Meta:\n ...
[ 4, 7, 8, 9, 10 ]
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.metrics.pairwise import cosine_similarity def get_df_4_model(user_id, n_recommendations = 20000): '''this func...
normal
{ "blob_id": "5c8de06176d06c5a2cf78ac138a5cb35e168d617", "index": 5122, "step-1": "<mask token>\n\n\ndef get_df_4_model(user_id, n_recommendations=20000):\n \"\"\"this function generates the latent dataframes used for the prediction model\"\"\"\n print('Generating dataframe for recommendation model')\n r...
[ 3, 4, 5, 6, 7 ]
def decimal_to_binary(num): if num == 0: return '0' binary = '' while num != 0: binary = str(num % 2) + binary num = num // 2 return binary def modulo(numerator, exp, denominator): binary = decimal_to_binary(exp) prev_result = numerator result = 1 for i in range(len(bi...
normal
{ "blob_id": "4e202cf7d7da865498ef5f65efdf5851c62082ff", "index": 6764, "step-1": "<mask token>\n", "step-2": "def decimal_to_binary(num):\n if num == 0:\n return '0'\n binary = ''\n while num != 0:\n binary = str(num % 2) + binary\n num = num // 2\n return binary\n\n\n<mask tok...
[ 0, 1, 2, 3 ]
from Stack import Stack from Regex import Regex from Symbol import Symbol class Postfix: def __init__(self, regex): self.__regex = regex.expression self.__modr = Postfix.modRegex(self.__regex) self.__pila = Stack() self.__postfix = self.convertInfixToPostfix() def getRegex(...
normal
{ "blob_id": "acc39044fa1ae444dd4a737ea37a0baa60a2c7bd", "index": 4040, "step-1": "<mask token>\n\n\nclass Postfix:\n\n def __init__(self, regex):\n self.__regex = regex.expression\n self.__modr = Postfix.modRegex(self.__regex)\n self.__pila = Stack()\n self.__postfix = self.convert...
[ 4, 5, 7, 9, 11 ]
import numpy as np import cv2 from PIL import Image import pytesseract as tess #Function to check the area range and width-height ratio def ratio(area, width,height): ratio = float(width)/float(height) if ratio < 1: ratio = 1/ ratio if (area<1063.62 or area> 73862.5) or (ratio<3 or ratio> 6): return False...
normal
{ "blob_id": "ab610af97d2b31575ea496b8fddda693353da8eb", "index": 2870, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef ratio(area, width, height):\n ratio = float(width) / float(height)\n if ratio < 1:\n ratio = 1 / ratio\n if (area < 1063.62 or area > 73862.5) or (ratio < 3 or rat...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python import fileinput import sys import os from argparse import ArgumentParser from probin.model.composition import multinomial as mn from probin.dna import DNA from Bio import SeqIO from corrbin.misc import all_but_index, Uniq_id, GenomeGroup from corrbin.multinomial import Experiment from corrbin.co...
normal
{ "blob_id": "b9a262bd6ddbca3b214825a473d870e70e8b5e57", "index": 9443, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main(open_name_file, dir_path, kmer_length, x_set):\n groups = []\n DNA.generate_kmer_hash(kmer_length)\n for line in open_name_file:\n if line[0:12] == 'family_na...
[ 0, 1, 2, 3, 4 ]
from flask import jsonify, request, render_template, redirect, session, flash from init import app from init import mysql #Devuelve la pagina de reportes @app.route('/reportes') def reportes(): try: cur = mysql.connect().cursor() if 'usuario' in session: return render_template('views/re...
normal
{ "blob_id": "77995aab723fb118be3f986b8cd93f349690baca", "index": 2090, "step-1": "<mask token>\n\n\n@app.route('/reportes')\ndef reportes():\n try:\n cur = mysql.connect().cursor()\n if 'usuario' in session:\n return render_template('views/reportes.html', id=session['id'])\n el...
[ 4, 5, 6, 7, 8 ]
import scrapy import time import os.path from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from tempfile import mkstem...
normal
{ "blob_id": "237a93ff73cb98fd9d4006f14d3cadbdc09259a4", "index": 9885, "step-1": "<mask token>\n\n\nclass ProductSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self):\n options = webdriver.ChromeOptions()\n options.add_argument('--start-maximized')\...
[ 2, 3, 5, 6, 7 ]
############################################################ # Hierarchical Reinforcement Learning for Relation Extraction # Multiprocessing with CUDA # Require: PyTorch 0.3.0 # Author: Tianyang Zhang, Ryuichi Takanobu # E-mail: keavilzhangzty@gmail.com, truthless11@gmail.com ###########################################...
normal
{ "blob_id": "699410536c9a195024c5abbcccc88c17e8e095e3", "index": 6003, "step-1": "<mask token>\n\n\nclass BotModel(nn.Module):\n\n def __init__(self, dim, statedim, rel_count):\n super(BotModel, self).__init__()\n self.dim = dim\n self.hid2state = nn.Linear(dim * 3 + statedim * 2, statedi...
[ 7, 9, 10, 11, 12 ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('products', '0007_auto_20150904_1320'), ] operations = [ migrations.AddField( model_name='custome...
normal
{ "blob_id": "fd52379d125d6215fe12b6e01aa568949511549d", "index": 6964, "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 = [('products', ...
[ 0, 1, 2, 3, 4 ]
# Generated by Django 2.1.3 on 2020-06-05 23:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('index', '0005_userip_serial_number'), ] operations = [ migrations.AddField( model_name='userip', name='ip_attributio...
normal
{ "blob_id": "a90db2073d43d54cbcc04e3000e5d0f2a2da4a55", "index": 5281, "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 = [('index', '00...
[ 0, 1, 2, 3, 4 ]
#! /usr/bin/env python """ Normalizes a vidoe by dividing against it's background. See: BackgroundExtractor.py to get the background of a video. USING: As a command line utility: $ Normalizer.py input_video input_image output_video As a module: from Normalizer import Normalizer ...
normal
{ "blob_id": "141e0f20ce912ecf21940f78e9f40cb86b91dc2b", "index": 6121, "step-1": "<mask token>\n\n\nclass Normalizer:\n <mask token>\n\n def imageFromArg(self, image):\n if isinstance(image, (str, unicode)):\n return cv2.imread(image, 0)\n else:\n return image\n\n def...
[ 5, 7, 10, 11, 13 ]
def entete(): entete=''' <!DOCTYPE HTML> <html lang=“fr”> <head> <title>AMAP'PATATE</title> <meta charset="UTF-8" /> <link rel="stylesheet" type="text/css" href="/IENAC15/amapatate/css/font-awesome.min.css" /> <link rel="s...
normal
{ "blob_id": "933758002c5851a2655ed4c51b2bed0102165116", "index": 4742, "step-1": "def entete():\n entete = \"\"\"\n <!DOCTYPE HTML>\n<html lang=“fr”>\n <head>\n <title>AMAP'PATATE</title>\n <meta charset=\"UTF-8\" />\n <link rel=\"stylesheet...
[ 1, 2, 3, 4, 5 ]
numbers = [1, 1, 1, 1, 1] new_numbers = [2, 2, 2, 3, 3] print(numbers + new_numbers) print(numbers * 5)
normal
{ "blob_id": "843df062702c9abf34cf14d911d927d786f1d912", "index": 1573, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(numbers + new_numbers)\nprint(numbers * 5)\n", "step-3": "numbers = [1, 1, 1, 1, 1]\nnew_numbers = [2, 2, 2, 3, 3]\nprint(numbers + new_numbers)\nprint(numbers * 5)\n", "step-4"...
[ 0, 1, 2 ]
#Packages to be imported import requests import pandas as pd from geopy.distance import distance import json from datetime import date from datetime import datetime import time #POST request to get authentication token URL = "https://api.birdapp.com/user/login" email = {"email": "himanshu.agarwal20792@gmail.com"} head...
normal
{ "blob_id": "625a5d14aaf37493c3f75ec0cdce77d45ca08f78", "index": 9520, "step-1": "#Packages to be imported\nimport requests\nimport pandas as pd\nfrom geopy.distance import distance\nimport json\nfrom datetime import date\nfrom datetime import datetime\nimport time\n\n#POST request to get authentication token\nU...
[ 0 ]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'src/ui_LibraryTab.ui' # # Created: Tue Jun 9 21:46:41 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Tab(object): def setupUi(se...
normal
{ "blob_id": "ef85f94282bfd7c9491c4e28bab61aaab5c792a5", "index": 232, "step-1": "<mask token>\n\n\nclass Ui_Tab(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Ui_Tab(object):\n <mask token>\n\n def retranslateUi(self, Tab):\n _translate = QtCore.QCoreApplicatio...
[ 1, 2, 3, 4, 5 ]
from haven import haven_utils as hu import itertools, copy EXP_GROUPS = {} EXP_GROUPS['starter_issam'] = hu.cartesian_exp_group({ 'batch_size': 32, 'opt': {'name': 'adamW', 'lr': 0.0001, 'wd': 1e-6}, 'model': {'name': 'resnext50_32x4d_ssl'}, ...
normal
{ "blob_id": "dafefc65335a0d7e27057f51b43e52b286f5bc6b", "index": 6067, "step-1": "<mask token>\n", "step-2": "<mask token>\nEXP_GROUPS = {}\nEXP_GROUPS['starter_issam'] = hu.cartesian_exp_group({'batch_size': 32,\n 'opt': {'name': 'adamW', 'lr': 0.0001, 'wd': 1e-06}, 'model': {'name':\n 'resnext50_32x4d_...
[ 0, 1, 2, 3 ]
threehome = 25 * 3 twotonnel = 40 * 2 alldude = threehome + twotonnel print('%s Заварушку устроили' % alldude)
normal
{ "blob_id": "e492680efe57bd36b58c00977ecd79196501997a", "index": 7952, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('%s Заварушку устроили' % alldude)\n", "step-3": "threehome = 25 * 3\ntwotonnel = 40 * 2\nalldude = threehome + twotonnel\nprint('%s Заварушку устроили' % alldude)\n", "step-4":...
[ 0, 1, 2 ]
[Interactive Programming with Python - Part 1] [Arithmetic Expressions] # numbers - two types, an integer or a decimal number # two correspending data types int() and float() print 3, -1, 3.14159, -2.8 # we can convert between data types using int() and float() # note that int() take the "whole" part of a decimal n...
normal
{ "blob_id": "f1396179152641abf76256dfeab346907cb1e386", "index": 2738, "step-1": "[Interactive Programming with Python - Part 1]\n\n[Arithmetic Expressions]\n\n# numbers - two types, an integer or a decimal number\n# two correspending data types int() and float()\n\nprint 3, -1, 3.14159, -2.8\n\n# we can convert...
[ 0 ]
#给你一个字符串 croakOfFrogs,它表示不同青蛙发出的蛙鸣声(字符串 "croak" )的组合。由于同一时间可以有多只青蛙呱呱作响,所以 croakOfFrogs 中会混合多个 “croak” 。请你返回模拟字符串中所有蛙鸣所需不同青蛙的最少数目。 #注意:要想发出蛙鸣 "croak",青蛙必须 依序 输出 ‘c’, ’r’, ’o’, ’a’, ’k’ 这 5 个字母。如果没有输出全部五个字母,那么它就不会发出声音。 #如果字符串 croakOfFrogs 不是由若干有效的 "croak" 字符混合而成,请返回 -1 。 #来源:力扣(LeetCode) #链接:https://leetcode-cn.com/pr...
normal
{ "blob_id": "b4491b5522e85fec64164b602045b9bd3e58c5b8", "index": 4666, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def minNumberOfFrogs(self, croakOfFrogs: str) ->int:\n c, r, o, a, k = 0, 0, 0, 0, 0\n ans = 0\n for i in ...
[ 0, 1, 2, 3 ]
import json from django import template from django.core.serializers.json import DjangoJSONEncoder from django.utils.safestring import mark_safe register = template.Library() @register.filter def jsonify(object): return mark_safe(json.dumps(object, cls=DjangoJSONEncoder)) @register.simple_tag def get_crop_url(c...
normal
{ "blob_id": "987579da6b7ae208a66e375e0c9eca32b97199c5", "index": 4704, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@register.filter\ndef jsonify(object):\n return mark_safe(json.dumps(object, cls=DjangoJSONEncoder))\n\n\n@register.simple_tag\ndef get_crop_url(crop, width=None, scale=1):\n if...
[ 0, 3, 4, 5 ]
import tkinter as tk from tkinter import ttk win = tk.Tk() win.title('Loop') ############ Time consuming : # nameLable1 = ttk.Label(win,text="Enter your name : ") # nameLable1.grid(row=0,column=0,sticky=tk.W) # ageLable1 = ttk.Label(win,text="Enter your age: ") # ageLable1.grid(row=1,column=0,sticky=tk.W) #...
normal
{ "blob_id": "2eb49d08136c3540e1305310f03255e2ecbf0c40", "index": 3175, "step-1": "<mask token>\n\n\ndef submitAction():\n for i in userDict:\n print(f'{userDict.get(i).get()}')\n exit()\n\n\n<mask token>\n", "step-2": "<mask token>\nwin.title('Loop')\n<mask token>\nfor i in range(len(labels)):\n ...
[ 1, 2, 3, 4, 5 ]
import base64 import json class BaseTestCloudAuth: """ Required setup: initialize test case teardown: del items for test decode: check decoded token and assigned info """ ACCESS_TOKEN = "" SCOPE_ACCESS_TOKEN = "" ID_TOKEN = "" TESTCLIENT = None def assert_get_res...
normal
{ "blob_id": "9a2b5b9b2b2f9532b5d0749147aca644c2ac26e3", "index": 2878, "step-1": "<mask token>\n\n\nclass BaseTestCloudAuth:\n \"\"\"\n Required\n setup: initialize test case\n teardown: del items for test\n decode: check decoded token and assigned info\n \"\"\"\n ACCESS_TOKEN = ...
[ 3, 4, 5, 6, 7 ]
from django.shortcuts import render from django.views.generic import View from django.http import JsonResponse from django_redis import get_redis_connection from django.contrib.auth.mixins import LoginRequiredMixin from good.models import GoodsSKU class CartAddView(View): '''添加购物车''' def post(self,request): ...
normal
{ "blob_id": "5feea24d269409306338f772f01b0ee1d2736e2e", "index": 9246, "step-1": "<mask token>\n\n\nclass UpdateCartView(View):\n <mask token>\n\n def post(self, request):\n user = request.user\n if not user.is_authenticated:\n return JsonResponse({'res': 0, 'errmsg': '请先登录'})\n ...
[ 11, 14, 17, 19, 20 ]
from peewee import * db = PostgresqlDatabase('contacts', user='postgres', password='', host='localhost', port=5432) intro_question = input("What would you like to do with Contacts? Create? Read? Find? Delete? Update? ") def read_contact(): contacts = Contact.select() for contact in c...
normal
{ "blob_id": "07544d1eb039da0081716aa489fc1a0a5a200145", "index": 1072, "step-1": "<mask token>\n\n\ndef read_contact():\n contacts = Contact.select()\n for contact in contacts:\n print(contact)\n print(contact.firstname + ' ' + contact.lastname + ' ' + contact.\n phone + ' ' + cont...
[ 7, 9, 10, 11, 12 ]
from requests import post import json import argparse import base64 from ReadFromWindow import new_image_string from ParsOnText import ParsOnText # Функция возвращает IAM-токен для аккаунта на Яндексе. def get_iam_token(iam_url, oauth_token): response = post(iam_url, json={"yandexPassportOauthToken": oauth_token})...
normal
{ "blob_id": "360063940bb82defefc4195a5e17c9778b47e9e5", "index": 792, "step-1": "<mask token>\n\n\ndef get_iam_token(iam_url, oauth_token):\n response = post(iam_url, json={'yandexPassportOauthToken': oauth_token})\n json_data = json.loads(response.text)\n if json_data is not None and 'iamToken' in json...
[ 1, 2, 3, 5, 6 ]
# 自定义购物车项类 class CartItem(): def __init__(self, book, amount): self.book = book self.amount = int(amount) # 自定义购物车 class Cart(): def __init__(self): self.book_list = [] self.total = 0 self.save = 0 def total_price(self): ele = 0 for i in self.book_li...
normal
{ "blob_id": "58efaad41d02bb5dffbf71c478c7fad12af68e5b", "index": 9900, "step-1": "<mask token>\n\n\nclass Cart:\n\n def __init__(self):\n self.book_list = []\n self.total = 0\n self.save = 0\n\n def total_price(self):\n ele = 0\n for i in self.book_list:\n ele ...
[ 5, 6, 7, 8, 9 ]
# Copyright (c) 2011-2020 Eric Froemling # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish,...
normal
{ "blob_id": "7c63abacce07ee9d4c2b3941d05f951b75c8d0ff", "index": 1157, "step-1": "<mask token>\n\n\nclass PlayerRecord:\n <mask token>\n character: str\n <mask token>\n\n @property\n def team(self) ->ba.SessionTeam:\n \"\"\"The ba.SessionTeam the last associated player was last on.\n\n ...
[ 17, 23, 28, 29, 30 ]
import pickle import pytest from reader import EntryError from reader import FeedError from reader import SingleUpdateHookError from reader import TagError from reader.exceptions import _FancyExceptionBase def test_fancy_exception_base(): exc = _FancyExceptionBase('message') assert str(exc) == 'message' ...
normal
{ "blob_id": "6fd4df7370de2343fe7723a2d8f5aacffa333835", "index": 3105, "step-1": "<mask token>\n\n\ndef test_fancy_exception_base():\n exc = _FancyExceptionBase('message')\n assert str(exc) == 'message'\n exc = _FancyExceptionBase(message='message')\n assert str(exc) == 'message'\n cause = Excepti...
[ 5, 6, 7, 8, 9 ]
""" 函数对象有一个__defaults__属性,是保存定位参数和关键字参数默认值的元组, 仅限关键字参数默认值在__kwdefaults__属性中,参数的名称在__code__属性中(__code__本身是对象引用,有很多属性) 使用inspect模块提取函数签名更加方便,很多框架和IDE都是以此来验证代码的 """ def tag(name, *content, cls=None, **attrs): """ 生成一个或多个HTML标签 """ if cls is not None: attrs['class'] = cls if attrs: attrs_str = ''.join(' %s="%s"' ...
normal
{ "blob_id": "a9b895e4d0830320276359944ca6fdc475fd144e", "index": 7923, "step-1": "<mask token>\n\n\ndef tag(name, *content, cls=None, **attrs):\n \"\"\" 生成一个或多个HTML标签 \"\"\"\n if cls is not None:\n attrs['class'] = cls\n if attrs:\n attrs_str = ''.join(' %s=\"%s\"' % (attr, value) for attr...
[ 1, 2, 3, 4, 5 ]
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0. from awscrt import http, io from awsiot import mqtt_connection_builder from utils.command_line_utils import CommandLineUtils # This sample shows how to create a MQTT connection using a certificate file and key ...
normal
{ "blob_id": "2ff398e38b49d95fdc8a36a08eeb5950aaea1bc9", "index": 2279, "step-1": "<mask token>\n\n\ndef on_connection_resumed(connection, return_code, session_present, **kwargs):\n print('Connection resumed. return_code: {} session_present: {}'.format(\n return_code, session_present))\n\n\n<mask token>...
[ 1, 2, 3, 4, 5 ]
''' LeetCode wants to give one of its best employees the option to travel among n cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could ta...
normal
{ "blob_id": "aa7cf08b40b2a13e39003f95e5e0ce7335cbdba2", "index": 1766, "step-1": "'''\nLeetCode wants to give one of its best employees the option to travel among n cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. ...
[ 0 ]
import re rule_regex = re.compile(r'([\.#]{5}) => ([\.#])') grid_regex = re.compile(r'initial state: ([\.#]+)') class Rule: def __init__(self, template, alive): self.template = template self.alive = alive def parse(string): match = rule_regex.match(string) if match: template = match.group(...
normal
{ "blob_id": "8c683c109aba69f296b8989915b1f3b3eecd9745", "index": 4274, "step-1": "<mask token>\n\n\nclass Rule:\n\n def __init__(self, template, alive):\n self.template = template\n self.alive = alive\n\n def parse(string):\n match = rule_regex.match(string)\n if match:\n ...
[ 5, 7, 9, 10, 12 ]
import urllib.request import http.cookiejar import requests import re import sys import time import json from bs4 import BeautifulSoup head = { "Host": "www.pkuhelper.com", "Accept": "*/*", "Accept-Language": "zh-Hans-CN;q=1", "Connection": "keep-alive", "Accept-Encoding": "gzip, deflate", "User-Agent": "PKU Hel...
normal
{ "blob_id": "a74653f01b62445c74c8121739bd9185ce21c85a", "index": 2764, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef crawler(pid):\n print('hole reply start!')\n cids = []\n texts = []\n names = []\n try:\n para = {'action': 'getcomment', 'pid': pid, 'token':\n '...
[ 0, 1, 2, 3, 4 ]
import sys sys.stdin = open("1868_input.txt") dr = [-1, -1, -1, 0, 0, 1, 1, 1] dc = [-1, 0, 1, -1, 1, -1, 0, 1] def is_wall(r, c): if r < 0 or r >= n or c < 0 or c >= n: return True return False def find(r, c, cnt): Q = [] Q.append((r, c)) visited[r][c] = 1 while Q: tr, tc = Q...
normal
{ "blob_id": "8bce394c651931304f59bbca3e2f019212be9fc1", "index": 4620, "step-1": "<mask token>\n\n\ndef is_wall(r, c):\n if r < 0 or r >= n or c < 0 or c >= n:\n return True\n return False\n\n\ndef find(r, c, cnt):\n Q = []\n Q.append((r, c))\n visited[r][c] = 1\n while Q:\n tr, t...
[ 2, 3, 4, 5, 6 ]
while True: print("Light Levels:" + input.light_level()) if input.light_level() < 6: light.set_all(light.rgb(255, 0, 255)) elif input.light_level() < 13: light.set_all(light.rgb(255, 0, 0)) else: light.clear()
normal
{ "blob_id": "7277b045f85d58383f26ab0d3299feb166f45e36", "index": 2575, "step-1": "<mask token>\n", "step-2": "while True:\n print('Light Levels:' + input.light_level())\n if input.light_level() < 6:\n light.set_all(light.rgb(255, 0, 255))\n elif input.light_level() < 13:\n light.set_all(...
[ 0, 1, 2 ]
import numpy as np import xgboost as xgb from sklearn.grid_search import GridSearchCV #Performing grid search import generateVector from sklearn.model_selection import GroupKFold from sklearn import preprocessing as pr positiveFile="../dataset/full_data/positive.csv" negativeFile="../dataset/full_data/negative.csv" ...
normal
{ "blob_id": "547844eca9eab097b814b0daa5da96d6a8ccee55", "index": 5843, "step-1": "import numpy as np\nimport xgboost as xgb\nfrom sklearn.grid_search import GridSearchCV #Performing grid search\nimport generateVector\nfrom sklearn.model_selection import GroupKFold\nfrom sklearn import preprocessing as pr\n\npo...
[ 0 ]
friends = ["Vino", "Ammu", "Appu"] print(friends) print(friends[0]) # returns the last element in the list print(friends[-1]) # returns the second to last element in the list print(friends[-2])
normal
{ "blob_id": "8050b757c20da7ad8dd3c12a30b523b752d6a3ff", "index": 9457, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(friends)\nprint(friends[0])\nprint(friends[-1])\nprint(friends[-2])\n", "step-3": "friends = ['Vino', 'Ammu', 'Appu']\nprint(friends)\nprint(friends[0])\nprint(friends[-1])\nprint...
[ 0, 1, 2, 3 ]
M, N = 3, 16 prime = set(range(M, N + 1)) for i in range(2, N + 1): prime -= set(range(i ** 2, N + 1, i)) for number in prime: print(number)
normal
{ "blob_id": "d190eb27ea146cf99ac7f8d29fb5f769121af60e", "index": 9437, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(2, N + 1):\n prime -= set(range(i ** 2, N + 1, i))\nfor number in prime:\n print(number)\n", "step-3": "M, N = 3, 16\nprime = set(range(M, N + 1))\nfor i in range(2...
[ 0, 1, 2 ]
import os import json import csv import re import requests import spacy import nltk from nltk.parse import CoreNLPParser from nltk.corpus import stopwords from nltk.stem import PorterStemmer stemmer = PorterStemmer() from time import time nlp = spacy.load('es_core_news_sm') from modules_api import conts_log sw_spanish=...
normal
{ "blob_id": "afb0359f4cdf5ed32bb785d969e9bf8919bb6add", "index": 3408, "step-1": "<mask token>\n\n\ndef preprocessing_terms(termlist, lang_in, timeEx, patternBasedClean,\n pluralClean, numbersClean, accentClean):\n date = '2020-06-03'\n print('terms:', termlist)\n print('lang:', lang_in)\n process...
[ 8, 9, 10, 13, 14 ]
def multiple_parameters(name, location): print(f"Hello {name}") print(f"I live in {location}") #positional arguments multiple_parameters("Selva", "Chennai") #keyword arguments multiple_parameters(location="Chennai", name="Selva")
normal
{ "blob_id": "baf3bde709ec04b6f41dce8a8b8512ad7847c164", "index": 3100, "step-1": "<mask token>\n", "step-2": "def multiple_parameters(name, location):\n print(f'Hello {name}')\n print(f'I live in {location}')\n\n\n<mask token>\n", "step-3": "def multiple_parameters(name, location):\n print(f'Hello {...
[ 0, 1, 2, 3 ]
""" Author: Eric J. Ma Purpose: This is a set of utility variables and functions that can be used across the PIN project. """ import numpy as np from sklearn.preprocessing import StandardScaler BACKBONE_ATOMS = ["N", "CA", "C", "O"] AMINO_ACIDS = [ "A", "B", "C", "D", "E", "F", "G", ...
normal
{ "blob_id": "330df4f194deec521f7db0389f88171d9e2aac40", "index": 2384, "step-1": "<mask token>\n", "step-2": "<mask token>\nscaler.fit(np.array([v for v in ISOELECTRIC_POINTS.values()]).reshape(-1, 1))\n<mask token>\nfor k, v in ISOELECTRIC_POINTS.items():\n ISOELECTRIC_POINTS_STD[k] = scaler.transform(np.a...
[ 0, 1, 2, 3, 4 ]
from django.contrib.auth.hashers import make_password from django.core import mail from rest_framework import status from django.contrib.auth.models import User import time from api.tests.api_test_case import CustomAPITestCase from core.models import Member, Community, LocalCommunity, TransportCommunity, Profile, Noti...
normal
{ "blob_id": "75c00eec7eacd37ff0b37d26163c2304620bb9db", "index": 5868, "step-1": "<mask token>\n\n\nclass MemberTests(CustomAPITestCase):\n\n def setUp(self):\n \"\"\"\n Make a user for authenticating and\n testing community actions\n \"\"\"\n owner = self.user_model.objects...
[ 23, 29, 33, 36, 38 ]
import time import pickle class BayesNetClassifier: def __init__(self, train_file, out_file): self.train_file = train_file self.out_file = out_file self.word_count_loc = {} self.word_probs = {} self.l_probs = {} self.word_counts = {} self.common_wo...
normal
{ "blob_id": "dee7b12862d02837fbb0f2310b136dd768ca7bab", "index": 3277, "step-1": "<mask token>\n\n\nclass BayesNetClassifier:\n\n def __init__(self, train_file, out_file):\n self.train_file = train_file\n self.out_file = out_file\n self.word_count_loc = {}\n self.word_probs = {}\n ...
[ 3, 6, 7, 8, 10 ]
# Part 1 - Build the CNN from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense ## Initialize the CNN classifier = Sequential() ## Step 1 - Convolution Layer classifier.add(Convolution2D(32, 3, 3,...
normal
{ "blob_id": "b0aeede44a4b54006cf0b7d541d5b476a7178a93", "index": 6155, "step-1": "<mask token>\n", "step-2": "<mask token>\nclassifier.add(Convolution2D(32, 3, 3, border_mode='same', input_shape=(64,\n 64, 3), activation='relu'))\nclassifier.add(MaxPooling2D(pool_size=(2, 2)))\nclassifier.add(Convolution2D(...
[ 0, 1, 2, 3, 4 ]
from ..utils import Object class ChatMembersFilterAdministrators(Object): """ Returns the owner and administrators Attributes: ID (:obj:`str`): ``ChatMembersFilterAdministrators`` No parameters required. Returns: ChatMembersFilter Raises: :class:`telegram.Error` ...
normal
{ "blob_id": "6dfd59bbab74a3a657d2200d62964578c296ee54", "index": 5713, "step-1": "<mask token>\n\n\nclass ChatMembersFilterAdministrators(Object):\n <mask token>\n <mask token>\n\n def __init__(self, **kwargs):\n pass\n\n @staticmethod\n def read(q: dict, *args) ->'ChatMembersFilterAdminist...
[ 3, 4, 5, 6, 7 ]
from math import * def heron(a, b, c): tmp = [a, b, c] tmp.sort() if tmp[0] + tmp[1] <= tmp[-1]: raise ValueError ("Warunek trojkata jest nie spelniony") halfPerimeter = (a + b + c)/2 return sqrt(halfPerimeter * (halfPerimeter - a)*(halfPerimeter-b)*(halfPerimeter-c)) print heron...
normal
{ "blob_id": "bbd421d39894af163b56e7104c3b29a45635d5a3", "index": 5425, "step-1": "from math import *\r\n\r\ndef heron(a, b, c):\r\n tmp = [a, b, c]\r\n tmp.sort()\r\n if tmp[0] + tmp[1] <= tmp[-1]:\r\n raise ValueError (\"Warunek trojkata jest nie spelniony\")\r\n halfPerimeter = (a + b + c)/2...
[ 0 ]
import asyncio import logging from datetime import datetime from discord.ext import commands from discord.ext.commands import Bot, Context from humanize import precisedelta from sqlalchemy.exc import SQLAlchemyError from sqlalchemy_utils import ScalarListException from config import CONFIG from models import Reminder...
normal
{ "blob_id": "0f54853901a26b66fe35106593ded6c92785b8db", "index": 2682, "step-1": "<mask token>\n\n\nclass Reminders(commands.Cog):\n\n def __init__(self, bot: Bot):\n self.bot = bot\n self.bot.loop.create_task(reminder_check(self.bot))\n\n @commands.group(help=LONG_HELP_TEXT, brief=SHORT_HELP...
[ 3, 4, 5, 6, 7 ]
from setuptools import setup from Cython.Build import cythonize setup( ext_modules=cythonize("utils.pyx"), )
normal
{ "blob_id": "66c71111eae27f6e9fee84eef05cc1f44cc5a477", "index": 3745, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(ext_modules=cythonize('utils.pyx'))\n", "step-3": "from setuptools import setup\nfrom Cython.Build import cythonize\nsetup(ext_modules=cythonize('utils.pyx'))\n", "step-4": "fro...
[ 0, 1, 2, 3 ]
import logging import os import time from datetime import datetime from pathlib import Path from configargparse import ArgumentParser from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.x509.oid import ExtensionOID from cryptography.x509.extensions import ExtensionN...
normal
{ "blob_id": "83be35b79dcaa34f9273281976ebb71e81c58cdd", "index": 8673, "step-1": "<mask token>\n\n\nclass SslExporter(object):\n gauges = {}\n\n def __init__(self, cert_paths):\n self.cert_paths = cert_paths\n\n def collect(self):\n self.gauges['ssl_valid_days'] = GaugeMetricFamily('ssl_va...
[ 6, 7, 8, 9, 10 ]
'For learning OWL and owlready2' 'From "https://qiita.com/sci-koke/items/a650c09bf77331f5537f"' 'From "https://owlready2.readthedocs.io/en/latest/class.html"' '* Owlready2 * Warning: optimized Cython parser module "owlready2_optimized" is not available, defaulting to slower Python implementation' '↑ This wartning mean...
normal
{ "blob_id": "cc7f1f38efcd4d757c1d11e2bd53695fca44e15a", "index": 212, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith onto:\n\n\n class Pizza(Thing):\n pass\n\n\n class MeatPizza(Pizza):\n pass\n\n\n class Topping(Thing):\n pass\n\n\n class has_Topping((Pizza >> Toppi...
[ 0, 1, 2, 3, 4 ]
import sys class Obj: def __init__(self, name): self.name = name self.down = [] def add_child(self, obj): self.down.append(obj) def prnt(self, prev): if not self.down: print(prev + '=' + self.name) else: for d in self.down: ...
normal
{ "blob_id": "7d3f4e0a5031f9ce618c568b440c7425489060a1", "index": 4122, "step-1": "<mask token>\n\n\nclass Obj:\n\n def __init__(self, name):\n self.name = name\n self.down = []\n\n def add_child(self, obj):\n self.down.append(obj)\n\n def prnt(self, prev):\n if not self.down:...
[ 5, 6, 7, 8 ]
# Find a list of patterns in a list of string in python any([ p in s for p in patterns for s in strings ])
normal
{ "blob_id": "c0b6c0636d1900a31cc455795838eb958d1daf65", "index": 9421, "step-1": "<mask token>\n", "step-2": "any([(p in s) for p in patterns for s in strings])\n", "step-3": "# Find a list of patterns in a list of string in python\nany([ p in s for p in patterns for s in strings ])\n", "step-4": null, "...
[ 0, 1, 2 ]
class ListNode: def __init__(self, val: int, next=None): self.val = val self.next = next def reverseKGroup(head: ListNode, k: int) -> ListNode: prev, cur, rs, successor = None, head, head, None def reverseK(node: ListNode, count: int) -> ListNode: nonlocal successor nonloc...
normal
{ "blob_id": "67904f3a29b0288a24e702f9c3ee001ebc279748", "index": 3542, "step-1": "class ListNode:\n <mask token>\n\n\n<mask token>\n", "step-2": "class ListNode:\n\n def __init__(self, val: int, next=None):\n self.val = val\n self.next = next\n\n\n<mask token>\n\n\ndef print_list(head: List...
[ 1, 3, 4, 5, 6 ]
#!/usr/bin/env python from scapy.all import * from optparse import OptionParser import socket import struct class MagicARP: def __init__(self, iface): self.iface = iface self.macrecs = {} def magic_arp(self, pkt): # only look for queries if ARP in pkt and pkt[ARP].op == 1: # Get a rand...
normal
{ "blob_id": "c58bfa620df9f1b1f31c83a76d0d8a4576cbd535", "index": 7795, "step-1": "#!/usr/bin/env python\n\nfrom scapy.all import *\nfrom optparse import OptionParser\nimport socket\nimport struct\n\n\n\n\t\nclass MagicARP:\n\t\n\tdef __init__(self, iface):\n\t\t\n\t\tself.iface = iface\n\t\tself.macrecs = {}\n\t...
[ 0 ]
#!/usr/bin/python3 """Locked class module""" class LockedClass: """test class with locked dynamic attruibute creation """ __slots__ = 'first_name'
normal
{ "blob_id": "d90a4b00d97cecf3612915a72e48a363c5dcc97b", "index": 5006, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass LockedClass:\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass LockedClass:\n <mask token>\n __slots__ = 'first_name'\n", "step-4": "<mask tok...
[ 0, 1, 2, 3, 4 ]
from __future__ import unicode_literals import json class BaseModel(object): def get_id(self): return unicode(self.id) @classmethod def resolve(cls, id_): return cls.query.filter_by(id=id_).first() @classmethod def resolve_all(cls): return cls.query.all()
normal
{ "blob_id": "c9079f27e3c0aca09f99fa381af5f35576b4be75", "index": 4717, "step-1": "<mask token>\n\n\nclass BaseModel(object):\n <mask token>\n <mask token>\n\n @classmethod\n def resolve_all(cls):\n return cls.query.all()\n", "step-2": "<mask token>\n\n\nclass BaseModel(object):\n\n def ge...
[ 2, 3, 4, 5 ]
import os import z5py from shutil import copytree, copyfile ROOT = '/g/kreshuk/pape/Work/data/mito_em/data' SCRATCH = '/scratch/pape/mito_em/data' def create_file(out_path, ref_path): os.makedirs(out_path, exist_ok=True) copyfile( os.path.join(ref_path, 'attributes.json'), os.path.join(out_pa...
normal
{ "blob_id": "9d3db4ca5bf964c68e9778a3625c842e74bf9dbd", "index": 1228, "step-1": "<mask token>\n\n\ndef create_file(out_path, ref_path):\n os.makedirs(out_path, exist_ok=True)\n copyfile(os.path.join(ref_path, 'attributes.json'), os.path.join(\n out_path, 'attributes.json'))\n\n\ndef copy_to_scratch...
[ 3, 5, 6, 7, 8 ]
# -*- coding: utf-8 -*- """ Created on Fri Sep 13 10:18:35 2019 @author: zehra """ import numpy as np import pickle import matplotlib.pyplot as plt from scipy.special import expit X_train, y_train, X_val, y_val, X_test, y_test = pickle.load(open("data.pkl", "rb")) id2word, word2id = pickle.load( open("dicts.pkl", "r...
normal
{ "blob_id": "3accf1c066547c4939c104c36247370b4a260635", "index": 8959, "step-1": "<mask token>\n\n\ndef sigmoid(x):\n return expit(x)\n\n\ndef LRcost(t, pred):\n pred[pred == 0.0] = 10 ** -10\n cost_per_sample = -t * np.log(pred) - (1 - t) * np.log(1 - pred)\n avg_cost = np.mean(cost_per_sample)\n ...
[ 3, 4, 5, 6, 7 ]
from sys import stdin last_emp = emp_id = '' for line in stdin: data = line.strip().split(',') if last_emp != '' and last_emp != emp_id: print(f'{emp_id},{emp_surname},{emp_name},{position},{dep_id},{dep_id},{dep_name},{num_of_emp},{head}') if len(data) == 5: last_emp = emp_id em...
normal
{ "blob_id": "3a2b1ddab422d450ad3b5684cbed1847d31fb8e6", "index": 2839, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor line in stdin:\n data = line.strip().split(',')\n if last_emp != '' and last_emp != emp_id:\n print(\n f'{emp_id},{emp_surname},{emp_name},{position},{dep_id},...
[ 0, 1, 2, 3, 4 ]
# This script runs nightly to process users' preinstall history # no it doesn't, you liar from bson.objectid import ObjectId import ConfigParser import os from text_processing.textprocessing import start_text_processing_queue from pymongo import MongoClient import time from os import listdir from os.path import isfile,...
normal
{ "blob_id": "73058bd9533ef6c0d1a4faf96930077147631917", "index": 9289, "step-1": "# This script runs nightly to process users' preinstall history\n# no it doesn't, you liar\nfrom bson.objectid import ObjectId\nimport ConfigParser\nimport os\nfrom text_processing.textprocessing import start_text_processing_queue\...
[ 0 ]
import random import time class Cells: UNDEFINED = 0 DEAD = 1 ALIVE = 2 def __init__(self, nx, ny, density = 5): self.nx = nx self.ny = ny self._cells = [[Cells.UNDEFINED for y in range(ny)] for x in range(nx)] self._nextCells = [[Cells.UNDEFINED for y in range(ny)] for...
normal
{ "blob_id": "563e534e4794aa872dcdc5319b9a1943d19f940f", "index": 1289, "step-1": "<mask token>\n\n\nclass Cells:\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, nx, ny, density=5):\n self.nx = nx\n self.ny = ny\n self._cells = [[Cells.UNDEFINED for y in range(...
[ 5, 6, 7, 8, 9 ]
from Shapes import * c1 = Circle(5) r1 = Rectangle(3,2) c2 = Circle(3) c3 = Circle(1) r2 = Rectangle(1,1) listShapes = [c1,r1,c2,c3,r2] for item in listShapes: print(item.toString()) print("Area: " + str(item.area())) print("Perimeter: " + str(item.perimeter()))
normal
{ "blob_id": "9ef5d57d536f5c88f705b1032cc0936e2d4cd565", "index": 1039, "step-1": "from Shapes import *\n\nc1 = Circle(5)\nr1 = Rectangle(3,2)\nc2 = Circle(3)\nc3 = Circle(1)\nr2 = Rectangle(1,1)\n\nlistShapes = [c1,r1,c2,c3,r2]\n\nfor item in listShapes:\n\tprint(item.toString())\n\tprint(\"Area: \" + str(item....
[ 0 ]
"""A lightweight Python wrapper of SoX's effects.""" import shlex from io import BufferedReader, BufferedWriter from subprocess import PIPE, Popen import numpy as np from .sndfiles import ( FileBufferInput, FileBufferOutput, FilePathInput, FilePathOutput, NumpyArrayInput, NumpyArrayOutput, ...
normal
{ "blob_id": "f98f2ef0d94839711b473ad1ca32b85645d4014e", "index": 8764, "step-1": "<mask token>\n\n\nclass AudioEffectsChain:\n\n def __init__(self):\n self.command = []\n\n def equalizer(self, frequency, q=1.0, db=-3.0):\n \"\"\"equalizer takes three parameters: filter center frequency in Hz,...
[ 22, 27, 29, 31, 42 ]
# -*- coding: utf-8 -*- """ ORIGINAL PROGRAM SOURCE CODE: 1: from __future__ import division, print_function, absolute_import 2: 3: import os 4: from os.path import join 5: 6: from scipy._build_utils import numpy_nodepr_api 7: 8: 9: def configuration(parent_package='',top_path=None): 10: from numpy.distutils....
normal
{ "blob_id": "4453b8176cda60a3a8f4800860b87bddfdb6cafa", "index": 7963, "step-1": "<mask token>\n\n\n@norecursion\ndef configuration(localization, *varargs, **kwargs):\n global module_type_store\n str_32070 = get_builtin_python_type_instance(stypy.reporting.\n localization.Localization(__file__, 9, 3...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python #encoding:utf8 import sys from collections import defaultdict def transform_word(word): ''' 将低频词转为四种形式之一。 ''' if any(c.isdigit() for c in word): return '_NUMERIC_' if word.isupper(): return '_ALL_CAP_' if word[-1].isupper(): return '_LAST_CAP_' ...
normal
{ "blob_id": "92a1f86ce8cc9563d455f9b1336dbcd298f01b6d", "index": 1747, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef transform_word(word):\n \"\"\"\n 将低频词转为四种形式之一。\n \"\"\"\n if any(c.isdigit() for c in word):\n return '_NUMERIC_'\n if word.isupper():\n return '_ALL_...
[ 0, 2, 3, 4, 5 ]
#!/usr/bin/env python ''' export_claims -- export claims in CSV format https://sfreeclaims.anvicare.com/docs/forms/Reference-CSV%20Specifications.txt ''' import csv from itertools import groupby from operator import itemgetter import wsgiref.handlers import MySQLdb import ocap from hhtcb import Xataface, WSGI def...
normal
{ "blob_id": "41f70cdfc9cbe5ec4560c1f3271a4636cca06d16", "index": 3012, "step-1": "#!/usr/bin/env python\n''' export_claims -- export claims in CSV format\n\nhttps://sfreeclaims.anvicare.com/docs/forms/Reference-CSV%20Specifications.txt\n'''\n\nimport csv\nfrom itertools import groupby\nfrom operator import itemg...
[ 0 ]
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload fr...
normal
{ "blob_id": "aa79d5cbe656979bf9c228f6a576f2bbf7e405ca", "index": 2950, "step-1": "<mask token>\n\n\n@pulumi.input_type\nclass _UserGpgKeyState:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\ncl...
[ 11, 19, 22, 26, 29 ]
import os def savelesson(text): os.path.expanduser("~/.buzzers/lessons") def getlessonlist(): path = os.path.expanduser("~/.buzzers") dirs = os.walk(os.path.expanduser("~/.buzzers/lessons")) #"/home/loadquo/files/lhsgghc/Programs/PCSoftware/src/admin/lessons") lessons = [] for root, d, fs in dirs: ...
normal
{ "blob_id": "de003440be513d53b87f526ea95c0fbbc4a9f66f", "index": 2584, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef getlessonlist():\n path = os.path.expanduser('~/.buzzers')\n dirs = os.walk(os.path.expanduser('~/.buzzers/lessons'))\n lessons = []\n for root, d, fs in dirs:\n ...
[ 0, 1, 2, 3, 4 ]
#H############################################################## # FILENAME : rec.py # # DESCRIPTION : # Classifies text using defined regular expressions # # PUBLIC FUNCTIONS : # int processToken( string ) # # NOTES : # This function uses specific critera to classify # Criteria desc...
normal
{ "blob_id": "6d543e9e24debaff7640006a3836c59ec0096255", "index": 5205, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef processToken(token):\n idPattern1 = re.compile('^([$]|[|]|[a-z])[A-Z0-9]*$')\n idPattern2 = re.compile('^([|][A-Z0-9]*[|])$')\n intPattern = re.compile('^(%)([0-9]|[A-Fa-...
[ 0, 1, 3, 4, 5 ]
class Node: def __init__(self, dataVal=None): self.dataVal = dataVal self.nextVal = None class LinkedList: def __init__(self): self.headVal = None def atBeginning(self, data): NewNode = Node(data) NewNode.nextVal = self.headVal self.headVal = NewNode ...
normal
{ "blob_id": "00260e23614a7b0a11ff3649e71392e4892de423", "index": 4511, "step-1": "<mask token>\n\n\nclass LinkedList:\n <mask token>\n <mask token>\n\n def atEnd(self, data):\n NewNode = Node(data)\n NewNode.nextVal = None\n if self.headVal is None:\n self.headVal = NewNo...
[ 6, 9, 12, 15, 17 ]
def strictly_greater_than(value): if value : # Change this line return "Greater than 100" elif value : # Change this line return "Greater than 10" else: return "10 or less" # Change the value 1 below to experiment with different values print(strictly_greater_than(1))
normal
{ "blob_id": "7620d76afc65ceb3b478f0b05339ace1f1531f7d", "index": 6708, "step-1": "<mask token>\n", "step-2": "def strictly_greater_than(value):\n if value:\n return 'Greater than 100'\n elif value:\n return 'Greater than 10'\n else:\n return '10 or less'\n\n\n<mask token>\n", "s...
[ 0, 1, 2, 3 ]
import pandas as pd import numpy as np import csv #import nltk #nltk.download('punkt') from nltk.tokenize import sent_tokenize csv_file=open("/home/debajit15/train+dev.csv") pd.set_option('display.max_colwidth', None) df=pd.read_csv(csv_file,sep=','); df = df[pd.notnull(df['Aspects'])] #print(df['Opinion_Words'].iloc[0...
normal
{ "blob_id": "c18c407476375fb1647fefaedb5d7ea0e0aabe3a", "index": 929, "step-1": "<mask token>\n\n\ndef train_validate_test_split(df, train_percent=0.8, validate_percent=0.2,\n seed=None):\n np.random.seed(seed)\n perm = np.random.permutation(df.index)\n m = len(df.index)\n train_end = int(train_pe...
[ 2, 3, 4, 5, 6 ]
from rest_framework import serializers from issue.models import Issue class IssueSerializer(serializers.ModelSerializer): """DRF Serializer For Listing Published Issue""" class Meta: model = Issue fields = ['issueName', 'website', 'issueBody', 'impact', 'published_on' ] class I...
normal
{ "blob_id": "e4422010337eade12226d84c79532cdbcae68d67", "index": 1495, "step-1": "<mask token>\n\n\nclass IssueCreateSerializer(serializers.ModelSerializer):\n <mask token>\n\n\n class Meta:\n model = Issue\n fields = ['issueName', 'website', 'issueBody', 'impact', 'project',\n 'em...
[ 3, 5, 6, 7 ]
#!usr/bin/env python # -*- coding:utf-8 _* """ @File : build_model_2.py @Author : ljt @Description: xx @Time : 2021/6/12 21:46 """ import numpy as np import SimpleITK as sitk import skimage.restoration.deconvolution from numpy.fft import fftn, ifftn new_img = sitk.ReadImage("../../data/ground_data/new_img.nii") s...
normal
{ "blob_id": "f84ab1530cbc6bd25c45fc607d8f1cd461b180bf", "index": 2089, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor h in range(11, 41):\n for i in range(model_img_array.shape[0]):\n for j in range(model_img_array.shape[2]):\n dis = np.sqrt(pow(13 - i, 2) + pow(9 - j, 2))\n ...
[ 0, 1, 2, 3, 4 ]
import os basedir = os.path.abspath(os.path.dirname(__file__)) from datetime import datetime class Config(object): # ... SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'postgres' or 'sqlite:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_TRACK_MODIFICATIONS = False MONGODB_DB...
normal
{ "blob_id": "118380f58cd173d2de5572a1591766e38ca4a7f8", "index": 8846, "step-1": "<mask token>\n\n\nclass Config(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Config(object):\n SQLALCHEMY_DATABASE_U...
[ 1, 2, 3, 4, 5 ]
from __future__ import absolute_import, division, print_function from .core import Bag, Item, from_sequence, from_filenames from ..context import set_options
normal
{ "blob_id": "4e77c7ac784ec235e9925004069131d16717e89a", "index": 9676, "step-1": "<mask token>\n", "step-2": "from __future__ import absolute_import, division, print_function\nfrom .core import Bag, Item, from_sequence, from_filenames\nfrom ..context import set_options\n", "step-3": null, "step-4": null, ...
[ 0, 1 ]
from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager import time import csv options = Options() # options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(ChromeDriverManager().install(), ...
normal
{ "blob_id": "8c5815c1dd71b2ae887b1c9b1968176dfceea4f9", "index": 6182, "step-1": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\nimport csv\n\noptions = Options()\n# options.add_argument('--headless')\n...
[ 0 ]
from flask import render_template, request, redirect, url_for from flask_login import current_user from application import app, db, login_required from application.auth.models import User from application.memes.models import Meme from application.comments.forms import CommentForm # only a dummy new comment form @app...
normal
{ "blob_id": "fe1d47b63e88935f8b2eb4bac883f3028d6f560b", "index": 4515, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@app.route('/comments/new/')\n@login_required(role='ANY')\ndef comments_form():\n return render_template('comments/new.html', form=CommentForm())\n", "step-3": "from flask import...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python3 # coding:utf-8 # 改进小红球 class Ball: def __init__(self, canvas, paddle, color): self.canvas = canvas self.paddle = paddle self.id = canvas.create_oval(10, 10, 25, 25, fill=color) self.canvas.move(self.id, 245, 100) starts = [-3, -2, -1, 1, 2, 3] ...
normal
{ "blob_id": "cb1e73d172314c8d3d31f6e49fa67582375c0c58", "index": 7183, "step-1": "class Ball:\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "class Ball:\n <mask token>\n\n def draw(self):\n self.canvas.move(self.id, self.x, self.y)\n pos = self.canvas.coords(self.id)\n...
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 1 11:06:35 2020 @author: fitec """ # version 1 print(" Début du projet covid-19 !! ") print(" test repository distant")
normal
{ "blob_id": "3657d02271a27c150f4c67d67a2a25886b00c593", "index": 3306, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(' Début du projet covid-19 !! ')\nprint(' test repository distant')\n", "step-3": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 1 11:06:35 2020\n\n...
[ 0, 1, 2 ]
#ribbon_a and ribbon_b are the two important variables here ribbon_a=None ribbon_b=None #Notes: # - As it turns out, the internal ADC in the Teensy is NOT very susceptible to fluctuations in the Neopixels' current...BUT...the ADS1115 IS. # Therefore, I think a better model would ditch the ADS1115 alltogether ...
normal
{ "blob_id": "06caee24b9d0bb78e646f27486b9a3a0ed5f2502", "index": 6796, "step-1": "<mask token>\n\n\nclass SingleTouchReading:\n <mask token>\n <mask token>\n\n def __init__(self, ribbon):\n self.ribbon = ribbon\n self.read_raw_lower()\n self.read_raw_upper()\n self.process_re...
[ 20, 32, 40, 43, 50 ]
''' 使用random模块,如何产生 50~150之间的数? ''' import random num1 = random.randint(50,151) print(num1)
normal
{ "blob_id": "7d3355ee775f759412308ab68a7aa409b9c74b20", "index": 708, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(num1)\n", "step-3": "<mask token>\nnum1 = random.randint(50, 151)\nprint(num1)\n", "step-4": "<mask token>\nimport random\nnum1 = random.randint(50, 151)\nprint(num1)\n", "step...
[ 0, 1, 2, 3, 4 ]
# file with function to randomly select user from all of the data, all of the games import ast import csv import numpy as np import pandas as pd import sys from nba_api.stats.static import players # some fun little work to get a random player def get_random_player(file_name): def need_s(num): return 's' i...
normal
{ "blob_id": "ac178d4e009a40bde5d76e854edc6f6ae8422610", "index": 1106, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_random_player(file_name):\n\n def need_s(num):\n return 's' if num != 1 else ''\n csv.field_size_limit(sys.maxsize)\n res = pd.read_csv(file_name, header=None)...
[ 0, 1, 2, 3 ]