code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
import cv2 as cv
from threading import Thread
class Reader(Thread):
def __init__(self, width, height, device=0):
super().__init__(daemon=True)
self._stream = cv.VideoCapture(device)
self._stream.set(cv.CAP_PROP_FRAME_WIDTH, width)
self._stream.set(cv.CAP_PROP_FRAME_HEIGHT, height)... | normal | {
"blob_id": "73bf31e43394c3f922b00b2cfcd5d88cc0e01094",
"index": 2339,
"step-1": "<mask token>\n\n\nclass Reader(Thread):\n <mask token>\n\n def __del__(self):\n self._frame = None\n self._stream.release()\n <mask token>\n\n def read(self):\n return self._frame\n",
"step-2": "<... | [
3,
4,
5,
6
] |
#!/usr/bin/env python
import argparse
import subprocess
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
def quote(items):
return ["'" + item + "'" for item in items]
if module_exists('urllib.parse'):
from url... | normal | {
"blob_id": "68371acc58da6d986d94d746abb4fea541d65fdd",
"index": 3384,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef module_exists(module_name):\n try:\n __import__(module_name)\n except ImportError:\n return False\n else:\n return True\n\n\ndef quote(items):\n r... | [
0,
3,
4,
5,
6
] |
#Write a Python program to get the maximum and minimum value in a dictionary.
d1={6: 10, 2: 20, 5: 30, 4: 40, 1: 50, 3: 60}
print(max(d1.values()))
print(min(d1.values()))
| normal | {
"blob_id": "53e397068fcf88bbbce4dcc1bf1b441a2fbbee48",
"index": 2261,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(max(d1.values()))\nprint(min(d1.values()))\n",
"step-3": "d1 = {(6): 10, (2): 20, (5): 30, (4): 40, (1): 50, (3): 60}\nprint(max(d1.values()))\nprint(min(d1.values()))\n",
"step... | [
0,
1,
2,
3
] |
#1.문자열에 홑따옴표 포함기키기 : 쌍따옴표
print("Python's Data Type")
#2.문자열에 쌍따옴표 포함시키기 : 홑따옴표
print('"Python is very easy" he said.')
#멀티라인(여러줄)표현하기
#1. 연속된 쌍따옴표 3개 사용하기
print("""No pain
No gain""")
#2. 연속된 쌍따옴표 3개 사용하기
print('''No pain
No gain''')
#3.이스케이프 코드 \n 삽입하기
print("No pain \n No gain")
"""
이스케이프(es... | normal | {
"blob_id": "eb81f1825c4ac8e20dde1daefbdad22f588e696e",
"index": 9431,
"step-1": "<mask token>\n",
"step-2": "print(\"Python's Data Type\")\nprint('\"Python is very easy\" he said.')\nprint(\"\"\"No pain\n No gain\"\"\")\nprint(\"\"\"No pain\n No gain\"\"\")\nprint(\"\"\"No pain \n No gain\"\... | [
0,
1,
2
] |
__author__ = 'sudab'
""" Generate a grid world """
import os, sys, getopt, pdb, string
import random
import numpy as np
import pygame
from skimage import io
import cv2
import pygame.locals as pgl
class Gridworld():
# a gridworld with uneven terrain
def __init__(self, filename=None, initial=0, nrows=8, ncols=8,... | normal | {
"blob_id": "1fbd4e45b061b4d6cefb46e3bc612533ec94250b",
"index": 481,
"step-1": "__author__ = 'sudab'\n\"\"\" Generate a grid world \"\"\"\nimport os, sys, getopt, pdb, string\nimport random\nimport numpy as np\nimport pygame\nfrom skimage import io\nimport cv2\nimport pygame.locals as pgl\n\nclass Gridworld():\... | [
0
] |
from unittest import TestCase
from spiral.spiral_matrix import SpiralMatrix
class TestOutwardCounterClockwise(TestCase):
def test_traverse_empty(self):
matrix = []
actual = [i for i in SpiralMatrix(matrix, clockwise=False, inward=False)]
self.assertEqual([], actual)
def test_traverse_... | normal | {
"blob_id": "84f6336261e1c276f029822754842514715791df",
"index": 3604,
"step-1": "<mask token>\n\n\nclass TestOutwardCounterClockwise(TestCase):\n <mask token>\n <mask token>\n\n def test_traverse_single_element(self):\n matrix = [[1]]\n actual = [i for i in SpiralMatrix(matrix, clockwise=... | [
5,
7,
11,
14,
15
] |
config_prefix = "<"
config_suported_types = ["PNG", "GIF", "JPEG"]
config_pattern = "^[A-Za-z0-9_]*$"
config_max_storage = int(1E9)
config_max_name_length = 20
config_message_by_line = 2
config_max_message_length = 2000
config_max_emote_length = 8*int(1E6)
config_pong = """
,;;;!!!!!;;.
:!!!!!!!!!!!!!!;
... | normal | {
"blob_id": "dc2deb7d4c9cc126a6d80435fe9dbc16d6ac8941",
"index": 9397,
"step-1": "<mask token>\n",
"step-2": "config_prefix = '<'\nconfig_suported_types = ['PNG', 'GIF', 'JPEG']\nconfig_pattern = '^[A-Za-z0-9_]*$'\nconfig_max_storage = int(1000000000.0)\nconfig_max_name_length = 20\nconfig_message_by_line = 2\... | [
0,
1,
2
] |
# Generated by Django 2.1.3 on 2019-04-10 11:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_auto_20190409_1917'),
]
operations = [
migrations.AlterField(
model_name='article',
name='estArchive',
... | normal | {
"blob_id": "21c8078a18ee4579fa9b4b1b667d6ea0c1ce99b3",
"index": 6005,
"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 = [('blog', '001... | [
0,
1,
2,
3,
4
] |
from graphviz import Digraph
from math import log2, ceil
def hue_to_rgb(p, q, t):
if t < 0: t += 1
if t > 1: t -= 1
if t < 1/6: return p + (q - p) * 6 * t
if t < 1/2: return q
if t < 2/3: return p + (q - p) * (2/3 - t) * 6
return p
def hsl_to_rgb(h, s, l):
h /= 360
q = l * (1 + s) if l... | normal | {
"blob_id": "881afd6877508243fa5056d2a82d88ba69ffb8c0",
"index": 7801,
"step-1": "<mask token>\n\n\nclass Node:\n\n def __init__(self, val, children=None, parent=None):\n self.id = str(val)\n self.val = val\n self.parent = parent\n self.depth = -1\n self.size = -1\n s... | [
21,
22,
25,
29,
33
] |
#!/usr/bin/env python3
import collections
import glob
import os
import pandas as pd
import numpy as np
import torch.nn.functional as F
import PIL.Image as Image
from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params
from inference.metrics.fid.fid_score import _compute_... | normal | {
"blob_id": "f6846bfc6c4d803cedaf37e079e01188733938c7",
"index": 8249,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef calc_optical_flow_metrics(flow_predictor, frames, movable_mask):\n if not movable_mask.any():\n return dict(flow_l2=float('nan'))\n assert not (frames < 0).any() and ... | [
0,
4,
5,
6,
7
] |
# Generated by Django 3.2.3 on 2021-05-23 19:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main_app', '0002_notebook_smathphone'),
]
operations = [
migrations.RenameModel(
old_name='Smathphone',
new_name='Smartphone... | normal | {
"blob_id": "7e11a33d82926ed544640a0192e905d373f575da",
"index": 2766,
"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 = [('main_app', ... | [
0,
1,
2,
3,
4
] |
from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
import random
import itertools
doc = """
Public good game section (Rounds and feedback).
"""
class Constants(BaseConstants):
name_in_url = 'public_goods'
players... | normal | {
"blob_id": "e766bba4dec0d37858f1f24083c238763d694109",
"index": 7874,
"step-1": "from otree.api import (\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\n Currency as c, currency_range\n)\nimport random\nimport itertools\n\ndoc = \"\"\"\n Public good game section (Rounds an... | [
0
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import Common.Common.GeneralSet as GeneralSet
import TestExample.Test as Test
from Common.Common.ProcessDefine import *
def MainRun():
Cmd()
Test.TestGo()
def Cmd():
if (len(sys.argv) != 3):
print('error cmdargument count!')
return... | normal | {
"blob_id": "734561c2f127418bdc612f84b3b1ba125b6a2723",
"index": 3784,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef MainRun():\n Cmd()\n Test.TestGo()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef MainRun():\n Cmd()\n Test.TestGo()\n\n\ndef Cmd():\n if len(sys.argv) !=... | [
0,
1,
2,
3,
4
] |
from django.conf import settings
from .base import *
import os
DEBUG = True
SECRET_KEY = os.environ['SECRET_KEY']
ROOT_URLCONF = 'floweryroad.urls.docker_production'
ALLOWED_HOSTS = [os.environ['WEB_HOST']]
CORS_ORIGIN_WHITELIST = [os.environ['CORS']]
DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_ps... | normal | {
"blob_id": "ab35684166f07a3ab9e64f2ff98980e25a3fc576",
"index": 1643,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nDEBUG = True\nSECRET_KEY = os.environ['SECRET_KEY']\nROOT_URLCONF = 'floweryroad.urls.docker_production'\nALLOWED_HOSTS = [os.environ['WEB_HOST']]\nCORS_ORIGIN_WHITELIST = [os.environ['CO... | [
0,
1,
2
] |
import datetime as dt
import json
import pandas as pd
import numpy as np
from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func
from iotfunctions.base import BaseTransformer
from iotfunctions.metadata import EntityType
from iotfunctions.db import Database
from iotfunctions import ui
with open('c... | normal | {
"blob_id": "f15a0956c4aa27da861f9bccbeff7a6b6a909b73",
"index": 1113,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('credentials_as.json', encoding='utf-8') as F:\n credentials = json.loads(F.read())\n<mask token>\nprint(df)\n",
"step-3": "<mask token>\nwith open('credentials_as.json', e... | [
0,
1,
2,
3
] |
import sqlite3
import hashlib
users = []
class UserModel:
id = 0
def __init__(self, name, password, birth, sex, phone, email, id=0):
if(id == 0):
self.id = self.id + 1
else:
self.id = id
self.name = name
self.email = email
#處理密碼
s = has... | normal | {
"blob_id": "e675283f14a3d29fba878e7f6d9592130611c2be",
"index": 1469,
"step-1": "<mask token>\n\n\nclass UserModel:\n <mask token>\n\n def __init__(self, name, password, birth, sex, phone, email, id=0):\n if id == 0:\n self.id = self.id + 1\n else:\n self.id = id\n ... | [
6,
7,
8,
9,
12
] |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: Sequitr
# Purpose: Sequitr is a small, lightweight Python library for common image
# processing tasks in optical microscopy, in particular, single-
# molecule imaging, super-resolution... | normal | {
"blob_id": "01f4d097cc5f4173fa5a13268b91753566a9f7e1",
"index": 3112,
"step-1": "#!/usr/bin/env python\n#-------------------------------------------------------------------------------\n# Name: Sequitr\n# Purpose: Sequitr is a small, lightweight Python library for common image\n# processing tasks... | [
0
] |
import time
from numba import njit
import scipy.sparse as sparse
import scipy.sparse.linalg as sparse_alg
L = 12
Nup = 6
Ndown = 6
t = -2.0
U = 10.0
hoppings = [(i, j, t) for i in range(L) for j in range(L) if abs(i - j) == 1]
@njit
def hammingWeight(n):
res = 0
for i in range(32):
if n & (1 << i):
... | normal | {
"blob_id": "325cc2fd82c44d0b7e291384159bd48d068e60f1",
"index": 1428,
"step-1": "<mask token>\n\n\n@njit\ndef hammingWeight(n):\n res = 0\n for i in range(32):\n if n & 1 << i:\n res += 1\n return res\n\n\n@njit\ndef getStates():\n spinUpStates = [i for i in range(1 << L) if hammin... | [
4,
5,
6,
7,
8
] |
""" view.py: Contains the View class. """
import random
import config
from graphics import *
class View:
""" The view class which handles the visual component of the application.
"""
def __init__(self, pygame, master):
""" Set up and initialise the view. Does not start the display. "... | normal | {
"blob_id": "2168d10a1b4796576cc7ebb6893e0dc8b58085ca",
"index": 4435,
"step-1": "<mask token>\n\n\nclass View:\n <mask token>\n\n def __init__(self, pygame, master):\n \"\"\" Set up and initialise the view. Does not start the display. \"\"\"\n self._pygame = pygame\n self._master = ma... | [
2,
5,
6,
7,
8
] |
#Program written and maintained by Matthew Meyerink
#File responsible for defining the game based on user input
from cpu_game import CPU_Game
from warning_color import Warning
class User_Game(CPU_Game):
#Get the user phrase to start the game
def get_user_phrase(self):
correct_form = False
w... | normal | {
"blob_id": "d0dbf5a13b8e718ed426a254546ba13da12b2c3e",
"index": 4149,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass User_Game(CPU_Game):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass User_Game(CPU_Game):\n\n def get_user_phrase(self):\n correct_form = False\n whi... | [
0,
1,
2,
3,
4
] |
input = open('input').read()
stacks_input, instructions = input.split('\n\n')
stacks_input_lines = stacks_input.split('\n')
stack_numbers = map(int, stacks_input_lines[-1].split())
stacks = []
for _ in stack_numbers:
stacks.append([])
for line in stacks_input_lines[:-1]:
for stack_index, i in enumerate(range(1... | normal | {
"blob_id": "4927a440093e822250af25dfd6a2ce62d7cc099e",
"index": 8786,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor _ in stack_numbers:\n stacks.append([])\nfor line in stacks_input_lines[:-1]:\n for stack_index, i in enumerate(range(1, len(line), 4)):\n crate = line[i]\n if cra... | [
0,
1,
2,
3
] |
import functools
import re
from pprint import pprint
def heading(*, marker=''):
'''
Add a new line with the same number of heading markers as the characters in the title
Need to specify marker to one of the valid rst line markups
'''
def wrapper_heading(func):
@functools.wraps(func)
... | normal | {
"blob_id": "d1b2420778e788d78be2a12a27c80f5fa1b15a0f",
"index": 465,
"step-1": "<mask token>\n\n\ndef code_pre_block(func):\n \"\"\"\n formats a code block according to rst format\n \"\"\"\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n block = func(*args, **kwargs)\n n... | [
7,
8,
9,
10,
11
] |
# This is the template file for Lab #5, Task #1
import numpy
import lab5
def digitize(samples,threshold):
return 1*(samples > threshold)
class ViterbiDecoder:
# given the constraint length and a list of parity generator
# functions, do the initial set up for the decoder. The
# following useful instance ... | normal | {
"blob_id": "19221823f14cf06a55d445fc241fc04e64e5873c",
"index": 8323,
"step-1": "# This is the template file for Lab #5, Task #1\nimport numpy\nimport lab5\n\ndef digitize(samples,threshold):\n\treturn 1*(samples > threshold)\n\nclass ViterbiDecoder:\n # given the constraint length and a list of parity gener... | [
0
] |
# 同一目录下的引用调用还是随意导入使用的
# 跨包使用就需要使用TwoUsage里面的两种方式。
import Importex
Importex.atest()
| normal | {
"blob_id": "1a66e7f59ada43deb8e28b9806dc4fb9be4ae247",
"index": 5771,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nImportex.atest()\n",
"step-3": "import Importex\nImportex.atest()\n",
"step-4": "# 同一目录下的引用调用还是随意导入使用的\n# 跨包使用就需要使用TwoUsage里面的两种方式。\n\nimport Importex\n\nImportex.atest()\n",
"step-... | [
0,
1,
2,
3
] |
import argparse
p = argparse.ArgumentParser()
p.add_argument("--foo", action="store_true")
args = p.parse_args()
print(args.foo)
| normal | {
"blob_id": "2cc9f8c476026311456857d3395a14a45e2f4b80",
"index": 1460,
"step-1": "<mask token>\n",
"step-2": "<mask token>\np.add_argument('--foo', action='store_true')\n<mask token>\nprint(args.foo)\n",
"step-3": "<mask token>\np = argparse.ArgumentParser()\np.add_argument('--foo', action='store_true')\narg... | [
0,
1,
2,
3,
4
] |
"""This program displays a customizable list of items by priority value,
with priority 1 being the highest. Allows the user to add, edit,
mark complete, show completed (hidden), and remove items. Stores the list of
items in a .txt file located where this program's main.py file is. All
changes are automatically save... | normal | {
"blob_id": "168a12e6653a0526f29c163913def50147481154",
"index": 632,
"step-1": "<mask token>\n\n\nclass ListItem:\n \"\"\"A custom object that stores four pieces of data representing each\n entry in the todo list. Contains the text of the todo list entry,\n the priority of the entry, the group code (NY... | [
8,
11,
12,
18,
24
] |
import json
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
total=list()
url= input ('Enter Location: ') #user input url
print('Retrieving: ', url)
uh = urllib.request.urlope... | normal | {
"blob_id": "cd175c236dd1d1c7387a21a491e80d6723f161dc",
"index": 7762,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Retrieving: ', url)\n<mask token>\nprint('Retrieved', len(data), 'characters')\n<mask token>\nprint('User count:', len(info['comments']))\n<mask token>\nfor items in x:\n y = it... | [
0,
1,
2,
3,
4
] |
import pandas
def ludwig_get_model_definition(df: 'Dataframe', target: str, features: list):
input_features, output_features = [], []
for p in features:
if (pandas.api.types.is_numeric_dtype(df[p])):
input_features.append({'name': p, 'type': 'numerical',
'preprocessing'... | normal | {
"blob_id": "b7521a604fb49591df814d469f53d35574126fdb",
"index": 7609,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef ludwig_get_model_definition(df: 'Dataframe', target: str, features: list):\n input_features, output_features = [], []\n for p in features:\n if pandas.api.types.is_nu... | [
0,
1,
2,
3
] |
from django.db import models
# Create your models here.
class Login(models.Model):
trinity_id = models.CharField('',max_length=200)
trinity_password = models.CharField('',max_length=500)
objects = models.Manager() | normal | {
"blob_id": "1c5cb9363c2903905f1026ede77615e8373c250b",
"index": 7321,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Login(models.Model):\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Login(models.Model):\n trinity_id = models.CharField('', m... | [
0,
1,
2,
3,
4
] |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
# add DenseNet structure
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# self.x = x
self.block0 = nn.Sequential(
# input image 96x96
nn.ReLU(),
... | normal | {
"blob_id": "49cdeb59e75ed93122b3a62fbdc508b7d66166d6",
"index": 2337,
"step-1": "<mask token>\n\n\nclass Net(nn.Module):\n <mask token>\n <mask token>\n\n def _initialize_weights(self):\n pass\n",
"step-2": "<mask token>\n\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net,... | [
2,
3,
4,
5,
6
] |
RANGES = {
# Intervalles de la gamme majeure
0: [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1],
# Intervalles de la gamme mineure naturelle
1: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0],
# Intervalles de la gamme mineure harmonique
2: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1]
}
RANGES_NAMES = {
'fr': ['Maje... | normal | {
"blob_id": "18bad56ff6d230e63e83174672b8aa8625c1ebb4",
"index": 994,
"step-1": "\nRANGES = {\n # Intervalles de la gamme majeure\n 0: [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], \n # Intervalles de la gamme mineure naturelle\n 1: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0],\n # Intervalles de la gamme mineure... | [
0
] |
#!/usr/bin/python
import os;
import math;
# os.chdir('data/postgres/linux.env')
os.chdir('data/mysql/linux.env')
# os.chdir('data/mongo/linux.env')
col_time = 0;
col_read_ops = 1
col_read_err = 2
col_write_ops = 3
col_write_err = 4
class ColumnData:
def __init__(self, chart, title, data):
self.chart = ... | normal | {
"blob_id": "bb208d40ce098b05594aaf9c579f64b909738d52",
"index": 1067,
"step-1": "#!/usr/bin/python\n\nimport os;\nimport math;\n\n# os.chdir('data/postgres/linux.env')\nos.chdir('data/mysql/linux.env')\n# os.chdir('data/mongo/linux.env')\n\ncol_time = 0;\ncol_read_ops = 1\ncol_read_err = 2\ncol_write_ops = 3\nc... | [
0
] |
""" Unit test for the Supermarket checkout exercise """
import unittest
from decimal import *
from ShoppingCart import *
# Unit tests -----
class ScannerTests(unittest.TestCase):
def setUp(self):
pricingRulesWithSingleDiscount = { 'Apple': { 1 : '0.50' , 3 : '1.30' },
'Orange'... | normal | {
"blob_id": "fc2a123f8a86d149af9fc73baa360a029fcde574",
"index": 6316,
"step-1": "<mask token>\n\n\nclass ScannerTests(unittest.TestCase):\n <mask token>\n <mask token>\n <mask token>\n\n def testPricingSingleItems(self):\n scanner = Scanner(self.singleItemListOneDiscount)\n groceryList... | [
5,
7,
8,
11,
14
] |
class Solution(object):
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
acc = []
self.backtrack(acc, 1, n)
return acc
def backtrack(self, acc, counter, n):
if counter > n:
return
elif len(acc) == n:
... | normal | {
"blob_id": "79f4ede16628c6fbf37dfb4fe5afb8489c120f5a",
"index": 6597,
"step-1": "<mask token>\n",
"step-2": "class Solution(object):\n <mask token>\n <mask token>\n",
"step-3": "class Solution(object):\n\n def lexicalOrder(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n... | [
0,
1,
2,
3
] |
import tkinter as tk
from telnetConn import telnetConnection
fields = 'Host Address', 'UserName', 'Password', 'Message To', 'Text'
def fetch(entries):
input_list = []
for entry in entries:
field = entry[0]
text = entry[1].get()
input_list.append(text)
# print('%s:... | normal | {
"blob_id": "3328c2ae0816c146398ecde92a056d1e77683696",
"index": 7357,
"step-1": "<mask token>\n\n\ndef fetch(entries):\n input_list = []\n for entry in entries:\n field = entry[0]\n text = entry[1].get()\n input_list.append(text)\n telnetConnection(input_list[0], input_list[1], inp... | [
2,
3,
4,
5,
6
] |
# -*- coding: utf-8 -*-
# __author__ = 'XingHuan'
# 3/27/2018
import os
import imageio
import time
os.environ['IMAGEIO_FFMPEG_EXE'] = 'D:/Program Files/ffmpeg-3.4/bin/ffmpeg.exe'
reader = imageio.get_reader('test1080.mov')
print reader
fps = reader.get_meta_data()['fps']
print fps
# for i, im in enumerate(reader)... | normal | {
"blob_id": "1e292872c0c3c7f4ec0115f0769f9145ef595ead",
"index": 8325,
"step-1": "# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 3/27/2018\n\nimport os\nimport imageio\nimport time\n\nos.environ['IMAGEIO_FFMPEG_EXE'] = 'D:/Program Files/ffmpeg-3.4/bin/ffmpeg.exe'\n\n\nreader = imageio.get_reader('test1080... | [
0
] |
import torch.nn as nn
def my_loss():
return nn.CrossEntropyLoss()
| normal | {
"blob_id": "418f2e1cbe4fb3ef369e981e72bf40eeddfd052e",
"index": 2408,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef my_loss():\n return nn.CrossEntropyLoss()\n",
"step-3": "import torch.nn as nn\n\n\ndef my_loss():\n return nn.CrossEntropyLoss()\n",
"step-4": null,
"step-5": null,
... | [
0,
1,
2
] |
from rest_framework import serializers
#from rest_framework.response import Response
from .models import Category, Product
class RecursiveSerializer(serializers.Serializer):
def to_representation(self, value):
serializer = self.parent.parent.__class__(value, context=self.context)
return ... | normal | {
"blob_id": "cd9cc656a62728b3649b00c03ca8d05106015007",
"index": 7949,
"step-1": "<mask token>\n\n\nclass CategorySerializers(serializers.ModelSerializer):\n childcategories = RecursiveSerializer(many=True, read_only=True)\n\n\n class Meta:\n model = Category\n fields = 'id', 'name', 'parent'... | [
3,
4,
5,
6,
7
] |
from test.demo_test_case import DemoTestCase
class UserTest(DemoTestCase):
def test_access_secure_area(self):
r = self.get('/api/user')
self.assertEqual(401, r.status_code)
def test_login_bad_password(self):
r = self.post('/api/connect', {'user': 'admin', 'password':
'bad... | normal | {
"blob_id": "0a1d102075cebee13e25f3eb703811d1e22f53c2",
"index": 1957,
"step-1": "<mask token>\n\n\nclass UserTest(DemoTestCase):\n <mask token>\n\n def test_login_bad_password(self):\n r = self.post('/api/connect', {'user': 'admin', 'password':\n 'badpassword'})\n self.assertEqual... | [
3,
4,
5,
6
] |
from app.View.view import View
class GameController:
instance = None
@staticmethod
def get_instance():
if GameController.instance is None:
GameController()
return GameController.instance
def __init__(self):
if GameController.instance is not None:
raise... | normal | {
"blob_id": "d9b405d5159a153fb8d2f1991ceb3dc47f98bcbc",
"index": 9192,
"step-1": "<mask token>\n\n\nclass GameController:\n <mask token>\n\n @staticmethod\n def get_instance():\n if GameController.instance is None:\n GameController()\n return GameController.instance\n <mask t... | [
3,
4,
5,
6
] |
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from django.contrib.auth.forms import SetPasswordForm
from . import views
urlpatterns = [
url(regex=r'^(?P<pk>\d+)$', view=views.UserDetailView.as_view(), name='user_detail'),
url(regex=r'^update/(?P<pk>\d+)$', view=views.UserUpd... | normal | {
"blob_id": "1ac0f5c62ee3cb60d4443b65d429f4f0e6815100",
"index": 5488,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url(regex='^(?P<pk>\\\\d+)$', view=views.UserDetailView.\n as_view(), name='user_detail'), url(regex='^update/(?P<pk>\\\\d+)$', view\n =views.UserUpdateView.as_view()... | [
0,
1,
2,
3
] |
import sqlite3
import sys
import threading
from time import sleep
sq = None
def get_queue(category, parser):
if sq == None:
return liteQueue(category, parser)
return sq
"""
SqLite Job Handler class for Links
"""
class liteQueue:
_create = "CREATE TABLE IF NOT EXISTS link ( 'url' TEXT,'cat... | normal | {
"blob_id": "ed6eda4b6dbf3e94d8efb53004b19cd9c49e927e",
"index": 3979,
"step-1": "<mask token>\n\n\nclass liteQueue:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _get_conn(self):\n id = threading.current_thread().i... | [
5,
6,
7,
8,
11
] |
{
'variables': {
'node_shared_openssl%': 'true'
},
'targets': [
{
'target_name': 'keypair',
'sources': [
'secp256k1/keypair.cc'
],
'conditions': [
# For Windows, require either a 32-bit or 64-bit
# separately-compiled OpenSSL library.
# Currently set up to ... | normal | {
"blob_id": "e7b30353fd25beb9d5cdeee688e4ffa6955d4221",
"index": 8437,
"step-1": "<mask token>\n",
"step-2": "{'variables': {'node_shared_openssl%': 'true'}, 'targets': [{'target_name':\n 'keypair', 'sources': ['secp256k1/keypair.cc'], 'conditions': [[\n 'OS==\"win\"', {'conditions': [['target_arch==\"x6... | [
0,
1,
2
] |
import sys
numList = list(range(3))
for i in range(3):
numList[i] = int(sys.stdin.readline())
result = numList[0] * numList[1] * numList[2]
resultList = list(str(result))
intList = list(range(10))
for i in intList:
print(resultList.count(str(i)))
| normal | {
"blob_id": "c3de6cd76ca7180a1a4d236bb2a6a18f7594f38b",
"index": 1304,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(3):\n numList[i] = int(sys.stdin.readline())\n<mask token>\nfor i in intList:\n print(resultList.count(str(i)))\n",
"step-3": "<mask token>\nnumList = list(range(3)... | [
0,
1,
2,
3
] |
import cv2
import numpy as np
import pandas as pd
import tkinter as tk
import random
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import Scale,Tk
from tkinter.ttk import Notebook
refPt = []
PtBGR=[]
r=[]
g=[]
b=[]
refPt = []
Serial=[]
PtBGR=[]
r1=[]
r2=[]
r3=[]
r4=[]
rate=[... | normal | {
"blob_id": "a126b1775ffe1ba1aebc288ce17fac8ada0b0756",
"index": 312,
"step-1": "<mask token>\n\n\ndef quitScreen():\n messagebox.showinfo('collecting data', '點擊視窗開始分析')\n root.destroy()\n root2 = Tk()\n root2.destroy()\n\n\ndef getTextInput():\n global result, result2\n result = text.get(1.0, ... | [
5,
6,
8,
9,
10
] |
#!/usr/local/bin/python3
import time, json, os, sqlite3, uuid, json, base64, sys
import requests as http
import numpy as np
from os.path import isfile, join
from datetime import date, datetime
from argparse import ArgumentParser
PRINTER_IP = ""
FRAMERATE = 30
TIMELAPSE_DURATION = 60
TIMELAPSE_PATH = "timelapses"
DATA... | normal | {
"blob_id": "d443e9054481984d5372343170254268dca8a3b1",
"index": 3235,
"step-1": "<mask token>\n\n\ndef is_printing():\n try:\n status = http.get('http://' + PRINTER_IP + '/api/v1/printer/status',\n timeout=1)\n if status.json() == 'printing':\n state = http.get('http://' +... | [
8,
9,
10,
11,
12
] |
import requests
from bs4 import BeautifulSoup
import json
import geojson
import re
import time
_apiKey = "SNgeI1tCT-oihjeZDGi6WqcM0a9QAttLhKTecPaaETQ"
def Geocode(address, apiKey):
URL = 'https://geocode.search.hereapi.com/v1/geocode'
# Параметры запроса
params = {
'q': address,
'apiKey':... | normal | {
"blob_id": "d32496c9bce86f455b24cd9c6dc263aee1bf82af",
"index": 3552,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef Geocode(address, apiKey):\n URL = 'https://geocode.search.hereapi.com/v1/geocode'\n params = {'q': address, 'apiKey': apiKey}\n import pdb\n pdb.set_trace()\n respo... | [
0,
2,
3,
4,
5
] |
import tensorflow.keras
from preprocessing_and_training.train import reshape_and_predict
import glob
""" Script for prediction - testing and importing the trained model from train.py """
def make_predictions(file_list, model, is_game=False):
""" Predictions with model that is locally saved
:param file_list:... | normal | {
"blob_id": "a17c448b068b28881f9d0c89be6037503eca3974",
"index": 5700,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef make_single_prediction(wav_file, model, is_game):\n \"\"\" Predictions with model that is locally saved\n\n :param wav_file: wav-file we want to predict\n :param model: T... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python3
"""(Optional) Test for GameDealer class."""
import unittest
import os, sys
from functools import reduce
sys.path.insert(0, os.path.join(os.path.split(__file__)[0], ".."))
import Lab19_Extending_Builtins.lab19_3 as game_dealer
WHOLE_DECK = sorted(game_dealer.Deck())
class ReportingDealer(... | normal | {
"blob_id": "06a721c12e3140d4d1cf544a598f512595c4ab66",
"index": 3013,
"step-1": "<mask token>\n\n\nclass ReportingDealer(game_dealer.GameDealer):\n <mask token>\n\n def Report(self):\n \"\"\"For testing.\"\"\"\n return [p.hand for p in self.players]\n\n\nclass TestPlayCards(unittest.TestCase... | [
8,
10,
11,
12,
13
] |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import socket
import select
import time
"""=====================Head Define====================="""
UDP_RECEIVE_TIMEOUT = 1
LOOP_DELAY = 1
"""=====================Class====================="""
class UDP_packet:
def __init__(self,board_info, board_add, state):
se... | normal | {
"blob_id": "7c2a59f698b75d0de89a16310d97a01506c99cb3",
"index": 9840,
"step-1": "<mask token>\n\n\nclass UDP_packet:\n\n def __init__(self, board_info, board_add, state):\n self.board_type = int('{0:08b}'.format(board_info)[:4], 2)\n self.board_num = int('{0:08b}'.format(board_info)[4:], 2)\n ... | [
6,
7,
8,
9,
10
] |
from sys import stdin
def main():
lines = stdin
n, k = map(int, lines.next().split())
if k > n:
print -1
else:
arr = map(int, lines.next().split())
arr.sort(reverse = True)
print "%d %d" % (arr[k - 1], arr[k - 1])
main()
| normal | {
"blob_id": "fc04623db0d07f3a0a55ad49a74643a74e5203a6",
"index": 4938,
"step-1": "from sys import stdin\n\ndef main():\n lines = stdin\n n, k = map(int, lines.next().split())\n\n if k > n:\n print -1\n else:\n arr = map(int, lines.next().split())\n arr.sort(reverse = True)\n print \"%d %d\" % (ar... | [
0
] |
import torch
from torch.nn import functional as F
from sklearn.metrics import f1_score, accuracy_score
@torch.no_grad()
def validate(data, model):
model.evaluate()
out = model(data.x, data.train_index)
return model.loss(out[data.val_mask == 1], data.y[data.val_mask == 1])
@torch.no_grad()
def validate_... | normal | {
"blob_id": "83c109bc5aab6739a3a32116fae4f0c011d6118e",
"index": 4136,
"step-1": "<mask token>\n\n\n@torch.no_grad()\ndef validate(data, model):\n model.evaluate()\n out = model(data.x, data.train_index)\n return model.loss(out[data.val_mask == 1], data.y[data.val_mask == 1])\n\n\n@torch.no_grad()\ndef ... | [
3,
4,
5,
6,
7
] |
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import random
import numpy as np
import timeit
def main():
root = tk.Tk()
# root.geometry('800x500')
root.resizable(width=False, height=False)
root.title('Tugas Algoritma')
canva... | normal | {
"blob_id": "8a9feae4ce209def2c98b7bed993f9b5c019a533",
"index": 7480,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n root = tk.Tk()\n root.resizable(width=False, height=False)\n root.title('Tugas Algoritma')\n canvas = tk.Canvas(root, height=500, width=800)\n canvas.pack... | [
0,
1,
2,
3,
4
] |
class Solution:
def minimumDeletions(self, nums: List[int]) ->int:
n = len(nums)
a = nums.index(min(nums))
b = nums.index(max(nums))
if a > b:
a, b = b, a
return min(a + 1 + n - b, b + 1, n - a)
| normal | {
"blob_id": "14f3c941856ddf6bd7b3e046f21072f0b5f7b036",
"index": 5009,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def minimumDeletions(self, nums: List[int]) ->int:\n n = len(nums)\n a = nums.index(min(nums))\n b = nums.... | [
0,
1,
2
] |
import typing
import time
import cv2
import os
from .ABC import ABC
from .Exceptions import *
from .Constants import *
class Video(ABC):
def __init__(self, filename: str, *, scale: float = 1, w_stretch: float = 2, gradient: typing.Union[int, str] = 0, verbose: int = False):
if not os.path.isfile(filename... | normal | {
"blob_id": "24368b6c607c0524f8b52b279a6dce0fde72294b",
"index": 8936,
"step-1": "<mask token>\n\n\nclass Video(ABC):\n\n def __init__(self, filename: str, *, scale: float=1, w_stretch: float=2,\n gradient: typing.Union[int, str]=0, verbose: int=False):\n if not os.path.isfile(filename):\n ... | [
4,
5,
6,
7,
8
] |
"""
contains generic code for use in main menus. currently this is a function which turns dictionaries of functions
into a menu. I envision any further menu functions being stored here so don't expect it to run like a pipeline but
rather like a suite of individual menus.
TODO - refactor spider selection function as je... | normal | {
"blob_id": "f28b47e1b07011ce9d0708331f68d7f16195c567",
"index": 7225,
"step-1": "<mask token>\n\n\ndef final_option(dict_of_options, back):\n \"\"\"\n adds the final option to the dictionary based on a boolean\n\n :param dict_of_options: dictionary with readable labels as keys and uncalled functions as... | [
8,
10,
11,
12,
13
] |
# 拆包
t1 = (4,7,3)
# a,b=t1 # ValueError:too many values to unpack(拆包) (expected 3, got 2)
a,b,c = t1
print(a,b,c)
a = t1
print(a)
# x,y,z = (6,) # ValueError: not enough values to unpack (expected 3, got 1)
# s1 = 'hello'
# s2 = s1
# 变量个数与元祖个数不一致
t1 = (12,23,42,12,43)
a,*_,c = t1
print(a,c,_)
a,c,*_ = t1
p... | normal | {
"blob_id": "c65755d7a58c1cda7d6eea83876e0522a7ca9c74",
"index": 2679,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(a, b, c)\n<mask token>\nprint(a)\n<mask token>\nprint(a, c, _)\n<mask token>\nprint(a, c, _)\n<mask token>\nprint(a, c, b)\n<mask token>\nprint(a, b)\nprint(*b)\n<mask token>\nprint... | [
0,
1,
2,
3
] |
from population import Population
class REvolution:
def __init__(self, original_ind, combine_params, mutate_params, fitness, pop_params, method):
self.population = Population(1, fitness, pop_params)
self.combine_params = combine_params
self.mutate_params = mutate_params
self.fitnes... | normal | {
"blob_id": "fe13b57484e0f0796164fda99c0d759238a67153",
"index": 7215,
"step-1": "<mask token>\n\n\nclass REvolution:\n <mask token>\n <mask token>\n <mask token>\n\n def get_pop(self):\n ids = ['x: {} => y: {}'.format('%.3f' % i.value[0], '%.3f' % self.\n fitness(i.value)) for i in... | [
2,
4,
5,
6,
7
] |
c = "こ に ち わ "
print (len(c))
| normal | {
"blob_id": "26f466a6a2fd09bb108ca89e4537192c070ff83b",
"index": 1335,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(len(c))\n",
"step-3": "c = 'こ に ち わ '\nprint(len(c))\n",
"step-4": "c = \"こ に ち わ \"\nprint (len(c))\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
} | [
0,
1,
2,
3
] |
import NLC
app = NLC.create_app()
if __name__ == '__main__':
app.run(port=NLC.port, debug=True)
| normal | {
"blob_id": "de2de26d0c82213393e8174d1144c3510c63b899",
"index": 2515,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n app.run(port=NLC.port, debug=True)\n",
"step-3": "<mask token>\napp = NLC.create_app()\nif __name__ == '__main__':\n app.run(port=NLC.port, debug=True... | [
0,
1,
2,
3
] |
from sharpie import Sharpie
class SharpieSet():
def __init__(self):
self.sharpies = []
self.usable_sharpies = []
self.usable_sharpies_count = 0
def add_sharpie(self, sharpie: Sharpie):
self.sharpies.append(sharpie)
def count_usable(self):
for i in self.sharpies:
... | normal | {
"blob_id": "4524dd5f5cddd475ca39fea7ec94fa3c1df6bd2e",
"index": 3268,
"step-1": "<mask token>\n\n\nclass SharpieSet:\n <mask token>\n\n def add_sharpie(self, sharpie: Sharpie):\n self.sharpies.append(sharpie)\n <mask token>\n\n def remove_unusable(self):\n for i in self.sharpies:\n ... | [
3,
4,
5,
6,
7
] |
class Violation(object):
def __init__(self, line, column, code, message):
self.line = line
self.column = column
self.code = code
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return 'Violation(line={}, column={}, code="{}... | normal | {
"blob_id": "c513ad6ef12ae7be5d17d8d44787691cbc065207",
"index": 9989,
"step-1": "class Violation(object):\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Violation(object):\n\n def __init__(self, line, column, code, message):\n self.line = line\n self.column = colum... | [
1,
2,
3,
4
] |
#!/usr/bin/env python3
import sys
sys.path.insert(0, '../../common/python/')
from primality import prime_factors
"""
phi(n) = n*sum_{p|n} (1 - 1/p)
1/phi(n) = (1/n)*sum_{p|n} p/(p - 1)
n/phi(n) = sum_{p|n} p/(p - 1)
"""
def n_over_phi(n):
top = 1
bot = 1
pfactors = prime_factors(n)
for p, count i... | normal | {
"blob_id": "2d248ac1df1845bc5a2ee62a7171c1c47ca6d0ca",
"index": 3665,
"step-1": "<mask token>\n\n\ndef n_over_phi(n):\n top = 1\n bot = 1\n pfactors = prime_factors(n)\n for p, count in pfactors.items():\n top *= p\n bot *= p - 1\n return top / bot\n\n\ndef maximise_n_over_phi(upto)... | [
2,
3,
4,
5,
6
] |
from abc import ABC
# This is base class
class Vehicle(ABC):
pass
# GroundVehicle inherits from Vehicle
class GroundVehicle(Vehicle):
pass
# Car inherits from GroundVehicle
class Car(GroundVehicle):
pass
# Motorcycle inherits from GroundVehicle
class Motorcycle(GroundVehicle):
pass
# FlightVehicle ... | normal | {
"blob_id": "d7db617131bf6e72c7aa808030f7286ddb609cc2",
"index": 4579,
"step-1": "<mask token>\n\n\nclass Motorcycle(GroundVehicle):\n pass\n\n\nclass FlightVehicle(Vehicle):\n pass\n\n\nclass Starship(FlightVehicle):\n pass\n\n\nclass Airplane(FlightVehicle):\n pass\n",
"step-2": "<mask token>\n\n... | [
4,
6,
7,
8,
9
] |
def solution(num):
if num < 10:
num = str(num) + str(0)
else:
num = str(num)
cycle_val = 0
new_num = ""
temp_num = num[:]
while new_num != num:
sum_num = int(temp_num[0]) + int(temp_num[1])
new_num = temp_num[-1] + str(int(temp_num[0]) + int(tem... | normal | {
"blob_id": "cec772f1e470aae501aa7c638ec4cbb565848804",
"index": 9258,
"step-1": "<mask token>\n",
"step-2": "def solution(num):\n if num < 10:\n num = str(num) + str(0)\n else:\n num = str(num)\n cycle_val = 0\n new_num = ''\n temp_num = num[:]\n while new_num != num:\n ... | [
0,
1,
2,
3,
4
] |
"""
Copyright (c) 2017- Sinergise and contributors
For the full list of contributors, see the CREDITS file in the root directory of this source tree.
This source code is licensed under the MIT license, see the LICENSE file in the root directory of this source tree.
"""
import numpy as np
import pytest
from numpy.test... | normal | {
"blob_id": "b7d7b6c070f237f9ab59f3367417ecf2672fbaaf",
"index": 6437,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@pytest.mark.parametrize(('num_of_elements', 'middle_idx', 'window_size',\n 'expected_indices'), [(100, 0, 10, (0, 10)), (100, 1, 10, (0, 10)), (\n 100, 50, 10, (45, 55)), (271,... | [
0,
2,
3,
4,
5
] |
import os
import subprocess
import re
# import fcntl
# path_ffmpeg =
path_ffmpeg = r'C:\work\ffmpeg\ffmpeg-3.4.2-win64-static\bin\ffmpeg.exe'
dir_ts_files = r'E:\ts'
dir_output = r'E:\hb'
path_lock = r'C:\work\ffmpeg\encode.lock'
def get_work_base(f_base):
re_num = re.compile(r'(\d+)\-.+')
r = re_num.searc... | normal | {
"blob_id": "502e2d2222863236a42512ffc98c2cc9deaf454f",
"index": 7058,
"step-1": "<mask token>\n\n\ndef chk_tmp_file(f_tmp):\n pass\n\n\ndef get_file_base(path):\n fname = os.path.basename(path)\n return fname.split('.ts')[0]\n\n\ndef _exec_transcode(path):\n f_base = get_file_base(path)\n work_ba... | [
6,
7,
8,
9,
11
] |
#!/usr/bin/python
# The program was written by YU Ho Yung and LEUNG Kin Tung in group 24.
# The program is written with stubs for the phase 3
#
import pymongo
from scrapy.selector import Selector
import pandas as pd
# import numpy as np
import datetime
import re
import pprint
import subprocess
import scrapy
from pym... | normal | {
"blob_id": "b3a07107ef64bb50f4768954cbb579d8e66bd003",
"index": 6612,
"step-1": "<mask token>\n\n\ndef isCourseCode(corseCode):\n try:\n matchObj = re.match('[A-Z]?[A-Z]?[A-Z]?[A-Z]?\\\\d?\\\\d?\\\\d?\\\\d?([A-Z]?)',\n str(corseCode))\n if matchObj != None:\n return True\n... | [
6,
13,
14,
18,
19
] |
# Generated by Django 3.2.3 on 2021-08-26 09:18
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Restaura... | normal | {
"blob_id": "1ea61ab4003de80ffe9fb3e284b6686d4bf20b15",
"index": 787,
"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 = Tr... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
__author__ = "morganlnance"
'''
Analysis functions using PyRosetta4
'''
def get_sequence(pose, res_nums=None):
# type: (Pose, list) -> str
"""
Return the sequence of the <pose>, or, return the sequence listed in <res_nums>
:param pose: Pose
:param res_nums: list() of Pose residu... | normal | {
"blob_id": "876e9f03c908338a247b6bf1f23011e609bbc2a5",
"index": 8739,
"step-1": "<mask token>\n\n\ndef write_fasta_file(pdb_names, pdb_sequences, filename, dump_dir=''):\n \"\"\"\n Use a list of <pdb_names> and their corresponding <pdb_sequences> to write out a FASTA formatted file\n Need a <filename> ... | [
1,
2,
3,
4,
5
] |
distance = float(input("Введите начальную дистанцию: "))
target = int(input("Введите целевую дистанцию: "))
day = 1
print("{:>3}-й день: {:.3}".format(day, distance)) # некрасивенько
while target > distance:
day += 1
distance += distance / 10
print("{:>3}-й день: {:.3}".format(day, distance))
print("Ответ: ... | normal | {
"blob_id": "9033ba0a19d765a83737d59289735a9ffd02abb1",
"index": 7519,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('{:>3}-й день: {:.3}'.format(day, distance))\nwhile target > distance:\n day += 1\n distance += distance / 10\n print('{:>3}-й день: {:.3}'.format(day, distance))\nprint('О... | [
0,
1,
2,
3
] |
import cv2
import torch
print('haha')
| normal | {
"blob_id": "00f8992173321dfa5ac5b125a2e663b159fafb23",
"index": 4267,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('haha')\n",
"step-3": "import cv2\nimport torch\nprint('haha')\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
#! /usr/bin/env python
from nutils import *
@log.title
def makeplots( domain, geom, c, psi, index ):
force = c * psi.grad(geom)
xpnt, cpnt = domain.elem_eval( [ geom, c ], ischeme='bezier5', title='mesh', separate=True )
xy, uv = domain.elem_eval( [ geom, force ], ischeme='uniform1', title='quiver', separate=... | normal | {
"blob_id": "bf2a827e9c314da2ce9ad9f8f61b82c9c798e2f9",
"index": 1942,
"step-1": "#! /usr/bin/env python\n\nfrom nutils import *\n\n\n@log.title\ndef makeplots( domain, geom, c, psi, index ):\n\n force = c * psi.grad(geom)\n xpnt, cpnt = domain.elem_eval( [ geom, c ], ischeme='bezier5', title='mesh', separate=... | [
0
] |
from django.urls import path
from django.conf.urls import include, url
from . import views
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
appname = 'home'
urlpatterns = [
path('', views.home, name='home'),
]
urlpatterns += staticfiles_urlpatterns() | normal | {
"blob_id": "dd23cd068eea570fc187dad2d49b30376fbd4854",
"index": 4856,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns += staticfiles_urlpatterns()\n",
"step-3": "<mask token>\nappname = 'home'\nurlpatterns = [path('', views.home, name='home')]\nurlpatterns += staticfiles_urlpatterns()\n",
... | [
0,
1,
2,
3,
4
] |
from django.db import models
class UserData(models.Model):
username = models.CharField(max_length=24)
email = models.EmailField(max_length=32, blank=True, null=True)
password = models.CharField(max_length=32)
created_data = models.DateTimeField()
email_is_confirm = models.CharField(max_length=20, ... | normal | {
"blob_id": "8f57e120a1a84eb0b9918128580c152aabc6a724",
"index": 6778,
"step-1": "<mask token>\n\n\nclass UserData(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n verbose_name = 'Данные пользователя'\n ... | [
4,
5,
6,
7,
8
] |
"""Coroutine utilities."""
from decorator import decorator
@decorator
def coroutine(f, *a, **kw):
"""This decorator starts the coroutine for us."""
i = f(*a, **kw)
i.next()
return i
| normal | {
"blob_id": "6bde0ce30f33b155cc4c9ce9aa2ea6a6c5a1231d",
"index": 5472,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@decorator\ndef coroutine(f, *a, **kw):\n \"\"\"This decorator starts the coroutine for us.\"\"\"\n i = f(*a, **kw)\n i.next()\n return i\n",
"step-3": "<mask token>\nfr... | [
0,
1,
2,
3
] |
import pytest
import kdlc
from shutil import rmtree
import os
# from .context import kdlc
test_generated_dir = os.path.dirname(__file__) + "/generated/"
@pytest.fixture(scope="session")
def my_setup(request):
print("\nDoing setup")
def fin():
print("\nDoing teardown")
if os.path.exists(tes... | normal | {
"blob_id": "7ff029e2f0054146e438f4e4f13269e83e28c469",
"index": 8727,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@pytest.fixture(scope='session')\ndef my_setup(request):\n print('\\nDoing setup')\n\n def fin():\n print('\\nDoing teardown')\n if os.path.exists(test_generated_d... | [
0,
1,
2,
3,
4
] |
import hashlib
a = hashlib.pbkdf2_hmac("sha256", b"hallo", b"salt", 1)
b = hashlib.pbkdf2_hmac("sha256", a, b"salt", 1)
c = hashlib.pbkdf2_hmac("sha256", b"hallo", b"salt", 2)
print(b)
print(c) | normal | {
"blob_id": "20ac73789fa7297a9230a6a2b814349d2b7da5fb",
"index": 1851,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(b)\nprint(c)\n",
"step-3": "<mask token>\na = hashlib.pbkdf2_hmac('sha256', b'hallo', b'salt', 1)\nb = hashlib.pbkdf2_hmac('sha256', a, b'salt', 1)\nc = hashlib.pbkdf2_hmac('sha25... | [
0,
1,
2,
3,
4
] |
import pygame
from random import randint, choice
BLACK = (0,0,0)
#----------------------------------------------------------
class Ball(pygame.sprite.Sprite):
#------------------------------------------------------
def __init__(self, color, width, height):
# Initialize as a Sprite
super(... | normal | {
"blob_id": "6f216420f641c042bb2772b79c10f904ffa21938",
"index": 8733,
"step-1": "<mask token>\n\n\nclass Ball(pygame.sprite.Sprite):\n\n def __init__(self, color, width, height):\n super().__init__()\n self.image = pygame.Surface([width, height])\n self.image.fill(BLACK)\n self.im... | [
2,
4,
6,
7,
8
] |
"""
These are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py)
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import time
import urllib
try:
# For Python 3.0 and later
import urllib.request
except ImportError:
... | normal | {
"blob_id": "afb09f9d5860994f38e8553b19e7ebc339cc2df6",
"index": 8785,
"step-1": "<mask token>\n\n\ndef get_file_list(save_path, wld='*.105*.hdf'):\n \"\"\"\n\n Args:\n save_path: path to folder where raw MODIS files are\n wld: common wildcard in all of the raw MODIS files\n\n Returns:\n ... | [
6,
11,
12,
13,
16
] |
"""
SUMMARY
Auxiliary functions, provided here to avoid clutter
"""
"""
Transforms a point (P = [x, y]) using the x, y intervals (Δxy = [Δx, Δy]) into the corresponding discrete point (D = [xd, yd])
loc_min = [x_min, y_min]
"""
def discretize_location(P, loc_min, Δxy):
x_from_start = P[0] - loc_min[0]
y_from... | normal | {
"blob_id": "8bbc929e2ff2321b97195031fa675fbdab269fcb",
"index": 3288,
"step-1": "<mask token>\n\n\ndef first_append_to_last(arr):\n return arr + [arr[0]]\n\n\n<mask token>\n\n\ndef RMS(arr):\n n = len(arr)\n sq_sum = sum(a ** 2 for a in arr)\n return (sq_sum / n) ** 0.5\n\n\n<mask token>\n\n\ndef L1... | [
4,
5,
6,
7,
8
] |
def test_{{ project_name }}():
assert True
| normal | {
"blob_id": "1c1f1dab1ae2e8f18536784a5dec9de37c8a8582",
"index": 3995,
"step-1": "def test_{{ project_name }}():\n assert True\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
#encoding: utf-8
"""
Desc:
Author: Makoto OKITA
Date: 2016/09/03
"""
import numpy as np
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
import itertools
... | normal | {
"blob_id": "13e89e13f88ac306a62be3390f5292665f128a4d",
"index": 9332,
"step-1": "#encoding: utf-8\n\"\"\"\nDesc: \nAuthor: Makoto OKITA\nDate: 2016/09/03 \n\"\"\"\nimport numpy as np\nimport chainer\nfrom chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils\nfrom chainer... | [
0
] |
"""
- input: is a 'special' array (heavily nested array)
- output: return the product sum
- notes:
- special array is a non-empty array that contains either integers or other 'special' arrays
- product sum of a special array is the sum of its elements, where 'special' arrays inside are summed themselves and then mu... | normal | {
"blob_id": "87e5a615157db59d1eac4967c321829c878d00a5",
"index": 2234,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef product_sum_helper(array, depth):\n sum = 0\n for ele in array:\n if type(ele) is int:\n sum += ele\n else:\n sum += product_sum_helper(e... | [
0,
1,
2,
3
] |
#!/usr/bin/python
if __name__ == '__main__':
import sys
import os
sys.path.insert(0, os.path.abspath('config'))
import configure
configure_options = [
'CC=icc',
'CXX=icpc',
'FC=ifort',
'--with-blas-lapack-dir=/soft/com/packages/intel/13/update5/mkl/',
'--with-mkl_pardiso-dir=/soft/com/pack... | normal | {
"blob_id": "43eb221758ebcf1f01851fc6cda67b72f32a73c7",
"index": 6992,
"step-1": "<mask token>\n",
"step-2": "if __name__ == '__main__':\n import sys\n import os\n sys.path.insert(0, os.path.abspath('config'))\n import configure\n configure_options = ['CC=icc', 'CXX=icpc', 'FC=ifort',\n '... | [
0,
1,
2
] |
import os
import h5py
import numpy as np
from keras import backend as K
from keras.layers import Activation, BatchNormalization, Conv2D, Dense, Dot, \
Dropout, Flatten, Input, MaxPooling2D, GlobalAveragePooling2D
from keras import regularizers
from keras.layers import Average as KerasAverage
from keras.models imp... | normal | {
"blob_id": "0eefae7e0d341d74154bbe480f5ed766829e3ce3",
"index": 3734,
"step-1": "<mask token>\n\n\nclass TotalReshape(Layer):\n\n def __init__(self, target_shape, **kwargs):\n self.target_shape = target_shape\n super(TotalReshape, self).__init__(**kwargs)\n\n def compute_output_shape(self, i... | [
17,
20,
24,
29,
31
] |
import config
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def check_db_exists(opt):
try:
conn = psycopg2.connect(opt)
cur = conn.cursor()
cur.close()
print('Database exists.')
return True
except:
print("Database doesn't exist.")
return False
def create_db(opt):
if check... | normal | {
"blob_id": "09792da1c3cc38c7df7def2b487c2078de4e8912",
"index": 9514,
"step-1": "<mask token>\n\n\ndef check_db_exists(opt):\n try:\n conn = psycopg2.connect(opt)\n cur = conn.cursor()\n cur.close()\n print('Database exists.')\n return True\n except:\n print(\"Dat... | [
3,
4,
5,
6,
7
] |
#! /usr/local/bin/python3
# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
BASEURL = 'https://api.twitter.com/1.1/'
CK = '3rJOl1ODzm9yZy63FACdg'
CS = '5jPoQ5kQvMJFDYRNE8bQ4rHuds4xJqhvgNJM4awaE8'
AT = '333312023-6dTniMxvwlQG8bATKNYWBXaQkftz9t4ZjRBt7BWk'
AS = 'LQ8xXBTTN8F8CHQv9oDAqsGJFeexdnFf2DFzn3E... | normal | {
"blob_id": "63bfaa6e191e6090060877e737f4b003bed559cf",
"index": 9140,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_instance(rest_url, params):\n url = BASEURL + rest_url\n print(url)\n twitter = OAuth1Session(CK, CS, AT, AS)\n return twitter.get(url, params=params)\n",
"step-... | [
0,
1,
2,
3,
4
] |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.contrib import messages
# Create your views here.
from User.models import User, check_if_auth_user
from .models import Chat
# def recv_chat(request, id = None):
# check = check_if_auth_user(request)
# if... | normal | {
"blob_id": "9dfb3f58127b30467651ac4209277cd947643c65",
"index": 7411,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef begin_chat(request, id=None):\n check = check_if_auth_user(request)\n if not check:\n messages.error(request, 'Perform login first to start chatting')\n return... | [
0,
1,
2,
3
] |
# Copyright 2018 The Cornac Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | normal | {
"blob_id": "d414e4497bae23e4273526c0bbdecd23ed665cac",
"index": 4857,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef sample_items(num_items, shape, random_state=None):\n \"\"\"\n Randomly sample a number of items.\n\n Parameters\n ----------\n\n num_items: int\n Total numbe... | [
0,
1,
2,
3
] |
import botocore
class s3Obj:
def __init__(self, name, bucket_name, size, last_modified, storage_class):
self.name = name
self.size = size
self.last_modified = last_modified
self.storage_class = storage_class
self.bucket_name = bucket_name
self.acl = []
... | normal | {
"blob_id": "b3f376f4aec81cae853f996a74062e32bb4a8fa3",
"index": 2569,
"step-1": "<mask token>\n\n\nclass s3Obj:\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass s3Obj:\n <mask token>\n\n def getACL(self, client_s3):\n \"\"\"\n get ACL info and update the object\n ... | [
1,
2,
3,
4,
5
] |
'''
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0
'''
class Solution(o... | normal | {
"blob_id": "0a7ffc027511d5fbec0076f6b25a6e3bc3dfdd9b",
"index": 12,
"step-1": "'''\nGiven a sorted array and a target value, return the index if the target is found.\nIf not, return the index where it would be if it were inserted in order.\n\nYou may assume no duplicates in the array.\n\nHere are few examples.\... | [
0
] |
#!/usr/bin/env python2
from rpcz import compiler
PROTO = '../index_server.proto'
compiler.generate_proto(PROTO, '.')
compiler.generate_proto(
PROTO, '.',
with_plugin='python_rpcz', suffix='_rpcz.py')
| normal | {
"blob_id": "e868998833774c829b05ae8da3280bed61363be1",
"index": 177,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncompiler.generate_proto(PROTO, '.')\ncompiler.generate_proto(PROTO, '.', with_plugin='python_rpcz', suffix=\n '_rpcz.py')\n",
"step-3": "<mask token>\nPROTO = '../index_server.proto'\... | [
0,
1,
2,
3,
4
] |
def twenty():
pass
| normal | {
"blob_id": "3727c4413cd69305c8ee8d02f4532629da7d25de",
"index": 7135,
"step-1": "<mask token>\n",
"step-2": "def twenty():\n pass\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
onfiguration name="test3" type="PythonConfigurationType" factoryName="Python" temporary="true">
<module name="hori_check" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
</envs>
<opt... | normal | {
"blob_id": "48affa1b823a2543b6bbda615247324f5c249a69",
"index": 5831,
"step-1": "onfiguration name=\"test3\" type=\"PythonConfigurationType\" factoryName=\"Python\" temporary=\"true\">\n <module name=\"hori_check\" />\n <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n <option name=\"PARENT_EN... | [
0
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 16:38:15 2013
@author: a92549
Fixes lack of / between tzvp and tzvpfit
"""
import sys
def main(argv):
for com in argv:
with open(com, 'rb') as f:
txt = f.read()
if 'tzvp tzvpfit' in txt:
parts = txt.spl... | normal | {
"blob_id": "85974e48c7eafdf39379559820ed7f0bdc07fb7a",
"index": 3680,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main(argv):\n for com in argv:\n with open(com, 'rb') as f:\n txt = f.read()\n if 'tzvp tzvpfit' in txt:\n parts = txt.split('tzvp tzvpfit',... | [
0,
1,
2,
3,
4
] |
from PyQt4 import QtGui
from PyQt4.QtCore import pyqtSignal, pyqtSlot, QObject, Qt
from twisted.internet.defer import inlineCallbacks
import numpy as np
from connection import connection
import pyqtgraph as pg
from pyqtgraph.SignalProxy import SignalProxy
import sys
import time
global harwareConfiguration
class grap... | normal | {
"blob_id": "8173afbd82b8da04db4625ac686c0d052e65a21c",
"index": 9470,
"step-1": "<mask token>\n\n\nclass graphingwidget(QtGui.QWidget):\n <mask token>\n <mask token>\n\n def __init__(self, reactor, configpath):\n super(graphingwidget, self).__init__()\n self.reactor = reactor\n sel... | [
7,
8,
9,
10,
11
] |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
from eight import *
from whoosh.fields import TEXT, ID, Schema
bw2_schema = Schema(
name=TEXT(stored=True, sortable=True),
comment=TEXT(stored=True),
product=TEXT(stored=True, sortable=True),
categories=TEXT(stored=True),
... | normal | {
"blob_id": "07aafcb3db9c57ad09a29a827d72744ef0d22247",
"index": 3319,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nbw2_schema = Schema(name=TEXT(stored=True, sortable=True), comment=TEXT(\n stored=True), product=TEXT(stored=True, sortable=True), categories=TEXT\n (stored=True), location=TEXT(sto... | [
0,
1,
2,
3
] |
from application.identifier import Identifier
if __name__ == '__main__':
idf = Identifier()
while raw_input('Hello!, to start listening press enter, to exit press q\n'
) != 'q':
idf.guess()
| normal | {
"blob_id": "d8da01433b2e6adb403fdadc713d4ee30e92c787",
"index": 4829,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n idf = Identifier()\n while raw_input('Hello!, to start listening press enter, to exit press q\\n'\n ) != 'q':\n idf.guess()\n",
"step-3"... | [
0,
1,
2
] |
import os
import unittest
import tempfile
from bpython import config
TEST_THEME_PATH = os.path.join(os.path.dirname(__file__), "test.theme")
class TestConfig(unittest.TestCase):
def test_load_theme(self):
struct = config.Struct()
struct.color_scheme = dict()
config.load_theme(struct, TEST... | normal | {
"blob_id": "d5efbbb6e818e797652f304f3d022e04be245778",
"index": 4931,
"step-1": "<mask token>\n\n\nclass TestConfig(unittest.TestCase):\n\n def test_load_theme(self):\n struct = config.Struct()\n struct.color_scheme = dict()\n config.load_theme(struct, TEST_THEME_PATH, struct.color_schem... | [
2,
3,
4,
5,
6
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.