code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
BLUE = "#1A94D6" GREEN = "#73AD21" PALE_GREEN = "#BBF864" PALE_BLUE = "#A2C4DA" BRIGHT_BLUE = "#04BAE3" ORANGE = "#FF8000" DARK_ORANGE = "#E65C00" LIGHT_ORANGE = "#FFAA3E" PALE_ORANGE = "#F8C381" GUAVA = "#FF4F40" FUSCIA = "#E22EFF" PALE_FUSCIA = "#DFA0E9" PURPLE = "#AE37C1" PALE_PURPLE = "#C3AACF" COLORS = [BLU...
normal
{ "blob_id": "6d8c32fe51fadbe6b6ee14419e1e37c65d4f57bf", "index": 2508, "step-1": "<mask token>\n", "step-2": "BLUE = '#1A94D6'\nGREEN = '#73AD21'\nPALE_GREEN = '#BBF864'\nPALE_BLUE = '#A2C4DA'\nBRIGHT_BLUE = '#04BAE3'\nORANGE = '#FF8000'\nDARK_ORANGE = '#E65C00'\nLIGHT_ORANGE = '#FFAA3E'\nPALE_ORANGE = '#F8C38...
[ 0, 1, 2 ]
import numpy as np class RandomPlayer: def __init__(self, game): self.game = game def play(self, board): a = np.random.randint(self.game.getActionSize()) valids = self.game.getValidMoves(board, 1) while valids[a] != 1: a = np.random.randint(self.game.getActionSize(...
normal
{ "blob_id": "efe099bc5cd0319ffefd779f1e854f1a60edc5fa", "index": 9240, "step-1": "<mask token>\n\n\nclass MinimaxPlayer:\n\n def __init__(self, game):\n self.game = game\n\n def play(self, Board):\n key = -1\n bem = -99999999\n board = self.to_board(Board)\n print(Board)\...
[ 7, 9, 14, 16, 17 ]
""" @Description: @Author : HCQ @Contact_1: 1756260160@qq.com @Project : pytorch @File : call_test @Time : 2022/5/24 下午10:19 @Last Modify Time @Version @Desciption -------------------- -------- ----------- 2022/5/24 下午10:19 1.0 None """ class Person(): def __cal...
normal
{ "blob_id": "7b1c7228c1fc9501ab857cba62a7e073691e75c9", "index": 755, "step-1": "<mask token>\n\n\nclass Person:\n\n def __call__(self, name):\n print('__call__' + ' Hello ' + name)\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Person:\n\n def __call__(self, name):\n ...
[ 2, 3, 4, 5, 6 ]
""" DB models. """ from sqlalchemy import Column, Integer, String, ForeignKey, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from db.session import map_engine, replay_engine MapBase = declarative_base(bind=map_engine) ReplayBase = declarative_base(bind=replay...
normal
{ "blob_id": "6b3cb7a42c8bc665e35206b135f6aefea3439758", "index": 7381, "step-1": "<mask token>\n\n\nclass Line(MapBase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return (\"<Line(id='{}', len='{}', p0='{}', p1='...
[ 14, 16, 17, 18, 21 ]
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO p1=float(input('digite o p1:')) c1=float(input('digite o c1:')) p2=float(input('digite o p2:')) c2=float(input('digite o c2:')) if p1*c1=p2*c2: print('O') if pi*c1>p2*c2: print('-1') else: print('1')
normal
{ "blob_id": "210fcb497334ad8bf5433b917fc199c3e22f0f6e", "index": 6978, "step-1": "# -*- coding: utf-8 -*-\n#COMECE AQUI ABAIXO\n\np1=float(input('digite o p1:'))\nc1=float(input('digite o c1:'))\np2=float(input('digite o p2:'))\nc2=float(input('digite o c2:'))\n\nif p1*c1=p2*c2:\n print('O')\n\nif pi*c1>p2*c2...
[ 0 ]
import math import os import sys import pandas import numpy as np import seaborn as sns import tensorflow as tf import logging # from utils.simulation_functions import simulation_cox_gompertz from utils.preprocessing import formatted_data, normalize_batch, event_t_bin_prob,risk_t_bin_prob,\ batch_t_categorize, next_b...
normal
{ "blob_id": "ebebdb0e79e9d78b818dab3f93d130ccddd2914e", "index": 1185, "step-1": "<mask token>\n\n\ndef saveDatadic(file_path, name, dataset):\n np.save(file_path + name + '_x', dataset['x'])\n np.save(file_path + name + '_t', dataset['t'])\n np.save(file_path + name + '_e', dataset['e'])\n\n\n<mask tok...
[ 7, 10, 14, 17, 18 ]
from __future__ import absolute_import import numpy as np import matplotlib.pyplot as pl import seaborn as sb sb.set_color_codes('muted') import scipy.optimize as op from scipy import stats def errorbar(t, f, s, fp=None, **kwargs): with sb.axes_style('white'): fig, ax = pl.subplots(1, 1, figsize=(10,3)) ...
normal
{ "blob_id": "1e929bc3c97de859a16a4ac8d5ac2ebadefd0516", "index": 6624, "step-1": "<mask token>\n\n\ndef errorbar(t, f, s, fp=None, **kwargs):\n with sb.axes_style('white'):\n fig, ax = pl.subplots(1, 1, figsize=(10, 3))\n ax.errorbar(t, f, s, marker='o', color='b', linestyle='none', **kwargs)\n ...
[ 4, 5, 6, 7, 8 ]
'''code for recursuve binary search ''' def rbinarysearch(l, k, begin, end): if(begin == end): if(l[begin] == k): return 1 else: return 0 if(end-begin == 1): if(l[end] == k) or (l[begin] == k): return 1 else: return 0 if(end...
normal
{ "blob_id": "7171edc3eecd2f0cdebd914e89a7a7e0353ddf63", "index": 9209, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef rbinarysearch(l, k, begin, end):\n if begin == end:\n if l[begin] == k:\n return 1\n else:\n return 0\n if end - begin == 1:\n if ...
[ 0, 1, 2, 3 ]
import numpy as np import cv2 import colorsys from matplotlib import pyplot as plt img = cv2.imread('coins.jpg') b,g,r = cv2.split(img) rgb_img = cv2.merge([r,g,b]) gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Blurring image grayBlur = cv2.medianBlur(gray, 3) # Binary threshold ret, thresh = cv2.threshold(grayBl...
normal
{ "blob_id": "39dda191ab2137b5f5538660f17e39b0a1358bf4", "index": 206, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(nodes):\n r, g, b = colorsys.hsv_to_rgb(float(i) / nodes, 1.0, 1.0)\n R, G, B = int(255 * r), int(255 * g), int(255 * b)\n color = [R, G, B]\n print(color)\n ...
[ 0, 1, 2, 3, 4 ]
from abc import ABC class Parent(ABC): def printing(self): print(self._words) class Parent2(ABC): form = "Parent2 Setup: %s" class Child(Parent, Parent2): def __init__(self, words): self._words = self.form % words super(Child, self).printing() if __name__ == "__main__": Child("hello world")
normal
{ "blob_id": "9ba60270a4afcf242de53692afd8ebff7d9b37a7", "index": 4361, "step-1": "<mask token>\n\n\nclass Parent2(ABC):\n form = 'Parent2 Setup: %s'\n\n\nclass Child(Parent, Parent2):\n\n def __init__(self, words):\n self._words = self.form % words\n super(Child, self).printing()\n\n\n<mask t...
[ 4, 6, 7, 8, 9 ]
#!/usr/bin/env python import rospy from op3_utils.op3_utils import * from vision import * import cv2 import sys import rosnode #Yellow >> Right #Red >> Left class States: INIT = -1 GET_READY = 1 FIND_BAR = 2 WALK_2_BAR = 3 WALK_SIDEWAYS = 4 PICK_BAR = 5 WALK_WITH_BAR = 6 LIFT_BAR = 7 ...
normal
{ "blob_id": "b3a2db38e2074b02c8837bfce85d06598a7b194d", "index": 5701, "step-1": "<mask token>\n\n\nclass States:\n INIT = -1\n GET_READY = 1\n FIND_BAR = 2\n WALK_2_BAR = 3\n WALK_SIDEWAYS = 4\n PICK_BAR = 5\n WALK_WITH_BAR = 6\n LIFT_BAR = 7\n WALK_2_FINISH = 8\n END = 99\n\n\n<ma...
[ 3, 4, 5, 6, 7 ]
##Linear Queue Data Structure #Main Queue Class class LinearQueue(): def __init__(self, length): #When initiating, user defines the length. #The head and tail pointers are set at -1 (i.e. not pointing to anything, index beginning at zero) #The queue is set as a series of None objects in a l...
normal
{ "blob_id": "0efac7d9d1a9180eafa8c9c4e3a42b4c68e718a2", "index": 4597, "step-1": "class LinearQueue:\n <mask token>\n\n def enqueue(self, *args):\n for i in args:\n if not self.isFull():\n self._tail += 1\n self._queue[self._tail] = i\n else:\n ...
[ 4, 6, 7, 8, 9 ]
import os # must pip install sox # type sudo apt install sox into cmd duration = .2 # seconds freq = 550 # Hz os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))
normal
{ "blob_id": "8397dcdcb9ec2f35dac0c26b8878a23f9149512b", "index": 3113, "step-1": "<mask token>\n", "step-2": "<mask token>\nos.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))\n", "step-3": "<mask token>\nduration = 0.2\nfreq = 550\nos.system('play -nq -t alsa synth {} sine {}'.format(durat...
[ 0, 1, 2, 3, 4 ]
''' Calculations used by algorithms All calculations for training shall have a standard API that takes in `batch` from algorithm.sample() method and return np array for calculation. `batch` is a dict containing keys to any data type you wish, e.g. {rewards: np.array([...])} ''' from slm_lab.lib import logger, util impo...
normal
{ "blob_id": "07095bc815f5342b66ef4ca74b769321f3ef2ec5", "index": 7240, "step-1": "<mask token>\n\n\ndef calc_returns(batch, gamma):\n \"\"\"\n Calculate the simple returns (full rollout) for advantage\n i.e. sum discounted rewards up till termination\n \"\"\"\n rewards = batch['rewards']\n asse...
[ 3, 4, 5, 6, 7 ]
class Solution: # complexity: 2*n^2 + 4*n^2 -> 8*n^2 def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: # complexity: n*2*l where l is the length of the word -> 2*n^2 words_freq = { word: word.count(min(word)) for word in words } quer...
normal
{ "blob_id": "e9918f4fac2e13b36d9b20ffc28dc6508aad6f9b", "index": 2159, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def numSmallerByFrequency(self, queries: List[str], words: List[str]\n ) ->List[int]:\n words_freq = {word: word....
[ 0, 1, 2, 3 ]
class thrs: def __init__(self, input_wave): from numpy import mod, array, sqrt, dot,median,convolve self.D0 = 20 self.last_det = 0 self.mu = 0.6 self.a_up = 0.2 self.a_down = 0.6 self.z_cumulative = 10 self.n_max = max(input_wave[:1000]) self...
normal
{ "blob_id": "2cdee8799678e8ead21a0f81c42eb7ce209cfec7", "index": 7289, "step-1": "class thrs:\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "class thrs:\n <mask token>\n <mask token>\n\n def getThrs(self, pos):\n if pos - self.last_det < self.D0:\n return self.n...
[ 1, 2, 3, 4, 5 ]
from django.conf import settings from django.contrib import admin from django.urls import path, include, reverse_lazy from django.views.generic import RedirectView, TemplateView from mainapp.views import ShortURLRedirect urlpatterns = [ path('', TemplateView.as_view(template_name='mainapp/index.html'), name='inde...
normal
{ "blob_id": "573674e50e05880a2822f306c125207b382d872f", "index": 6389, "step-1": "<mask token>\n", "step-2": "<mask token>\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += path('__debug__/', include(debug_toolbar.urls)),\n", "step-3": "<mask token>\nurlpatterns = [path('', TemplateView.as_vi...
[ 0, 1, 2, 3, 4 ]
# coding: utf-8 # In[2]: from HSTLens_base_classifier_resnet17_s import BaseKerasClassifier from keras.layers import Activation, AveragePooling2D, MaxPooling2D from keras.layers import Conv2D, ELU, Dropout, LeakyReLU from keras.layers.normalization import BatchNormalization class deeplens_classifier(BaseKerasCl...
normal
{ "blob_id": "6bd47fb71a32b8383a75e72111d802008bc6bc68", "index": 3350, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass deeplens_classifier(BaseKerasClassifier):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass deeplens_classifier(BaseKerasClassifier):\n\n def _model_definition(self,...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python import remctl import json import datetime import time,random import argparse if __name__ == '__main__': parser = argparse.ArgumentParser( description = "List all TCC Forge overlays" ) parser.add_argument( '-n', '--now', action = "store_false", default = True, dest = 'now', help ...
normal
{ "blob_id": "1ce34bfec6a9acfeaf0d5c5835ebebed4d7ee369", "index": 2056, "step-1": "#!/usr/bin/env python\n\nimport remctl\nimport json\nimport datetime\nimport time,random\nimport argparse\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(\n\t\tdescription = \"List all TCC Forge overlays\"\n\t)\n\...
[ 0 ]
import pandas as pd import statistics import csv df = pd.read_csv("height-weight.csv") heightlist = df["Height(Inches)"].to_list() weightlist = df["Weight(Pounds)"].to_list() heightmean = statistics.mean(heightlist) heightmedian = statistics.median(heightlist) heightmode = statistics.mode(heightlist) heigh...
normal
{ "blob_id": "3f4b05a1d0c4c2a2b085a0265bafbf89b5635e31", "index": 8021, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(heightmean)\nprint(heightmedian)\nprint(heightmode)\nprint(heightstdev)\n<mask token>\nprint(firstpercentage)\nprint(secondpercentage)\nprint(thirdpercentage)\n", "step-3": "<mask...
[ 0, 1, 2, 3, 4 ]
from db import do_command, do_command_no_return, do_insert def get_grocery(upc): cmd = "SELECT name FROM grocery WHERE upc = ?" rtVal = do_command(cmd, [upc]) length = len(rtVal) if length > 0: return {'success': bool(len(rtVal)), 'grocery': rtVal[0]} return {'success': bool(len(rtVal))...
normal
{ "blob_id": "92b24fe82929ed4590e5350188673c2245136d03", "index": 5554, "step-1": "<mask token>\n\n\ndef get_grocery_id(upc):\n cmd = 'SELECT id FROM grocery WHERE upc = ?'\n rtVal = do_command(cmd, [upc])\n if len(rtVal) > 0:\n return rtVal[0]['id']\n else:\n return -1\n\n\n<mask token>...
[ 3, 5, 6, 9, 10 ]
n=7 a=[] for i in range(1,n+1): print(i) if(i<n): print("+") a.append(i) print("= {}".format(sum(a)))
normal
{ "blob_id": "de9b85c250dea15ff9201054957ebc38017a8c35", "index": 5435, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(1, n + 1):\n print(i)\n if i < n:\n print('+')\n a.append(i)\nprint('= {}'.format(sum(a)))\n", "step-3": "n = 7\na = []\nfor i in range(1, n + 1):\n pr...
[ 0, 1, 2, 3 ]
# File Name: create_data.py from sqlalchemy.orm import sessionmaker from faker import Faker from db_orm import Base, engine, User, Course from sqlalchemy import MedaData session = sessionmaker(engine)() fake = Faker('zh-cn') # 创建表 users_table = Table('users', metadata, Column('id', Integer, primary_key = True), ...
normal
{ "blob_id": "6c94b487eaa179a70ea6528b0214d04d5148574f", "index": 4070, "step-1": "<mask token>\n\n\ndef create_users():\n for i in range(10):\n user = User(name=fake.name(), email=fake.email())\n session.add(user)\n\n\ndef create_courses():\n for user in session.query(User).all():\n fo...
[ 3, 4, 5, 6, 7 ]
import datetime from collections import defaultdict from django.db.models import Prefetch from urnik.models import Termin, Rezervacija, Ucilnica, DNEVI, MIN_URA, MAX_URA, Srecanje, Semester, RezervacijaQuerySet class ProsteUcilniceTermin(Termin): HUE_PRAZEN = 120 # zelena HUE_POLN = 0 # rdeca def __i...
normal
{ "blob_id": "3ce9c0aeb6b4e575fbb3fced52a86a1dcec44706", "index": 4713, "step-1": "<mask token>\n\n\nclass ProsteUcilnice(object):\n <mask token>\n\n def __init__(self, ucilnice):\n self.ucilnice = set(ucilnice)\n self.zasedenost_ucilnic = defaultdict(dict)\n self.rezerviranost_ucilnic ...
[ 20, 22, 26, 27, 28 ]
#import os import queue as q #Считываем ввод file = open('input.txt', 'r') inp = '' for i in file: for j in i: if (j != '\n'): inp += j else: inp += ' ' inp += ' ' #print(inp) file.close() #Записываем все пути в двумерный массив tmp = '' #Переменная для хранения текущего ...
normal
{ "blob_id": "bb847480e7e4508fbfb5e7873c4ed390943e2fcf", "index": 3589, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in file:\n for j in i:\n if j != '\\n':\n inp += j\n else:\n inp += ' '\ninp += ' '\nfile.close()\n<mask token>\nfor i in inp:\n if i != ' ...
[ 0, 1, 2, 3, 4 ]
import json import pickle import zlib from diskcollections.interfaces import IHandler class PickleHandler(IHandler): dumps = staticmethod(pickle.dumps) loads = staticmethod(pickle.loads) class PickleZLibHandler(IHandler): @staticmethod def dumps(obj, protocol=pickle.HIGHEST_PROTOCOL, level=zlib. ...
normal
{ "blob_id": "60202758a0a42fc26dc1bca9f134a70f28967093", "index": 2728, "step-1": "<mask token>\n\n\nclass PickleZLibHandler(IHandler):\n\n @staticmethod\n def dumps(obj, protocol=pickle.HIGHEST_PROTOCOL, level=zlib.\n Z_DEFAULT_COMPRESSION):\n pickled = pickle.dumps(obj, protocol=protocol)\n ...
[ 8, 9, 10, 11 ]
#!/usr/bin/python3 import i3ipc if __name__ == "__main__": i3 = i3ipc.Connection() wp = [int(w["name"]) for w in i3.get_workspaces() if w["num"] != -1] for k in range(1, 16): if k not in wp: i3.command("workspace {}".format(k)) break
normal
{ "blob_id": "cd07dd596f760e232db5c0fd8e27360d61bda635", "index": 8947, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n i3 = i3ipc.Connection()\n wp = [int(w['name']) for w in i3.get_workspaces() if w['num'] != -1]\n for k in range(1, 16):\n if k not in wp:\n ...
[ 0, 1, 2, 3 ]
#! /usr/bin/env python import RPIO import sys RPIO.setwarnings(False) gpio = int(sys.argv[1]) RPIO.setup(gpio, RPIO.OUT) input_value = RPIO.input(gpio) print input_value
normal
{ "blob_id": "382597628b999f2984dba09405d9ff3dd2f35872", "index": 6765, "step-1": "#! /usr/bin/env python\n\nimport RPIO\nimport sys\n\nRPIO.setwarnings(False)\n\ngpio = int(sys.argv[1])\n\nRPIO.setup(gpio, RPIO.OUT)\ninput_value = RPIO.input(gpio)\n\nprint input_value", "step-2": null, "step-3": null, "ste...
[ 0 ]
from django.db.models import Model, CharField, IntegerField, ManyToManyField, ForeignKey, PROTECT from django.core.validators import MaxValueValidator, MinValueValidator from polymorphic.models import PolymorphicModel from model_utils import Choices class Tendencia(Model): valor = CharField(max_length=16, unique=...
normal
{ "blob_id": "c07454dfb9dabb89c86f63063231ae9cf915aa38", "index": 4116, "step-1": "<mask token>\n\n\nclass Classe(PolymorphicModel):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n...
[ 15, 20, 23, 25, 35 ]
# -*- coding: utf-8 -*- import requests import os def line(body): url = "https://notify-api.line.me/api/notify" access_token = 'I89UnoDRgRSInUXJOTg5fAniBE08CUuxVqj8ythMLt8' headers = {'Authorization': 'Bearer ' + access_token} message = body payload = {'message': message} r = requests.post(url...
normal
{ "blob_id": "8b598703df67fb8287fe6cdccda5b73bf2892da8", "index": 4878, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef line(body):\n url = 'https://notify-api.line.me/api/notify'\n access_token = 'I89UnoDRgRSInUXJOTg5fAniBE08CUuxVqj8ythMLt8'\n headers = {'Authorization': 'Bearer ' + acces...
[ 0, 1, 2, 3, 4 ]
import src.integralimage as II import src.adaboost as AB import src.utils as UT import numpy as np if __name__ == "__main__": pos_training_path = 'dataset-1/trainset/faces' neg_training_path = 'dataset-1/trainset/non-faces' pos_testing_path = 'dataset-1/testset/faces' neg_testing_path = 'dataset-1/tes...
normal
{ "blob_id": "3f4f60ff315c8e7e4637a84629894012ed13280e", "index": 3163, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n pos_training_path = 'dataset-1/trainset/faces'\n neg_training_path = 'dataset-1/trainset/non-faces'\n pos_testing_path = 'dataset-1/testset/faces'\n ...
[ 0, 1, 2, 3 ]
import sys import memo from StringIO import StringIO import inspect alternate_dict = {} alternate_dict['cartesian_to_polar'] = ['cartesian_to_polar','cartesianToPolar','cartesion_to_polar','Polar_Coordinates'] alternate_dict['mercator'] = ['mercator','mercator_projection','mecartor','Mercator','Mercator_projection'] ...
normal
{ "blob_id": "eedd909e777a4127b5fd55108805314b3b196dd1", "index": 5222, "step-1": "import sys\nimport memo \nfrom StringIO import StringIO\nimport inspect\n\nalternate_dict = {}\nalternate_dict['cartesian_to_polar'] = ['cartesian_to_polar','cartesianToPolar','cartesion_to_polar','Polar_Coordinates']\nalternate_di...
[ 0 ]
import numpy as np class Adaline: def __init__(self, eta = 0.0001, n_iter = 2000): self.eta = eta self.n_iter = n_iter self.error = [] def fit(self, X, Y): X = np.hstack((np.ones((X.shape[0],1)), X)) self.w = np.random.uniform(-1, 1, (X.shape[1], 1)) for n in ...
normal
{ "blob_id": "02e711dfc122007c74949cd9f86e2aeb9d334871", "index": 329, "step-1": "<mask token>\n\n\nclass Adaline:\n <mask token>\n\n def fit(self, X, Y):\n X = np.hstack((np.ones((X.shape[0], 1)), X))\n self.w = np.random.uniform(-1, 1, (X.shape[1], 1))\n for n in range(self.n_iter):\n...
[ 2, 3, 4, 5, 6 ]
""" You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exi...
normal
{ "blob_id": "3abeac4fb80244d2da14e14a6048c09b0c0c1393", "index": 6047, "step-1": "<mask token>\n\n\nclass Solution(object):\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution(object):\n\n def nextGreaterElement(self, findNums, nums):\n \"\"\"\n :type findNums: ...
[ 1, 2, 3, 4, 5 ]
''' 236. Lowest Common Ancestor of a Binary Tree https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p...
normal
{ "blob_id": "ec9184fa3562ef6015801edf316faa0097d1eb57", "index": 4821, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Solution:\n\n def postorder(self, node: 'TreeNode', p: 'TreeNode', q: 'TreeNode'\n ...
[ 0, 1, 2, 3, 4 ]
from simple_avk.AVK import SimpleAVK from simple_avk.exceptions import MethodError, LongpollError
normal
{ "blob_id": "2bccfba2448059a41185b117b224813e344b50f8", "index": 5673, "step-1": "<mask token>\n", "step-2": "from simple_avk.AVK import SimpleAVK\nfrom simple_avk.exceptions import MethodError, LongpollError\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
from solution import find_days import pudb def test(): T = [1, 2, 3, 1, 0, 4] # pudb.set_trace() res = find_days(T) assert res == [1, 1, 3, 2, 1, 0]
normal
{ "blob_id": "db36c82717aa0bacffce7a3e2724ed2bb586c7fb", "index": 7862, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test():\n T = [1, 2, 3, 1, 0, 4]\n res = find_days(T)\n assert res == [1, 1, 3, 2, 1, 0]\n", "step-3": "from solution import find_days\nimport pudb\n\n\ndef test():\n ...
[ 0, 1, 2, 3 ]
"""deserialization tools""" import typing as t from datetime import datetime from functools import partial from toolz import compose, flip, valmap from valuable import load, xml from . import types registry = load.PrimitiveRegistry({ bool: dict(true=True, false=False).__getitem__, datetime: partial(flip(...
normal
{ "blob_id": "2dcb2d8d41096f0affe569d8ddbdd190885d5f14", "index": 4738, "step-1": "<mask token>\n", "step-2": "<mask token>\nregistry = load.PrimitiveRegistry({bool: dict(true=True, false=False).\n __getitem__, datetime: partial(flip(datetime.strptime),\n '%Y-%m-%dT%H:%M:%S%z'), str: str.strip, **{c: c fo...
[ 0, 1, 2, 3 ]
import tkinter from tkinter import ttk, filedialog, messagebox import serial.tools.list_ports from PIL import ImageTk, Image from read_bytes import read root = tkinter.Tk() root.title('ChadBotX') # Define constants for mode selection MODE_RECORD = 1 MODE_PLAYBACK = 2 # Define gui state portname = tkinter.StringVar(r...
normal
{ "blob_id": "6455741bbda42b9d84428545ddd50a5d1b54a7ba", "index": 1376, "step-1": "<mask token>\n\n\ndef get_ports():\n ports = serial.tools.list_ports.comports()\n ports_str = []\n for port in ports:\n ports_str.append(port.device)\n return ports_str\n\n\ndef start():\n opt_mode = mode.get(...
[ 2, 4, 5, 6, 7 ]
import xml.etree.ElementTree as ET #tree = ET.parse('rutas/rutas_prueba.xml') #treeToAdd = ET.parse('rutas/rutas_prueba_agregar.xml') #root = tree.getroot() #git rootToAdd = treeToAdd.getroot() #for child in root: # for test in child: # print(test.tag, test.attrib) #for elem in root.iter(): # print(...
normal
{ "blob_id": "b4b7e20c9558bd1b29a1c1fa24bfca8a2d292b27", "index": 398, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor root in rootsToAdd:\n for elem in root:\n root1.append(elem)\nrutas0k_10k.write('rutas/rutas0k-110k.xml')\n", "step-3": "<mask token>\nrutas0k_10k = ET.parse('rutas/rutas0k...
[ 0, 1, 2, 3, 4 ]
# 5/1/2020 # Import median function from numpy import numpy as np from numpy import median # Plot the median number of absences instead of the mean sns.catplot(x="romantic", y="absences", data=student_data, kind="point", hue="school", ci=None, estimator = median) # S...
normal
{ "blob_id": "11072601e31ceba13f8adf6c070f84ca5add35e9", "index": 3300, "step-1": "<mask token>\n", "step-2": "<mask token>\nsns.catplot(x='romantic', y='absences', data=student_data, kind='point',\n hue='school', ci=None, estimator=median)\nplt.show()\n", "step-3": "import numpy as np\nfrom numpy import m...
[ 0, 1, 2, 3 ]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Jul 8 18:04:13 2018 @author: zhangchi """ class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ row = len(A[0]) result = [[] for _ in range(row)] ...
normal
{ "blob_id": "3882aaf94b19967a1d1eff23fa4862ea71de3b38", "index": 7014, "step-1": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 8 18:04:13 2018\n\n@author: zhangchi\n\"\"\"\n\nclass Solution(object):\n def transpose(self, A):\n \"\"\"\n :type A: List[List[int]]\n ...
[ 0 ]
#finding postgresql info import re import subprocess def get_postgre_version(): p = subprocess.Popen("psql --version",stdout=subprocess.PIPE,shell=True) k = re.findall(r'psql\s+\(PostgreSQL\)\s+(.*)',p.stdout.read()) postgre_version = k[0] return postgre_version version=get_postgre_version() print ver...
normal
{ "blob_id": "e6b84a2190a84c871e7191ef49fb7ee8b8148c9a", "index": 7062, "step-1": "#finding postgresql info\nimport re\nimport subprocess\ndef get_postgre_version():\n p = subprocess.Popen(\"psql --version\",stdout=subprocess.PIPE,shell=True)\n k = re.findall(r'psql\\s+\\(PostgreSQL\\)\\s+(.*)',p.stdout.rea...
[ 0 ]
from difflib import SequenceMatcher import csv naam = "straat" def similar(a, b): return SequenceMatcher(None, a, b).ratio() f = open("straten.txt", "r") f.readline() names = f.readlines() for name in names: if similar(name[:-1].lower(),naam.lower()) > 0.7: sim = similar(name[:-1].lower(),naam.lower(...
normal
{ "blob_id": "2f1193e3ab5e0527ab5f89141613eddb18b5f61d", "index": 2787, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\n\n<mask token>\nf.readline()\n<mask token>\nfor name in names:\n if similar(name[:-1].lower(), naam.lower()) >...
[ 0, 2, 3, 4, 5 ]
import pycmc # open project, get Crag, CragVolumes, and intensity images crag = ... cragVolumes = ... raw = ... membrane = ... nodeFeatures = ... edgeFeatures = ... statisticsFeatureProvider = pycmc.StatisticsFeatureProvider(cragVolumes, raw, "raw") shapeFeatureProvider = pycmc.ShapeFeatureProvider(cragVolumes) ...
normal
{ "blob_id": "37d817436ce977339594867ef917177e7371a212", "index": 6847, "step-1": "<mask token>\n", "step-2": "<mask token>\nfeatureProvider.add(shapeFeatureProvider)\nfeatureProvider.add(statisticsFeatureProvider)\n<mask token>\nfeatureExtractor.extractFeatures(nodeFeatures, edgeFeatures, featureProvider)\n", ...
[ 0, 1, 2, 3, 4 ]
# Taken from: https://github.com/flyyufelix/cnn_finetune/blob/master/vgg16.py # based on: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3 # -*- coding: utf-8 -*- import keras import itertools import sys from sklearn.metrics import confusion_matrix import numpy as np import matplotlib import ma...
normal
{ "blob_id": "906b7f02d6a7968bbf4780e682d4f9a92526326a", "index": 9123, "step-1": "\r\n# Taken from: https://github.com/flyyufelix/cnn_finetune/blob/master/vgg16.py \r\n# based on: https://gist.github.com/baraldilorenzo/07d7802847aaad0a35d3\r\n\r\n# -*- coding: utf-8 -*-\r\nimport keras\r\nimport itertools\r\nimp...
[ 0 ]
import wfdb as wf import numpy as np from scipy import signal as ss from datasets import mitdb as dm from matplotlib import pyplot as plt def show_path(path): """ As a plot """ # Read in the data record = wf.rdsamp(path) annotation = wf.rdann(path, 'atr') data = record.p_signals cha = data[:, 0...
normal
{ "blob_id": "4ba722e685c7608fcfd5111131c96847c0408a02", "index": 1905, "step-1": "import wfdb as wf\nimport numpy as np\nfrom scipy import signal as ss\nfrom datasets import mitdb as dm\nfrom matplotlib import pyplot as plt\n\ndef show_path(path):\n \"\"\" As a plot \"\"\"\n # Read in the data\n record ...
[ 0 ]
# -*- coding:utf-8 -*- ''' Created on 2018/2/23 @author : xxfore ''' import time import sys import re sys.dont_write_bytecode = True class TimeUtils(object): @staticmethod def convert_timestamp_to_date(timestamp): time_local = time.localtime(timestamp) dt = time.strftime("%Y-%m-%d %H:%M:%S",t...
normal
{ "blob_id": "933f74e4fda0b30bdf70ff3f3dbde2383b10c694", "index": 8773, "step-1": "<mask token>\n\n\nclass TimeUtils(object):\n <mask token>\n\n\nclass StringUtils(object):\n\n @staticmethod\n def remove_emoji_from_string(text):\n co = re.compile(u'[𐀀-\\U0010ffff]')\n return co.sub(u'', te...
[ 3, 4, 5, 6, 7 ]
# # @lc app=leetcode.cn id=2006 lang=python3 # # [2006] 差的绝对值为 K 的数对数目 # # @lc code=start class Solution: def countKDifference(self, nums: List[int], k: int) -> int: def abs(x,y): if(x-y>=0): return x-y else: return y-x ret = 0 for i...
normal
{ "blob_id": "351b2c2a18473e6ac541a96165c69c836ea101de", "index": 846, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n", "step-3": "class Solution:\n\n def countKDifference(self, nums: List[int], k: int) ->int:\n\n def abs(x, y):\n if x - y >= 0:\n ...
[ 0, 1, 2, 3 ]
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User # Create your models here. class Event(models.Model): name = models.CharField('Назва', max_length=200) date = models.DateField('Дата') address = models.CharField('Адреса', max_length=255, blank=True, null=True)...
normal
{ "blob_id": "137f9310256f66ccd9fbe6626659c3c4daea0efc", "index": 8949, "step-1": "<mask token>\n\n\nclass Atendent(models.Model):\n user = models.ForeignKey(User)\n event = models.ForeignKey(Event, null=True, blank=True)\n state = models.IntegerField(null=True, blank=True)\n", "step-2": "<mask token>\...
[ 2, 4, 5, 6, 7 ]
# Copyright (c) 2021 Cisco and/or its affiliates. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # # Licensed under the Apache License 2.0 or # GNU General Public License v2.0 or later; you may not use this file # except in compliance with one of these Licenses. You # may obtain a copy of the Licenses at:...
normal
{ "blob_id": "ea6d726e8163ed0f93b8078323fa5f4e9115ad73", "index": 1639, "step-1": "<mask token>\n\n\nclass TrafficScriptArg:\n <mask token>\n <mask token>\n\n def get_arg(self, arg_name):\n \"\"\"Get argument value.\n\n :param arg_name: Argument name.\n :type arg_name: str\n :...
[ 2, 3, 4, 5, 6 ]
# -*- coding: utf-8 -*- import scrapy class QuoteesxtractorSpider(scrapy.Spider): name = 'quoteEsxtractor' allowed_domains = ['quotes.toscrape.com'] start_urls = ['http://quotes.toscrape.com/'] def parse(self, response): for quote in response.css('.quote') : # print(quote.getall()...
normal
{ "blob_id": "ce26ad27b7729164e27c845e2803a670b506bad8", "index": 580, "step-1": "<mask token>\n\n\nclass QuoteesxtractorSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass QuoteesxtractorSpider(scrapy.Spider):\n <mask token>\n...
[ 1, 2, 3, 4, 5 ]
import numpy as np # Read in training data and labels # Some useful parsing functions # male/female -> 0/1 def parseSexLabel(string): if (string.startswith('male')): return 0 if (string.startswith('female')): return 1 print("ERROR parsing sex from " + string) # child/teen/adult/senior ->...
normal
{ "blob_id": "6822a0a194e8b401fecfed2b617ddd5489302389", "index": 4718, "step-1": "<mask token>\n\n\ndef parseSexLabel(string):\n if string.startswith('male'):\n return 0\n if string.startswith('female'):\n return 1\n print('ERROR parsing sex from ' + string)\n\n\n<mask token>\n\n\ndef pars...
[ 2, 3, 4, 5, 7 ]
from django.urls import path from admin_panel import views urlpatterns = [path('admin_panel/', views.AdminPanel.as_view(), name= 'admin_panel'), path('admin_panel/connection/', views.Connection. as_view(), name='connect_group-teacher'), path( 'admin_panel/connection/<str:choiced_departament>', views.Connect...
normal
{ "blob_id": "34a7fd66a9e2eae25994336f22a76c24c11a6e1b", "index": 7408, "step-1": "<mask token>\n", "step-2": "<mask token>\nurlpatterns = [path('admin_panel/', views.AdminPanel.as_view(), name=\n 'admin_panel'), path('admin_panel/connection/', views.Connection.\n as_view(), name='connect_group-teacher'),...
[ 0, 1, 2 ]
from __future__ import print_function # Python 2/3 compatibility import boto3 import json import decimal AWS_KEY = '****' AWS_SECRET = '****' def handler(event, context): dynamodb = boto3.resource('dynamodb', region_name='us-west-2', aws_access_key_id=AWS_KEY , aws_secret_access_key=AWS_SECRET) table = dynamo...
normal
{ "blob_id": "511ea9eb1dc234a488c19f9ee9fbd40f81955d54", "index": 5172, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef handler(event, context):\n dynamodb = boto3.resource('dynamodb', region_name='us-west-2',\n aws_access_key_id=AWS_KEY, aws_secret_access_key=AWS_SECRET)\n table = dyn...
[ 0, 1, 2, 3, 4 ]
def get_bios_boot_order(self): result = { } boot_device_list = [] boot_device_details = [] key = 'Bios' bootsources = 'BootSources' response = self.get_request((self.root_uri + self.systems_uri)) if (response['ret'] is False): return response result['ret'] = True ...
normal
{ "blob_id": "bbe7df31a44ccf51c305cd620dc7c4155b7e1a97", "index": 2668, "step-1": "<mask token>\n", "step-2": "def get_bios_boot_order(self):\n result = {}\n boot_device_list = []\n boot_device_details = []\n key = 'Bios'\n bootsources = 'BootSources'\n response = self.get_request(self.root_ur...
[ 0, 1, 2 ]
version https://git-lfs.github.com/spec/v1 oid sha256:91f725dc0dba902c5c2c91c065346ab402c8bdbf4b5b13bdaec6773df5d06e49 size 964
normal
{ "blob_id": "42187f460a64572d2581ed5baec41eaff47466f8", "index": 8672, "step-1": "version https://git-lfs.github.com/spec/v1\noid sha256:91f725dc0dba902c5c2c91c065346ab402c8bdbf4b5b13bdaec6773df5d06e49\nsize 964\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ]...
[ 0 ]
from kraken.core.maths import Vec3, Vec3, Euler, Quat, Xfo from kraken.core.objects.components.base_example_component import BaseExampleComponent from kraken.core.objects.attributes.attribute_group import AttributeGroup from kraken.core.objects.attributes.scalar_attribute import ScalarAttribute from kraken.core.objec...
normal
{ "blob_id": "20167058697450f342c2ac3787bd1721f860dc58", "index": 3169, "step-1": "<mask token>\n\n\nclass SimpleControlComponentGuide(SimpleControlComponent):\n <mask token>\n\n def __init__(self, name='SimpleControl', parent=None):\n Profiler.getInstance().push(\n 'Construct Simple Contr...
[ 12, 15, 17, 18, 20 ]
print("hello world") print("welcome to london")
normal
{ "blob_id": "cd322f9771f1ac90931a7229ffd5effd1cae1a54", "index": 7207, "step-1": "<mask token>\n", "step-2": "print('hello world')\nprint('welcome to london')\n", "step-3": "print(\"hello world\")\nprint(\"welcome to london\")", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#Testing Operating System Descriptions #OS : LMDE 4 Debbie #Version: 4.6.7 #Kernal Version : 4.19.0-8-amd64 #Scripting Langages : Python3 #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------...
normal
{ "blob_id": "422491852b80c2fc4a2e73c01fd01acaad4cf9c8", "index": 7573, "step-1": "<mask token>\n", "step-2": "<mask token>\nregr.fit(X_train, y_train)\nprint(regr.score(X_test, y_test))\n<mask token>\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))\nprint('Mean Squared Error:', metri...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python import rospy from mark1.srv import WordCount, WordCountResponse s= set('',) def count_words(request): s.update(set( request.words.split() )) print s return WordCountResponse( len( request.words.split())) rospy.init_node('mark_service_server') service = rospy.Service('Word_count', W...
normal
{ "blob_id": "e90e4d2c777554999ab72d725d7e57bdfd508d3a", "index": 3966, "step-1": "#!/usr/bin/env python\nimport rospy\nfrom mark1.srv import WordCount, WordCountResponse\n\ns= set('',)\n\ndef count_words(request):\n s.update(set( request.words.split() ))\n print s\n return WordCountResponse( len( reques...
[ 0 ]
""" Auteur:Fayçal Chena Date : 07 avril 2020 Consignes : Écrire une fonction alea_dice(s) qui génère trois nombres (pseudo) aléatoires à l’aide de la fonction randint du module random, représentant trois dés (à six faces avec les valeurs de 1 à 6), et qui renvoie la valeur booléenne True si les dés forment un 421, et l...
normal
{ "blob_id": "ad5a9e353d065eee477381aa6b1f233f975ea0ed", "index": 3374, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef foo_6(x, y):\n return y, x\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef foo_6(x, y):\n return y, x\n\n\n<mask token>\nfoo_6(a, b)\nprint(a, b)\n", "step-4": "<...
[ 0, 1, 2, 3, 4 ]
from peewee import BlobField class BytesField(BlobField): """This is a BlobField adapted to our needs Default BlobField returns memoryview when getting data from the db. We want bytes. """ def adapt(self, value): if value and isinstance(value, memoryview): return value.tobytes() ...
normal
{ "blob_id": "b11869076c2c8d6207df861cd1d0b0434b3f9477", "index": 9836, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass BytesField(BlobField):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass BytesField(BlobField):\n <mask token>\n\n def adapt(self, value):\n ...
[ 0, 1, 2, 3, 4 ]
# Import the SDK import json import boto3 from botocore.exceptions import ClientError import uuid #dbclient = boto3.client('dynamodb') dbresource = boto3.resource('dynamodb', region_name='eu-west-1') rekclient = boto3.client('rekognition','eu-west-1') collection_name = 'swiftarycelebrity' ScannedFacestable = dbresour...
normal
{ "blob_id": "6369c692e358c0dfd1193c6e961ecf9b521ea9ba", "index": 4649, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor Images in Faces:\n lv_FaceId = Images['FaceId']\n lv_ImageId = Images['ImageId']\n lv_ExternalImageId = Images['ExternalImageId'],\n lv_Names = ExternalImageId.split('_')\...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python #coding=utf-8 from datetime import * import unittest def getSnapshot(historyData, id): data = historyData.split('\n') lines = len(data) if lines < 2 : return 'Input is too short!' index = 0 curid = '' idlist = dict() recordtime = '' animal_pos = dict() f...
normal
{ "blob_id": "ddbcc8e768f93a0b4f8776b19e752c57feb5bbf9", "index": 6362, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef getSnapshot(historyData, id):\n data = historyData.split('\\n')\n lines = len(data)\n if lines < 2:\n return 'Input is too short!'\n index = 0\n curid = ''\n...
[ 0, 1, 2, 3 ]
import argparse import logging import enum from abc import ABCMeta, abstractmethod from nmigen import * from ....gateware.pads import * from ....gateware.i2c import I2CTarget from ... import * class Event(enum.IntEnum): START = 0x10 STOP = 0x20 RESTART = 0x30 WRITE = 0x40 READ = 0x50 ...
normal
{ "blob_id": "0f2882971f08450e970e188ed2a06ae1683c682c", "index": 7552, "step-1": "<mask token>\n\n\nclass I2CTargetApplet(GlasgowApplet, name='i2c-target'):\n logger = logging.getLogger(__name__)\n help = 'accept I²C transactions'\n description = \"\"\"\n Process transactions on the I²C bus as a soft...
[ 7, 12, 13, 16, 18 ]
# -*- coding: utf-8 -*- ''' LE JEU DE LA VIE Mini projet numéro 2 de NSI Modélisation Objet : Q1) On peut dégager, au premier abord : une classe cellule (avec un attribut état et un autre voisins) et une classe grille (avec un attribut ordonnée et un autre abscisse). En effet, ce sont les deux éléments du jeu....
normal
{ "blob_id": "cef904b70eb9a997c3c48884ee34665a77e18897", "index": 8465, "step-1": "<mask token>\n\n\nclass Cellule:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def basculer(self):\n \"\"\"mutateur qui change l'état actuel de la cellule ...
[ 20, 23, 24, 28, 32 ]
# -*- coding: utf-8 -*- """ Created on Wed Aug 22 18:05:44 2018 @author: Administrator """ from sklearn.model_selection import cross_val_score, train_test_split from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.model_selection import StratifiedKFold from sklearn.m...
normal
{ "blob_id": "aaa0ac5e31e2c10b5baba6077e952fff1a92ef82", "index": 882, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('cross-vali score is: {}'.format(score.mean()))\n<mask token>\nfor train_index, test_index in kfold.split(iris.data, iris.target):\n print(train_index, test_index)\n<mask token>\n...
[ 0, 2, 3, 4, 5 ]
import json from datetime import datetime, timedelta from itertools import product from django.db.models import QuerySet import pytz from model_mommy import mommy from ...views import get_authors, get_featured_challenges, get_term_of_user class TestNonMiscView: """Test for non view functions in ideax.views (...
normal
{ "blob_id": "8d6e4d06e390b4a45e576239189745c2e37217c5", "index": 2699, "step-1": "<mask token>\n\n\nclass TestNonMiscView:\n <mask token>\n <mask token>\n\n def test_get_term_of_user(self, rf, db):\n mommy.make('Use_Term', term='EULA Test', final_date=datetime.now(\n pytz.UTC) + timede...
[ 5, 6, 7, 9, 10 ]
#!/usr/bin/env python ############################################################################### # Copyright 2017 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy ...
normal
{ "blob_id": "4b552731fcfc661c7ad2d63c7c47f79c43a8ae5e", "index": 4839, "step-1": "<mask token>\n\n\nclass Config(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def get_pb(cls):\n \"\"\"Get a pb instance from the...
[ 4, 6, 7, 9, 10 ]
import urllib.request, urllib.parse, urllib.error from urllib.request import urlopen import xml.etree.ElementTree as ET import ssl # # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter a URL: ') # if len(url) < 1 : url = 'ht...
normal
{ "blob_id": "3b8c4f19e28e54e651862ec9b88b091c9faff02b", "index": 9525, "step-1": "<mask token>\n", "step-2": "<mask token>\nif len(url) < 1:\n url = 'http://py4e-data.dr-chuck.net/comments_70857.xml'\n<mask token>\nprint(len(xml))\n<mask token>\nprint('Comment count:', len(lst))\n<mask token>\nfor item in l...
[ 0, 1, 2, 3, 4 ]
import os import redis import requests import lxml.html ads_api_url = "http://adslabs.org/adsabs/api/search/" ads_html_url = "http://labs.adsabs.harvard.edu/adsabs/abs/" rdb = redis.Redis() def get_dev_key(): # Credit: Andy Casey ads_dev_key_filename = os.path.abspath( os.path.expanduser("~/.ads/dev...
normal
{ "blob_id": "9e314cdf4ef09ecf4a4b43358ae32f76c40aaea8", "index": 8037, "step-1": "<mask token>\n\n\ndef get_dev_key():\n ads_dev_key_filename = os.path.abspath(os.path.expanduser('~/.ads/dev_key')\n )\n if os.path.exists(ads_dev_key_filename):\n with open(ads_dev_key_filename, 'r') as fp:\n ...
[ 2, 3, 4, 5, 6 ]
import smtplib import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from datetime import datetime from threading import Thread FROM = os.getenv('EMAIL_FROM') TO = os.getenv('EMAIL_TO') HOST = os.getenv('EMAIL_HOST') PORT = os.getenv('EMAIL_PORT') PASSWORD = os.getenv('EMAIL_PAS...
normal
{ "blob_id": "60c3f6775d5112ff178bd3774c776819573887bb", "index": 9367, "step-1": "<mask token>\n\n\ndef _send(body, subject):\n msg = MIMEMultipart()\n msg['From'] = FROM\n msg['To'] = TO\n msg['Subject'] = subject\n msg.attach(MIMEText(body, 'plain'))\n server = smtplib.SMTP(host=HOST, port=in...
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- """ This is the very first A.I. in this series. The vision is to devlop 'protocol droid' to talk to, to help with tasks, and with whom to play games. The droid will be able to translate langages and connect ppl. """ import speech_recognition as sr import pyttsx3 import pywhatkit ...
normal
{ "blob_id": "f5d353694a719472320f4d6fa28bc9d2cc5a69b0", "index": 951, "step-1": "<mask token>\n\n\ndef talk(text):\n engine.say('heyo' + text)\n engine.runAndWait()\n\n\ndef take_command():\n try:\n with sr.Microphone() as source:\n print('listening....')\n voice = listener....
[ 2, 4, 5, 6, 7 ]
import os import sys import pytest def run_test(file_name, capture_stdout=True, allure_dir=None): cmd = [ file_name, "-vvv", ] if capture_stdout: cmd.append("-s") test_name = os.path.splitext(os.path.basename(file_name))[0] alluredir = os.path.normpath("%s/%s/" % (allure_dir or "...
normal
{ "blob_id": "7e7a50cb8e66a71c1df2d61241f8a55c042b7d59", "index": 2664, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef run_test(file_name, capture_stdout=True, allure_dir=None):\n cmd = [file_name, '-vvv']\n if capture_stdout:\n cmd.append('-s')\n test_name = os.path.splitext(os.pa...
[ 0, 1, 2, 3 ]
import pulumi import pulumi_aws as aws bar = aws.elasticache.get_replication_group(replication_group_id="example")
normal
{ "blob_id": "4bf140ae01f2eaa0c67f667766c3ec921d552066", "index": 6073, "step-1": "<mask token>\n", "step-2": "<mask token>\nbar = aws.elasticache.get_replication_group(replication_group_id='example')\n", "step-3": "import pulumi\nimport pulumi_aws as aws\nbar = aws.elasticache.get_replication_group(replicati...
[ 0, 1, 2, 3 ]
#### # This is the script for storing the schema of your TerminusDB # database for your project. # Use 'terminusdb commit' to commit changes to the database and # use 'terminusdb sync' to change this file according to # the exsisting database schema #### from typing import List from terminusdb_client.woqlschema impor...
normal
{ "blob_id": "f702cdef3782ddc96244f3cf8e2026581d60baa9", "index": 1537, "step-1": "<mask token>\n\n\nclass State(DocumentTemplate):\n _key = ValueHashKey()\n country: 'Country'\n name: str\n", "step-2": "<mask token>\n\n\nclass Address(DocumentTemplate):\n <mask token>\n city: 'City'\n coordin...
[ 2, 13, 14, 15, 16 ]
# encoding: utf-8 '''🤠 PDS Roundup: A step takes you further towards a complete roundup''' from enum import Enum from .util import commit, invoke import logging, github3, tempfile, zipfile, os _logger = logging.getLogger(__name__) class Step(object): '''An abstract step; executing steps comprises a roundup'''...
normal
{ "blob_id": "21e86e4719cda5c40f780aca6e56eb13c8c9b8e5", "index": 988, "step-1": "<mask token>\n\n\nclass StepName(Enum):\n <mask token>\n null = 'null'\n unitTest = 'unitTest'\n integrationTest = 'integrationTest'\n changeLog = 'changeLog'\n requirements = 'requirements'\n docs = 'docs'\n ...
[ 15, 20, 21, 25, 27 ]
class Rover(object): DIRECTIONS = 'NESW' MOVEMENTS = { 'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0) } def __init__(self, init_string, plateau_dimensions): ''' give the rover a sense of the plateau it's on ''' max_x, max_y = p...
normal
{ "blob_id": "1f49d2341f0bcc712baede28f41c208a01b92e6d", "index": 2998, "step-1": "class Rover(object):\n\n DIRECTIONS = 'NESW'\n MOVEMENTS = {\n 'N': (0, 1),\n 'E': (1, 0),\n 'S': (0, -1),\n 'W': (-1, 0)\n }\n\n def __init__(self, init_string, plateau_dimensions):\n ...
[ 0 ]
from turtle import Turtle class Paddle(Turtle): def __init__(self, x_position, y_position): super().__init__() self.shape('square') self.shapesize(stretch_wid=5, stretch_len=1) self.penup() self.color("white") self.goto(x=x_position, y=y_position) self.speed...
normal
{ "blob_id": "f49b80d0b8b42bafc787a36d0a8be98ab7fa53e7", "index": 3558, "step-1": "<mask token>\n\n\nclass Paddle(Turtle):\n <mask token>\n\n def up(self):\n y_pos = self.ycor()\n x_pos = self.xcor()\n self.goto(y=y_pos + 20, x=x_pos)\n\n def down(self):\n y_pos = self.ycor()\...
[ 3, 4, 5, 6, 7 ]
import numpy as np import cv2 import os from moviepy.editor import * N = 1 # Initiate SIFT detector sift = cv2.xfeatures2d.SIFT_create() # count file number in folder frames list = os.listdir('./frames') number_files = len(list) # array to store similarity of 2 consecutive frames similarity = [] boundaries = [] ke...
normal
{ "blob_id": "397d9b1030a1ec08d04d2101f65a83547495b861", "index": 7165, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(0, number_files - N - 1, N):\n img1 = cv2.imread('./frames/frame%d.jpg' % i, 0)\n img2 = cv2.imread('./frames/frame%d.jpg' % (i + N), 0)\n kp1, des1 = sift.detectA...
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 17 22:28:30 2019 @author: donsdev """ arr = [] sub = [] n = int(input()) while n > 0: arr.append(n) n-=1 while len(arr) + len(sub) > 1: while len(arr) > 1: arr.pop() sub.append(arr.pop()) arr = sub[::-1] + arr su...
normal
{ "blob_id": "d5d31920f7fd4ed2913c5880dba61c2015181be9", "index": 5760, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile n > 0:\n arr.append(n)\n n -= 1\nwhile len(arr) + len(sub) > 1:\n while len(arr) > 1:\n arr.pop()\n sub.append(arr.pop())\n arr = sub[::-1] + arr\n sub ...
[ 0, 1, 2, 3 ]
import os import sys from tensor2tensor.bin import t2t_trainer def problem_args(problem_name): args = [ '--generate_data', '--model=transformer', '--hparams_set=transformer_librispeech_v1', '--problem=%s' % problem_name, '--data_dir=/tmp/refactor_test/problems/%s/data' % problem_name, '--t...
normal
{ "blob_id": "cc5ad95419571d3eb2689b428e5805ad69958806", "index": 4796, "step-1": "<mask token>\n\n\ndef problem_args(problem_name):\n args = ['--generate_data', '--model=transformer',\n '--hparams_set=transformer_librispeech_v1', '--problem=%s' %\n problem_name, '--data_dir=/tmp/refactor_test/pr...
[ 1, 2, 3, 4, 5 ]
""" Tests for `yatsm.utils` """ import numpy as np import pytest from yatsm import utils @pytest.mark.parametrize('nrow,njob', [(793, 13), (700, 1), (700, 700)]) def test_distribute_jobs_interlaced(nrow, njob): assigned = [] for i in range(njob): assigned.extend(utils.distribute_jobs(i, njob, nrow, i...
normal
{ "blob_id": "a513dfd84b5d9267b7e96fedc88e5b6dabeea19e", "index": 640, "step-1": "<mask token>\n\n\n@pytest.mark.parametrize('nrow,njob', [(793, 13), (700, 1), (700, 700)])\ndef test_distribute_jobs_sequential(nrow, njob):\n assigned = []\n for i in range(njob):\n assigned.extend(utils.distribute_job...
[ 4, 6, 7, 8, 9 ]
from google.cloud import vision from google.cloud.vision import types from google.oauth2 import service_account import os # import re import io import pdf2image import tempfile import datetime # Google API credentials = service_account.Credentials.from_service_account_file("APIKey.json") client = vision.ImageAnnot...
normal
{ "blob_id": "be69a9981fe6b53c3b9c4d2893913e4f9f7efb26", "index": 6697, "step-1": "<mask token>\n\n\ndef boxes_to_obj(self, bound):\n return {'x1': bound.vertices[0].x, 'x2': bound.vertices[1].x, 'y1':\n bound.vertices[0].y, 'y2': bound.vertices[2].y}\n\n\ndef generateTempFolder(self, prifx, src):\n ...
[ 3, 5, 6, 7, 8 ]
import os from PIL import Image import cv2 import shutil root = './train' save_path = './thumbnail' for r, d, files in os.walk(root): if files != []: for i in files: fp = os.path.join(r, i) label = i.split('_')[0] dst = os.path.join(save_path, label) if not o...
normal
{ "blob_id": "cc19ff829cc4a11c3dc873353fa2194ec9a87718", "index": 8584, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor r, d, files in os.walk(root):\n if files != []:\n for i in files:\n fp = os.path.join(r, i)\n label = i.split('_')[0]\n dst = os.path.join(s...
[ 0, 1, 2, 3, 4 ]
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DATE from sqlalchemy.orm import relationship from database import Base class User(Base): __tablename__ = "users" username = Column(String, primary_key=True, index=True) email = Column(String, unique=True, index=True) name = Column(...
normal
{ "blob_id": "acf69cd714f04aeceb4be39b8a7b2bc5d77cd69f", "index": 3307, "step-1": "<mask token>\n\n\nclass Documents(Base):\n __tablename__ = 'documents'\n id = Column(Integer, primary_key=True, index=True)\n name_doc = Column(String, index=True)\n exp = Column(DATE, index=True)\n notif = Column(In...
[ 2, 3, 4, 5, 6 ]
import os import multiprocessing import time import psycopg2 #os.system("myproject1\\runscrapy2.py") #from scrapy import cmdline #os.system("scrapy crawl parts") #cmdline.execute("cd myproject1".split()) #cmdline.execute("myproject1\\runscrapy.bat".split()) # start = time.perf_counter() connection = psycopg2.conne...
normal
{ "blob_id": "8e0d729fa55aabede123d89a507296b7d8a45c8b", "index": 1705, "step-1": "<mask token>\n\n\ndef urls():\n os.system('urls.bat')\n\n\ndef urls_1():\n os.system('urls_1.bat')\n\n\n<mask token>\n\n\ndef urls_3():\n os.system('urls_3.bat')\n\n\ndef urls_4():\n os.system('urls_4.bat')\n\n\ndef url...
[ 39, 53, 59, 67, 75 ]
"""Handles loading and tokenising of datasets""" import enum import numpy as np import os.path import pickle from tqdm import tqdm import nltk from nltk import WordPunctTokenizer nltk.download('punkt') from nltk.tokenize import word_tokenize from lib.utils import DATASETS_BASE_PATH, SAVED_POS_BASE_PATH from lib.pos im...
normal
{ "blob_id": "0150e1db3ef2f6c07280f21971b43ac71fc4cada", "index": 8984, "step-1": "<mask token>\n\n\nclass DatasetType(enum.Enum):\n \"\"\"\n Represents the type of dataset\n \"\"\"\n TRAIN = 0\n VAL = 1\n TEST = 2\n\n\nclass Language(enum.Enum):\n \"\"\"\n Represents the dataset language\...
[ 7, 8, 11, 12, 13 ]
# -*- coding: utf-8 -*- # Copyright (c) 2017 Feng Shuo # # 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 from itertools impo...
normal
{ "blob_id": "a299bd230a25a646060f85cffc8e84c534e2f805", "index": 8185, "step-1": "# -*- coding: utf-8 -*-\n# Copyright (c) 2017 Feng Shuo\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a cop...
[ 0 ]
#!/usr/bin/env python # Sanjaya Gajurel, Computational Scientist, Case Western Reserve University, April 2015 import vtk # ------------------------------------------------------------------------------ # Script Entry Point # ------------------------------------------------------------------------------ if __name__ ==...
normal
{ "blob_id": "de7515cb71c8e30018b14baf8846648d0c76a592", "index": 7461, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n print(\n 'vtkGraph: Building a graph using Unstructured Grid & dumping it in a vtk file, vertex.vtu, to be visualized using ParaView'\n )\n ...
[ 0, 1, 2, 3 ]
def assert_number(arg): if not isinstance(arg, (int, float)): raise TypeError(f"Expected number, got {type(arg)}")
normal
{ "blob_id": "2de62c73507acac597d70557adfe8286e2f28a1f", "index": 5569, "step-1": "<mask token>\n", "step-2": "def assert_number(arg):\n if not isinstance(arg, (int, float)):\n raise TypeError(f'Expected number, got {type(arg)}')\n", "step-3": "def assert_number(arg):\n if not isinstance(arg, (in...
[ 0, 1, 2 ]
#coding=utf-8 import unittest,time,os from time import sleep from appium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from HTMLTestRunner import HTMLTestRunner from appium.webdriver.common.touch_action import TouchAction from pub_Student import login,logout # Returns ...
normal
{ "blob_id": "8d7697a0e49dc9e966b9657171c66ccda57279d6", "index": 1930, "step-1": "<mask token>\n\n\nclass TestStudent(unittest.TestCase):\n\n def setUp(self):\n desired_caps = {}\n desired_caps['platformName'] = 'Android'\n desired_caps['platformVersion'] = '7.0'\n desired_caps['au...
[ 5, 6, 7, 8, 9 ]
#!/usr/bin/python2.7 import sys import datetime import psycopg2 import json import collections from pprint import pprint from pyral import Rally, rallyWorkset import copy import os import argparse from ConfigParser import SafeConfigParser import traceback global rally global server_name """ WARNING: This was hacked...
normal
{ "blob_id": "be0afa5184f753ed5f9a483379a4d81cd7af4886", "index": 6845, "step-1": "#!/usr/bin/python2.7\nimport sys\nimport datetime\nimport psycopg2\nimport json\nimport collections\nfrom pprint import pprint\nfrom pyral import Rally, rallyWorkset\nimport copy\nimport os\nimport argparse\nfrom ConfigParser impor...
[ 0 ]
from vkaudiotoken import get_vk_official_token import requests import json import telebot import urllib import sys #check start args try: if len(sys.argv) != 4: raise Exception botApiKey = sys.argv[1] login = sys.argv[2] password = sys.argv[3] except: print('Not enough arguments') pr...
normal
{ "blob_id": "47817d6cf58ac54e501ed24ae3ababc821bdd5c8", "index": 1949, "step-1": "<mask token>\n\n\ndef getTracks(result):\n data = json.loads(result.content.decode('utf-8'))\n tracks = data['response']['items']\n tracks.reverse()\n return tracks\n\n\ndef getMp3FromM3u8(url):\n if url.find('index....
[ 3, 4, 5, 6, 7 ]
from flask import Flask, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://sql3354595:7Haz6Ng1fm@sql3.freemysqlhosting.net/sql3354595' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = 'mysecret' db = S...
normal
{ "blob_id": "d7240703bc4cf9b566e7b50a536c83497cd8c6d7", "index": 7116, "step-1": "<mask token>\n\n\nclass TipoUsuarios(db.Model):\n id = db.Column(db.Integer, primary_key=True, nullable=False)\n texto = db.Column(db.String(50))\n usuarios = db.relationship('Usuarios', backref='tipo', lazy='dynamic')\n\n...
[ 7, 8, 10, 11, 12 ]
import numpy as np from scipy.linalg import solve from matplotlib import pylab as plt def f(x): return (np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)) xx = np.arange(1, 15, 0.1) yy = f(xx) # 1 степень x = np.array([1,15]) y = f(x) A = np.array([[1,1], [1,15]]) w = solve(A, y) y1 = w[0] +...
normal
{ "blob_id": "a610ccf4fe154ee12de9212a10958fda2000b425", "index": 7122, "step-1": "<mask token>\n\n\ndef f(x):\n return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef f(x):\n return np.sin(x / 5) * np.exp(x / 10) + 5 * np.exp(-x / 2)\n\n\n<mask t...
[ 1, 2, 3, 4, 5 ]
import serial from settings import * class CommunicationController: def __init__(self): global board board = serial.Serial(ROBOT_SERIAL, BAUDRATE, serial.EIGHTBITS, timeout=0) self.count = 0 print("Communication controller") def sendCommand(self, right, back, left): self...
normal
{ "blob_id": "48291ab3deb1ca1ba672d3e642d55635a7270171", "index": 955, "step-1": "<mask token>\n\n\nclass CommunicationController:\n <mask token>\n\n def sendCommand(self, right, back, left):\n self.count += 1\n if self.count >= BUFFER_RESET_BOUND:\n board.reset_output_buffer()\n ...
[ 2, 3, 4, 5, 6 ]
version https://git-lfs.github.com/spec/v1 oid sha256:a2959c4cccf29b3797cc2e2dcef87ddb5a0779d9fb992bb38e190b791ae37eb0 size 88352
normal
{ "blob_id": "932bb7c9dbf3e97c966d2d7d537e747756831e30", "index": 608, "step-1": "version https://git-lfs.github.com/spec/v1\noid sha256:a2959c4cccf29b3797cc2e2dcef87ddb5a0779d9fb992bb38e190b791ae37eb0\nsize 88352\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ...
[ 0 ]
"""Those things that are core to tests. This module provides the most fundamental test entities, which include such things as: - Tests - Suites - Test states """ from __future__ import print_function __docformat__ = "restructuredtext" import os import textwrap import time import weakref import inspect from clevers...
normal
{ "blob_id": "cac9d84f20a79b115c84ff4fe8cf4640182a42d7", "index": 754, "step-1": "<mask token>\n\n\nclass Test(TestItem):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def abortRun(self):\n self._runHistory.pop()\n <m...
[ 33, 64, 81, 104, 122 ]