code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
from django.shortcuts import render, get_object_or_404
from django.template.loader import render_to_string
from django.http import JsonResponse
from django.contrib.auth.models import User
from diagen.utils.DiagramCreator import build_diagram_from_code
from diagen.utils.TextConverter import convert_text_to_code
from dia... | normal | {
"blob_id": "fbbf27f063f6d866e5d0b1210ea9acaebb3bdfb4",
"index": 4398,
"step-1": "<mask token>\n\n\ndef _build_default_components_text():\n text = ''\n for c in DEFAULT_COMPONENTS:\n text += c + '\\n'\n return text\n\n\n<mask token>\n\n\ndef autentificate_user(request):\n username = request.PO... | [
8,
10,
13,
14,
16
] |
# Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module implements helpers for GN SDK e2e tests.
"""
# Note, this is run on bots, which only support python2.7.
# Be sure to only use python2.7 feature... | normal | {
"blob_id": "bbb3d27ce8f4c1943ecc7ab542346c9f41cbd30e",
"index": 1256,
"step-1": "<mask token>\n\n\nclass popen:\n <mask token>\n\n def __init__(self, command):\n self._command = command\n self._process = None\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass popen:... | [
2,
4,
5,
6,
7
] |
# -*- coding: utf-8 -*-
num = input().split()
A = float(num[0])
B = float(num[1])
C = float(num[2])
if A == 0:
print("Impossivel calcular")
else:
delta = B**2 - (4*A*C)
if delta < 0.0:
print("Impossivel calcular")
else:
raiz = delta ** 0.5
r1 = (-B+raiz)/(2*A)
r2 =... | normal | {
"blob_id": "f114a86a3c6bea274b01763ce3e8cd5c8aea44a0",
"index": 3115,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif A == 0:\n print('Impossivel calcular')\nelse:\n delta = B ** 2 - 4 * A * C\n if delta < 0.0:\n print('Impossivel calcular')\n else:\n raiz = delta ** 0.5\n ... | [
0,
1,
2,
3
] |
import pyttsx
engine = pyttsx.init()
rate = engine.getProperty('rate')
engine.setProperty('rate', rate-55)
engine.say('Hello , whats your name ?');
engine.say('I am mr. robot. What news would you like to listen to today ?');
#engine.say('Sally sells seashells by the seashore.')
#engine.say('Sally sells seashells by the... | normal | {
"blob_id": "d638194a37dc503b7dfb5410abf264be67c3a4f0",
"index": 4126,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nengine.setProperty('rate', rate - 55)\nengine.say('Hello , whats your name ?')\nengine.say('I am mr. robot. What news would you like to listen to today ?')\nengine.runAndWait()\n",
"ste... | [
0,
1,
2,
3,
4
] |
from . import *
from ..utils.constants import NUM_SEARCH_RESULT
def get_course_by_id(course_id):
return Course.query.filter_by(id=course_id).first()
def get_course_by_subject_and_course_num(subject_code, course_num):
return Course.query.filter_by(subject_code=subject_code, course_num=course_num).first()
d... | normal | {
"blob_id": "b3f0aae91c885d0e15ff3e456b5cab43fca65b67",
"index": 4184,
"step-1": "<mask token>\n\n\ndef get_course_by_id(course_id):\n return Course.query.filter_by(id=course_id).first()\n\n\n<mask token>\n\n\ndef create_course(subject_code, course_num, title):\n optional_course = get_course_by_subject_and... | [
4,
5,
6,
7,
8
] |
import csv, io
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.views import generic
from itertools import chain
from .models import Player, League, Team
class IndexView(generic.ListView):
templ... | normal | {
"blob_id": "bce794616889b80c152a8ebec8d02e49a96684e9",
"index": 2955,
"step-1": "<mask token>\n\n\nclass IndexView(generic.ListView):\n template_name = 'players/players.html'\n context_object_name = 'players'\n\n def get_queryset(self):\n return list(chain(Player.objects.all(), Player._meta.get_... | [
4,
7,
8,
9,
10
] |
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'ecommerce.settings.development')
application = get_asgi_application()
| normal | {
"blob_id": "1cb320cf57823511b0398adce097b770b2131eb6",
"index": 9307,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nos.environ.setdefault('DJANGO_SETTINGS_MODULE',\n 'ecommerce.settings.development')\n<mask token>\n",
"step-3": "<mask token>\nos.environ.setdefault('DJANGO_SETTINGS_MODULE',\n 'e... | [
0,
1,
2,
3
] |
import gdal
import sys, gc
sys.path.append("..")
import getopt
import redis
import time
import subprocess
import numpy as np
from os import listdir, makedirs
from os.path import isfile, join, exists
from operator import itemgetter
from natsort import natsorted
from config import DatasetConfig, RasterParams
from datase... | normal | {
"blob_id": "2b82d66803ae0a0b03204318975d3c122f34f0cf",
"index": 7003,
"step-1": "<mask token>\n\n\ndef main(argv):\n \"\"\"\n Main function which shows the usage, retrieves the command line parameters and invokes the required functions to do\n the expected job.\n\n :param argv: (dictionary) options ... | [
5,
6,
7,
8,
9
] |
import cv2
import numpy as np
import time
import itertools
from unionfind import UnionFind
R = 512
C = 512
# Setup window
cv2.namedWindow('main')
#img_i = np.zeros((R, C), np.uint8)
img_i = cv2.imread("window1.png", cv2.IMREAD_GRAYSCALE)
#img_i = cv2.threshold(img_i, 127, 255, cv2.THRESH_BINARY)[1]
do... | normal | {
"blob_id": "86d3e90493ed04bbe23792716f46a68948911dc3",
"index": 6861,
"step-1": "<mask token>\n\n\nclass BFCell:\n <mask token>\n\n def __init__(self, r, c, id, occupied):\n \"\"\"BFCell(row, col)\"\"\"\n self.r = r\n self.c = c\n self.id = id\n self.occupied = occupied\... | [
7,
12,
15,
16,
20
] |
#+++++++++++++++++++exp.py++++++++++++++++++++
#!/usr/bin/python
# -*- coding:utf-8 -*-
#Author: Squarer
#Time: 2020.11.15 20.20.51
#+++++++++++++++++++exp.py++++++++++++++++++++
from pwn import*
#context.log_level = 'debug'
context.arch = 'amd64'
elf = ELF('./npuctf_2020_easyheap')
libc = ... | normal | {
"blob_id": "eeedf4930a7fa58fd406a569db6281476c2e3e35",
"index": 4870,
"step-1": "<mask token>\n\n\ndef add(size, cont):\n sh.sendlineafter('Your choice :', '1')\n sh.sendlineafter('Size of Heap(0x10 or 0x20 only) : ', str(size))\n sh.sendlineafter('Content:', str(cont))\n\n\ndef edit(index, cont):\n ... | [
4,
6,
7,
8,
9
] |
"""insta URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based v... | normal | {
"blob_id": "63c0786d277c5576822d6e521f65850762ab5eb0",
"index": 9198,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n",
"step-3": "<mask token>\nurlpatterns = [path('admin/', admin.site.urls), path('post/', post_views.\n ... | [
0,
1,
2,
3,
4
] |
#代码整体框架
#引用库
#创建窗口
def GameStart():
#游戏背景对象
Background = pygame.image.load()
#挡板背景对象
Baddle = pygame.image.load()
#球对象
Ball = pygame.image.load()
#挡板位置信息
BaffleX
BaffleY
#球位置信息
BallX
ballY
BallSpeed
#帧率控制Clock对象
#显示时间Clock对象
#... | normal | {
"blob_id": "9aeaab445ae9df5c27cc4375a8b6bf320d5ab873",
"index": 6378,
"step-1": "#代码整体框架\n\n#引用库\n\n#创建窗口\n\n\ndef GameStart():\n\n\n #游戏背景对象\n \n Background = pygame.image.load()\n \n #挡板背景对象\n\n Baddle = pygame.image.load()\n\n #球对象 \n\n Ball = pygame.image.load()\n\n #挡板位置信息\n\n... | [
0
] |
# Author: Loren Matilsky
# Date created: 03/02/2019
import matplotlib.pyplot as plt
import numpy as np
import sys, os
sys.path.append(os.environ['raco'])
sys.path.append(os.environ['rapl'])
sys.path.append(os.environ['rapl'] + '/timetrace')
from common import *
from cla_util import *
from plotcommon import *
from timey... | normal | {
"blob_id": "97a059d6d34b924a0512ebe6ff5ab1d5ccc072d5",
"index": 8966,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.append(os.environ['raco'])\nsys.path.append(os.environ['rapl'])\nsys.path.append(os.environ['rapl'] + '/timetrace')\n<mask token>\nkwargs_default.update(plot_timey_kwargs_default... | [
0,
1,
2,
3,
4
] |
import logging
import os
import logzero
from gunicorn.glogging import Logger
_log_level = os.environ.get("LOG_LEVEL", "info").upper()
log_level = getattr(logging, _log_level)
log_format = "%(color)s[%(levelname)1.1s %(asctime)s %(name)s]%(end_color)s %(message)s"
formatter = logzero.LogFormatter(fmt=log_format)
logg... | normal | {
"blob_id": "b8b50ef021c4b25edbab355e1db5d62d3c5a28ad",
"index": 7257,
"step-1": "<mask token>\n\n\nclass GunicornLogger(Logger):\n <mask token>\n",
"step-2": "<mask token>\nlogzero.setup_logger(**logger_args)\nlogzero.setup_default_logger(**logger_args)\n<mask token>\n\n\nclass GunicornLogger(Logger):\n\n ... | [
1,
3,
4,
5,
6
] |
import os
from datetime import timedelta
ROOT_PATH = os.path.split(os.path.abspath(__name__))[0]
DEBUG = True
JWT_SECRET_KEY = 'shop'
# SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format(
# os.path.join(ROOT_PATH, 's_shop_flask.db'))
SQLALCHEMY_TRACK_MODIFICATIONS = False
user = 'shop'
passwd = 'shopadmin'
db = 'shop... | normal | {
"blob_id": "3908d303d0e41677aae332fbdbe9b681bffe5391",
"index": 1044,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nROOT_PATH = os.path.split(os.path.abspath(__name__))[0]\nDEBUG = True\nJWT_SECRET_KEY = 'shop'\nSQLALCHEMY_TRACK_MODIFICATIONS = False\nuser = 'shop'\npasswd = 'shopadmin'\ndb = 'shopdb'\... | [
0,
1,
2,
3
] |
import unittest
import json
import os
import copy
from nested.nested_dict import NestedDict
from pprint import pprint
class TestNestedDict(unittest.TestCase):
@classmethod
def setUpClass(cls):
path = os.path.dirname(__file__)
cls.afile = os.path.join(path, '../nested/data/food_nested_dict.jso... | normal | {
"blob_id": "f9a255a464b5f48a1a8be2e2887db721a92e7f4e",
"index": 1474,
"step-1": "<mask token>\n\n\nclass TestNestedDict(unittest.TestCase):\n <mask token>\n <mask token>\n\n def test_dfood(self):\n self.assertEqual(self.dfood.keys(), [u'0001', u'0002', u'0003'])\n <mask token>\n <mask toke... | [
3,
6,
8,
10,
12
] |
# Generated by Django 3.1.5 on 2021-02-24 18:34
from django.db import migrations, models
import stdimage.models
class Migration(migrations.Migration):
dependencies = [
('Site', '0004_arquivopdf'),
]
operations = [
migrations.CreateModel(
name='historico',
fields=... | normal | {
"blob_id": "321147f2e2d8caf6d9224e2a8969f51ded48baf7",
"index": 8130,
"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 = [('Site', '000... | [
0,
1,
2,
3,
4
] |
def ex(x, y):
max = 0
print(x) if x > y else print(y)
return max
| normal | {
"blob_id": "4ffc00e9425992bdd8277341d67a0739119a4798",
"index": 2773,
"step-1": "<mask token>\n",
"step-2": "def ex(x, y):\n max = 0\n print(x) if x > y else print(y)\n return max\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
from __future__ import print_function # Should comes first than torch
import torch
from torch.autograd import Variable
##
## Autograd.Variable is the central class of the package. It wraps a Tensor, and supports nearly all of operations defined on it. Once you finish your computation you can call .backward() and have ... | normal | {
"blob_id": "ba1648143d49110a163da02e60fb0fd024a10b79",
"index": 5140,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('# ------------- Simple Variable ------------- #')\n<mask token>\nprint(x)\n<mask token>\nprint(y)\nprint(y.grad_fn)\n<mask token>\nprint('z = y * y * 3\\n', z, out)\nprint('# -----... | [
0,
1,
2,
3,
4
] |
# read in file of customs declaration responses
declarations_file = open('day6_declarations.txt', 'r')
lines = declarations_file.readlines()
# initialise variables
group_responses = [] # temporary container for all responses of each group member
count_any_member_has_response = 0 # count for part... | normal | {
"blob_id": "cb6ed6422a5591f1de0a947f75ad080f250e8443",
"index": 7718,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor line in lines:\n if line == '\\n' or line == lines[-1]:\n if line == lines[-1]:\n line = line.strip()\n group_responses.append(line)\n group_res... | [
0,
1,
2,
3
] |
from Bio import BiopythonWarning, SeqIO
from Bio.PDB import MMCIFParser, Dice, PDBParser
from Bio.SeqUtils import seq1
import time
import requests
import re
import warnings
warnings.simplefilter('ignore', BiopythonWarning)
def get_response(url):
response = requests.get(url)
cnt = 20
while cnt != 0:
... | normal | {
"blob_id": "ad5cdcfd9d7a3c07abcdcb701422f3c0fdc2b374",
"index": 8860,
"step-1": "<mask token>\n\n\nclass Cif:\n\n def get_chain(self):\n return [chain for chain in list(self.structure.get_models())[0] if \n chain.get_id() == self.chain_id][0]\n\n def get_seq_from_pdb(self):\n seq_... | [
4,
6,
7,
9,
10
] |
from django import forms
from .models import Picture
class PictureUploadForm(forms.ModelForm):
class Meta:
model = Picture
exclude = ()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widge... | normal | {
"blob_id": "3d45fd7dcb3b382efaefe2797ebeb33216a840fa",
"index": 680,
"step-1": "<mask token>\n\n\nclass PictureUploadForm(forms.ModelForm):\n\n\n class Meta:\n model = Picture\n exclude = ()\n <mask token>\n <mask token>\n\n\nclass PictureUpdateForm(forms.Form):\n width = forms.Integer... | [
5,
6,
7,
8,
9
] |
import numpy as np
import matplotlib.pyplot as plt
def f(x:float,y:np.ndarray) -> np.ndarray:
"""
Работает с вектором { y , y'}
"""
# return some function result
return np.array([y[1], np.sqrt(abs(-np.exp(y[1])*y[0] + 2.71*y[0]**2/np.log(x)+1/x**2))])
# return np.array([y[1], -y[0]... | normal | {
"blob_id": "daccc5aafb3e250e7fa7ac9db69a147b7e916736",
"index": 193,
"step-1": "<mask token>\n\n\ndef f(x: float, y: np.ndarray) ->np.ndarray:\n \"\"\"\n Работает с вектором { y , y'}\n \"\"\"\n return np.array([y[1], np.sqrt(abs(-np.exp(y[1]) * y[0] + 2.71 * y[0] **\n 2 / np.log(x) + 1 / x *... | [
2,
3,
4,
5,
6
] |
import re
import ngram
import smoothedNgram
def split_into_sentences(text):
text = text.lower()
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', text)
getSentences(sentences,text)
return sentences
def getTextWithoutSpaces(text):
withoutLineBreaks = text.replace("\n", "")
withoutS... | normal | {
"blob_id": "6d7db5b9a64ec25763f5af6ceec1a46d629d549c",
"index": 472,
"step-1": "<mask token>\n\n\ndef getTextWithoutSpaces(text):\n withoutLineBreaks = text.replace('\\n', '')\n withoutSpaces = re.sub(' +', ' ', withoutLineBreaks)\n return withoutSpaces\n\n\ndef getSentences(sentences, text):\n data... | [
3,
5,
6,
7,
8
] |
print ("Hello, Django girls!")
volume = 57
if volume < 20:
print("It's kinda quiet.")
elif 20 <= volume < 40:
print("It's nice for background music")
elif 40 <= volume < 60:
print("Perfect, I can hear all the details")
elif 60 <= volume < 80:
print("Nice for parties")
elif 80 <= volume < 100:
print... | normal | {
"blob_id": "00fd5efa4c66b7bd4617f4c886eddcdf38b951b7",
"index": 9507,
"step-1": "<mask token>\n",
"step-2": "print('Hello, Django girls!')\n<mask token>\nif volume < 20:\n print(\"It's kinda quiet.\")\nelif 20 <= volume < 40:\n print(\"It's nice for background music\")\nelif 40 <= volume < 60:\n prin... | [
0,
1,
2,
3
] |
"""
Pide una cadena y un carácter por teclado y muestra cuantas veces aparece el carácter en la cadena.
Autor: David Galván Fontalba
Fecha: 27/10/2019
Algoritmo:
Pido un cadena
Pido un caracter
contador en 0
Hago una variable que empieza siendo 0, i
mientras i <= len(cadena)
si cadena[i] == caracter
... | normal | {
"blob_id": "65301be73bb56147609a103a932266013c3c0bd6",
"index": 1148,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(\n 'Bienvenido a este programa para que introduzcas una frase y un carácter, y decirte cuántas veces aparece ese carácter en tu frase.'\n )\nprint(\n \"\"\"----------------... | [
0,
1,
2,
3
] |
import cv2
cam = cv2.VideoCapture("./bebop.sdp")
while True:
ret, frame = cam.read()
cv2.imshow("frame", frame)
cv2.waitKey(1)
| normal | {
"blob_id": "d13b402b90bb948e5722f45096a8c0a33e4cac67",
"index": 6968,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n ret, frame = cam.read()\n cv2.imshow('frame', frame)\n cv2.waitKey(1)\n",
"step-3": "<mask token>\ncam = cv2.VideoCapture('./bebop.sdp')\nwhile True:\n ret, fr... | [
0,
1,
2,
3,
4
] |
from .tokening import sign_profile_tokens, validate_token_record, \
get_profile_from_tokens
from .zone_file import create_zone_file
from .legacy import is_profile_legacy_format, get_person_from_legacy_format
| normal | {
"blob_id": "de24b341102f5979cc48b22c3a07d42915b6dd18",
"index": 7146,
"step-1": "<mask token>\n",
"step-2": "from .tokening import sign_profile_tokens, validate_token_record, get_profile_from_tokens\nfrom .zone_file import create_zone_file\nfrom .legacy import is_profile_legacy_format, get_person_from_legacy_... | [
0,
1,
2
] |
import json
import math
import pandas as pd
import datetime
record_file = r"D:\Doc\data\BBOS.log"
all_records = []
with open(record_file, "r") as f:
all_line = f.readlines()
for line in all_line:
record_time = line[line.index("[") + 1: line.index("]")]
record_order = json.loads(line[l... | normal | {
"blob_id": "fbbadb5cbd2b324686fc5faa0b1bc6236fc8d87b",
"index": 9218,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open(record_file, 'r') as f:\n all_line = f.readlines()\n for line in all_line:\n record_time = line[line.index('[') + 1:line.index(']')]\n record_order = json.lo... | [
0,
1,
2,
3,
4
] |
from rest_framework import serializers
from .models import *
class VisitaSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Visita
fields = ('id', 'usuario', 'lugar', 'fecha_visita', 'hora_visita') | normal | {
"blob_id": "72bbd100a37a86dec7684257f2bec85d7367c009",
"index": 5810,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass VisitaSerializer(serializers.HyperlinkedModelSerializer):\n\n\n class Meta:\n model = Visita\n fields = 'id', 'usuario', 'lugar', 'fecha_visita', 'hora_visita'\... | [
0,
1,
2,
3
] |
import multiprocessing
import sys
import warnings
from pathlib import Path
import attr
import librosa
import pandas as pd
from rich.progress import BarColumn, Progress, TimeRemainingColumn
from sklearn.preprocessing import LabelEncoder
from tslearn.piecewise import SymbolicAggregateApproximation
from tslearn.preproces... | normal | {
"blob_id": "0e57e25c11ba97aef5467f61d99065609e127f5b",
"index": 2782,
"step-1": "<mask token>\n\n\n@attr.s\nclass MusicDB(object):\n <mask token>\n <mask token>\n <mask token>\n\n @feat.default\n def _feat_default(self):\n our_feat = utils.load_tracks(givegenre=True, outliers=False, fill=F... | [
4,
6,
8,
9,
11
] |
# Generated by Django 2.1.5 on 2021-06-01 19:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('fotbal', '0008_auto_20210601_2109'),
]
operations = [
migrations.RemoveField(
model_name='komenty',
name='jmeno',
),... | normal | {
"blob_id": "71ffad81bcbc480dc0a750680bc72e1d5c48556a",
"index": 3619,
"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 = [('fotbal', '0... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import hashlib
import re
from datetime import datetime
import gevent
import requests
import scrapy
from gevent.pool import Pool
from lxml import etree
from scrapy.http import HtmlResponse
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
... | normal | {
"blob_id": "eb853e430b996a81dc2ef20c320979a3e04d956a",
"index": 237,
"step-1": "<mask token>\n\n\nclass Beautyleg7Spider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def parse(self, response):\n if self.db_session is No... | [
3,
6,
8,
9,
13
] |
def my_filter(L, num):
return [x for x in L if x % num]
print 'my_filter', my_filter([1, 2, 4, 5, 7], 2)
def my_lists(L):
return [range(1, x+1) for x in L]
print 'my_lists', my_lists([1, 2, 4])
print 'my_lists', my_lists([0])
def my_function_composition(f, g):
return {f_key: g[f_val] for f_key, f_val in f.item... | normal | {
"blob_id": "119ebdf4c686c52e052d3926f962cefdc93681cd",
"index": 9984,
"step-1": "def my_filter(L, num):\n\treturn [x for x in L if x % num]\n\nprint 'my_filter', my_filter([1, 2, 4, 5, 7], 2)\n\n\ndef my_lists(L):\n\treturn [range(1, x+1) for x in L]\n\nprint 'my_lists', my_lists([1, 2, 4])\nprint 'my_lists', m... | [
0
] |
from urllib import request
import time
import random
from useragents import ua_list
import re
import os
class MaoyanSpider(object):
def __init__(self):
self.url = 'https://maoyan.com/board/4?offset={}'
# 请求功能函数 - html
def get_html(self,url):
headers = {
'User-Agent':random.choi... | normal | {
"blob_id": "7ef0bb3e8cbba4a29249a09cf7bc91e053411361",
"index": 2225,
"step-1": "<mask token>\n\n\nclass MaoyanSpider(object):\n\n def __init__(self):\n self.url = 'https://maoyan.com/board/4?offset={}'\n\n def get_html(self, url):\n headers = {'User-Agent': random.choice(ua_list)}\n ... | [
6,
9,
10,
11,
12
] |
'''
Seperate a number into several, maximize their product
'''
# recursive
def solution1(n):
if n <= 4:
return n
else:
return max(map(lambda x: solution1(x)*solution1(n-x), range(1, n//2 + 1)))
# dp
def solution2(n):
result_list = [1,2]
for i in range(3, n+1):
max_mult = max(l... | normal | {
"blob_id": "76db5955b29696ca03ab22ef14ac018e0618e9e3",
"index": 2729,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef solution2(n):\n result_list = [1, 2]\n for i in range(3, n + 1):\n max_mult = max(list(map(lambda x: result_list[x] * (i - x - 1),\n range(i - 1))))\n ... | [
0,
1,
2,
3,
4
] |
import re
text = "Python is an interpreted high-level general-purpose programming language."
fiveWord = re.findall(r"\b\w{5}\b", text)
print("Following are the words with five Letters:")
for strWord in fiveWord:
print(strWord)
| normal | {
"blob_id": "aa15d51760c16181907994d329fb7ceede6a539b",
"index": 5858,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Following are the words with five Letters:')\nfor strWord in fiveWord:\n print(strWord)\n",
"step-3": "<mask token>\ntext = (\n 'Python is an interpreted high-level general... | [
0,
1,
2,
3,
4
] |
import io
from PIL import Image
def bytes_from_file(path, size, quality=15):
img = Image.open(path)
img = img.resize(size)
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="JPEG", quality=quality)
return img_byte_arr.getvalue()
| normal | {
"blob_id": "3344eb5b3e5b5eaee7b08d0991be732dae62c7fc",
"index": 7137,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef bytes_from_file(path, size, quality=15):\n img = Image.open(path)\n img = img.resize(size)\n img_byte_arr = io.BytesIO()\n img.save(img_byte_arr, format='JPEG', qualit... | [
0,
1,
2,
3
] |
# coding:utf-8
'''
对称二叉树
实现一个函数,用来判断一个二叉树是不是对称的
如果一颗二叉树和它的镜像是一样的,就是对称的
'''
class BinaryTreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetryBonaryTree(self, pRoot):
if pRoot is None:
return... | normal | {
"blob_id": "c1a9c220b9100a927076753d6483ad7c069dea8c",
"index": 4271,
"step-1": "# coding:utf-8\n\n'''\n对称二叉树\n实现一个函数,用来判断一个二叉树是不是对称的\n如果一颗二叉树和它的镜像是一样的,就是对称的\n'''\n\n\nclass BinaryTreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass ... | [
0
] |
{
"module_spec": {
"module_name": "Spec1"
}
}
| normal | {
"blob_id": "1cfb0690ebe1d7c6ab93fa6a4bc959b90b991bc8",
"index": 7016,
"step-1": "<mask token>\n",
"step-2": "{'module_spec': {'module_name': 'Spec1'}}\n",
"step-3": "{\n \"module_spec\": {\n \"module_name\": \"Spec1\"\n }\n}\n\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
... | [
0,
1,
2
] |
from flask import (
Flask,
render_template,
request
)
import requests
app = Flask(__name__)
base_url = "https://api.github.com/users/"
@app.route("/", methods = ["GET", "POST"])
def index():
if request.method == "POST":
githubName = request.form.get("githubname")
responseUser = request... | normal | {
"blob_id": "62094d036596f39e7cf936fe7a91e67d53ee055e",
"index": 9557,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n githubName = request.form.get('githubname')\n responseUser = requests.get('{}{... | [
0,
2,
3,
4,
5
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 13:19:51 2020
@author: Warren
Script to check sdf file format for Fragalysis upload
"""
from rdkit import Chem
import validators
import numpy as np
import os
from viewer.models import Protein, CompoundSet
import datetime
# Set .sdf format versio... | normal | {
"blob_id": "0082f75332321dba498f06d4c4a99c9248829b59",
"index": 654,
"step-1": "<mask token>\n\n\ndef check_compound_set(description_mol, validate_dict):\n y_m_d = description_mol.GetProp('generation_date').split('-')\n submitter_dict = {'submitter__name': description_mol.GetProp(\n 'submitter_name... | [
9,
10,
14,
16,
18
] |
from speaker_verification import *
import numpy as np
region = 'westus'
api_key = load_json('./real_secrets.json')['api_key']
wav_path = './enrollment.wav'
temp_path = './temp.wav'
# If you want to list users by profile_id
print('All users are: ', list_users(api_key, region))
# This is handled by the development / p... | normal | {
"blob_id": "5195dcf262c0be08f83cf66e79d48e51811a67a0",
"index": 6866,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('All users are: ', list_users(api_key, region))\n<mask token>\nenroll_user(api_key, region, wav_path, profile_id)\nprint(f'Likelihood that {wav_path} came from this subject')\nident... | [
0,
1,
2,
3,
4
] |
import boto3, os, shutil, datetime, time, sys
session = boto3.Session(profile_name='default')
s3 = boto3.resource('s3')
bucket = s3.Bucket('netball-ml-processed')
#print(bucket.objects)
#needs to be run with *** sudo **** otherwise it won't work...
while True:
#change to the motion working Directory
os.... | normal | {
"blob_id": "ec0697d8d78fafe6bfd4630be2a1fb20eb9eb4cf",
"index": 2472,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n os.chdir('/home/ec2-user/ML-Processed')\n print(str(os.getcwd()))\n for f in os.listdir(os.getcwd()):\n print('looping in file')\n file_name, file_ext... | [
0,
1,
2,
3,
4
] |
from source.ga.population import create_population, random_genome
def test_create_population(race_example):
population = create_population(race_example, 20)
assert population
def test_random_genome(race_basic):
genome = random_genome(race_basic)
assert genome
def test_random_genome_example(race_ex... | normal | {
"blob_id": "0802aac57cd28104cdb6ff45d993aa224f80b830",
"index": 2877,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_random_genome(race_basic):\n genome = random_genome(race_basic)\n assert genome\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef test_create_population(race_exa... | [
0,
1,
2,
3,
4
] |
from utils import *
from Dataset.input_pipe import *
from Learning.tf_multipath_classifier import *
def config_graph():
paths = []
path = {}
path['input_dim'] = 4116
path['name'] = 'shared1'
path['computation'] = construct_path(path['name'], [512, 512], batch_norm=False, dropout=True, dropout_rate=0.5, noise=Fa... | normal | {
"blob_id": "8039430f1b65cc76f9a78b1094f110de29f0f965",
"index": 4885,
"step-1": "<mask token>\n\n\ndef config_graph():\n paths = []\n path = {}\n path['input_dim'] = 4116\n path['name'] = 'shared1'\n path['computation'] = construct_path(path['name'], [512, 512],\n batch_norm=False, dropout... | [
1,
2,
3,
4,
5
] |
import voldemort
import time
authorStore = voldemort.StoreClient('authorStore', [{'0', 6666}])
stack = []
components = []
index = 1
# Implementation of the Tarjan algorithm for the detection of strongly connected components.
# Function collects all authors in the database and outputs them as strongly connected compon... | normal | {
"blob_id": "bb2c684fd5b962c97c033d4b4c2027d52b7371fd",
"index": 499,
"step-1": "<mask token>\n\n\ndef tarjan():\n timer = time.time\n start = timer()\n voldemortResult = authorStore.get('_authors')\n allAuthors = voldemortResult[0][0]\n nodes = {}\n for author in allAuthors.get('content'):\n ... | [
2,
3,
4,
5,
6
] |
from collections import Counter
def main():
N = int(input())
A = tuple(map(int, input().split()))
c = Counter(A).most_common()
if c[0][0] == 0 and c[0][1] == N:
print("Yes")
elif len(c) == 2 and c[0][1] == 2*N//3 and c[1][0] == 0 and c[1][1] == N//3:
print("Yes")
elif ... | normal | {
"blob_id": "7c6ada250770e04b395dda774a78042da69e2854",
"index": 8681,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n N = int(input())\n A = tuple(map(int, input().split()))\n c = Counter(A).most_common()\n if c[0][0] == 0 and c[0][1] == N:\n print('Yes')\n elif le... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 23 10:16:40 2014
@author: Yusuke
"""
import math
result = []
for i in range(6 * 9**5):
sum_num = 0
for j_digit in str(i):
sum_num += int(j_digit) ** 5
if sum_num == i:
print i
result.append(i)
print math.fsum(result)
| normal | {
"blob_id": "08ccc58fe139db3f4712aa551b80f6ea57e0ad76",
"index": 1888,
"step-1": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 23 10:16:40 2014\n\n@author: Yusuke\n\"\"\"\nimport math\n\nresult = []\nfor i in range(6 * 9**5):\n sum_num = 0\n for j_digit in str(i):\n sum_num += int(j_digit) **... | [
0
] |
"""
Created on Fri Aug 4 19:19:31 2017
@author: aw1042
"""
import requests
import threading
import sys
import re
import xml.etree.ElementTree as ET
import smtplib
from credentials import *
argsObj = {}
for arg1, arg2 in zip(sys.argv[:-1], sys.argv[1:]):
if arg1[0] == '-':
argsObj[arg1] = arg2
posts = ... | normal | {
"blob_id": "297a17ca5aaafb368a1e4cba35e387c67e9f793f",
"index": 7420,
"step-1": "\"\"\"\nCreated on Fri Aug 4 19:19:31 2017\n\n@author: aw1042\n\"\"\"\nimport requests\nimport threading\nimport sys\nimport re\nimport xml.etree.ElementTree as ET\nimport smtplib\nfrom credentials import *\n\n\n\nargsObj = {}\nfo... | [
0
] |
# coding: utf-8
from korean.morphophonemics.phonology import Syllable
from notes.old_morphology import Noun, Verb
class Case (object):
pass
class Nominative (Case):
def apply(self, noun):
if noun.has_tail():
noun.syllables.append(Syllable(u'이'))
else:
noun.syl... | normal | {
"blob_id": "1077efaa4379ff0e114a0b8d4d3b7156758e070f",
"index": 9861,
"step-1": "# coding: utf-8\n\nfrom korean.morphophonemics.phonology import Syllable\nfrom notes.old_morphology import Noun, Verb\n\n\nclass Case (object):\n pass \n\nclass Nominative (Case):\n def apply(self, noun):\n if n... | [
0
] |
# coding: utf-8
# In[1]:
import pandas as pd
import os,re,sys
import numpy as np
import glob as glob
# In[2]:
def createNewDataFrame():
columns = ['document_id','content','cat','subcat']
df_ = pd.DataFrame(columns=columns)
return(df_)
# In[3]:
def getcategories(foldername):
cats = folderna... | normal | {
"blob_id": "1aa01845ab98005b1fee33b4fc153bb029e450e0",
"index": 2061,
"step-1": "<mask token>\n\n\ndef createNewDataFrame():\n columns = ['document_id', 'content', 'cat', 'subcat']\n df_ = pd.DataFrame(columns=columns)\n return df_\n\n\ndef getcategories(foldername):\n cats = foldername.split('_')\n... | [
2,
3,
4,
5,
6
] |
import serial, time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(7, GPIO.OUT)
pwm1 = GPIO.PWM(23,100)
pwm2 = GPIO.PWM(24,100)
pwm1.start(100)
pwm2.start(100... | normal | {
"blob_id": "647aa37c53aac7c620e5095c7a9368f4ad038608",
"index": 8209,
"step-1": "import serial, time\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(4, GPIO.OUT)\nGPIO.setup(17, GPIO.OUT)\nGPIO.setup(27, GPIO.OUT)\nGPIO.setup(22, GPIO.OUT)\nGPIO.setup(23, GPIO.OUT)\nGPIO.setup(24, GPIO.OUT)\nGPIO... | [
0
] |
## Script (Python) "after_rigetta"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=state_change
##title=
##
doc = state_change.object
#Aggiornamento dello stato su plominoDocument
doc.updateStatus()
if script.run_script(doc, script.... | normal | {
"blob_id": "096d82e1f9e8832f6605d23c8bb324e045b6b14f",
"index": 7393,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndoc.updateStatus()\nif script.run_script(doc, script.id) != False:\n if doc.naming('richiesta') != 'integrazione':\n doc.sendThisMail('rigetta')\n script.run_script(doc, scri... | [
0,
1,
2,
3
] |
from functools import wraps
class aws_retry:
"""retries the call (required for some cases where data is not consistent yet in AWS"""
def __init__(self, fields):
self.fields = fields # field to inject
def __call__(self, function):
pass
#code ... | normal | {
"blob_id": "493b29433f0c3646e7f80fca2f656fc4a5256003",
"index": 8884,
"step-1": "<mask token>\n\n\nclass aws_retry:\n <mask token>\n\n def __init__(self, fields):\n self.fields = fields\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass aws_retry:\n <mask token>\n\n def __init__(self,... | [
2,
3,
4,
5,
6
] |
animal = 'cat'
def f():
global animal
animal = 'dog'
print('local_scope:', animal)
print('local:', locals())
f()
print('global_scope:', animal)
print('global:', locals())
| normal | {
"blob_id": "4f3908e12102cfd58737952803c710772e960b0e",
"index": 2385,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef f():\n global animal\n animal = 'dog'\n print('local_scope:', animal)\n print('local:', locals())\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef f():\n gl... | [
0,
1,
2,
3
] |
from model import *
from data import *
import os
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
data_gen_args = dict(horizontal_flip = True,
vertical_flip = True)
imageTargetSize = (256, 256)
trainPath = '/work/scratch/zhangbin/EmbryoTracking_ClaireBinZhang/Motili... | normal | {
"blob_id": "ba379ed90bccd05d058f69f33a960779f8b8bcd5",
"index": 5632,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsaveResult(\n '/work/scratch/zhangbin/EmbryoTracking_ClaireBinZhang/MotilityAnalysis/20160317 10 dpf 60 fps 15 min (2)/here'\n , results)\n<mask token>\nplt.plot(epoch_count, traini... | [
0,
1,
2,
3,
4
] |
import unittest2 as unittest
class GpTestCase(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(GpTestCase, self).__init__(methodName)
self.patches = []
self.mock_objs = []
def apply_patches(self, patches):
if self.patches:
raise Exception('Test c... | normal | {
"blob_id": "e9c88e18472281438783d29648c673aa08366abb",
"index": 1686,
"step-1": "<mask token>\n\n\nclass GpTestCase(unittest.TestCase):\n\n def __init__(self, methodName='runTest'):\n super(GpTestCase, self).__init__(methodName)\n self.patches = []\n self.mock_objs = []\n\n def apply_... | [
4,
6,
7,
8,
9
] |
#!/usr/bin/python
###########################################################################
#
# Copyright 2019 Dell, Inc.
#
# 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.... | normal | {
"blob_id": "102ba5c1cb4beda6f9b82d37d9b343fe4f309cfb",
"index": 5268,
"step-1": "#!/usr/bin/python\n###########################################################################\n#\n# Copyright 2019 Dell, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file exc... | [
0
] |
from ...routes import Route
from .providers import SQSProvider
from .message_translators import SQSMessageTranslator, SNSMessageTranslator
class SQSRoute(Route):
def __init__(self, provider_queue, provider_options=None, *args, **kwargs):
provider_options = provider_options or {}
provider = SQSPro... | normal | {
"blob_id": "041f1d7c482fe4f65e8cc5a508da62ee6ccf59ff",
"index": 6686,
"step-1": "<mask token>\n\n\nclass SNSQueueRoute(Route):\n\n def __init__(self, provider_queue, provider_options=None, *args, **kwargs):\n provider_options = provider_options or {}\n provider = SQSProvider(provider_queue, **p... | [
2,
3,
4,
5
] |
# coding:utf-8
class Solution:
def searchInsert(self, nums, target: int):
n = len(nums)
left = 0
right = n - 1
# 返回大于等于target的第一个索引则用left,否则用right
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
... | normal | {
"blob_id": "9ec1cca08fac2fd976c1f596f7d340befc4eb339",
"index": 2020,
"step-1": "class Solution:\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "class Solution:\n\n def searchInsert(self, nums, target: int):\n n = len(nums)\n left = 0\n right = n ... | [
1,
3,
4,
5,
6
] |
from utils import *
EvinceRelation("different from")
| normal | {
"blob_id": "4f15e2743b33e2f672cd258172da852edb7e4118",
"index": 2103,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nEvinceRelation('different from')\n",
"step-3": "from utils import *\nEvinceRelation('different from')\n",
"step-4": "from utils import *\n\nEvinceRelation(\"different from\")\n\n",
... | [
0,
1,
2,
3
] |
class TreeNode(object):
"""
Implementation of a TreeNode
A TreeNode is a Node with a value and a list of children. Each child is also
a TreeNode
Class invariants:
- self.value: The value for this TreeNode : Any
- self.children: The list of children for this Node : TreeNode List
"""
d... | normal | {
"blob_id": "f7e2fc7b5420b90f733a9520b75555bd869cea98",
"index": 7929,
"step-1": "class TreeNode(object):\n <mask token>\n <mask token>\n\n def add_child(self, value):\n \"\"\"\n Adds a value to the list of children for this node\n\n Parameter value: the value to add to the Tree \n Preco... | [
4,
5,
6,
7
] |
from django.http import HttpResponseRedirect
from django.shortcuts import render
__author__ = 'jhonjairoroa87'
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jsonp.renderers import JSONPRenderer
from django.db import models
from .form import NameForm
def mu... | normal | {
"blob_id": "4c483636316dfa660f10b1aba900813bc3e95ebe",
"index": 9463,
"step-1": "<mask token>\n\n\nclass Divide(APIView):\n renderer_classes = JSONPRenderer,\n\n @staticmethod\n def get(request):\n try:\n first_number = int(request.GET.get('a'))\n second_number = int(reques... | [
3,
6,
9,
10,
11
] |
# pylint: disable=wrong-import-position,wrong-import-order
from gevent import monkey
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from waitlist.app import app
http_server = WSGIServer(("0.0.0.0", 5000), app)
http_server.serve_forever()
| normal | {
"blob_id": "c36625dfbd733767b09fcb5505d029ae2b16aa44",
"index": 7077,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmonkey.patch_all()\n<mask token>\nhttp_server.serve_forever()\n",
"step-3": "<mask token>\nmonkey.patch_all()\n<mask token>\nhttp_server = WSGIServer(('0.0.0.0', 5000), app)\nhttp_serve... | [
0,
1,
2,
3,
4
] |
import urllib.request
class GetData:
key = 'fDs8VW%2BvtwQA8Q9LhBW%2BT2ETVBWWJaITjKfpzDsNJO8ugDsvdboInI16ZD295Txxtxwhc4G3PwMAvxd%2FWvz2gQ%3D%3D&pageNo=1&numOfRows=999'
url = "http://apis.data.go.kr/B552657/ErmctInfoInqireService/getEgytBassInfoInqire?serviceKey=" + key
def main(self):
data = urllib... | normal | {
"blob_id": "58ca520a2f43cef26a95de446f9c7a82819b0b66",
"index": 833,
"step-1": "<mask token>\n\n\nclass GetData:\n key = (\n 'fDs8VW%2BvtwQA8Q9LhBW%2BT2ETVBWWJaITjKfpzDsNJO8ugDsvdboInI16ZD295Txxtxwhc4G3PwMAvxd%2FWvz2gQ%3D%3D&pageNo=1&numOfRows=999'\n )\n url = (\n 'http://apis.data.go... | [
3,
4,
5,
6,
7
] |
A = []
ans = 0
def merge(left, mid, right):
global A
global ans
n1 = mid - left
n2 = right - mid
l = []
r = []
for i in range(n1):
l += [A[left + i]]
for i in range(n2):
r += [A[mid + i]]
l += [10**18]
r += [10**18]
i = 0
j = 0
ans += right - left
for k in range(left, right):
if l[i] <= r[j]:
A[... | normal | {
"blob_id": "dc81ab808720c3a2c76174264c9be9bcdd99c292",
"index": 1265,
"step-1": "<mask token>\n\n\ndef Msort(left, right):\n if left + 1 < right:\n mid = int((left + right) / 2)\n Msort(left, mid)\n Msort(mid, right)\n merge(left, mid, right)\n\n\ndef main():\n global ans\n ... | [
2,
3,
4,
5,
6
] |
import pandas as pd
# read the data
df = pd.read_csv("data/lottery.csv")
# extract needed column
df1 = df[['1','2','3','4','5','6','bonus']]
# translate dataframe to list for convenience
df2 = df1.values.tolist()
# cnt_number is each number's apearance times
cnt_number = []
for i in range(0, 46):
cnt_number.app... | normal | {
"blob_id": "b257e36b3cb4bda28cf18e192aa95598105f5ae9",
"index": 2705,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(0, 46):\n cnt_number.append(0)\nfor i in range(0, len(df2)):\n for j in range(0, 7):\n cnt_index = df2[i][j]\n cnt_number[int(cnt_index)] += 1\nfor k in... | [
0,
1,
2,
3,
4
] |
"""A utility for outputting graphs as pickle files.
To test, run ``openbiolink generate --no-download --no-input --output-format pickle --qual hq``.
"""
import os
import pickle
from typing import Mapping
from openbiolink.edge import Edge
from openbiolink.graph_creation.graph_writer.base import GraphWriter
__all__ =... | normal | {
"blob_id": "58d069f6700149793c3446bdd4677f08eaf301ee",
"index": 670,
"step-1": "<mask token>\n\n\nclass GraphPickleWriter(GraphWriter):\n <mask token>\n\n def write(self, *, tp_nodes, tp_edges: Mapping[str, Edge],\n tp_namespaces, tn_nodes, tn_edges, tn_namespaces):\n \"\"\"Write the graph a... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/python
# coding=utf8
# author: Sun yang
import running
if __name__ == '__main__':
running.go() | normal | {
"blob_id": "12442e4debc7fbf102ab88b42464f4ca8eb91351",
"index": 8454,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n running.go()\n",
"step-3": "import running\nif __name__ == '__main__':\n running.go()\n",
"step-4": "#!/usr/bin/python\r\n# coding=utf8\r\n# author:... | [
0,
1,
2,
3
] |
"""Support for Bond covers."""
import asyncio
import logging
from typing import Any, Callable, Dict, List, Optional
from bond import BOND_DEVICE_TYPE_MOTORIZED_SHADES, Bond
from homeassistant.components.cover import DEVICE_CLASS_SHADE, CoverEntity
from homeassistant.config_entries import ConfigEntry
from homeassistan... | normal | {
"blob_id": "ba9d7b877eda3f7469db58e2ee194b601e3c3e08",
"index": 4227,
"step-1": "<mask token>\n\n\nclass BondCover(CoverEntity):\n <mask token>\n\n def __init__(self, bond: Bond, device: BondDevice):\n \"\"\"Create HA entity representing Bond cover.\"\"\"\n self._bond = bond\n self._d... | [
10,
11,
12,
14,
15
] |
'''
@mainpage Rat15S Compiler
@section intro_sec Introduction
This will become a Rat15S compiler. Currently working on Lexical Analyzer.
@author Reza Nikoopour
@author Eric Roe
'''
def main():
tokens = Lexer()
if __name__ == '__main__':
sys.path.append('Lib')
from lexicalanalyzer import Lexer
mai... | normal | {
"blob_id": "d081abf3cd9bc323486772b4f6235fbbc9022099",
"index": 5498,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n tokens = Lexer()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef main():\n tokens = Lexer()\n\n\nif __name__ == '__main__':\n sys.path.append('Lib')\n ... | [
0,
1,
2,
3
] |
import logging
from typing import List, Optional
import uuid
from pydantic import BaseModel
from obsei.payload import TextPayload
from obsei.preprocessor.base_preprocessor import (
BaseTextPreprocessor,
BaseTextProcessorConfig,
)
logger = logging.getLogger(__name__)
class TextSplitterPayload(BaseModel):
... | normal | {
"blob_id": "151cc71ff1a63897238e2cc55269bd20cc6ee577",
"index": 2336,
"step-1": "<mask token>\n\n\nclass TextSplitterConfig(BaseTextProcessorConfig):\n max_split_length: int = 512\n split_stride: int = 0\n document_id_key: Optional[str]\n\n\nclass TextSplitter(BaseTextPreprocessor):\n\n def preproce... | [
4,
5,
6,
7,
8
] |
import sys
n = int(sys.stdin.readline().rstrip())
l = list(map(int,sys.stdin.readline().rstrip().split()))
m = int(sys.stdin.readline().rstrip())
v = list(map(int,sys.stdin.readline().rstrip().split()))
card = [0] * (max(l)-min(l)+1)
a = min(l)
b = max(l)
for i in l:
card[i-a]+=1
for j in v:
if ((j>=a)&(j<... | normal | {
"blob_id": "6b0081e829f9252e44fa7b81fbfcdd4115856373",
"index": 3748,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in l:\n card[i - a] += 1\nfor j in v:\n if (j >= a) & (j <= b):\n print(card[j - a], end=' ')\n else:\n print(0, end=' ')\n",
"step-3": "<mask token>\nn = i... | [
0,
1,
2,
3,
4
] |
# # -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
import urllib
import urllib2
import cookielib
from excel import *
from user import *
List=[]
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
postdata = urllib.urlencode({'zjh':user(0),'mm... | normal | {
"blob_id": "3c7280bbd23bd3472915da0760efbfd03bfe995d",
"index": 9314,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nreload(sys)\nsys.setdefaultencoding('utf-8')\n<mask token>\nwrite_schedule(cut(get_son(schedule[0], List)))\n",
"step-3": "<mask token>\nreload(sys)\nsys.setdefaultencoding('utf-8')\n<m... | [
0,
1,
2,
3,
4
] |
from setuptools import setup, find_packages
setup(
name="champ",
version="0.0.1",
description='Channel modeling in Python',
url='https://github.com/sgherbst/champ',
author='Steven Herbst',
author_email='sherbst@stanford.edu',
packages=['champ'],
include_package_data=True,
zip_safe=F... | normal | {
"blob_id": "885fd32c9520dfdc2becd6b1a3d0c0f5f5397112",
"index": 7449,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='champ', version='0.0.1', description=\n 'Channel modeling in Python', url='https://github.com/sgherbst/champ',\n author='Steven Herbst', author_email='sherbst@stanford.e... | [
0,
1,
2,
3
] |
# take any non-negative and non-zero integer number and name it c0;if it's even, evaluate a new c0 as c0 ÷ 2;
# otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1;
# if c0 ≠ 1, skip to point 2.
# The hypothesis says that regardless of the initial value of c0,it will always go to 1.
# Write a program which reads on... | normal | {
"blob_id": "e7db3390d30f86e19eee930c48e5f848f41cc579",
"index": 645,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n if c0 % 2 == 0:\n c0 //= 2\n if c0 != 1:\n step += 1\n print(' New value is ', c0, ':', 'step', step)\n continue\n el... | [
0,
1,
2,
3
] |
import numpy as np
class EdgeListError(ValueError):
pass
def check_edge_list(src_nodes, dst_nodes, edge_weights):
"""Checks that the input edge list is valid."""
if len(src_nodes) != len(dst_nodes):
raise EdgeListError("src_nodes and dst_nodes must be of same length.")
if edge_weights is N... | normal | {
"blob_id": "cdbc7d703da69adaef593e6a505be25d78beb7ce",
"index": 7815,
"step-1": "<mask token>\n\n\nclass EdgeListError(ValueError):\n pass\n\n\n<mask token>\n\n\nclass AdjacencyMatrixError(ValueError):\n pass\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass EdgeListError(ValueError):\n pass\n... | [
2,
4,
5,
6,
8
] |
import urllib3
with open('python.jpg', 'rb') as f:
data = f.read()
http = urllib3.PoolManager()
r = http.request('POST', 'http://httpbin.org/post', body=data, headers={
'Content-Type': 'image/jpeg'})
print(r.data.decode())
| normal | {
"blob_id": "98dbc6c3bdc3efb4310a2dbb7b1cc1c89eb4582b",
"index": 7354,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('python.jpg', 'rb') as f:\n data = f.read()\n<mask token>\nprint(r.data.decode())\n",
"step-3": "<mask token>\nwith open('python.jpg', 'rb') as f:\n data = f.read()\nhtt... | [
0,
1,
2,
3
] |
SQL_INSERCION_COCHE = "INSERT INTO tabla_coches(marca, modelo, color, motor, precio) VALUES (%s,%s,%s,%s,%s);"
SQL_LISTADO_COCHES = "SELECT * FROM tabla_coches;"
| normal | {
"blob_id": "fd41e6d8530d24a8a564572af46078be77e8177f",
"index": 6573,
"step-1": "<mask token>\n",
"step-2": "SQL_INSERCION_COCHE = (\n 'INSERT INTO tabla_coches(marca, modelo, color, motor, precio) VALUES (%s,%s,%s,%s,%s);'\n )\nSQL_LISTADO_COCHES = 'SELECT * FROM tabla_coches;'\n",
"step-3": "SQL_INS... | [
0,
1,
2
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Spotlight Volume configuration plist plugin."""
import unittest
# pylint: disable=unused-import
from plaso.formatters import plist as plist_formatter
from plaso.parsers import plist
from plaso.parsers.plist_plugins import spotlight_volume
from tests.parsers.... | normal | {
"blob_id": "6d1b882af2a027f2eecaa3a881dbcab1e3a3b92b",
"index": 9608,
"step-1": "<mask token>\n\n\nclass SpotlightVolumePluginTest(test_lib.PlistPluginTestCase):\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass SpotlightVolumePluginTest(test_lib.Pl... | [
1,
4,
5,
6,
7
] |
import azure.functions as func
import json
from ..common import cosmos_client
def main(req: func.HttpRequest) -> func.HttpResponse:
return func.HttpResponse(
body = json.dumps(cosmos_client.DB.Goals),
mimetype="application/json",
charset="utf-8"
)
# [
# {'amoun... | normal | {
"blob_id": "e38be2890526c640ba8d9db5a376ff57ba9e0aa2",
"index": 8703,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main(req: func.HttpRequest) ->func.HttpResponse:\n return func.HttpResponse(body=json.dumps(cosmos_client.DB.Goals),\n mimetype='application/json', charset='utf-8')\n",
... | [
0,
1,
2,
3
] |
# ELABORE UM PROGRAMA QUE CALCULE O A SER PAGO POR UM PRODUTO CONSIDERANDO O PRECO NORMAL E A FORMA DE PAGAMENTO
# a vista dinehiro ou cheque: 10%
# a vista no cartao: 5%
# 2x: preco normal
# 3x ou mais: 20% de juros | normal | {
"blob_id": "fa271d3888dc60582fa0883eaf9f9ebbdffeed9d",
"index": 3064,
"step-1": "# ELABORE UM PROGRAMA QUE CALCULE O A SER PAGO POR UM PRODUTO CONSIDERANDO O PRECO NORMAL E A FORMA DE PAGAMENTO\n# a vista dinehiro ou cheque: 10%\n# a vista no cartao: 5%\n# 2x: preco normal\n# 3x ou mais: 20% de juros",
"step-... | [
1
] |
from Common.TreasureIsland import TIenv
from .Agent import TIagent
import torch
feature_size = (8, 8)
env = TIenv(frame_rate=0, num_marks=1, feature_size=feature_size)
agent = TIagent(feature_size=feature_size, learning_rate=0.0001)
EPISODE_COUNT = 50000
STEP_COUNT = 40
for episode in range(EPISODE_COUNT):
o... | normal | {
"blob_id": "bf133e73f0c842603dbd7cc3a103a2aa95e2236e",
"index": 4359,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor episode in range(EPISODE_COUNT):\n obs = env.reset()\n agent.reset()\n steps = 0\n if (episode + 1) % 100 == 0:\n state = {'model_state': agent.model.state_dict(), ... | [
0,
1,
2,
3,
4
] |
from common.utils import create_brokers
from Bot import DataGatherBot, ArbitrageBot
import api_config as config
### PAPER 이라고 정의한
# brokers = create_brokers('PAPER', config.CURRENCIES, config.EXCHANGES)
# bot = ArbitrageBot(config, brokers)
# brokers = create_brokers('BACKTEST', config.CURRENCIES, config.EXCHANGES)
#... | normal | {
"blob_id": "4436fa36ec21edb3be467f74d8b9705780535f22",
"index": 6786,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntrade_bot.start(sleep=1)\nprint('Done!')\n",
"step-3": "<mask token>\nbrokers = create_brokers('LIVE', config.CURRENCIES, config.EXCHANGES)\ngp = brokers[2]\ntrade_bot = ArbitrageBot(co... | [
0,
1,
2,
3,
4
] |
from hierarchical_envs.pb_envs.gym_locomotion_envs import InsectBulletEnv
import argparse
import joblib
import tensorflow as tf
from rllab.misc.console import query_yes_no
# from rllab.sampler.utils import rollout
#from pybullet_my_envs.gym_locomotion_envs import Ant6BulletEnv, AntBulletEnv, SwimmerBulletEnv
from hie... | normal | {
"blob_id": "e85f203e71c8fdad86bd82b19104263cca72caf1",
"index": 4817,
"step-1": "from hierarchical_envs.pb_envs.gym_locomotion_envs import InsectBulletEnv\nimport argparse\n\nimport joblib\nimport tensorflow as tf\n\nfrom rllab.misc.console import query_yes_no\n# from rllab.sampler.utils import rollout\n#from p... | [
0
] |
from torch.utils.data.sampler import Sampler
import torch
import random
class SwitchingBatchSampler(Sampler):
def __init__(self, data_source, batch_size, drop_last=False):
self.data_source = data_source
self.batch_size = batch_size
self.drop_last = drop_last
# Divide the indices into two indices groups
se... | normal | {
"blob_id": "6b7bc40ba842ff565e7141fb1d51def99d9ab96a",
"index": 1124,
"step-1": "<mask token>\n\n\nclass SwitchingBatchSampler(Sampler):\n <mask token>\n\n def __iter__(self):\n second_size = self.data_len - self.first_size\n self.first_iter = iter(torch.randperm(self.first_size))\n s... | [
2,
3,
4,
5,
6
] |
# Generated by Django 2.1.7 on 2019-03-14 07:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('training_area', '0002_event'),
]
operations = [
migrations.AddField(
model_name='event',
... | normal | {
"blob_id": "9555ed63b3906ec23c31839691a089aad9d96c63",
"index": 9917,
"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 = [('training_ar... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
from lxml import etree
if __name__ == '__main__':
# xpath可以解析网页中的内容,html或者xml类型的文件都是<>开头结尾,层次非常明显
# data = '''<div>
# <ul>
# <li class="item-0"><a href="http://www.baidu.com">百度</a></li>
# <li class="item-1"><a href="http://www.baidu.com">百度</a></li>
... | normal | {
"blob_id": "52c356b903b1fbb8cbf24c899ed86d7bf134a821",
"index": 6387,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n tree = etree.parse('./data.html')\n result = tree.xpath('//div[@id=\"p\"]//li')\n for r in result:\n print('--------', etree.tostring(r, encod... | [
0,
1,
2,
3
] |
print("2 + 3 * 4 =")
print(2 + 3 * 4)
print("2 + (3 * 4) = ")
print(2 + (3 * 4))
| normal | {
"blob_id": "58d137d614a0d5c11bf4325c1ade13f4f4f89f52",
"index": 3184,
"step-1": "<mask token>\n",
"step-2": "print('2 + 3 * 4 =')\nprint(2 + 3 * 4)\nprint('2 + (3 * 4) = ')\nprint(2 + 3 * 4)\n",
"step-3": "print(\"2 + 3 * 4 =\")\nprint(2 + 3 * 4)\n\nprint(\"2 + (3 * 4) = \")\nprint(2 + (3 * 4))\n",
"step-... | [
0,
1,
2
] |
# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
import datetime
class GoldpriceSpider(scrapy.Spider):
name = 'goldprice'
allowed_domains = ['g-banker.com']
start_urls = ['https://g-banker.com/']
def __init__(self):
self.browser = webdriver.PhantomJS()
self.price =... | normal | {
"blob_id": "e59404149c739a40316ca16ab767cbc48aa9b685",
"index": 3526,
"step-1": "<mask token>\n\n\nclass GoldpriceSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self):\n self.browser = webdriver.PhantomJS()\n self.price = None\n\n def parse(self... | [
4,
5,
6,
7,
8
] |
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | normal | {
"blob_id": "57d1fb805fce2ba75ea2962598e809ba35fd7eb6",
"index": 3490,
"step-1": "<mask token>\n\n\ndef _find_warnings(filename, lines, ast_list, static_is_optional):\n\n def print_warning(node, name):\n print(\"{}:{}: static data '{}'\".format(filename, lines.\n get_line_number(node.start),... | [
2,
3,
4,
5,
6
] |
class Solution:
def asteroidCollision(self, asteroids: List[int]) ->List[int]:
output = []
index = 0
for i in asteroids:
if len(output) == 0:
index = 0
if index == 0:
output.append(i)
index += 1
continue... | normal | {
"blob_id": "fef4749ce7b8668a5a138aa1245010866a85c853",
"index": 2485,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def asteroidCollision(self, asteroids: List[int]) ->List[int]:\n output = []\n index = 0\n for i in astero... | [
0,
1,
2
] |
def erato(n):
m = int(n ** 0.5)
sieve = [True for _ in range(n+1)]
sieve[1] = False
for i in range(2, m+1):
if sieve[i]:
for j in range(i+i, n+1, i):
sieve[j] = False
return sieve
input()
l = list(map(int, input().split()))
max_n = max(l)
prime_l = erato(max_n)
... | normal | {
"blob_id": "28eb1d7a698480028fb64827746b3deec0f66a9a",
"index": 6224,
"step-1": "<mask token>\n",
"step-2": "def erato(n):\n m = int(n ** 0.5)\n sieve = [(True) for _ in range(n + 1)]\n sieve[1] = False\n for i in range(2, m + 1):\n if sieve[i]:\n for j in range(i + i, n + 1, i):... | [
0,
1,
2,
3,
4
] |
import sys
import pathlib
from matplotlib import pyplot as plt
import matplotlib as mpl
script_name = pathlib.Path(sys.argv[0]).stem
FIGURES_DIR = pathlib.Path(
__file__).parents[2] / "figures" / "simulations" / script_name
FIGURES_DIR.mkdir(exist_ok=True, parents=True)
# mpl.rc("text", usetex=True)
# mpl.rc("fo... | normal | {
"blob_id": "fc26574ac8628d7e2896e3e6d055ac61264c7db0",
"index": 1302,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nFIGURES_DIR.mkdir(exist_ok=True, parents=True)\n",
"step-3": "<mask token>\nscript_name = pathlib.Path(sys.argv[0]).stem\nFIGURES_DIR = pathlib.Path(__file__).parents[2\n ] / 'figure... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
import urllib
from urllib2 import HTTPError
from datetime import datetime
from flask.views import MethodView
from flask.ext.login import current_user, login_required
from flask.ext.paginate import Pagination as PaginationBar
from flask import render_template, redirect, url_for, request, jsonify... | normal | {
"blob_id": "1a561ca0268d084c8fdde5de65ce0c7e68154eec",
"index": 4993,
"step-1": "<mask token>\n\n\nclass OperationLog(MethodView):\n decorators = [login_required, admin_required]\n\n def get(self, page):\n per_page = 10\n count = UserOperation.query.count()\n query = UserOperation.que... | [
17,
24,
27,
37,
47
] |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 15:26:08 2019
@author: Qlala
"""
import numpy as np;
import random as rand;
import os;
#os.system("del test_frame2.txt")
#frame=open("test_frame2.txt","w");
#ba=bytearray(rand.getrandbits(8) for _ in range(400000))
#frame.write("0"*1000000)
#frame.close()
#ba.decode('... | normal | {
"blob_id": "281f2f47f9d7f0d87a354d37f9ff2c14a5598068",
"index": 2893,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nos.chdir('test')\nfor i in range(1000):\n t_frame = open('test_f' + str(i), 'w')\n t_frame.write('0' * 1000000)\n t_frame.close()\nos.chdir('..')\n",
"step-3": "<mask token>\ni... | [
0,
1,
2,
3
] |
def most_expensive_item(products):
return max(products.items(), key=lambda p: p[1])[0]
| normal | {
"blob_id": "f1e335d0187aeb78d857bc523eb33221fd2e7e6d",
"index": 7148,
"step-1": "<mask token>\n",
"step-2": "def most_expensive_item(products):\n return max(products.items(), key=lambda p: p[1])[0]\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pywikibot
from pywikibot import pagegenerators
import re
from pywikibot import xmlreader
import datetime
import collections
from klasa import *
def fraz(data):
data_slownie = data[6:8] + '.' + data[4:6] + '.' + data[0:4]
lista_stron = getListFromXML(data)
... | normal | {
"blob_id": "2b928dad60bfb0ba863e9039a5462faa885644f3",
"index": 4643,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef fraz(data):\n data_slownie = data[6:8] + '.' + data[4:6] + '.' + data[0:4]\n lista_stron = getListFromXML(data)\n site = pywikibot.Site('pl', 'wiktionary')\n outputPag... | [
0,
1,
2,
3
] |
from common import *
import serial
CMD_BAUD = chr(129)
BAUD_RATES = [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200]
class Communication(Module):
def __init__(self, parent, port_name, baud_rate):
self.parent = parent
if not isinstance(port_name, str):
ra... | normal | {
"blob_id": "eab5bf4776582349615ad56ee1ed93bc8f868565",
"index": 768,
"step-1": "<mask token>\n\n\nclass Communication(Module):\n <mask token>\n <mask token>\n\n def receive(self, length):\n if not isinstance(length, int):\n raise Exception('Receive length must be an integer.')\n ... | [
3,
6,
7,
9,
10
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.