code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0015_auto_20151216_1136'),
]
operations = [
migrations.AlterField(
model_name='duration',
... | normal | {
"blob_id": "0cba18ca7126dda548a09f34dc26b83d6471bf68",
"index": 1652,
"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 = [('courses', '... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
import json
import argparse
def parse_args():
"""
Parse input arguments.
:return:
"""
parser = argparse.ArgumentParser(description='以图搜图API测试')
parser.add_argument('--ak', dest='access_key', help='access_key for qiniu account',
type=str)
pars... | normal | {
"blob_id": "c7147741784b37b42200869002d4df5ddc900675",
"index": 2001,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef parse_args():\n \"\"\"\n Parse input arguments.\n :return:\n \"\"\"\n parser = argparse.ArgumentParser(description='以图搜图API测试')\n parser.add_argument('--ak', des... | [
0,
1,
2,
3,
4
] |
"""
Code for Alexa skill to check PB tracking
"""
from __future__ import print_function
import traceback
import requests
import os
import json
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {... | normal | {
"blob_id": "a5ef2adbf85b5ab80c59697340f94bc57d60952e",
"index": 4463,
"step-1": "<mask token>\n\n\ndef build_response(session_attributes, speechlet_response):\n return {'version': '1.0', 'sessionAttributes': session_attributes,\n 'response': speechlet_response}\n\n\ndef get_welcome_response():\n \"... | [
9,
10,
12,
13,
14
] |
# Generated by Django 2.2.3 on 2019-07-14 13:34
from django.db import migrations, models
def forwards_func(apps, schema_editor):
""" Add Theater Rooms """
TheaterRoom = apps.get_model("main", "TheaterRoom")
db_alias = schema_editor.connection.alias
TheaterRoom.objects.using(db_alias).bulk_create([
... | normal | {
"blob_id": "a4b61a5a79e314e56ba25c6e2e735bd2ee4ef0d3",
"index": 4551,
"step-1": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\ndef reverse_func(apps, schema_editor):\n \"\"\" No need to do anything since the t... | [
1,
3,
4,
5,
6
] |
from src.testcase.case import Case
from src.utils import *
from src.protocol.register import get_conn
from src.precondition import *
class OneCase(object):
"""
Main flow of running one case's autotest
"""
PASS = True
FAIL = False
def __init__(self, case_path, *args, **kwargs):
self._c... | normal | {
"blob_id": "f658959bf7fa5e02a577119930c9b9c1ef59f432",
"index": 2845,
"step-1": "<mask token>\n\n\nclass OneCase(object):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, case_path, *args, **kwargs):\n self._case_path = str(case_path)\n self._case_dict = {}\n ... | [
7,
9,
10,
13,
14
] |
from django.contrib import admin
from .models import Contactus,ContactusAdmin,Company,CompanyAdmin,Products,ProductsAdmin,Brands,BrandsAdmin
# Register your models here.
admin.site.register(Contactus,ContactusAdmin),
admin.site.register(Company,CompanyAdmin),
admin.site.register(Products,ProductsAdmin),
admin.site.reg... | normal | {
"blob_id": "9586dc118be4388491770d823a38e8068e3b91cb",
"index": 5960,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nadmin.site.register(Contactus, ContactusAdmin),\nadmin.site.register(Company, CompanyAdmin),\nadmin.site.register(Products, ProductsAdmin),\nadmin.site.register(Brands, BrandsAdmin),\n",
... | [
0,
1,
2,
3
] |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('mgdata.dat.csv')
training_set = dataset.iloc[:1100, 1:2].values
X_train=[]
y_train=[]
for i in range(20,1090):
X_train.append(training_set[i-20:i,0])
y_train.append(training_set[i,0])
X_train=np.asarray... | normal | {
"blob_id": "28a3763715f5405f8abe2de17ed5f9df1019278b",
"index": 6878,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(20, 1090):\n X_train.append(training_set[i - 20:i, 0])\n y_train.append(training_set[i, 0])\n<mask token>\nclassifier.add(Dense(output_dim=35, init='uniform', activat... | [
0,
1,
2,
3,
4
] |
import datetime
class Event(object):
def __init__(self):
self.id = None
self.raw = None
self.create_dt = datetime.datetime.now()
self.device_id = None
self.collector_id = None
self.device_hostname = None
self.device_domain_name = None
self.device_ip... | normal | {
"blob_id": "7554b00f8c4d40f1d3ee2341f118048ca7ad10ea",
"index": 709,
"step-1": "<mask token>\n\n\nclass Event(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Event(object):\n <mask token>\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n ... | [
1,
2,
3,
4
] |
import json
from bokeh.plotting import figure, output_file
from bokeh.io import show
from bokeh.palettes import inferno
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.transform import factor_cmap
from bokeh.models import HoverTool
# from bokeh.io import export_svgs
def read_summary(summary_file):
... | normal | {
"blob_id": "7036ae5f74e6cb04518c20bb52122a1dfae76f23",
"index": 712,
"step-1": "<mask token>\n\n\ndef read_summary(summary_file):\n return json.loads(open(summary_file, 'r').read())\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary['ontology_events']:\n print(o)\n d[o] = sum... | [
3,
4,
5,
6,
7
] |
from django.apps import AppConfig
class BoletoGerenciaNetConfig(AppConfig):
name = 'boletogerencianet'
| normal | {
"blob_id": "c2069113f322c97e953fba6b9d21b90a8b13a066",
"index": 2308,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass BoletoGerenciaNetConfig(AppConfig):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass BoletoGerenciaNetConfig(AppConfig):\n name = 'boletogerencianet'\n",
"step-4"... | [
0,
1,
2,
3
] |
import ply.lex as lex
print("hello word!")
| normal | {
"blob_id": "84d0c439fcee4339250ced11dd2264740cc20d9c",
"index": 9567,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('hello word!')\n",
"step-3": "import ply.lex as lex\nprint('hello word!')\n",
"step-4": "import ply.lex as lex\n\nprint(\"hello word!\")\n",
"step-5": null,
"step-ids": [
... | [
0,
1,
2,
3
] |
class MyClass:
name = "alice"
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def say_hello(self):
self.greet = "Hello"
def say_hi(self):
print("HI~~~~~")
p1 = MyClass()
p2 = MyClass()
print(p1.name)
p1.s... | normal | {
"blob_id": "babb5ac680c74e19db5c86c2c3323e8285d169ff",
"index": 9939,
"step-1": "class MyClass:\n <mask token>\n\n def set_name(self, name):\n self.name = name\n\n def get_name(self):\n return self.name\n\n def say_hello(self):\n self.greet = 'Hello'\n\n def say_hi(self):\n ... | [
5,
6,
7,
8,
9
] |
"""Gaussian mixture model, with Stochastic EM algorithm."""
import numpy as np
from sklearn.mixture.gaussian_mixture import _estimate_gaussian_parameters, _compute_precision_cholesky
from Core.gllim import MyGMM
class SEMGaussianMixture(MyGMM):
"""Remarque : on utilise la variable Y pour les observations, au li... | normal | {
"blob_id": "39475626b7e3e0f4c8143b300c002a2eb50cc23a",
"index": 9341,
"step-1": "<mask token>\n\n\nclass SEMGaussianMixture(MyGMM):\n <mask token>\n <mask token>\n\n def _draw_conditionnal_Z(self, Y):\n \"\"\"\n Tire un échantillon de loi Z sachant Y\n\n :param Y: Observations (n_s... | [
8,
9,
10,
11,
12
] |
import pdb
from django.db.models import Count
from django.shortcuts import render_to_response, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.template import RequestContext
from models import *
from forms import *
from django.htt... | normal | {
"blob_id": "565e994576a57f8bbdcb201f2439bd7e595fa53e",
"index": 9679,
"step-1": "<mask token>\n\n\ndef list(request):\n techniques = Technique.objects.annotate(num_images=Count('images')\n ).order_by('-num_images')\n return render_to_response('technique/list.html', {'techniques':\n technique... | [
1,
2,
3,
4
] |
# coding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License... | normal | {
"blob_id": "4dde161d25ed41154e13b94cc9640c6aac055f87",
"index": 6164,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nUNK_TOKEN = '<unk>'\nBOS_TOKEN = '<bos>'\nEOS_TOKEN = '<eos>'\nPAD_TOKEN = '<pad>'\nUNK_IDX = 0\nLARGE_POSITIVE_FLOAT = 1e+18\nLARGE_NEGATIVE_FLOAT = -LARGE_POSITIVE_FLOAT\nGLOVE_NPZ_SHA1... | [
0,
1,
2
] |
from fastapi import FastAPI, Header, Cookie, Form, Request, requests, Body, Response, HTTPException, status, Path, Query
from fastapi.responses import HTMLResponse
from typing import Optional
from fastapi.testclient import TestClient
from typing import List, Callable
from fastapi.staticfiles import StaticFiles
from fas... | normal | {
"blob_id": "70188d011ef60b1586864c4b85a9f9e70e5a4caf",
"index": 7386,
"step-1": "<mask token>\n\n\nclass Item(BaseModel):\n name: str\n price: float\n\n\nclass ValidationError(APIRoute):\n\n def get_route_handler(self) ->Callable:\n original_route_handler = super().get_route_handler()\n\n ... | [
3,
4,
5,
6,
7
] |
from torchtext import data
from torchtext import datasets
import re
import spacy
spacy_de = spacy.load('de')
spacy_en = spacy.load('en')
url = re.compile('(<url>.*</url>)')
def tokenize_de(text):
return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))]
def tokenize_en(text):
return [tok.text ... | normal | {
"blob_id": "4e715ccb4f95e7fe7e495a1181ad5df530f5a53f",
"index": 5773,
"step-1": "<mask token>\n\n\ndef tokenize_de(text):\n return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))]\n\n\ndef tokenize_en(text):\n return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))]\n\n\n<ma... | [
2,
3,
4,
5
] |
from pyspark.sql.types import StructType, StructField, StringType, TimestampType, IntegerType
from main.config.spark_config import SparkConfiguration
import main.config.constants as Constants
from main.connectors.kafka_connector import KafkaConnector, extract_json_data
def main():
# Configure Spark Session
co... | normal | {
"blob_id": "23099b29fb5898c2556d1612690e33860662ca35",
"index": 9846,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n config = {'spark.jars.packages':\n 'io.delta:delta-core_2.12:0.8.0,org.postgresql:postgresql:9.4.1211,org.apache.spark:spark-streaming-kafka-0-10_2.12:3.0.0,or... | [
0,
1,
2,
3,
4
] |
# Generated by Django 2.1.1 on 2018-09-24 04:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('backend', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Aro',
fie... | normal | {
"blob_id": "8dff22249abbae9e30ba1ad423457270e0cd9b20",
"index": 7027,
"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 = [('backend', '... | [
0,
1,
2,
3,
4
] |
import numpy as np
class Layer:
def __init__(self):
pass
@property
def need_update(self):
return False
class FC(Layer):
def __init__(self, W, b, lr, decay, epoch_drop, l2=0):
self.W = W.copy()
self.b = b.copy()
self.alpha_0 = lr
self.decay = decay
... | normal | {
"blob_id": "a5a764586faabb5af58f4649cdd20b6b18236a99",
"index": 6080,
"step-1": "<mask token>\n\n\nclass Leaky_Relu(Layer):\n\n def forward(self, x):\n self.x = x.copy()\n return np.maximum(x, self.x * 0.01)\n\n def backprop(self, back_grad):\n grad = back_grad.copy()\n grad[se... | [
19,
29,
32,
34,
38
] |
import messages
import os
import requests
from bs4 import BeautifulSoup
URL = "https://mailman.kcl.ac.uk/mailman/"
ADMIN = "admin/"
ROSTER = "roster/"
OUTPUT_FOLDER = "../output/"
def makeoutput(path):
if os.path.exists(path):
pass
else:
os.mkdir(path)
def mailinglist_cookies(mailinglist, password): # this o... | normal | {
"blob_id": "0e337ce21450e0fdb7688183d0542ebf902a9614",
"index": 1293,
"step-1": "<mask token>\n\n\ndef makeoutput(path):\n if os.path.exists(path):\n pass\n else:\n os.mkdir(path)\n\n\ndef mailinglist_cookies(mailinglist, password):\n try:\n cookie_request = requests.post(URL + ADM... | [
4,
5,
6,
7,
8
] |
# Generated by Django 3.0.4 on 2020-03-27 11:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('web', '0005_remove_product_image'),
]
operations = [
migrations.CreateMode... | normal | {
"blob_id": "c10e1cf2f1ce5b11d19ddddbfc3dc9652d830a3c",
"index": 1132,
"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 = [('web', '0005... | [
0,
1,
2,
3,
4
] |
work_hours = 8
work_days = 5
pay_periods = 2
total = work_hours * work_days * pay_periods
rate = 17
pay = total * rate
print(pay)
# variables
name = "josh"
age = 30
# float
weight = 160.5
# list
kill_streak = [3, 5, 1, 9] # [90.9] list can contain sub lists
# range
players = list(range(1,10))
odds =... | normal | {
"blob_id": "af2ef3c77cefe675f3d30c3234401f0f9bda3505",
"index": 8916,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(pay)\n<mask token>\nprint(odds)\nprint(type(name), type(age), type(weight), type(kill_streak))\n<mask token>\nprint(mean)\n<mask token>\nprint(tens)\n<mask token>\nprint(average_age... | [
0,
1,
2,
3
] |
## 허프변환에 의한 직선 검출
# cv2.HoughLines(image, rho, theta, threshold, lines=None, srn=None, stn=None, min-theta=None, max-theta=None) => lines
# image : 에지 입력 영상(Canny 연산을 이용한 에지 영상)
# rho(로우) : 축적 배열에서 rho 값의 간격(보통 1.0 사용)
# theta(세타) : 축적 배열에서 theta 값의 간격(보통 np.pi/180)
# rho, theta 값이 커지면 축적배열의 크기는 작아지고, 값이 작으면 축적배... | normal | {
"blob_id": "ff7cb8261f3abb70599725fe7c598c571d037226",
"index": 9535,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif src is None:\n print('Image load failed')\n sys.exit()\n<mask token>\nif lines is not None:\n for i in range(lines.shape[0]):\n pt1 = lines[i][0][0], lines[i][0][1]\n ... | [
0,
1,
2,
3,
4
] |
import tensorflow as tf
from models.base_model import BaseModel
from utils.im_utils import batch_convert_2_int
from datasets.single_dataset import SingleDataset
from datasets.unpaired_dataset import UnpairedDataset
from models.generators.maskshadowgan_generators import Generator
from models.discriminators.maskshadowgan... | normal | {
"blob_id": "cbbe273a19a4e60b760e35aeb8d43972a46760f5",
"index": 3436,
"step-1": "<mask token>\n\n\nclass MaskShadowGANModel(BaseModel):\n <mask token>\n <mask token>\n\n def generate_dataset(self):\n \"\"\"\n Add ops for dataset loaders to graph\n \"\"\"\n if self.training:\... | [
8,
9,
11,
12,
13
] |
# Run 'python setup.py build' on cmd
import sys
from cx_Freeze import setup, Executable
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 't... | normal | {
"blob_id": "f317d67b98eab1f0f192fa41f9bcc32b0c1e8eb0",
"index": 8301,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='Arkanoid', version='1.0', description='Python Game', options=\n options, executables=executables)\n",
"step-3": "<mask token>\nPYTHON_INSTALL_DIR = os.path.dirname(os.pat... | [
0,
1,
2,
3,
4
] |
import json
import argparse
import sys
import os
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument("-sd","--startdate", help="Date to start scheduling trials, format is MM/DD.", required=True)
ap.add_argument("-r", "--round",help="A number.", required=True)
ap.add_argument("-hs... | normal | {
"blob_id": "e4767d8a4991a1180cc185c4c2d77104d63f9c7a",
"index": 6858,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n ap = argparse.ArgumentParser()\n ap.add_argument('-sd', '--startdate', help=\n 'Date to start scheduling trials, format is MM/DD.', required=True... | [
0,
1,
2,
3
] |
import os
import cv2
import numpy as np
import torch
import torch.utils.data
import torchvision
from torchvision import transforms
from utils.utils import loadYaml
from .base_datalayer import BaseDataLayer
import albumentations as albu
class Datalayer(BaseDataLayer):
def __init__(self, config, augmentation=None,... | normal | {
"blob_id": "9928eaa32468453f405d8bb650f3e0e85a7933bf",
"index": 5514,
"step-1": "<mask token>\n\n\nclass Datalayer(BaseDataLayer):\n <mask token>\n <mask token>\n\n def __getitem__(self, item):\n if np.random.random() > 0.5 and len(self.bg_masks_path) > 0:\n random_id_bg = np.random.r... | [
2,
3,
4,
5,
6
] |
from collections import Counter, defaultdict
import pandas as pd
from glob import glob
import subsamplex
files = glob('outputs.txt/*.unique.txt.gz')
files.sort()
biome = pd.read_table('cold/biome.txt', squeeze=True, index_col=0)
duplicates = set(line.strip() for line in open('cold/duplicates.txt'))
counts = defaultdi... | normal | {
"blob_id": "74eea67b8640a03e616bebdadba49891017b921d",
"index": 8914,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfiles.sort()\n<mask token>\nfor i, fname in enumerate(files):\n sample = fname.split('/')[1].split('.')[0]\n if sample in duplicates:\n skipped += 1\n if skipped % 100... | [
0,
1,
2,
3,
4
] |
import os
import mysql.connector
import time
from flask import Flask, render_template
app = Flask(__name__)
def dbconnect():
return mysql.connector.connect(user= , password= , host="mysqlshereen.mysql.database.azure.com", port=3306, database='test')
@app.route('/result', methods=['POST', 'GET'])
def query():
... | normal | {
"blob_id": "3314ffdbc2f10170176c590aebf49c416bcc8856",
"index": 2136,
"step-1": "import os\n\nimport mysql.connector\nimport time\nfrom flask import Flask, render_template\n\napp = Flask(__name__)\n\ndef dbconnect():\n\n return mysql.connector.connect(user= , password= , host=\"mysqlshereen.mysql.database.az... | [
0
] |
# -*- coding: utf-8 -*-
from services.interfaces.i_service import IService
from services.dbservices.db_service import DBService
class GetCommunitiesByOffsetService(IService):
def __init__(self, core, parameters):
super(GetCommunitiesByOffsetService, self).__init__(core, parameters)
def run(self):
... | normal | {
"blob_id": "051bd11c42815ec8f8ece8eae9d33890da77129c",
"index": 148,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass GetCommunitiesByOffsetService(IService):\n <mask token>\n\n def run(self):\n return DBService(self.core).getNextFields('Communities', self.\n parameters['... | [
0,
2,
3,
4,
5
] |
# coding: utf-8
import os
import factory
import datetime
from journalmanager import models
from django.contrib.auth.models import Group
from django.core.files.base import File
_HERE = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(_HERE, 'xml_samples', '0034-8910-rsp-48-2-0216.xml')) as xml_fil... | normal | {
"blob_id": "44d87f112ab60a202e4c8d64d7aec6f4f0d10578",
"index": 31,
"step-1": "<mask token>\n\n\nclass IssueTitleFactory(factory.Factory):\n \"\"\"\n ``issue`` must be provided\n \"\"\"\n FACTORY_FOR = models.IssueTitle\n language = factory.SubFactory(LanguageFactory)\n title = u'Bla'\n\n\ncla... | [
22,
39,
42,
45,
47
] |
class Solution:
def uncommonFromSentences(self, A: str, B: str) ->List[str]:
word_count = {}
A = A.split()
B = B.split()
whole = A + B
for word in whole:
if word not in word_count:
word_count[word] = 1
else:
word_count[... | normal | {
"blob_id": "09420360ddcf2f74c2e130b4e09ae2a959e42e50",
"index": 8305,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def uncommonFromSentences(self, A: str, B: str) ->List[str]:\n word_count = {}\n A = A.split()\n B = B.spl... | [
0,
1,
2
] |
# -*- coding: utf-8 -*-
"""Test(s) for static files
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import pytest
import os
_TEST_ID = '__NO_SUCH_STRING_IN_PAGE__'
def s... | normal | {
"blob_id": "65b5db0bc6f23c342138060b7a006ff61e2dcf45",
"index": 3761,
"step-1": "<mask token>\n\n\ndef test_injection(fc):\n from pykern import pkcompat, pkunit\n from pykern.pkdebug import pkdc, pkdp, pkdlog\n from pykern.pkunit import pkeq, pkok, pkre\n import re\n r = fc.get('myapp')\n pkok... | [
1,
2,
3,
4,
5
] |
import dataset
import json
import gc
import os
jsonDir = "/home/jr/share/python/music-visualizer/merged"
db = dataset.connect('sqlite:///test.db')
table = db['Songs']
for root, subFolders, files in os.walk(jsonDir):
for f in files:
print("file:{}".format(f))
gc.collect()
tmpJson = json.lo... | normal | {
"blob_id": "3461e9dceb2c0bfc49002809154f8be4cd8c66e2",
"index": 1483,
"step-1": "import dataset\nimport json\nimport gc\nimport os\n\njsonDir = \"/home/jr/share/python/music-visualizer/merged\"\n\ndb = dataset.connect('sqlite:///test.db')\ntable = db['Songs']\n\nfor root, subFolders, files in os.walk(jsonDir):\... | [
0
] |
permissions = ('restart', )
commands = ('restart', )
def get_command(session, parsed_message):
return 'stop', 'restart'
def parse_response(permission, response):
return response
| normal | {
"blob_id": "acd5cf675522c90fc9fbc96bdeb52f66835626b4",
"index": 3489,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef parse_response(permission, response):\n return response\n",
"step-3": "<mask token>\n\n\ndef get_command(session, parsed_message):\n return 'stop', 'restart'\n\n\ndef pars... | [
0,
1,
2,
3,
4
] |
from django.db import models
import string
import random
def id_generator(size=32, chars=string.ascii_uppercase + string.digits):
exists = True
while exists == True:
ran = ''.join(random.choice(chars) for _ in range(size))
if len(Item.objects.filter(random_str=ran)) == 0:
exists = False
return ran
# Crea... | normal | {
"blob_id": "efba815fe64cddb5315b17b2cbaf1d3fc38c11ee",
"index": 4995,
"step-1": "<mask token>\n\n\nclass Item(models.Model):\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 <mask token>\n <m... | [
2,
3,
4,
6,
7
] |
from erlport.erlterms import Atom
from scipy.optimize import basinhopping
import numpy as np
import qsim
class Bounds(object):
'''Required for acceptance testing in scipy.optimize.basinhopping'''
def __init__(self, xmin, xmax, costs):
self.xmax = xmax
self.xmin = xmin
self.costs = costs... | normal | {
"blob_id": "0f4bdaecef356e01cbef527d4886564d9ef840fa",
"index": 5573,
"step-1": "<mask token>\n\n\nclass Bounds(object):\n \"\"\"Required for acceptance testing in scipy.optimize.basinhopping\"\"\"\n\n def __init__(self, xmin, xmax, costs):\n self.xmax = xmax\n self.xmin = xmin\n self... | [
16,
17,
22,
23,
24
] |
"""
Routes and views for the flask application.
"""
from datetime import datetime
from flask import render_template, redirect, url_for, request, jsonify
from athena_App import app
from athena_App.formClass import QuestionForm
import time
#attention:
#this module include large word vector which need a lot of time to ... | normal | {
"blob_id": "3457a7c080da041ad279239bd6a3d214a3b8e49f",
"index": 6695,
"step-1": "<mask token>\n\n\n@app.route('/QAsearch', methods=['POST', 'GET'])\ndef QAsearch():\n \"\"\"Renders the QAsearch page.\"\"\"\n question = ''\n form = QuestionForm()\n question = form.question.data\n if form.validate_... | [
9,
10,
11,
12,
13
] |
from . import scramsha1, scrammer
| normal | {
"blob_id": "8c336edddadbf4689721b474c254ded061ecf4b5",
"index": 743,
"step-1": "<mask token>\n",
"step-2": "from . import scramsha1, scrammer\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
def get_perms(string):
toRtn = []
freq_table = count_letters(string)
get_perms_helper(freq_table, "", len(string), toRtn)
return toRtn
def count_letters(string):
freq = {}
for letter in string:
if letter not in freq:
freq[letter] = 0
freq[letter] += 1
return freq... | normal | {
"blob_id": "719a993e1f5c5d1e803b04a5561373f2b9a5a5c2",
"index": 8524,
"step-1": "def get_perms(string):\n toRtn = []\n freq_table = count_letters(string)\n get_perms_helper(freq_table, \"\", len(string), toRtn)\n return toRtn\n\ndef count_letters(string):\n freq = {}\n for letter in string:\n ... | [
0
] |
import re
from collections import defaultdict
def count_words(sentence):
# extract all the words as per definition
sentence = re.findall(r"\b[\w'-]+\b", sentence.lower().replace('_', ' '))
counts = defaultdict(lambda: 0)
# Counting the frequency of each words
for word in sentence:
counts[w... | normal | {
"blob_id": "7f5f16ea10980e0ade7357cdae38f47f8d7cdf01",
"index": 2446,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef count_words(sentence):\n sentence = re.findall(\"\\\\b[\\\\w'-]+\\\\b\", sentence.lower().replace('_', ' '))\n counts = defaultdict(lambda : 0)\n for word in sentence:\n ... | [
0,
1,
2,
3
] |
from django import forms
from django.forms import widgets
# from product.models import PRODUCT_OTHER_CHOICE, PRODUCT_CATEGORY_CHOICES
PRODUCT_OTHER_CHOICE = 'other'
PRODUCT_CATEGORY_CHOICES = (
(PRODUCT_OTHER_CHOICE, 'Разное'),
('food', 'Еда'),
('drink', 'Вода'),
('cloth', 'Одежда'),
('electronics'... | normal | {
"blob_id": "e8a024796b6426e572571e46030678e90c537229",
"index": 7549,
"step-1": "<mask token>\n\n\nclass ProductForm(forms.Form):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass FindForm(forms.Form):\n name = forms.CharField(max_length=100, label='Наименов... | [
3,
4,
5,
6,
7
] |
import http.client
import json
conn = http.client.HTTPSConnection("v3.football.api-sports.io")
headers = {
'x-rapidapi-host': "v3.football.api-sports.io",
'x-rapidapi-key': ""
}
conn.request("GET", "/teams/statistics?season=2016&team=768&league=4", headers=headers)
res = conn.getresponse()
data = res.re... | normal | {
"blob_id": "a6617934c5e6527cf59225a5d159d1ce8a33db50",
"index": 6681,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nconn.request('GET', '/teams/statistics?season=2016&team=768&league=4',\n headers=headers)\n<mask token>\n",
"step-3": "<mask token>\nconn = http.client.HTTPSConnection('v3.football.a... | [
0,
1,
2,
3,
4
] |
# csv URL
url = "https://covid19-dashboard.ages.at/data/CovidFallzahlen.csv"
# read csv from URL
import pandas as pd
import geopandas as gpd
import numpy as np
df=pd.read_csv(url,sep=";")
df.to_csv("/var/www/FlaskApp/FlaskApp/data/covid_data.csv",sep=";",index=False)
# transforming timestamps to proper DateTime forma... | normal | {
"blob_id": "516ea681a55255e4c98e7106393180f9ad2e0250",
"index": 8455,
"step-1": "<mask token>\n\n\ndef csv_parser(statement):\n import psycopg2\n return_ls = []\n try:\n connection = psycopg2.connect(user='icu_bot', password=\n '5B2xwP8h4Ln4Y8Xs', host='85.214.150.208', port='5432',\n... | [
1,
2,
3,
4,
5
] |
import serial
import time
from Files_management import get_mov_parameters,change_mov_parameters
#-------------------------------------------------------------------------------
def create_port():
port = get_mov_parameters()[1]
try:
ser = serial.Serial(port=port,baudrate=9600,timeout=1)
return s... | normal | {
"blob_id": "72cda573bf9c744213a2957d51171f437f211353",
"index": 3467,
"step-1": "<mask token>\n\n\ndef send_value(value):\n port = create_port()\n status = get_mov_parameters()[0]\n if port_status(port):\n if status == '1' or status == 'True':\n string = ''.join([str(value), ' \\n'])\... | [
1,
3,
4,
5,
6
] |
import json
from test.test_basic import BaseCase
class TestUserRegister(BaseCase):
"""
TestClass to test the register function.
"""
def test_successful_register(self):
# Given
payload = json.dumps({
"username": "userjw",
"password": "1q2w3e4r"
})
... | normal | {
"blob_id": "486362463dc07bdafea85de39a4a6d58cb8c8f26",
"index": 9643,
"step-1": "<mask token>\n\n\nclass TestUserRegister(BaseCase):\n <mask token>\n <mask token>\n\n def test_signup_with_non_existing_field(self):\n payload = json.dumps({'username': 'userjw', 'password': '1q2w3e4r',\n ... | [
3,
5,
6,
8,
9
] |
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWa... | normal | {
"blob_id": "87f8cc65cf7d0ea932de79a6daf5b29ad387ec6f",
"index": 7103,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass TestSTCHANGE:\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass TestSTCHANGE:\n\n def setup_method(self, method):\n self.d... | [
0,
1,
4,
5,
6
] |
import socket
import struct
from fsuipc_airspaces.position import Position
# Adapted from tools/faker.js in github.com/foucdeg/airspaces
_START_BUFFER = bytes([68, 65, 84, 65, 60, 20, 0, 0, 0])
_END_BUFFER = bytes([0] * 20)
_START_TRANSPONDER = bytes([104, 0, 0, 0, 0, 0, 0, 0])
_END_TRANSPONDER = bytes([0] * 24)
d... | normal | {
"blob_id": "68fa47e528e5c7c553c3c49ee5b7372b8a956302",
"index": 3364,
"step-1": "<mask token>\n\n\nclass XPlaneDataOut:\n\n def __init__(self, host: str, port: int) ->None:\n self.address = host, port\n self.socket = socket.socket(family=socket.AF_INET, type=socket.\n SOCK_DGRAM)\n\n... | [
3,
4,
5,
6,
7
] |
# Generated by Django 3.1.3 on 2020-11-27 02:17
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('foodBookApp', '0027_remove_post_total_comments'),
]
... | normal | {
"blob_id": "84d9400dc4ee0bebce3f5f7da0bd77a280bb54a9",
"index": 8503,
"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 = [migrations.sw... | [
0,
1,
2,
3,
4
] |
import VL53L1X
from sensor_msgs.msg import Range
class _VL53L1():
def __init__(self, address=0x29):
address = int(address, 16)
print("initialising sensor with address: {}".format(hex(address)))
try:
self.tof = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=address)
... | normal | {
"blob_id": "c6d9b971ab6919846807b740313d450d086ecc23",
"index": 7643,
"step-1": "<mask token>\n\n\nclass _VL53L1:\n <mask token>\n\n def set_range(self, rng):\n if rng < 4 and rng >= 0:\n self.tof.set_range()\n else:\n raise Exception('Invalid range: 1 - short, 2 - med,... | [
3,
4,
5,
6,
7
] |
# -*- coding: utf-8 -*-
"""
Modul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav,
"zglasnianie utworu")
"""
print("Laduje modul o nazwie: "+__name__)
import numpy as np
def wczytywanie_ustawien(plik_konfiguracyjny = "defs.txt"):
"""
wczytywanie pl... | normal | {
"blob_id": "8220a6d33cda5861e74d6236757abbc81685a998",
"index": 6369,
"step-1": "<mask token>\n\n\ndef wczytywanie_ustawien(plik_konfiguracyjny='defs.txt'):\n \"\"\" \n wczytywanie pliku z ustawieniami (pliku defs.txt) do slownika\n \n arg:\n str: plik_konfiguracyjny - nazwa pliku konfiguracy... | [
1,
3,
4,
5,
6
] |
import tweepy
import time
import twitter_credentials as TC
auth = tweepy.OAuthHandler(TC.CONSUMER_KEY, TC.CONSUMER_SECRET)
auth.set_access_token(TC.ACCESS_TOKEN, TC.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
count = 1
# Query to get 50 tweets with either Indiana or Weather in them
for tweet in tweepy.Cursor(api.sea... | normal | {
"blob_id": "4da1a97c2144c9aaf96e5fe6508f8b4532b082d4",
"index": 7861,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nauth.set_access_token(TC.ACCESS_TOKEN, TC.ACCESS_TOKEN_SECRET)\n<mask token>\nfor tweet in tweepy.Cursor(api.search, q='Indiana OR Weather').items(50):\n print(str(count) + '. ' + twee... | [
0,
1,
2,
3,
4
] |
from django.shortcuts import render, redirect
# Create your views here.
from item.models import Item, Unit
def str_to_bool(s):
return True if s.lower() == 'true' else False
def item(request):
if not request.session.get('is_login', None):
return redirect('/item/item')
else:
item_list = ... | normal | {
"blob_id": "22b2ebdbb48caa593bece030d238089a0aa27053",
"index": 1983,
"step-1": "<mask token>\n\n\ndef item(request):\n if not request.session.get('is_login', None):\n return redirect('/item/item')\n else:\n item_list = Item.objects.all()\n return render(request, 'item/item.html', loc... | [
4,
5,
6,
8,
11
] |
from __future__ import division # floating point division
import csv
import random
import math
import numpy as np
import dataloader as dtl
import classalgorithms as algs
def getaccuracy(ytest, predictions):
correct = 0
for i in range(len(ytest)):
if ytest[i] == predictions[i]:
correct ... | normal | {
"blob_id": "c8ab53c77ff3646a30ca49eaafc275afeadd2ca6",
"index": 9545,
"step-1": "from __future__ import division # floating point division\nimport csv\nimport random\nimport math\nimport numpy as np\n\nimport dataloader as dtl\nimport classalgorithms as algs\n \n \ndef getaccuracy(ytest, predictions):\n cor... | [
0
] |
/Users/apple/anaconda/lib/python3.5/operator.py | normal | {
"blob_id": "b4a267873c5823ecfa62a5e90b67c37f9cca3cd2",
"index": 8181,
"step-1": "/Users/apple/anaconda/lib/python3.5/operator.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# Copyright (c) 2008 JAILLET Simon - CrysaLEAD - www.crysalead.fr
from . import models
from . import wizards
from odoo import api, SUPERUSER_ID
from odoo.addons.account.models.chart_template import preserve_existing_tag... | normal | {
"blob_id": "74b38599dd793282612a468a760f6301b9f039d6",
"index": 9878,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef _preserve_tag_on_taxes(cr, registry):\n preserve_existing_tags_on_taxes(cr, registry, 'l10n_lb')\n env = api.Environment(cr, SUPERUSER_ID, {})\n accounts = env['account.a... | [
0,
1,
2,
3
] |
def summation(numbers):
positive_numbers = []
normalized_numbers = []
numbers_list = numbers.split()
for idx, arg in enumerate(numbers_list):
int_arg = int(arg)
if int_arg < 0:
new_arg = abs(int_arg) * 2
else:
new_arg = int_arg
positive_numbers.app... | normal | {
"blob_id": "791df87235f5da634fc62ebc3a3741cea6e2deca",
"index": 3841,
"step-1": "<mask token>\n",
"step-2": "def summation(numbers):\n positive_numbers = []\n normalized_numbers = []\n numbers_list = numbers.split()\n for idx, arg in enumerate(numbers_list):\n int_arg = int(arg)\n if... | [
0,
1
] |
n, x0, y0 = list(map(int, input().split()))
cards = [y0] + list(map(int, input().split()))
# yの手持ちはゲームに関与するため、リストに加えてしまう
xs = [[-1] * (n+1) for i in range(n+1)]
ys = [[-1] * (n+1) for i in range(n+1)]
#xs[i][j] = xの手番で、xがcards[i]を持ちyがcards[j]を持っているとき(i<j)の最善スコア
#ys[i][j] = yの手番で、xがcards[j]を持ちyがcards[i]を持っているとき(i<j)の... | normal | {
"blob_id": "81b9fc78d92fdc4392cb71a77fdfd354ff950ae3",
"index": 6153,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(n + 1):\n xs[i][-1] = abs(cards[-1] - cards[i])\n ys[i][-1] = abs(cards[-1] - cards[i])\nfor j in range(n - 1, -1, -1):\n xs_temp = max(ys[j][j + 1:n + 1])\n ys... | [
0,
1,
2,
3
] |
import heapq
from util import edit_distance
def autocomplete(suggest_tree, bktree, prefix, count=5):
"""Suggest top completions for a prefix given a SuggestTree and BKTree.
Completions for a given prefix are weighted primarily by their weight in the
suggest tree, and secondarily by their Levenshtein... | normal | {
"blob_id": "24891cdefcd061f04e7b7768b1bde4e32b78adcc",
"index": 8690,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef completion_proximity_score(prefix, completion):\n \"\"\"Calculate a score based on suffix length where a shorter length always\n yields a higher score.\"\"\"\n if prefix ... | [
0,
1,
2,
3,
4
] |
# %%
import os
print(os.getcwd())
# %%
from TransformerModel.Model import Model
from dataset.DatasetLoader import DatasetLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping
import argparse
from argparse import ArgumentParser, ArgumentTypeError
# %%
def run_training(arguments_... | normal | {
"blob_id": "328a03acab2a0550bea0795d22110a152db6c503",
"index": 806,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run_training(arguments_parser):\n data = DatasetLoader(arguments_parser)\n data.setup()\n arguments_parser.num_training_steps = len(data.train_dataloader()\n ) * ar... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
"""add_columns.py: This script reads an SCEC ETAS forecast directory name
and extracts key fields that are then added as attributes in the SCEC Deriva
schema.
This script is an example of how the ERD used by Deriva is extended as additional
information or metadata is added to the asset descri... | normal | {
"blob_id": "a745f72081e06ff3399f9d7f65a30d7eef594689",
"index": 2292,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n hostname = 'forecast.derivacloud.org'\n catalog_id = '5'\n model = Model.from_catalog(DerivaServer('https', hostname, credentials=\n get_crede... | [
0,
1,
2,
3
] |
debt = 100
equity = 50
ratio = debt / equity
if ratio <= 2:
print('😊')
else:
print('⚠️')
print('Ratio is', ratio)
| normal | {
"blob_id": "40b1fac14aaa81039aec8e80ce1c91bb881cfe78",
"index": 3474,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif ratio <= 2:\n print('😊')\nelse:\n print('⚠️')\nprint('Ratio is', ratio)\n",
"step-3": "debt = 100\nequity = 50\nratio = debt / equity\nif ratio <= 2:\n print('😊')\nelse:\n... | [
0,
1,
2
] |
import tensorflow as tf
def Float32():
return tf.float32
def Float16():
return tf.float16
| normal | {
"blob_id": "c60b8eec57d845c73ee3e00432747d23748c1706",
"index": 9537,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef Float32():\n return tf.float32\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef Float32():\n return tf.float32\n\n\ndef Float16():\n return tf.float16\n",
"step... | [
0,
1,
2,
3
] |
#!/usr/bin/python3
# Distributed with a free-will license.
# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
# ADC121C_MQ131
# This code is designed to work with the ADC121C_I2CGAS_MQ131 I2C Mini Module available from ControlEverything.com.
# https://www.controleveryth... | normal | {
"blob_id": "678189ac5b0105c90178647843335f9d4402dc66",
"index": 1416,
"step-1": "<mask token>\n\n\ndef getOzoneData():\n data = bus.read_i2c_block_data(80, 0, 2)\n raw_adc = (data[0] & 15) * 256 + data[1]\n ppm = 1.99 * raw_adc / 4096.0 + 0.01\n return ppm\n\n\n<mask token>\n",
"step-2": "<mask to... | [
1,
2,
3,
4,
5
] |
class IndividualStack:
def __init__(self):
self.stack=[None]*5
class StackwithStacks:
def __init__(self):
self.stacks = []
self.stackcount=-1
self.count=0
self.st = None
def push(self, element):
if self.count%5==0:
self.stackcount = self.stackco... | normal | {
"blob_id": "a8f52772522d1efc097c3d17d9c08199816f1168",
"index": 3785,
"step-1": "class IndividualStack:\n def __init__(self):\n self.stack=[None]*5\n\n\nclass StackwithStacks:\n def __init__(self):\n self.stacks = []\n self.stackcount=-1\n self.count=0\n self.st = None\n... | [
0
] |
f = open("resources/yesterday.txt", 'r')
yesterday_lyric = ""
while 1 :
line = f.readline()
if not line :
break
yesterday_lyric = yesterday_lyric + line.strip() + "\n"
f.close()
# 대소문자 구분없이 yesterday 단어의 개수 세기 : 대문자로 또는 소문자로 만들고 카운드 세기
num_of_yesterday = yesterday_lyric.upper().count("YESTERDAY")
... | normal | {
"blob_id": "8559448822b3d3989a9795e7b497a2791588c327",
"index": 9539,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile 1:\n line = f.readline()\n if not line:\n break\n yesterday_lyric = yesterday_lyric + line.strip() + '\\n'\nf.close()\n<mask token>\nprint(\"Number of a Word 'YESTER... | [
0,
1,
2,
3
] |
#! /usr/bin python3
# -*- coding: utf-8 -*-
from scrapy import Request
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.spiders import CrawlSpider
from scrapy.spiders import Rule
from xici_bbs.spiders.author import get_author_item
from xici_bbs.spiders.comment import get_comment_list, get_comme... | normal | {
"blob_id": "f1eaba91e27dc063f3decd7b6a4fe4e40f7ed721",
"index": 7948,
"step-1": "<mask token>\n\n\nclass XiciSpider(CrawlSpider):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def parse_author(self, response):\n author_item = get_author... | [
3,
4,
5,
6,
7
] |
fileName = str(input("Please write the name of the file you would like to open: "))
file_handle = open(fileName, "w")
contents = str(input("Please write the content you would like to save."))
file_handle.write(contents)
file_handle.close()
print(contents) | normal | {
"blob_id": "aed09a3c04f284fa0b8844a47c5bc9d1621a9b5f",
"index": 2034,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfile_handle.write(contents)\nfile_handle.close()\nprint(contents)\n",
"step-3": "fileName = str(input(\n 'Please write the name of the file you would like to open: '))\nfile_handle =... | [
0,
1,
2,
3
] |
umur = raw_input("Berapakah umurmu?")
tinggi = raw_input("Berapakah tinggimu?")
berat = raw_input("Berapa beratmu?")
print "Jadi, umurmu adalah %r, tinggumu %r, dan beratmu %r." % (umur, tinggi, berat)
| normal | {
"blob_id": "7d2335c956776fc5890a727d22540eabf2ea4b94",
"index": 5862,
"step-1": "umur = raw_input(\"Berapakah umurmu?\")\ntinggi = raw_input(\"Berapakah tinggimu?\")\nberat = raw_input(\"Berapa beratmu?\")\n\nprint \"Jadi, umurmu adalah %r, tinggumu %r, dan beratmu %r.\" % (umur, tinggi, berat)\n",
"step-2": ... | [
0
] |
import os
import config as cfg
import numpy as np
class lfwdata():
def __init__(self):
self._pairs = []
pairs = open(os.path.join(cfg.LFW_IMAGEPATH, '../pairs.txt'))
pairs.readline()
for pair in pairs:
pair = pair.split()
if len(pair) == 3:
... | normal | {
"blob_id": "ccdd7a5e0a1de75762530a7cadd919a2ee753d18",
"index": 1758,
"step-1": "<mask token>\n\n\nclass lfwdata:\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass lfwdata:\n\n def __init__(self):\n self._pairs = []\n pairs = open(os.path.join(cfg.LFW_IMAGEPATH, '../p... | [
1,
2,
3,
4,
5
] |
import numpy as np
print(np.random.binomial(10, 0.5, 1))
| normal | {
"blob_id": "0a3e0eeda14e42bfff7797b3c42a0aebd9a72ade",
"index": 3212,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(np.random.binomial(10, 0.5, 1))\n",
"step-3": "import numpy as np\nprint(np.random.binomial(10, 0.5, 1))\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
... | [
0,
1,
2
] |
from typing import Any
from jinja2.environment import Environment
MAX_RANGE = ... # type: int
UNSAFE_FUNCTION_ATTRIBUTES = ... # type: Any
UNSAFE_METHOD_ATTRIBUTES = ... # type: Any
UNSAFE_GENERATOR_ATTRIBUTES = ... # type: Any
def safe_range(*args): ...
def unsafe(f): ...
def is_internal_attribute(obj, attr): ..... | normal | {
"blob_id": "697f4dd640ddba0411eb6eb68e7ce079a6330670",
"index": 9837,
"step-1": "<mask token>\n\n\nclass SandboxedEnvironment(Environment):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def intercept_unop(self, operator):\n ...\n <mask token>\n <ma... | [
10,
11,
13,
17,
21
] |
import string
fhand = open("romeo-full.txt")
counts = dict()
for line in fhand:
line.tranc | normal | {
"blob_id": "5493887e32dbe7ae27eca79d28da8488183b37a3",
"index": 8792,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor line in fhand:\n line.tranc\n",
"step-3": "<mask token>\nfhand = open('romeo-full.txt')\ncounts = dict()\nfor line in fhand:\n line.tranc\n",
"step-4": "import string\nfhand... | [
0,
1,
2,
3,
4
] |
# Copyright (c) 2018-2020, NVIDIA CORPORATION.
import os
import shutil
import subprocess
import sys
import sysconfig
from distutils.spawn import find_executable
from distutils.sysconfig import get_python_lib
import numpy as np
import pyarrow as pa
from Cython.Build import cythonize
from Cython.Distutils import build_e... | normal | {
"blob_id": "b3095f181032727544ce3ee6f1ad3a70976c0061",
"index": 7892,
"step-1": "<mask token>\n\n\nclass build_ext_and_proto(build_ext):\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\nif not CUDA_HOME:\n path_to_cuda_gdb = shutil.which('cuda-gdb')\n if path_to_cuda_gdb is None:\n ... | [
1,
3,
4,
5,
6
] |
from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from zerver.decorator import REQ, has_request_variables, webhook_view
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message, get_setup_webhook_message
from zerver.models import UserP... | normal | {
"blob_id": "f60d02fb14364fb631d87fcf535b2cb5782e728f",
"index": 6539,
"step-1": "<mask token>\n\n\n@webhook_view('Freshping')\n@has_request_variables\ndef api_freshping_webhook(request: HttpRequest, user_profile: UserProfile,\n payload: Dict[str, Any]=REQ(argument_type='body')) ->HttpResponse:\n body = ge... | [
1,
3,
4,
5,
6
] |
pairs = ['usdt', 'btc']
warn_msg = '** WARN ** '
info_msg = '** INFO **'
| normal | {
"blob_id": "26289d88ac51ee359faa81ca70b01879d2b1f840",
"index": 9460,
"step-1": "<mask token>\n",
"step-2": "pairs = ['usdt', 'btc']\nwarn_msg = '** WARN ** '\ninfo_msg = '** INFO **'\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
# -*- coding: utf-8 -*-
def create_map(rows):
maze = []
for row in rows:
row = row[:-1]
subarr = []
for i in row:
subarr.append(i)
maze.append(subarr)
return maze
def print_map(chart):
for subarr in chart:
print(subarr)
def find_start(chart):
... | normal | {
"blob_id": "bde37f3b41c810ab465de5e0ae374703af9f01f3",
"index": 9033,
"step-1": "def create_map(rows):\n maze = []\n for row in rows:\n row = row[:-1]\n subarr = []\n for i in row:\n subarr.append(i)\n maze.append(subarr)\n return maze\n\n\ndef print_map(chart):\n... | [
3,
4,
5,
6,
7
] |
import os
import glob
ONE_KB = 1024
def get_files(dirname, size_in_kb):
"""Return files in dirname that are >= size_in_kb"""
return (
filename
for _, _, files in os.walk(dirname)
for filename in files
if int(filename) >= size_in_kb * ONE_KB
)
# Pybites solution
def get_f... | normal | {
"blob_id": "0dec0f04cfe891eea74ef45484fa7433e3429dcd",
"index": 7570,
"step-1": "<mask token>\n\n\ndef get_files1(dirname, size_in_kb):\n \"\"\"Return files in dirname that are >= size_in_kb\"\"\"\n for file in glob.glob(os.path.join(dirname, '*')):\n if os.stat(file).st_size >= size_in_kb * ONE_KB... | [
1,
2,
3,
4,
5
] |
from django.shortcuts import render,get_object_or_404, redirect
from django.contrib import admin #어드민 쓸꺼면 써야됨
from .models import Blog #앱을 가지고 오겠다는거
from django.utils import timezone
admin.site.register(Blog) #블로그 형식을 가져와 등록하겠다.
# Create your views here.
def home(request):
blogs = Blog.objects
return render(reque... | normal | {
"blob_id": "bc25338612f525f616fb26c64d8b36667d297d40",
"index": 3921,
"step-1": "<mask token>\n\n\ndef home(request):\n blogs = Blog.objects\n return render(request, 'home.html', {'blogs': blogs})\n\n\ndef detail(request, blog_id):\n blog_detail = get_object_or_404(Blog, pk=blog_id)\n return render(... | [
3,
4,
5,
6,
7
] |
# Global version information
__version__ = "0.6.1"
| normal | {
"blob_id": "8aeb7786984f27fabdcaffa54f52eb868c277fdb",
"index": 7707,
"step-1": "<mask token>\n",
"step-2": "__version__ = '0.6.1'\n",
"step-3": "# Global version information\n__version__ = \"0.6.1\"\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
#Copyright [2017] [Mauro Riva <lemariva@mail.com> <lemariva.com>]
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#http://www.apache.org/licenses/LICENSE-2.0
#Unless required by applicable law ... | normal | {
"blob_id": "894d8d00fd05bf8648f1b95ecf30b70e7b4e841b",
"index": 8640,
"step-1": "<mask token>\n\n\nclass vu_meter:\n <mask token>\n <mask token>\n\n def init_adc(self):\n self.adc = ADC(0)\n self.adcUnit = self.adc.channel(pin=self.adcPin)\n self.adcMean = 0\n\n def init_leds(se... | [
7,
11,
12,
14,
15
] |
import stock as stk
import portfolio as portf
import plot
import sys
import cmd
import os
import decision as des
class CLI(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = '$> '
self.stk_data_coll = stk.StockDataCollection()
self.add_to_plot_lst = []
... | normal | {
"blob_id": "d386047c087155b1809d47349339eb6882cf8e26",
"index": 5013,
"step-1": "import stock as stk\nimport portfolio as portf\nimport plot\nimport sys\nimport cmd\nimport os\nimport decision as des\n \n \nclass CLI(cmd.Cmd):\n\n def __init__(self):\n cmd.Cmd.__init__(self)\n self.prompt =... | [
0
] |
import pygame
from settings import *
import random
class Cell:
def __init__(self, game, x, y, bombs):
self.game = game
self.x = x
self.y = y
self.i = x // TILESIZE
self.j = y // TILESIZE
self.revelada = False
self.bomba = False
self.bombas_total = bo... | normal | {
"blob_id": "e31f1e24c319f338d728661dfd50e758526112d6",
"index": 7796,
"step-1": "<mask token>\n\n\nclass Cell:\n <mask token>\n\n def reveal(self):\n if not self.game.is_game_over:\n self.revelada = True\n if self.bombs_around == 0:\n self.flood()\n i... | [
6,
9,
10,
11,
12
] |
# -*- coding: cp1251 -*-
import arcpy as a
from arcpy import AddMessage as msg, AddWarning as warning, AddError as error
from os import mkdir, walk
from os.path import join, dirname, basename, splitext
from glob import glob as get_files
from shutil import copy
from collections import OrderedDict
input_folder = a.GetP... | normal | {
"blob_id": "409e0fc0b1c1d86c5526d33ba271a8387eecf748",
"index": 9872,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmsg(\"\"\"\nПроверка на наличие подпапок исходной папки в выходной:\"\"\")\nfor folder in input_folders:\n if folder in output_folders:\n warning(' ' + folder)\n else:\n ... | [
0,
1,
2,
3,
4
] |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | normal | {
"blob_id": "443ed24ab396e83dbf12558207376258124bca8b",
"index": 4094,
"step-1": "<mask token>\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--src_path', default='', type=str)\n parser.add_argument('--save_path', default='', type=str)\n parser.add_argument('--interpolat... | [
1,
2,
3,
4,
5
] |
"""empty message
Revision ID: 42cf7f6532dd
Revises: e6d4ac8564fb
Create Date: 2019-04-01 16:13:37.207305
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '42cf7f6532dd'
down_revision = 'e6d4ac8564fb'
branch_labels = None
depends_on = None
def upgrade():
# ... | normal | {
"blob_id": "42d9f40dd50056b1c258508a6cb3f9875680276a",
"index": 3393,
"step-1": "<mask token>\n\n\ndef downgrade():\n op.drop_column('stakeholder', 'archived')\n",
"step-2": "<mask token>\n\n\ndef upgrade():\n op.add_column('stakeholder', sa.Column('archived', sa.Boolean(),\n nullable=False, defa... | [
1,
2,
3,
4,
5
] |
from __future__ import absolute_import, print_function, division, unicode_literals
import tensorflow as tf
def get_encoder(conf):
if conf.encoder == 'linear':
model = tf.keras.Sequential([tf.keras.layers.Dense(conf.d_model * 2),
tf.keras.layers.ReLU(),
... | normal | {
"blob_id": "548eebb9628374df320021c714454e05d2c606c0",
"index": 5336,
"step-1": "<mask token>\n\n\ndef get_encoder(conf):\n if conf.encoder == 'linear':\n model = tf.keras.Sequential([tf.keras.layers.Dense(conf.d_model * 2\n ), tf.keras.layers.ReLU(), tf.keras.layers.Dense(conf.d_model)])\n... | [
9,
10,
12,
13,
14
] |
N, D = map(int, input().split())
ans = 0
D2 = D*D
for i in range(N):
x, y = map(int, input().split())
if (x*x+y*y) <= D2:
ans += 1
print(ans)
| normal | {
"blob_id": "947055d1d6acc50e1722d79ea30e327414cd9c41",
"index": 8523,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(N):\n x, y = map(int, input().split())\n if x * x + y * y <= D2:\n ans += 1\nprint(ans)\n",
"step-3": "N, D = map(int, input().split())\nans = 0\nD2 = D * D\... | [
0,
1,
2,
3
] |
import requests
from bs4 import BeautifulSoup
import sys
import re
if len(sys.argv)<2:
print("Syntax : python %s <port>")%(str(sys.argv[0]))
else:
print('-'*55)
print("HTB WEB-CHALLENGE coded by ZyperX [Freelance]")
print('-'*55)
r=requests.session()
port=str(sys.argv[1])
url="http://docker.hackthebox.eu:"
url=... | normal | {
"blob_id": "88ec9484e934ce27b13734ca26f79df71b7677e6",
"index": 82,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif len(sys.argv) < 2:\n print('Syntax : python %s <port>') % str(sys.argv[0])\nelse:\n print('-' * 55)\n print('HTB WEB-CHALLENGE coded by ZyperX [Freelance]')\n print('-' * 55)... | [
0,
1,
2,
3,
4
] |
from ethereum.abi import (
decode_abi,
normalize_name as normalize_abi_method_name,
method_id as get_abi_method_id)
from ethereum.utils import encode_int, zpad, decode_hex
import json
import time
from web3 import Web3, HTTPProvider, TestRPCProvider
from solc import compile_source
from web3.contract import ... | normal | {
"blob_id": "6437cb90ebaed7cf59df780062ebccf77fcef084",
"index": 4123,
"step-1": "<mask token>\n\n\ndef decode_contract_call(contract_abi: list, call_data: str):\n call_data_bin = decode_hex(call_data)\n method_signature = call_data_bin[:4]\n for description in contract_abi:\n if description.get(... | [
1,
2,
3,
4,
5
] |
import logging
import time
import random
import pickle
import os
from sys import maxsize
import torch
from tensorboardX import SummaryWriter
from baselines.common.schedules import LinearSchedule
from abp.utils import clear_summary_path
from abp.models.feature_q_model import feature_q_model
from abp.adaptives.common.p... | normal | {
"blob_id": "424a0e8a7a80e24aec4bdb9b8c84fd9a5e6090c6",
"index": 6782,
"step-1": "<mask token>\n\n\nclass SADQ_GQF(object):\n <mask token>\n <mask token>\n\n def should_explore(self):\n self.epsilon = self.epsilon_schedule.value(self.steps)\n self.summary.add_scalar(tag='%s/Epsilon' % self... | [
11,
16,
19,
22,
23
] |
#This program sorts the files on Desktop on the basis of file extension and move them in separate folders in Documents folder.
desktop_directory="/home/vineeth/Desktop/" #LINUX
destination_folder="/home/vineeth/Documents/" #LINUX
#desktop_directory="C:/Users/VINEETH/Desktop/" #Windows
#destination_folder="C:/Users/VI... | normal | {
"blob_id": "805b64a7bd727a88081a6ead574fff9b1542070f",
"index": 2023,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor eachfile in os.listdir(desktop_directory):\n if os.path.isfile(desktop_directory + eachfile):\n fileName, fileExtension = os.path.splitext(eachfile)\n if all(fileExte... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
"""
Starter code for exploring the Enron dataset (emails + finances);
loads up the dataset (pickled dict of dicts).
The dataset has the form:
enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }
{features_dict} is a dictionary of features associated with that pers... | normal | {
"blob_id": "c5d224a3d63d0d67bc7a48fecec156cca41cdcf7",
"index": 5129,
"step-1": "#!/usr/bin/python\n\n\"\"\" \n Starter code for exploring the Enron dataset (emails + finances);\n loads up the dataset (pickled dict of dicts).\n\n The dataset has the form:\n enron_data[\"LASTNAME FIRSTNAME MIDDLEINIT... | [
0
] |
# *** Обработка исключений (исключительные события, искл. ситуации)***
# генерация исключения
a=100
b=0
# "деление на ноль" - пример ошибки (не рабочий)
# c=a/b
# решение - обработка исключений (отлов исключения)
# конструкция "try-except"
# try:
# c = a / b
# print("Все отлично")
# except:
# # тут долж... | normal | {
"blob_id": "bb02ba68eb6629dad364b5f015680e4126e655f3",
"index": 6173,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n var = int(input('Введите число: '))\n c = 100 / var\n print('Полет нормальный!')\nexcept ZeroDivisionError:\n c = 0\n print('Попытка деления на ноль')\nelse:\n pr... | [
0,
1,
2,
3
] |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import pwd
import sys
from string import ascii_letters, digits
from ConfigParser import SafeConfigParser
# copied from utils, avoid circular reference fun :)
def mk_boolean(value):
if... | normal | {
"blob_id": "63bd8a15dd489844968f46c4b0ffe157d567537a",
"index": 8044,
"step-1": "<mask token>\n\n\ndef get_config(p, section, key, env_var, default, boolean=False, integer=\n False, floating=False, islist=False):\n \"\"\" return a configuration variable with casting \"\"\"\n value = _get_config(p, sect... | [
4,
5,
6,
7,
8
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 1 11:14:13 2019
@author: dobri
"""
import numpy as np
from astropy.stats import circmean
x = np.multiply(np.pi,[(0,1/4,2/4,3/4,4/4),(1,5/4,6/4,7/4,8/4),(5/4,5/4,5/4,5/4,5/4),(0/5,2/5,4/5,6/5,8/5)])
s = np.shape(x)
phikprime = np.array(x*0, dtype... | normal | {
"blob_id": "c35ecad842477fc8501a763f7eb972f6e7fc13e1",
"index": 7525,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor j in range(0, len(x)):\n for k in range(0, len(x[j, :])):\n phikprime[j, k] = np.complex(np.cos(x[j, k]), np.sin(x[j, k]))\n phikprimebar[j] = np.sum(phikprime[j, :]) / s... | [
0,
1,
2,
3,
4
] |
""" Version 3 of IRC (Infinite Recursive classifier). Based on the idea that each output is placed in a certain
location.
Let me try to solve a simpler problem first. Let me forget about the gate and do non stop recursive classification
step by step, one bye one.
Update. 19 May 2015. Let me stept this up. Instead of h... | normal | {
"blob_id": "eb043c4c981b48763164e3d060fd52f5032be0ea",
"index": 8996,
"step-1": "\"\"\" Version 3 of IRC (Infinite Recursive classifier). Based on the idea that each output is placed in a certain\nlocation.\nLet me try to solve a simpler problem first. Let me forget about the gate and do non stop recursive clas... | [
0
] |
# 라이브러리 환경
import pandas as pd
import numpy as np
# sklearn 테이터셋에서 iris 데이터셋 로딩
from sklearn import datasets
iris = datasets.load_iris()
# iris 데이터셋은 딕셔너리 형태이므로, key 값 확인
'''
print(iris.keys())
print(iris['DESCR'])
print("데이터 셋 크기:", iris['target'])
print("데이터 셋 내용:\n", iris['target'])
'''
# data 속성의 데이터셋 크기
print("... | normal | {
"blob_id": "dc2c9293040204f0ec2156c41b8be624f4e5cf99",
"index": 8389,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('데이터 셋 크기:', iris['data'].shape)\n<mask token>\nprint(type(data1))\n<mask token>\nprint(df)\n<mask token>\nprint('데이터셋 내용:\\n', iris['data'][:7, :])\n<mask token>\nprint('데이터 프레임의 형... | [
0,
1,
2,
3,
4
] |
import numpy as np
from StudyCaseUdemy.Graph import Graph
class OrderVector:
def __init__(self, size):
self.size = size
self.last_pos = -1
self.values = np.empty(self.size, dtype=object)
def insert(self, vertex):
if self.last_pos == self.size - 1:
print('Capacidad m... | normal | {
"blob_id": "87291d066b94aca1d94cbe5d9281fc72da1b0c35",
"index": 9483,
"step-1": "<mask token>\n\n\nclass OrderVector:\n <mask token>\n\n def insert(self, vertex):\n if self.last_pos == self.size - 1:\n print('Capacidad max do Vector atingida')\n return\n pos = 0\n ... | [
6,
7,
9,
10,
11
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.