code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
#!/usr/bin/env python
from imgproc import *
from time import sleep
# open the webcam
#camera = Camera(640, 480)
camera = Camera(320, 240)
#camera = Camera(160, 120)
#while True:
# grab an image from the camera
frame = camera.grabImage()
print frame[x,y]
# open a view, setting the view to the size of the captur... | normal | {
"blob_id": "7dc7c7598c9069e5fbb336bb97161ebb7c74366e",
"index": 2277,
"step-1": "#!/usr/bin/env python\n\nfrom imgproc import *\nfrom time import sleep\n\n# open the webcam\n#camera = Camera(640, 480)\ncamera = Camera(320, 240)\n#camera = Camera(160, 120)\n\n#while True:\n\t\n\t# grab an image from the camera\n... | [
0
] |
import iotsim.readers as readers
import iotsim.networks as networks
import iotsim.constructors as contructors
import yaml
_inventory = dict(
assembly=dict(
Flatline=contructors.Flatline,
Seasaw=contructors.Seesaw,
Pulser=contructors.Pulser,
SimpleActuator=contructors.SimpleActuat... | normal | {
"blob_id": "1450d3b8cc4cef1c5f802e4d84e2211b7467fe12",
"index": 2212,
"step-1": "<mask token>\n\n\ndef inventory(component, component_type):\n try:\n component_inventory = _inventory[component]\n except KeyError:\n raise ValueError('Illegal assembly component: {}'.format(component))\n try... | [
2,
3,
4,
5,
6
] |
class Step:
def __init__(self, action):
self.action = action
def __str__(self) ->str:
return f'Step: {{action: {self.action.__str__()}}}'
def __repr__(self) ->str:
return f'Step: {{action: {self.action.__str__()}}}'
| normal | {
"blob_id": "9adff5da4e26088def9f0e32aa712a1f2b0336ba",
"index": 925,
"step-1": "class Step:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Step:\n <mask token>\n <mask token>\n\n def __repr__(self) ->str:\n return f'Step: {{action: {self.action.__str__()}}}'\n",
"... | [
1,
2,
3,
4
] |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import glob
def des_match(des_l,des_q):
bf=cv2.BFMatcher(cv2.NORM_L2,crossCheck=True)
matches=bf.match(des_l,des_q)
matches = sorted(matches,key=lambda x:x.distance)
return matches
def check_match(matches,threshold,txt):
count=0
if (matches... | normal | {
"blob_id": "4bc61ae2fe6453819a5bbf9cf05976f7800fa7c1",
"index": 4420,
"step-1": "import cv2\nimport numpy as np \nfrom matplotlib import pyplot as plt\nimport glob\n\n\n\n\ndef des_match(des_l,des_q):\n\tbf=cv2.BFMatcher(cv2.NORM_L2,crossCheck=True)\n\tmatches=bf.match(des_l,des_q)\n\tmatches = sorted(matches,k... | [
0
] |
# Generated by Django 2.2.6 on 2020-04-06 16:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fie... | normal | {
"blob_id": "1b71789ba7c2191b433a405723fe6c985c926610",
"index": 8620,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T... | [
0,
1,
2,
3,
4
] |
#While Loop
count = 0
while count<9:
print("Number:",count)
count = count+1
print("Good Bye")
#For Loop
fruits = ['Mango','Grapes','Apple']
for fruit in fruits:
print("current fruits:",fruit)
print("Good bye")
| normal | {
"blob_id": "9b3040fa02cf8f039bac146f8a73384731c56722",
"index": 9142,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile count < 9:\n print('Number:', count)\n count = count + 1\nprint('Good Bye')\n<mask token>\nfor fruit in fruits:\n print('current fruits:', fruit)\nprint('Good bye')\n",
"... | [
0,
1,
2,
3
] |
files = [
"arria2_ddr3.qip"
]
| normal | {
"blob_id": "cad881dd29be16de8375b3ce6e4a437562a05097",
"index": 5426,
"step-1": "<mask token>\n",
"step-2": "files = ['arria2_ddr3.qip']\n",
"step-3": "files = [\n \"arria2_ddr3.qip\"\n ]\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
from compass import models
from compass.models.MetabolicModel import MetabolicModel
def test_sbml_3():
model = models.load_metabolic_model("RECON1_xml")
assert isinstance(model, MetabolicModel)
assert len(model.reactions) == 3742
assert len(model.species) == 2766
def test_sbml_2():
model = model... | normal | {
"blob_id": "863bae04a90143ed942a478c4b71a2269e123bb5",
"index": 2980,
"step-1": "<mask token>\n\n\ndef test_mat():\n model = models.load_metabolic_model('RECON2_mat')\n assert isinstance(model, MetabolicModel)\n assert len(model.reactions) == 7440\n assert len(model.species) == 5063\n\n\ndef test_to... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/env python3
import sql_manager
import Client
from getpass import getpass
from settings import EXIT_CMD
def main_menu():
print("""Welcome to our bank service. You are not logged in.
Please register or login""")
while True:
command = input("guest@hackabank$ ")
if command =... | normal | {
"blob_id": "ee4fd4aef7ecdfbc8ff53028fdedc558814f46a7",
"index": 2383,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef logged_menu(logged_user):\n print('Welcome you are logged in as: ' + logged_user.get_username())\n while True:\n command = input('{}@hackabank# '.format(logged_user.g... | [
0,
1,
2,
3,
4
] |
from datetime import date
def solution(mon: int, day: int) -> str:
return date(2016, mon, day).strftime("%a").upper()
| normal | {
"blob_id": "67385d6d58cc79037660be546d41ea9ba1f790fa",
"index": 5043,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef solution(mon: int, day: int) ->str:\n return date(2016, mon, day).strftime('%a').upper()\n",
"step-3": "from datetime import date\n\n\ndef solution(mon: int, day: int) ->str:... | [
0,
1,
2,
3
] |
from tkinter import *
janela = Tk()
janela.title("Teste de frame")
janela.geometry("800x600")
frame = Frame(janela, width = 300, height = 300, bg = 'red').grid(row = 0, column = 0)
#frames servem para caso queira colocar labels e butoes dentro de uma area especifica
#assim deve se declarar o frame como pai no inicio ... | normal | {
"blob_id": "4ae24d1e39bdcde3313a8a0c8029a331864ba40e",
"index": 6985,
"step-1": "<mask token>\n",
"step-2": "<mask token>\njanela.title('Teste de frame')\njanela.geometry('800x600')\n<mask token>\nLabel(frame, text='lsdakçasd').grid(row=0, column=0)\njanela.mainloop()\n",
"step-3": "<mask token>\njanela = T... | [
0,
1,
2,
3,
4
] |
from django.conf import settings
from django.contrib import messages
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import DetailView, ListView, View
from assessments.models import (Mine, Company,
QuestionCategory, Question, Assessment, Response)
class Home... | normal | {
"blob_id": "d296e528d399ee772039777d139a1d8271711ee9",
"index": 2146,
"step-1": "<mask token>\n\n\nclass AssessmentList(ListView):\n model = Assessment\n\n\nclass AssessmentDetail(DetailView):\n model = Assessment\n\n\nclass AnswerQuestions(ListView):\n model = Question\n\n def post(self, request):\... | [
11,
14,
16,
17,
20
] |
# Copyright 2020 Google LLC.
# 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, softw... | normal | {
"blob_id": "d66945add0726c85b8ac29056269ed55c6eb9369",
"index": 3442,
"step-1": "<mask token>\n\n\ndef _MinutesToMicroseconds(minutes):\n return minutes * 60 * 1000000\n\n\n<mask token>\n\n\nclass _PickMaxRecord(beam.DoFn):\n\n def process(self, data):\n _, streams = data\n time_dicts = []\n... | [
4,
5,
6,
7,
8
] |
# Based on https://dev.to/jemaloqiu/design-pattern-in-python-2-observer-j4
class AbstractObservable():
"""
Abstract Observable
"""
def __init__(self):
self.__observers = []
def add_observer(self, observer):
self.__observers.append(observer)
def remove_observer(self, obse... | normal | {
"blob_id": "3b3f423cfb08413a4135646ea4d3d6dcb5d0cc10",
"index": 662,
"step-1": "<mask token>\n\n\nclass MonitorTruck(AbstractObservable):\n \"\"\"\n Concrete Observable class\n \"\"\"\n\n def __init__(self, name):\n super().__init__()\n self.name = name\n self.__physical_pro... | [
13,
21,
23,
25,
26
] |
"""
Various utilities for neural networks implemented by Paddle. This code is rewritten based on:
https://github.com/openai/guided-diffusion/blob/main/guided_diffusion/nn.py
"""
import math
import paddle
import paddle.nn as nn
class SiLU(nn.Layer):
def forward(self, x):
return x * nn.functional.sigmoid(... | normal | {
"blob_id": "364d70fab02291bafadebea68fee94c0210e2de9",
"index": 4365,
"step-1": "<mask token>\n\n\nclass SiLU(nn.Layer):\n\n def forward(self, x):\n return x * nn.functional.sigmoid(x)\n\n\nclass GroupNorm32(nn.GroupNorm):\n\n def forward(self, x):\n return super().forward(x)\n\n\n<mask toke... | [
9,
11,
12,
14,
16
] |
/home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/rnn/python/ops/rnn_cell.py | normal | {
"blob_id": "8c4aacb0dfacac2cc3e6fa91397ddfed75923fd9",
"index": 1721,
"step-1": "/home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/rnn/python/ops/rnn_cell.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
from django import forms
from django.forms import widgets
from tsuru_dashboard import settings
import requests
class ChangePasswordForm(forms.Form):
old = forms.CharField(widget=forms.PasswordInput())
new = forms.CharField(widget=forms.PasswordInput())
confirm = forms.CharField(widget=forms.PasswordInput... | normal | {
"blob_id": "27fc11ae68531c7dbafdcf134f0eef019210e2de",
"index": 8347,
"step-1": "<mask token>\n\n\nclass PasswordRecoveryForm(forms.Form):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TokenRequestForm(forms.Form):\n email = forms.EmailField()\n\n def send(self):\n url = '{0}/use... | [
14,
15,
18,
19,
20
] |
class Config:
DEBUG = False
TESTING = False
# mysql+pymysql://user:password@host:port/database
# SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://gjp:976431@49.235.194.73:3306/test'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1:3306/mydb'
SQLALCHEMY_TRACK_MODIFICATIONS = True
SECR... | normal | {
"blob_id": "d89f0ef24d8e8d23a77cbbb0ae8723c7dec8c00a",
"index": 4954,
"step-1": "<mask token>\n\n\nclass DevelopmentConfig(Config):\n <mask token>\n <mask token>\n\n\nclass ProductionConfig(Config):\n DATABASE_URI = ''\n\n\nclass TestingConfig(Config):\n TESTING = True\n",
"step-2": "<mask token>\... | [
5,
6,
7,
8,
9
] |
import csv
import Feature_extraction as urlfeature
import trainer as tr
import warnings
warnings.filterwarnings("ignore")
def resultwriter(feature, output_dest):
flag = True
with open(output_dest, 'w') as f:
for item in feature:
w = csv.DictWriter(f, item[1].keys())
if flag:
... | normal | {
"blob_id": "9d190face528d1a237f4c92bfb94a399f61a5af2",
"index": 9317,
"step-1": "<mask token>\n\n\ndef resultwriter(feature, output_dest):\n flag = True\n with open(output_dest, 'w') as f:\n for item in feature:\n w = csv.DictWriter(f, item[1].keys())\n if flag:\n ... | [
4,
5,
6,
7,
8
] |
import os, copy
from a import Moon, updateOneMoon, updateAllMoons
file_path = os.path.dirname(os.path.realpath(__file__))
input_path = file_path + "/b.in.txt"
inpt = open(input_path, 'r')
moons = []
for line in inpt:
new_moon = Moon(line)
moons.append(new_moon)
initial_moon_position = copy.deepcopy(moons)... | normal | {
"blob_id": "1f114b4716a44f5370495297511c305ecbb680c3",
"index": 7556,
"step-1": "import os, copy\nfrom a import Moon, updateOneMoon, updateAllMoons\n\nfile_path = os.path.dirname(os.path.realpath(__file__))\n\ninput_path = file_path + \"/b.in.txt\"\n\ninpt = open(input_path, 'r')\n\nmoons = []\n\nfor line in in... | [
0
] |
import re
import z3
digit_search = re.compile('\-?\d+')
def get_sensor_beacon(data_in):
sensors = {}
beacons = set()
for line in data_in:
s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))
sensors[(s_x, s_y)] = abs(s_x - b_x) + abs(s_y - b_y)
beacons.add((b_x, b_y))
... | normal | {
"blob_id": "c4bd55be86c1f55d89dfcbba2ccde4f3b132edcb",
"index": 9981,
"step-1": "<mask token>\n\n\ndef manhat(point_one, point_two):\n return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])\n\n\ndef find_edge(sensors, pos, dir):\n x, row = pos\n closer = []\n for sensor in sensor... | [
3,
4,
5,
7,
9
] |
L = [
[
"0",
"0",
"00"
],[
"..0",
"000"
],[
"00",
".0",
".0"
], [
"000",
"0"
]
]
J = [
[
".0",
".0",
"00"
],[
"0..",
"000"
],[
"00",
"0",
"0"... | normal | {
"blob_id": "5718eab8c5fac4cb7bfa1b049b63ca1e30610247",
"index": 9554,
"step-1": "<mask token>\n",
"step-2": "L = [['0', '0', '00'], ['..0', '000'], ['00', '.0', '.0'], ['000', '0']]\nJ = [['.0', '.0', '00'], ['0..', '000'], ['00', '0', '0'], ['000', '..0']]\nO = [['00', '00']]\nT = [['000', '.0'], ['0', '00',... | [
0,
1,
2
] |
#####################
# Aufgabe 2, 13.7 #
# v1.0 #
# baehll #
# 04.05.2018 #
#####################
class Pinnwand:
def __init__(self):
self.__zettel = []
def hefteAn(self, notiz):
#Analyse des Textes
prio = notiz.count("!")
self.__zettel.ap... | normal | {
"blob_id": "382a3b8bcd07c7098cecf2b770e46dfff50eeb98",
"index": 2695,
"step-1": "class Pinnwand:\n\n def __init__(self):\n self.__zettel = []\n\n def hefteAn(self, notiz):\n prio = notiz.count('!')\n self.__zettel.append((prio, notiz))\n <mask token>\n\n def __str__(self):\n ... | [
4,
5,
6,
7,
8
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
CELERY_TIMEZONE = 'Asia/Shanghai'
# CELERY_RESULT_BACKEND='redis://localhost:6379/1'
# BROKER_URL='redis://localhost:6379/2'
BROKER_BACKEND = 'mongodb' # mongodb作为任务队列(或者说是缓存)
<<<<<<< HEAD
BROKER_URL = 'mongodb://10.6.0.149:27017/' ... | normal | {
"blob_id": "9f01483aaa744972fae358577e6f093bd491f357",
"index": 7514,
"step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nCELERY_TIMEZONE = 'Asia/Shanghai'\n# CELERY_RESULT_BACKEND='redis://localhost:6379/1'\n# BROKER_URL='redis://localhost:6379/2'\nBROKER_BACKEN... | [
0
] |
"""
Given a string s. Return all the words vertically in the same
order in which they appear in s.
Words are returned as a list of strings, complete with spaces
when is necessary. (Trailing spaces are not allowed).
Each word would be put on only one column and that in one column
there will... | normal | {
"blob_id": "7c2897dcb732e75d7328e8c0484d5bd7f3b56e6f",
"index": 9190,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef StringToList(input_string):\n word_list = []\n word = ''\n for i in range(0, len(input_string)):\n if input_string[i] == ' ':\n word_list.append(word)\n... | [
0,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
from numpy import *
def loadDataSet(fileName, delim = '\t'):
fr = open(fileName)
stringArr = [line.strip().split(delim) for line in fr.readlines()]
datArr = [map(float,line) for line in stringArr]
return mat(datArr)
def pca(dataMat, topNfeat = 9999999):
meanVals = mean(dat... | normal | {
"blob_id": "5f00cd446b219203c401799ba7b6205c7f1f8e9f",
"index": 3510,
"step-1": "<mask token>\n\n\ndef replaceNanWithMean():\n dataMat = loadDataSet('secom.data.txt', '')\n numFeat = shape(dataMat)[1]\n for i in range(numFeat):\n meanVal = mean(dataMat[nonzero(~isnan(dataMat[:, i].A))[0], i])\n ... | [
1,
2,
3,
4,
5
] |
from django.http.response import HttpResponse
from django.shortcuts import render , HttpResponse
import requests
from django.conf import settings
from .forms import WeatherForm
# Create your views here.
def get_weather(request):
form = WeatherForm()
error = ""
output = {}
if request.method == 'POST':
... | normal | {
"blob_id": "be5a683309317f1f6ebc20ad3511fd2b2510e806",
"index": 5535,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_weather(request):\n form = WeatherForm()\n error = ''\n output = {}\n if request.method == 'POST':\n form = WeatherForm(request.POST)\n if form.is_va... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-12-19 15:17
from __future__ import absolute_import
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import Count
from tqdm import tqdm
def remove_duplicate_legal_reasons(apps, purpose_slug, source_obje... | normal | {
"blob_id": "6c86b4823756853bb502b34492ac8ad0a75daf7e",
"index": 7036,
"step-1": "<mask token>\n\n\ndef remove_duplicate_legal_reasons(apps, purpose_slug,\n source_object_content_type, source_object_id):\n LegalReason = apps.get_model(u'gdpr', u'LegalReason')\n duplicate_legal_reason_qs = LegalReason.ob... | [
4,
5,
6,
7,
8
] |
from rest_framework import serializers
class BillBaseSerializer(serializers.Serializer):
vendor = serializers.CharField(required=False)
amount = serializers.FloatField()
bill_date = serializers.DateField()
due_date = serializers.DateField()
class BillListSerializer(BillBaseSerializer):
id = seri... | normal | {
"blob_id": "23160c2f030b0bd862360e944fbbc283c6cb45b2",
"index": 6625,
"step-1": "<mask token>\n\n\nclass BillListSerializer(BillBaseSerializer):\n id = serializers.SerializerMethodField()\n\n def get_id(self, object):\n return object.key.id()\n\n\nclass BillCreateSerializer(BillBaseSerializer):\n ... | [
9,
10,
11,
12
] |
import re
class CoordinatesDataParser:
def __init__(self):
return
def get_coords(self, response):
html = response.xpath('.//body').extract_first()
longitude = re.search(r'-\d+\.\d{5,}', html)
longitude = longitude.group() if longitude else None
if longitude:
... | normal | {
"blob_id": "7d5f41cfa2d5423c6db2678f1eb8160638b50c02",
"index": 1835,
"step-1": "<mask token>\n\n\nclass CoordinatesDataParser:\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CoordinatesDataParser:\n\n def __init__(self):\n return\n <mask token>\n",
"step-3": "<mask ... | [
1,
2,
3,
4,
5
] |
import requests
# qq推送 申请参考https://cp.xuthus.cc/
key = ''
def main():
try:
api = 'http://t.weather.itboy.net/api/weather/city/' # API地址,必须配合城市代码使用
city_code = '101070201' # 进入https://where.heweather.com/index.html查询你的城市代码
tqurl = api + city_code
response = requests.get(tqurl)
... | normal | {
"blob_id": "4048d7bfc7922ef76d98d43e1ea266e732e0982e",
"index": 9111,
"step-1": "<mask token>\n\n\ndef main():\n try:\n api = 'http://t.weather.itboy.net/api/weather/city/'\n city_code = '101070201'\n tqurl = api + city_code\n response = requests.get(tqurl)\n d = response.j... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/python
try:
fh = open('testfile','w')
try:
fh.write('This is my test file for this exception')
finally:
print "Going to close file"
fh.close()
except IOError:
print" Error: can\'t find file or read data"
| normal | {
"blob_id": "a538c6d8c9f99bc37def5817a54c831393c051f3",
"index": 7395,
"step-1": "#!/usr/bin/python\n\n\ntry:\n fh = open('testfile','w')\n try:\n fh.write('This is my test file for this exception')\n finally:\n print \"Going to close file\"\n fh.close()\n\nexcept IOError:\n prin... | [
0
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-01-15 17:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Person... | normal | {
"blob_id": "4acdde648b5ec32c078579e725e6ae035298f25a",
"index": 3997,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = T... | [
0,
1,
2,
3,
4
] |
from .compat import reverse, action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework import pagination
from rest_framework import renderers
from . import registry
from .serializers import RunSerializer, RecordSerializer
from .models import Run
from .setti... | normal | {
"blob_id": "11a0c3307994a90d1d4de67d442ffa355e11e13b",
"index": 6836,
"step-1": "<mask token>\n\n\nclass RunViewSet(ModelViewSet):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def template_na... | [
11,
13,
17,
18,
22
] |
from sys import getsizeof
# using parenthesis indicates that we are creating a generator
a = (b for b in range(10))
print(getsizeof(a))
c = [b for b in range(10)]
# c uses more memory than a
print(getsizeof(c))
for b in a:
print(b)
print(sum(a)) # the sequence has disappeared
| normal | {
"blob_id": "2ee4b31f880441e87c437d7cc4601f260f34ae24",
"index": 6574,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(getsizeof(a))\n<mask token>\nprint(getsizeof(c))\nfor b in a:\n print(b)\nprint(sum(a))\n",
"step-3": "<mask token>\na = (b for b in range(10))\nprint(getsizeof(a))\nc = [b for... | [
0,
1,
2,
3,
4
] |
import json
import logging
import numpy as np
from python_speech_features import mfcc
from format_converters import get_segment
from schemas import *
from chains.mfcc import Mfcc
logger = logging.getLogger()
class MfccLocal(Mfcc):
"""
MfccLocal computes Mfcc features for each phoneme from the sample
tha... | normal | {
"blob_id": "44214492dd7283da4b9a77bd2a1fa9d9c0643ff2",
"index": 1188,
"step-1": "<mask token>\n\n\nclass MfccLocal(Mfcc):\n <mask token>\n abstract_class = False\n\n @staticmethod\n def sample_result_filename(out_sample_path):\n return f'{out_sample_path[:-5]}_mfcc_result.json'\n\n @static... | [
6,
7,
8,
9,
10
] |
from django import forms
BET_CHOICES = (
('1', 'Will rise'),
('x', 'Will stay'),
('2', 'Will fall'),
)
class NormalBetForm(forms.Form):
song = forms.CharField()
data = forms.ChoiceField(BET_CHOICES)
| normal | {
"blob_id": "2f6d51d5c14ddc1f6cd60ab9f3b5d4a879d14af0",
"index": 4590,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass NormalBetForm(forms.Form):\n song = forms.CharField()\n data = forms.ChoiceField(BET_CHOICES)\n",
"step-3": "<mask token>\nBET_CHOICES = ('1', 'Will rise'), ('x', 'Will ... | [
0,
2,
3,
4,
5
] |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... | normal | {
"blob_id": "b694c834555843cc31617c944fa873f15be2b9c5",
"index": 9598,
"step-1": "<mask token>\n\n\nclass IntegrityConstraintViolationError(_base.EdgeDBError):\n <mask token>\n\n\nclass MissingRequiredPointerError(IntegrityConstraintViolationError):\n code = '23502'\n\n def __init__(self, msg, *, source... | [
17,
18,
19,
23,
24
] |
botnet = open("bots.txt","r")
bots = botnet.read()
print(bots.split('\n'))
botnet.close() | normal | {
"blob_id": "ea876d903263c907f63b2f37a81f2576345dae62",
"index": 7692,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(bots.split('\\n'))\nbotnet.close()\n",
"step-3": "botnet = open('bots.txt', 'r')\nbots = botnet.read()\nprint(bots.split('\\n'))\nbotnet.close()\n",
"step-4": "botnet = open(\"b... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import gc
import logging
import os
import mock
import sys
import time
from shellbot import Context, Engine
from shellbot.i18n import Localization, localization as l10n, _
class LocalizationTests(unittest.TestCase):
def test_default(self):
lo... | normal | {
"blob_id": "debd51b923a6fc3b278a5083478bfb271a5913a8",
"index": 162,
"step-1": "<mask token>\n\n\nclass LocalizationTests(unittest.TestCase):\n\n def test_default(self):\n logging.info('*** default ***')\n localization = Localization()\n text = 'hello world'\n self.assertEqual(loc... | [
3,
4,
5,
6,
7
] |
"""
A module to generate simulated 2D time-series SOSS data
Authors: Joe Filippazzo
"""
import os
from pkg_resources import resource_filename
import multiprocessing
import time
from functools import partial
import warnings
import numpy as np
from astropy.io import fits
from bokeh.plotting import figure, show
from ho... | normal | {
"blob_id": "9f478df4ff19cfe6c6559b6489c874d49377b90e",
"index": 4949,
"step-1": "<mask token>\n\n\ndef calculate_psf_tilts():\n \"\"\"\n Calculate the tilt of the psf at the center of each column\n using all binned pixels in the given wavelength calibration file\n for both orders and save to file\n ... | [
7,
10,
11,
13,
14
] |
a=int(input("Choose a number: "))
for x in range(1,100000):
b=a*x;
print(x, '*', a,'=',b)
if b>100:
break
| normal | {
"blob_id": "043dd97d4d4ade29536a83c3557a34db3a4cb0f9",
"index": 2002,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor x in range(1, 100000):\n b = a * x\n print(x, '*', a, '=', b)\n if b > 100:\n break\n",
"step-3": "a = int(input('Choose a number: '))\nfor x in range(1, 100000):\n ... | [
0,
1,
2,
3
] |
from os import walk
from ccal import VERSION
from setuptools import setup
package_data = []
for directory_path, directory_names, file_names in walk("data"):
for file_name in file_names:
package_data.append("{}/{}".format(directory_path, file_name))
setup(
name="ccal",
version=VERSION,
desc... | normal | {
"blob_id": "11d0e84767f7e9e4687962a3a5c58dc882cc4dd2",
"index": 1934,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor directory_path, directory_names, file_names in walk('data'):\n for file_name in file_names:\n package_data.append('{}/{}'.format(directory_path, file_name))\nsetup(name='cca... | [
0,
1,
2,
3,
4
] |
import pyreadstat
import matplotlib.pyplot as plt
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
from sklearn.preprocessing import LabelEncoder
# Set random seed for reproducible results
np.random.seed(1)
# Read sav file and create a pandas dataf... | normal | {
"blob_id": "7282af4186a976296ac50840e9169b78a66e118b",
"index": 1683,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nnp.random.seed(1)\n<mask token>\nencoder.fit(Y)\n<mask token>\nmodel.add(Dense(5, input_dim=len(X[0])))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(len(onehot_Y[0]), activat... | [
0,
1,
2,
3,
4
] |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: sx
import string
def reverse(text):
"""将字符串翻转"""
return text[::-1]
def is_palindrome(text):
print(e for e in text if e.isalnum())
# 去掉标点空格
m = ''.join(e for e in text if e.isalnum())
print(m)
"""是否是回文数"""
return m == revers... | normal | {
"blob_id": "03a1f9f533f7550db32fa25578ef2f7f4c741510",
"index": 8583,
"step-1": "<mask token>\n\n\ndef reverse(text):\n \"\"\"将字符串翻转\"\"\"\n return text[::-1]\n\n\ndef is_palindrome(text):\n print(e for e in text if e.isalnum())\n m = ''.join(e for e in text if e.isalnum())\n print(m)\n \"\"\"... | [
2,
3,
4,
5,
6
] |
numbers = [3,4,6,7]
# 0 1 2 3
print(numbers)
print(numbers[1])
print(numbers[-1])
numbers[1] = 3
print(numbers)
del numbers[1]
print(numbers)
numbers.append(17)
print(numbers)
numbers.insert(2,5)
print(numbers)
numbers.sort()
print(numbers) | normal | {
"blob_id": "34d3eebf6ccb19f891ccbb16db47cd6412f1cb0f",
"index": 1155,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(numbers)\nprint(numbers[1])\nprint(numbers[-1])\n<mask token>\nprint(numbers)\ndel numbers[1]\nprint(numbers)\nnumbers.append(17)\nprint(numbers)\nnumbers.insert(2, 5)\nprint(number... | [
0,
1,
2,
3
] |
import numpy as np
from math import *
from visual import *
from visual.graph import *
def energy2(n):
return ((n*h/L)**2)/(8*m)*convert
def factorial(n):
out=1
for x in range(n):
out=out*(x+1)
return out
def bosonconfigs(numelvl,numpart):
x=numpart
n=numelvl
out=choose(x+n-1,x)
... | normal | {
"blob_id": "42f656898481768ea0bf1ca0b6afbe06de9dd597",
"index": 4132,
"step-1": "<mask token>\n\n\ndef energy2(n):\n return (n * h / L) ** 2 / (8 * m) * convert\n\n\ndef factorial(n):\n out = 1\n for x in range(n):\n out = out * (x + 1)\n return out\n\n\n<mask token>\n\n\ndef configs(x, elvl,... | [
7,
10,
12,
14,
15
] |
'''
Character class
'''
import pygame
from time import sleep
class Character:
def __init__(self, screen, side_length, border_width, valid_points, start_point, end_point, current_position, a_colour, na_colour,\
keys=None, k_colour=None):
self.screen = screen # pygame screen
self.side_length = side_length # ... | normal | {
"blob_id": "f7f96b19bdc20f732566709a7801002fe49d49eb",
"index": 3214,
"step-1": "<mask token>\n\n\nclass Character:\n\n def __init__(self, screen, side_length, border_width, valid_points,\n start_point, end_point, current_position, a_colour, na_colour, keys\n =None, k_colour=None):\n sel... | [
5,
6,
7,
8,
9
] |
# CIS 117 Python Programming - Lab 10
# Bryce DesBrisay
def middle(string):
characters = list(string)
length = len(characters)
middleNum = round((length + .5) / 2)
if length % 2 == 0:
return characters[middleNum - 1] + characters[middleNum]
else:
return characters[middleNum - 1]
de... | normal | {
"blob_id": "d60690892eddda656c11470aacd1fdc9d07a721a",
"index": 3563,
"step-1": "<mask token>\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\n<mask token>\n\n\ndef isPalindrome(string... | [
3,
4,
5,
6,
7
] |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 27 10:34:15 2021
@author: Ivan
課程教材:行銷人轉職爬蟲王實戰|5大社群平台+2大電商
版權屬於「楊超霆」所有,若有疑問,可聯絡ivanyang0606@gmail.com
第一章 爬蟲基本訓練
Html爬蟲Post教學-台灣股市資訊網
"""
import requests
from bs4 import BeautifulSoup
# 要抓取的網址
url = 'https://goodinfo.tw/StockInfo/StockDividendPolicy.asp?S... | normal | {
"blob_id": "a5918679b6e3a9bde54808264d9526c6a191578f",
"index": 7737,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsoup.find('td', {'style': 'color:red'}).text\n",
"step-3": "<mask token>\nurl = 'https://goodinfo.tw/StockInfo/StockDividendPolicy.asp?STOCK_ID=2002'\nheaders = {'User-Agent':\n 'Moz... | [
0,
1,
2,
3,
4
] |
from .base import Base
class Files(Base):
endpoint = "/files"
def upload_file(self, channel_id, files):
return self.client.post(self.endpoint, data={"channel_id": channel_id}, files=files)
def get_file(self, file_id):
return self.client.get(
self.endpoint + "/" + file_id,
... | normal | {
"blob_id": "0686dec7f3dc23f01ffff41f611a1bb597bb5352",
"index": 829,
"step-1": "<mask token>\n\n\nclass Files(Base):\n <mask token>\n\n def upload_file(self, channel_id, files):\n return self.client.post(self.endpoint, data={'channel_id':\n channel_id}, files=files)\n\n def get_file(s... | [
5,
6,
8,
9,
10
] |
import cv2
img = cv2.imread('imgs/1.png')
pixel = img[100, 100]
img[100, 100] = [57, 63, 99] # 设置像素值
b = img[100, 100, 0] # 57, 获取(100, 100)处, blue通道像素值
g = img[100, 100, 1] # 63
r = img[100, 100, 2] # 68
r = img[100, 100, 2] = 99 # 设置red通道
# 获取和设置
piexl = img.item(100, 100, 2)
img.itemset((100, 100, 2), 99)
| normal | {
"blob_id": "d13f06afeac938fc2cf4d3506b3f68c6de9de210",
"index": 6596,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nimg.itemset((100, 100, 2), 99)\n",
"step-3": "<mask token>\nimg = cv2.imread('imgs/1.png')\npixel = img[100, 100]\nimg[100, 100] = [57, 63, 99]\nb = img[100, 100, 0]\ng = img[100, 100, ... | [
0,
1,
2,
3,
4
] |
from collections import deque
n = -1
D = [(-1 , 0) , (0 , 1) , (1 , 0) , (0 , -1)]
B = -1
up = 0
right = 1
down = 2
left = 3
dic = {}
dic[0] = 'up'
dic[1] = 'right'
dic[2] = 'down'
dic[3] = 'left'
def possi(y , x):
global n
if y < 0 or y >= n or x < 0 or x >= n or B[y][x]:
return False
return True
... | normal | {
"blob_id": "feb912ac899208618f00c894458c1fda7a402652",
"index": 1452,
"step-1": "<mask token>\n\n\ndef possi(y, x):\n global n\n if y < 0 or y >= n or x < 0 or x >= n or B[y][x]:\n return False\n return True\n\n\ndef move(d, ay, ax, by, bx):\n ay += D[d][0]\n by += D[d][0]\n ax += D[d][... | [
4,
5,
6,
7,
8
] |
from envs import DATASET_FOLDER
from os.path import join
import json
import collections
from tqdm import tqdm
def add_space(context_list):
space_context = []
for idx, context in enumerate(context_list):
space_sent_list = []
sent_list = context[1]
if idx == 0:
for sent_idx, s... | normal | {
"blob_id": "a179d3d2f04a101eaa60b5964c2b1cd77071633f",
"index": 5344,
"step-1": "<mask token>\n\n\ndef find_answer(answer, sents):\n for s_idx, sent in enumerate(sents):\n if answer in sent:\n return s_idx\n return -1\n\n\n<mask token>\n\n\ndef docred_refiner():\n DOCRED_OUTPUT_PROCES... | [
3,
5,
6,
7,
8
] |
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print(calc(*[1, 2, 3]))
| normal | {
"blob_id": "a9ea3db019435733b5782d69450942373bb828e5",
"index": 9304,
"step-1": "<mask token>\n",
"step-2": "def calc(*numbers):\n sum = 0\n for n in numbers:\n sum = sum + n * n\n return sum\n\n\n<mask token>\n",
"step-3": "def calc(*numbers):\n sum = 0\n for n in numbers:\n su... | [
0,
1,
2
] |
# obtain the dataset
import pandas as pd
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
#titanic.info()
print(titanic.head())
# preprocessing
x = titanic.drop(['row.names', 'name', 'survived'], axis=1)
y = titanic['survived']
x['age'].fillna(x['age'].mean(),... | normal | {
"blob_id": "f1475d651c3b52611657a9767ad62796b55d8711",
"index": 3676,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(titanic.head())\n<mask token>\nx['age'].fillna(x['age'].mean(), inplace=True)\nx.fillna('UNKNOWN', inplace=True)\n<mask token>\ndtc.fit(x_train, y_train)\nprint(dtc.score(x_test, y_... | [
0,
1,
2,
3,
4
] |
# coding: utf-8
"""
CityPay POS API
CityPay Point of Sale API for payment with card present devices including EMV readers and contactless POS readers. The API is available from https://github.com/citypay/citypay-pos-api The API makes it simple to add EMV and contactless card acceptance to iOS, Android, Tabl... | normal | {
"blob_id": "775ac823f6784510fa919b08ee4150eb500710c4",
"index": 6423,
"step-1": "# coding: utf-8\n\n\"\"\"\n CityPay POS API\n\n CityPay Point of Sale API for payment with card present devices including EMV readers and contactless POS readers. The API is available from https://github.com/citypay/citypay-... | [
0
] |
#-*- coding:utf-8 -*-
"""
Django settings for hehotel project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.... | normal | {
"blob_id": "045ad27f46c2090ed39a49144c3aa17093b0d9c7",
"index": 7094,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nBASE_DIR = os.path.dirname(__file__)\nSECRET_KEY = '6@j!6%foulnrume$wc7i5cwc2ppf6hcxoa&xh_vtanfy_rc@yc'\nDEBUG = True\nEXCEPTION_INGORE_AJAX = True\nTEMPLATE_DEBUG = True\nTEMPLATE_DIRS =... | [
0,
1,
2,
3
] |
from datetime import timedelta
from django import template
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.utils import timezone
from api.analysis import *
from api.models import Service
register = template.Library()
# ... | normal | {
"blob_id": "43792a647243b9d667d6d98b62a086d742e8e910",
"index": 6093,
"step-1": "<mask token>\n\n\n@register.filter\ndef td_humanize(diff):\n if diff.total_seconds() < 0:\n return 'Meni jo!'\n days = diff.days\n if days >= 7:\n weeks, days = divmod(days, 7)\n result = str(weeks) + ... | [
2,
7,
8,
9,
12
] |
def decorate():
print('hi')
@decorate
def decorated():
print('decorated')
decorate()
| normal | {
"blob_id": "1328d62769ee2a0309021ff40fdbf78a2c5570c9",
"index": 9678,
"step-1": "<mask token>\n",
"step-2": "def decorate():\n print('hi')\n\n\n<mask token>\n",
"step-3": "def decorate():\n print('hi')\n\n\n@decorate\ndef decorated():\n print('decorated')\n\n\n<mask token>\n",
"step-4": "def deco... | [
0,
1,
2,
3
] |
def is_palindrome_v2(word):
'''(string)->boolean
returns if word is palindrome (ignores white space)'''
if len(word) < 2:
return True
if(not word[0].isalpha() or not word[1].isalpha()):
if(word[0].isalpha()):
return is_palindrome_v2(word[:-1])
if(word[-1].isal... | normal | {
"blob_id": "1fbe269c9c09fe58b0df1ebd4354cf9dc31a2f90",
"index": 7739,
"step-1": "<mask token>\n",
"step-2": "def is_palindrome_v2(word):\n \"\"\"(string)->boolean\n returns if word is palindrome (ignores white space)\"\"\"\n if len(word) < 2:\n return True\n if not word[0].isalpha() or not ... | [
0,
1,
2
] |
__author__ = 'Orka'
from movie_list import MovieList
from movie_random import MovieRandom
from remove_chosen_movie_from_list import RemoveChosenMovieFromList
from save_list_to_CSV import SaveListToCSV
from length_limit import LengthLimit
file_name = 'cinema.csv'
function = 'r+'
filename_save = 'cinema.csv'
f... | normal | {
"blob_id": "e35a106a3852a7a004fdae6819d4075e1fe929d6",
"index": 4373,
"step-1": "<mask token>\n\n\nclass LaunchMovieLottery(object):\n <mask token>\n\n def movie_list(self):\n movie_list = MovieList(file_name, function)\n self.return_movie_list = movie_list.return_movie_list()\n self.... | [
5,
6,
7,
8,
9
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('home_application', '0019_auto_20170809_1810'),
]
operations = [
migrations.CreateModel(
... | normal | {
"blob_id": "a1db566f4da16e7725212aeab29e946ef7c1672e",
"index": 5610,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('home_applic... | [
0,
1,
2,
3,
4
] |
import sys
import numpy as np
import bpcs as bp
from PIL import Image
if len(sys.argv)<4:
print("USAGE: {0} <PATH> <COLOR> <BIT>".format(sys.argv[0]))
print(" PATH: image path")
print(" COLOR: GRAY=-1, RED=0, GREEN=1, BLUE=2")
print(" BIT : 0~7 (0:MSB, 7:LSB)")
exit(1)
PATH = sys... | normal | {
"blob_id": "95ea811d38c314f5f19294500e16bae3d00d4fff",
"index": 1328,
"step-1": "<mask token>\n\n\ndef merge_bitplane_to_image(bitplane, arr, color):\n arr = bp.to_image(arr)\n img = np.zeros(arr.shape)\n img[:, :, color] = bitplane\n return img\n\n\n<mask token>\n",
"step-2": "<mask token>\nif le... | [
1,
2,
3,
4,
5
] |
import pandas as pd
from pandas import Series, DataFrame
def load_excel(data_path, data_name, episode_Num):
data_name = data_name + str(episode_Num) + '.xlsx'
dataframe = pd.read_excel(data_path + data_name, index_col=0)
return dataframe
def dataframe_to_numpy(dataframe):
numpy_array = dataframe.to_... | normal | {
"blob_id": "b63dc8b9aa2f0593a4a7eb52a722a9c4da6c9e08",
"index": 7804,
"step-1": "<mask token>\n\n\ndef dataframe_to_numpy(dataframe):\n numpy_array = dataframe.to_numpy()\n return numpy_array\n\n\n<mask token>\n\n\ndef data_slice(data, num_of_data):\n data = data[:, 1:num_of_data + 1]\n return data\... | [
2,
4,
5,
6
] |
# Goal: Let's Review
# Enter your code here. Read input from STDIN. Print output to STDOUT
T = int(input())
# Iterate through each inputted string
for i in range(T):
even = ''
odd = ''
s = str(input())
for i in range(len(s)):
if (i % 2 == 0):
even = even + s[i]
else:
... | normal | {
"blob_id": "f45313e4e8f3ecba0c7dc0288d9d5ec4e26f0ba6",
"index": 5284,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(T):\n even = ''\n odd = ''\n s = str(input())\n for i in range(len(s)):\n if i % 2 == 0:\n even = even + s[i]\n else:\n odd ... | [
0,
1,
2,
3
] |
staff = ['инженер-конструктор Игорь', 'главный бухгалтер МАРИНА',
'токарь высшего разряда нИКОЛАй', 'директор аэлита']
def employee_name(name):
getting_a_name = name.split()
name_staff = getting_a_name[-1]
name_staff = name_staff.capitalize()
return name_staff
i = 0
while i < len(staff):
nam... | normal | {
"blob_id": "4c4275b96d3eceb5ff89a746c68d7f8736a1c2a5",
"index": 8561,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef employee_name(name):\n getting_a_name = name.split()\n name_staff = getting_a_name[-1]\n name_staff = name_staff.capitalize()\n return name_staff\n\n\n<mask token>\n",... | [
0,
1,
2,
3
] |
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
ts=robjects.r('ts')
forecast = importr("forecast", lib_loc = "C:/Users/sand9888/Documents/sand9888/R/win-library/3.3")
import os
import pandas as pd
from rpy2.robjects import pandas2ri
pandas2ri.activate()
train = os.path.join('C:/DAT203.3x/... | normal | {
"blob_id": "e00cbe6e177ee841c6e64de842e5b8f95463b3a8",
"index": 2169,
"step-1": "<mask token>\n",
"step-2": "<mask token>\npandas2ri.activate()\n<mask token>\n",
"step-3": "<mask token>\nts = robjects.r('ts')\nforecast = importr('forecast', lib_loc=\n 'C:/Users/sand9888/Documents/sand9888/R/win-library/3... | [
0,
1,
2,
3,
4
] |
import asyncio
import logging
import random
from aiogram.dispatcher import FSMContext
from aiogram.types import ContentTypes, Message, CallbackQuery
from aiogram.utils.exceptions import BotBlocked
import keyboards
from data.config import ADMINS, ADMIN_CHAT_ID
from keyboards.inline.activate_menu import active_menu_cal... | normal | {
"blob_id": "302accfd5001a27c7bbe6081856d43dbec704168",
"index": 339,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@dp.message_handler(commands='upload', user_id=ADMINS, state='*')\nasync def upload_profile(command_msg: Message, state: FSMContext):\n profile_msg = command_msg.reply_to_message\n ... | [
0,
1,
2,
3
] |
#!/usr/bin/env python3
# Written by jack @ nyi
# Licensed under FreeBSD's 3 clause BSD license. see LICENSE
'''This class calls the system's "ping" command and stores the results'''
class sys_ping:
'''this class is a python wrapper for UNIX system ping command, subclass ping does the work, last stores data from t... | normal | {
"blob_id": "44dee207ffa4f78293484126234a3b606e79915b",
"index": 5056,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass sys_ping:\n <mask token>\n <mask token>\n\n\n class last:\n \"\"\"This class stores data from last sys_ping.ping()\"\"\"\n min_time, avg_time, max_time, m... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/python
try:
from Queue import Queue
except ImportError: # Python 3
from queue import Queue
class BFSWithQueue:
"""Breadth-First Search.
Attributes
----------
graph : input graph
color : dict with nodes, private
distance : dict with nodes (distances to source node)
... | normal | {
"blob_id": "0bce5d590b96e434cd8aee7531a321bc648c1981",
"index": 8722,
"step-1": "<mask token>\n\n\nclass BFSWithQueue:\n <mask token>\n <mask token>\n\n def run(self, source=None, pre_action=None, post_action=None):\n \"\"\"Executable pseudocode.\"\"\"\n if source is not None:\n ... | [
8,
10,
11,
12,
14
] |
from sklearn.datasets import fetch_mldata
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
import numpy as np
import os
import tarfile
import pickle
import subprocess
import sys
if sys.version_info.major == 2:
# Backward compatibility with python 2.
from six.... | normal | {
"blob_id": "6eec95932ef445ba588f200233495f59c4d77aac",
"index": 5396,
"step-1": "<mask token>\n\n\ndef get_gpu_name():\n try:\n out_str = subprocess.run(['nvidia-smi', '--query-gpu=gpu_name',\n '--format=csv'], stdout=subprocess.PIPE).stdout\n out_list = out_str.decode('utf-8').split... | [
5,
6,
7,
8,
11
] |
api_key = "your_key"
| normal | {
"blob_id": "f024b0736f5fcdebede8d5b0985cf9d7170db8fc",
"index": 7401,
"step-1": "<mask token>\n",
"step-2": "api_key = 'your_key'\n",
"step-3": "api_key = \"your_key\"\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
from django.conf import settings
from django.urls import resolve
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, JsonResponse, HttpResponseNotFound
from django.template.loader import get_template, render_to_string
from django.views.g... | normal | {
"blob_id": "55cf99e3493c9c94955fc7e75ac428cbd88ac5cf",
"index": 2453,
"step-1": "<mask token>\n\n\ndef preProcesar(request):\n id_archivo = request.GET.get('id_archivo')\n archivo = DataArchivoCargueProcesar.objects.filter(id=id_archivo).last()\n valores, columnas = iniPreviw(id_archivo, archivo.\n ... | [
8,
11,
12,
14,
15
] |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.preprocessing import LabelBinarizer
def tanh(x):
return np.tanh(x)
def tanh_deriv(x):
return 1.0 - np.tanh(x) * np... | normal | {
"blob_id": "a6a5fddb8e1eda4cc8e9c79ad83019f55d149a80",
"index": 2988,
"step-1": "<mask token>\n\n\ndef tanh(x):\n return np.tanh(x)\n\n\ndef tanh_deriv(x):\n return 1.0 - np.tanh(x) * np.tanh(x)\n\n\n<mask token>\n\n\nclass NeuralNetwork:\n\n def __init__(self, layers, activation='tanh'):\n \"\"... | [
6,
8,
9,
11,
12
] |
from .VimaptException import VimaptException
class VimaptAbortOperationException(VimaptException):
pass
| normal | {
"blob_id": "f52bac3e658a34b82721746364fab11d25d470c4",
"index": 5302,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass VimaptAbortOperationException(VimaptException):\n pass\n",
"step-3": "from .VimaptException import VimaptException\n\n\nclass VimaptAbortOperationException(VimaptException)... | [
0,
1,
2
] |
import openpyxl
from openpyxl import Workbook
import openpyxl as openpyxl
from openpyxl.chart import BarChart
wb = openpyxl.load_workbook('/Users/mac/Desktop/stu_scores _Grade 2.xlsx')
sheet = wb['stu_scores_01']
data = openpyxl.chart.Reference(sheet, min_col=3, min_row=34, max_row=34,max_col=7)
cat = openpyxl.chart.... | normal | {
"blob_id": "bb9ff561ff94bbe4d20f14287ba313386ea78609",
"index": 9121,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncharObj.append(seriesObj)\ncharObj.set_categories(cat)\nsheet.add_chart(charObj, 'I2')\n<mask token>\ncharObj.append(seriesObj)\ncharObj.set_categories(cat)\nsheet.add_chart(charObj, 'I18... | [
0,
1,
2,
3,
4
] |
from utils import to_device
from utils import build_dictionary,my_collate
from DataGenerator import DataGenerator
from torch.utils.data import DataLoader
from torch import optim
import torch.nn as nn
from ADSentimentModel import ADSentimentModel
import torch
def train(token2id, train_data, lr, batch_size, epochs,model... | normal | {
"blob_id": "d0364b7cad29c639af9df5c78e810144ffd6ce2e",
"index": 2415,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef train(token2id, train_data, lr, batch_size, epochs, model):\n dataset = DataGenerator(token2id, train_data)\n dataloader = DataLoader(dataset, batch_size=batch_size, collate... | [
0,
1,
2,
3,
4
] |
####################################################################################
# About
# Date: April 12, 2018
# Notes
'''
Code that renames a list of files in a directory
MUST Run in Python 3 environment!
jpeg Drop extra number at the end of unique ID
add DEL or INS based on variant type
'''
'''
Resources
-----... | normal | {
"blob_id": "d483314fa7e8a2514fd5089b872b9e480e7454f4",
"index": 8116,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nos.chdir(\n '/Volumes/lesleydata/manual_Curation_app/images/svviz_JMZook/1000_Rand_Samp_INS_DEL_2/app_images/DEL/PBDEL'\n )\nfor f in os.listdir():\n file_name, file_ext = os.pat... | [
0,
1,
2,
3,
4
] |
# encoding: utf-8
'''
Created on Nov 26, 2015
@author: tal
Based in part on:
Learn math - https://github.com/fchollet/keras/blob/master/examples/addition_rnn.py
See https://medium.com/@majortal/deep-spelling-9ffef96a24f6#.2c9pu8nlm
"""
Modified by Pavel Surmenok
'''
import argparse
import numpy as np
from keras.l... | normal | {
"blob_id": "572a098053ebae4f42cd020d1003cc18eceb6af0",
"index": 4984,
"step-1": "<mask token>\n\n\ndef generate_model(output_len, chars=None):\n \"\"\"Generate the model\"\"\"\n print('Build model...')\n chars = chars or CHARS\n model = Sequential()\n for layer_number in range(INPUT_LAYERS):\n ... | [
6,
7,
8,
10,
12
] |
def minvalue(weight,Day):
maximum = 0
res = 0
for x in range(0, len(weight)):
if weight[x] > maximum:
maximum = weight[x]
res += weight[x]
Capitivity = max(res // Day, maximum)
while True:
sum=0
day=1
for t in range(0, len(weight)):
if ... | normal | {
"blob_id": "a0ffb793650b0e911dd9bcbec0b7ba76f7829c12",
"index": 1539,
"step-1": "<mask token>\n",
"step-2": "def minvalue(weight, Day):\n maximum = 0\n res = 0\n for x in range(0, len(weight)):\n if weight[x] > maximum:\n maximum = weight[x]\n res += weight[x]\n Capitivity... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
from .base import BaseSchema
from marshmallow import fields
class BaseTickSchema(BaseSchema):
"""
Time : 时间
High : 最高价
Low : 最低价
Volume : 交易量
Last : 最新价
"""
Time = fields.String()
High = fields.String()
Low = ... | normal | {
"blob_id": "6cc23a3e2fa3b1baddf05b30a1054a7faf0371a6",
"index": 5528,
"step-1": "<mask token>\n\n\nclass BaseTickSchema(BaseSchema):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass BaseTickSchema(BaseSchema):\n ... | [
1,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
"""Form content type."""
from briefy.plone.content.interfaces import IBriefyContent
from plone.dexterity.content import Container
from zope.interface import implementer
class IForm(IBriefyContent):
"""Interface for a Composite Page."""
@implementer(IForm)
class Form(Container):
"""A ... | normal | {
"blob_id": "6e3de57f7c65e9f6195dabc3326b05744249cefe",
"index": 7991,
"step-1": "<mask token>\n\n\n@implementer(IForm)\nclass Form(Container):\n \"\"\"A Form.\"\"\"\n",
"step-2": "<mask token>\n\n\nclass IForm(IBriefyContent):\n <mask token>\n\n\n@implementer(IForm)\nclass Form(Container):\n \"\"\"A ... | [
2,
3,
4,
5,
6
] |
import torch
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader
# load the data Set
from torch.utils.data import random_split
from torchvision.datasets import ImageFolder
batch_size = 256
data_dir = 'nut_snacks/dataset/'
data_transforms = transfor... | normal | {
"blob_id": "4156b003210a41d6ec8f30e2d20adfb1f4b3deb0",
"index": 6024,
"step-1": "<mask token>\n\n\ndef mean_std(loader):\n mean = 0\n std = 0\n for images, _ in loader:\n batch_samples = images.size(0)\n images = images.view(batch_samples, images.size(1), -1)\n mean += images.mean(... | [
1,
2,
3,
4,
5
] |
"""
Templating support library and renderer configuration.
"""
from restish import templating
class Templating(templating.Templating):
"""
Application-specific templating implementation.
Overriding "args" methods makes it trivial to push extra, application-wide
data to the templates without any assis... | normal | {
"blob_id": "18391df9a3e52400fe4fc54d6381b9ce21e25f0b",
"index": 2296,
"step-1": "<mask token>\n\n\nclass Templating(templating.Templating):\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Templating(templating.Templating):\n \"\"\"\n Application-specific temp... | [
1,
3,
4,
5,
6
] |
from gevent.event import Event
from gevent.queue import Queue
from ping_pong_chat.aio_queue import AGQueue
received_event = Event()
leave_rooms_event = Event()
exit_event = Event()
output_message_queue = AGQueue()
input_message_queue = AGQueue()
matrix_to_aio_queue = AGQueue()
aio_to_matrix_queue = AGQueue()
sync_to_... | normal | {
"blob_id": "af1a6c6009b21962228fbe737f27c22bf9460762",
"index": 729,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nreceived_event = Event()\nleave_rooms_event = Event()\nexit_event = Event()\noutput_message_queue = AGQueue()\ninput_message_queue = AGQueue()\nmatrix_to_aio_queue = AGQueue()\naio_to_matr... | [
0,
1,
2,
3
] |
from setuptools import setup
setup(name = "dragonfab",
version = "1.3.0",
description = "Fabric support",
author = "Joel Pitt",
author_email = "joel@joelpitt.com",
url = "https://github.com/ferrouswheel/dragonfab",
install_requires = ['fabric', 'pip>=1.4', 'wheel'],
packages = ['dragonfab']... | normal | {
"blob_id": "61135a10adefd6ba8ffd63e997fa91ce9c78de06",
"index": 6444,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='dragonfab', version='1.3.0', description='Fabric support',\n author='Joel Pitt', author_email='joel@joelpitt.com', url=\n 'https://github.com/ferrouswheel/dragonfab', in... | [
0,
1,
2,
3
] |
from django.db import models
# Create your models here.
class Todo(models.Model):
title = models.CharField(max_length=200)
completed = models.IntegerField(default=0)
| normal | {
"blob_id": "4b075d8211d7047f6f08fe6f6f55e4703bdb6f1f",
"index": 3164,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Todo(models.Model):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Todo(models.Model):\n title = models.CharField(max_length=200)\n completed... | [
0,
1,
2,
3,
4
] |
from django.contrib import admin
from .models import StoreId
# Register your models here.
class StoreIdAdmin(admin.ModelAdmin):
list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id', 'start_date', 'end_date')
search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']
admin.site.register(S... | normal | {
"blob_id": "6475fd59ba2414ea9a174297a8d94e5a2e0a7d8f",
"index": 3783,
"step-1": "<mask token>\n\n\nclass StoreIdAdmin(admin.ModelAdmin):\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass StoreIdAdmin(admin.ModelAdmin):\n list_display = ('userid', 'aladin_id', 'yes... | [
1,
2,
3,
4,
5
] |
import tensorflow as tf
import numpy as np
def safe_nanmax(x):
with np.warnings.catch_warnings():
np.warnings.filterwarnings('ignore',
r'All-NaN (slice|axis) encountered')
return np.nanmax(x)
def safe_nanargmax(x):
try:
return np.nanargmax(x)
ex... | normal | {
"blob_id": "16bf4583b872f038edccbac4e567c1854d65e216",
"index": 4962,
"step-1": "<mask token>\n\n\nclass OfflineMetric:\n\n def __init__(self, *args, **kwargs):\n self.__name__ = self.name()\n <mask token>\n\n def handle_batch(self, model, x, labels, pred):\n raise NotImplementedError()\n... | [
18,
20,
32,
39,
46
] |
#!/usr/bin/env python
import numpy as np
import time, random
import sys, os, struct, socket
import psycopg2
import test_coords
import alex_random
import new_sim_utils
import sdr_kml_writer
from geo_utils import geo_utils
from beacon import beacon
from sim_data import data_utils
ENABLE_JITTER = False
ENABLE_DROPPED_... | normal | {
"blob_id": "530c2c185e57ffd3ac64628fc9f7f7985b0480fe",
"index": 5529,
"step-1": "#!/usr/bin/env python\n\nimport numpy as np\nimport time, random\nimport sys, os, struct, socket\nimport psycopg2\n\nimport test_coords\nimport alex_random\nimport new_sim_utils\nimport sdr_kml_writer\n\nfrom geo_utils import geo_u... | [
0
] |
/home/rip-acer-vn7-591g-1/catkin_ws/devel_cb/.private/nmea_navsat_driver/lib/python2.7/dist-packages/libnmea_navsat_driver/__init__.py | normal | {
"blob_id": "8fd020e7f1854d29cf903f86d91a3a9ffa9d08d3",
"index": 9390,
"step-1": "/home/rip-acer-vn7-591g-1/catkin_ws/devel_cb/.private/nmea_navsat_driver/lib/python2.7/dist-packages/libnmea_navsat_driver/__init__.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
... | [
0
] |
number = int(input("entrez un entier:"))
exposant = int(input("entrez un exposant:"))
def puissance(x, n):
if n == 0:
return 1
else:
return x * puissance(x, n-1)
print(puissance(number, exposant))
| normal | {
"blob_id": "beccae96b3b2c9dcd61bb538d07b85441a73662e",
"index": 9968,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef puissance(x, n):\n if n == 0:\n return 1\n else:\n return x * puissance(x, n - 1)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef puissance(x, n):\n ... | [
0,
1,
2,
3,
4
] |
import sys
import random
#coming into existence, all does not begin and end at this moment;
#not yet fully conscious, you pick up only snippets of your environment
for line in sys.stdin:
line = line.strip()
randLow = random.randint(0, 10)
randHigh = random.randint(11, 20)
print line[randLow:randHigh] | normal | {
"blob_id": "f3d61a9aa4205e91811f17c4e9520811445cc6a9",
"index": 3957,
"step-1": "import sys\nimport random\n\n#coming into existence, all does not begin and end at this moment; \n#not yet fully conscious, you pick up only snippets of your environment\nfor line in sys.stdin:\n\tline = line.strip()\n\n\trandLow =... | [
0
] |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=timezone.now)
autho... | normal | {
"blob_id": "25ce31aee44c80ce4a5c1af7d1ca12c73c14df47",
"index": 5530,
"step-1": "<mask token>\n\n\nclass Post(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SurveyHistory(models.Model):\n post = models.ForeignKey(to=Post, ... | [
4,
5,
6,
7,
8
] |
from subprocess import check_output
import json
import sys
import time
import os
import numpy as np
from hutch_python.utils import safe_load
from ophyd import EpicsSignalRO
from ophyd import EpicsSignal
from bluesky import RunEngine
from bluesky.plans import scan
from bluesky.plans import list_scan
from bluesky.plan_... | normal | {
"blob_id": "4473971552aa48236b19dec7e7c1ea1e622d5795",
"index": 7347,
"step-1": "<mask token>\n\n\nclass User:\n <mask token>\n <mask token>\n <mask token>\n\n def get_dscan(self, motor, start, end, nsteps, nEvents, record=True):\n daq.configure(nEvents, record=record)\n currPos = moto... | [
12,
21,
22,
24,
26
] |
'''
!pip install wget
from zipfile import ZipFile
import wget
print('Beginning file downlaod with wget module')
url = 'https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip'
wget.download(url, 'sample_data/')
print('2. Extract all files in ZIP to different dir... | normal | {
"blob_id": "13c9f0f58ec6da317c3802f594bb0db7c275dee9",
"index": 21,
"step-1": "<mask token>\n\n\ndef create_training_data():\n for category in CATEGORIES:\n path = os.path.join(DATADIR, category)\n classIndex = CATEGORIES.index(category)\n for img in os.listdir(path):\n try:\n... | [
1,
3,
4,
5,
6
] |
# coding=utf-8
from django.test import TestCase
from django_mptt_admin.util import get_tree_queryset, get_javascript_value
from ..models import Country
from .utils import read_testdata
class UtilTestCase(TestCase):
def setUp(self):
super(UtilTestCase, self).setUp()
read_testdata()
def tes... | normal | {
"blob_id": "ac5c4edda8a5df7abc030fd637866fa4c8fc4bfc",
"index": 1493,
"step-1": "<mask token>\n\n\nclass UtilTestCase(TestCase):\n <mask token>\n\n def test_get_tree_queryset(self):\n qs = get_tree_queryset(Country)\n self.assertEqual(len(qs), 257)\n self.assertEqual(qs[0].name, 'root... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/python
import os
def main():
os.system("notify-send 'Backup' 'NAS Backup Starting...' -i /usr/share/pixmaps/xarchiver/xarchiver-extract.png ")
os.system("sudo mount -o username='emre' //192.168.1.2/Samba /media/NAS")
os.system("sudo rsync -av --include='.profile' --include='.bash*' --exclude='.... | normal | {
"blob_id": "b6dd04219de1d4526d175254da539107362772d6",
"index": 9229,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n os.system(\n \"notify-send 'Backup' 'NAS Backup Starting...' -i /usr/share/pixmaps/xarchiver/xarchiver-extract.png \"\n )\n os.system(\"sudo mount -o... | [
0,
1,
2,
3,
4
] |
import boto3
class NetworkLookup:
def __init__(self):
self.loaded = 0
self.subnets = {}
self.vpcs = {}
def load(self):
if self.loaded:
return
client = boto3.client('ec2')
# load subnets
subnets_r = client.describe_subnets()
subnets_... | normal | {
"blob_id": "767c0e6d956701fcedddb153b6c47f404dec535a",
"index": 65,
"step-1": "<mask token>\n\n\nclass NetworkLookup:\n\n def __init__(self):\n self.loaded = 0\n self.subnets = {}\n self.vpcs = {}\n\n def load(self):\n if self.loaded:\n return\n client = boto3... | [
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.