code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 3 18:27:30 2020
@author: PREET MODH
"""
for _ in range(int(input())):
n=int(input())
xco,yco=[],[]
flagx,flagy,xans,yans=1,1,0,0
for x in range(4*n-1):
x,y=input().split()
xco.append(int(x))
yco.append(int(y))
... | normal | {
"blob_id": "d3b0a1d8b9f800c5d34732f4701ea2183405e5b4",
"index": 9523,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor _ in range(int(input())):\n n = int(input())\n xco, yco = [], []\n flagx, flagy, xans, yans = 1, 1, 0, 0\n for x in range(4 * n - 1):\n x, y = input().split()\n ... | [
0,
1,
2
] |
# This is a module
class MyMath:
def isEven(num):
if(num%2==0):
return True
return False
def isOdd(num):
if(num%2==0):
return False
return True
def isPrime(num):
for i in range(2,num):
if num%i==0:
return ... | normal | {
"blob_id": "20d363f5d02cc0b1069aa8951999c0cb22b85613",
"index": 7578,
"step-1": "class MyMath:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Calsi:\n\n def add(num1, num2):\n return num1 + num2\n\n def sub(num1, num2):\n return num1 - num2\n\n def mul(num1, num2):\n ... | [
5,
6,
7,
8,
9
] |
# -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2017
# All rights reserved.
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source ... | normal | {
"blob_id": "ee489c2e313a96671db79398218f8604f7ae1bf3",
"index": 3569,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef collect_env():\n \"\"\"Collect the information of the running environments.\n\n Returns:\n dict: The environment information. The following fields are contained.\n\n ... | [
0,
1,
2,
3
] |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: legolas
#
# Created: 05.03.2015
# Copyright: (c) legolas 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
print "T... | normal | {
"blob_id": "08abb94424598cb54a6b16db68759b216682d866",
"index": 6254,
"step-1": "#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: legolas\n#\n# Created: 05.03.2015\n# Copyright: (c) legolas 2015\n# Licence: <your li... | [
0
] |
import math
from chainer import cuda
from chainer import function
from chainer.functions import Sigmoid
from chainer.utils import type_check
import numpy
def _as_mat(x):
if x.ndim == 2:
return x
return x.reshape(len(x), -1)
class Autoencoder(function.Function):
def __init__(self, in_size, hidde... | normal | {
"blob_id": "97eb599ae8bf726d827d6f8313b7cf2838f9c125",
"index": 4098,
"step-1": "<mask token>\n\n\nclass Autoencoder(function.Function):\n <mask token>\n\n def hidden(self, x):\n h = _Encoder(self.W, self.b1)(x)\n if self.activation is not None:\n h = self.activation(h)\n h... | [
11,
13,
14,
15,
17
] |
from channels.db import database_sync_to_async
from django.db.models import Q
from rest_framework.generics import get_object_or_404
from main.models import UserClient
from main.services import MainService
from .models import Message, RoomGroup, UsersRoomGroup
class AsyncChatService:
@staticmethod
@database_s... | normal | {
"blob_id": "d71ffd022d87aa547b2a379f4c92d767b91212fd",
"index": 3827,
"step-1": "<mask token>\n\n\nclass ChatService:\n\n @staticmethod\n def is_room_exists(room_id: int) ->bool:\n return RoomGroup.objects.filter(id=room_id).exists()\n\n @staticmethod\n def create_users_room(**data) ->RoomGro... | [
6,
9,
11,
12,
13
] |
# coding=utf-8
import tensorflow as tf
import numpy as np
state = [[1.0000037e+00, 1.0000037e+00, 1.0000000e+00, 4.5852923e-01],
[1.0000000e+00, 1.0000000e+00, 1.0000000e+00, 8.3596563e-01],
[1.0000478e+00, 1.0000000e+00, 1.0000478e+00, 1.4663711e+00],
[1.0000037e+00, 1.0000478e+00, 1.00000... | normal | {
"blob_id": "5a3b88f899cfb71ffbfac3a78d38b748bffb2e43",
"index": 6295,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith tf.Session() as sess:\n sess.run(tf.initialize_all_variables())\n result = sess.run(fetches=s_t, feed_dict={s_t: [state]})\n print(result)\n result = sess.run(fetches=con... | [
0,
1,
2,
3,
4
] |
class Solution:
def minimumDeviation(self, nums: List[int]) ->int:
hq, left, right, res = [], inf, 0, inf
for num in nums:
if num % 2:
num = num * 2
heapq.heappush(hq, -num)
left = min(left, num)
while True:
right = -heapq.heap... | normal | {
"blob_id": "975b2f3443e19f910c71f872484350aef9f09dd2",
"index": 7370,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def minimumDeviation(self, nums: List[int]) ->int:\n hq, left, right, res = [], inf, 0, inf\n for num in nums:\n ... | [
0,
1,
2
] |
import sys, os, json
sys.path.append(os.path.join(os.path.dirname(__file__), "requests"))
import requests
def findNonPrefixes(prefix, array):
result = []
prefixLength = len(prefix)
for string in array:
if string[0:prefixLength] != prefix:
result.append(string)
return result
def run ():
r = requests.post("... | normal | {
"blob_id": "8419aee5dbc64b51f3c0f364716aad1630f00fe9",
"index": 7173,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef findNonPrefixes(prefix, array):\n result = []\n prefixLength = len(prefix)\n for string in array:\n if string[0:prefixLength] != prefix:\n result.append... | [
0,
2,
3,
4,
5
] |
"""
This module is an intermediate layer between flopy version 3.2
and the inowas-modflow-configuration format.
Author: Ralf Junghanns
EMail: ralf.junghanns@gmail.com
"""
from .BasAdapter import BasAdapter
from .ChdAdapter import ChdAdapter
from .DisAdapter import DisAdapter
from .GhbAdapter import GhbAdapter
from .L... | normal | {
"blob_id": "fb64003c1acbddcbe952a17edcbf293a54ef28ae",
"index": 2185,
"step-1": "<mask token>\n\n\nclass InowasFlopyCalculationAdapter:\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 def __init__(self, versio... | [
7,
11,
12,
13,
14
] |
import pandas
from sklearn.externals import joblib
import TrainTestProcesser
from sklearn.ensemble import RandomForestClassifier
from Select_OF_File import get_subdir
import matplotlib.pyplot as mp
import sklearn.model_selection as ms
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classificati... | normal | {
"blob_id": "b0bc55ab05d49605e2f42ea036f8405727c468d2",
"index": 3504,
"step-1": "<mask token>\n\n\ndef main():\n data_set = pandas.read_csv('dataset.csv', index_col=False, encoding='gbk')\n print('数据集的shape:', data_set.shape)\n dnumpy_x, dnumpy_y = TrainTestProcesser.split_dframe_x_y(data_set)\n fol... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/python
#_*_coding:utf-8_*_
import random
def main():
source = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ."
words = source.strip().split(" ")
new_str = list()
for word in words:
if len(word) > 4:
shuff... | normal | {
"blob_id": "14b98186fbc9c275cea3c042cdb4899f6d0c54c6",
"index": 3419,
"step-1": "#!/usr/bin/python\n#_*_coding:utf-8_*_\n\nimport random\n\ndef main():\n source = \"I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .\"\n words = source.strip().... | [
0
] |
# Ömer Malik Kalembaşı 150180112
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
img = plt.imread("clown.bmp")
u, s, v = np.linalg.svd(img)
zeros = np.zeros((200, 320))
for i in range(200):
zeros[i, i] = s[i]
for n in range(1, 7):
r = 2**i
p = np.dot(u, zeros[:... | normal | {
"blob_id": "b76b188dc77077ae70f320d01e9410d44b171974",
"index": 1903,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(200):\n zeros[i, i] = s[i]\nfor n in range(1, 7):\n r = 2 ** i\n p = np.dot(u, zeros[:, :r])\n svd = np.dot(p, v[:r, :])\n fig.add_subplot(3, 2, n)\n plt.... | [
0,
1,
2,
3,
4
] |
import sys
from reportlab.graphics.barcode import code39
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from parseAccessionNumbers import parseFile
def main():
if len(sys.argv) <= 1:
print "No filepath argument passed."
return
... | normal | {
"blob_id": "bc32518e5e37d4055f1bf5115953948a2bb24ba6",
"index": 3506,
"step-1": "import sys\nfrom reportlab.graphics.barcode import code39\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.lib.units import mm\nfrom reportlab.pdfgen import canvas\nfrom parseAccessionNumbers import parseFile\n\n\ndef ma... | [
0
] |
__source__ = 'https://leetcode.com/problems/merge-two-binary-trees/'
# Time: O(n)
# Space: O(n)
#
# Description: Leetcode # 617. Merge Two Binary Trees
#
# Given two binary trees and imagine that when you put one of them to cover the other,
# some nodes of the two trees are overlapped while the others are not.
#
# You... | normal | {
"blob_id": "42371760d691eac9c3dfe5693b03cbecc13fd94d",
"index": 6066,
"step-1": "<mask token>\n\n\nclass Solution(object):\n <mask token>\n\n\nclass TestMethods(unittest.TestCase):\n\n def test_Local(self):\n self.assertEqual(1, 1)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution... | [
3,
4,
7,
8,
10
] |
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import xml.etree.ElementTree as ET
tree = ET.parse('iliad1.xml')
root = tree.getroot()
file = open('iliad1_clean.txt','w')
for l in root.iter('l'):
file.write(''.join(l.itertext()) + "\n")
file.close() | normal | {
"blob_id": "cfea7848dfb41c913e5d8fec2f0f4f8afaaa09f3",
"index": 5928,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nreload(sys)\nsys.setdefaultencoding('utf-8')\n<mask token>\nfor l in root.iter('l'):\n file.write(''.join(l.itertext()) + '\\n')\nfile.close()\n",
"step-3": "<mask token>\nreload(sys... | [
0,
1,
2,
3,
4
] |
import numpy as np
import cPickle as pkl
data_l = []
data_path = "/home/marc/data/"
with open(data_path+'covtype.data') as fp:
for line in fp:
tmp_l = [ int(elem) for elem in line.split(',') ]
data_l.append(tmp_l)
data = np.array(data_l)
np.random.shuffle(data)
quintil = data.shape[0]/5
train_x = data[:qu... | normal | {
"blob_id": "c8975306473dda49be6c5f19f6663214ec7e7105",
"index": 7655,
"step-1": "import numpy as np\nimport cPickle as pkl\n\n\n\ndata_l = []\ndata_path = \"/home/marc/data/\"\nwith open(data_path+'covtype.data') as fp:\n for line in fp:\n\t\ttmp_l = [ int(elem) for elem in line.split(',') ]\n\t\tdata_l.appe... | [
0
] |
import os
import sys
import glob
import argparse
import shutil
import subprocess
import numpy as np
from PIL import Image
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision.utils import save_image
sys.path.append(os.pardir)
from model... | normal | {
"blob_id": "d6c06a465c36430e4f2d355450dc495061913d77",
"index": 5357,
"step-1": "<mask token>\n\n\ndef main():\n global device\n args = parse_args()\n cfg = Config.from_file(args.config)\n out = cfg.train.out\n if not os.path.exists(out):\n os.makedirs(out)\n cuda = torch.cuda.is_availa... | [
4,
6,
7,
8,
9
] |
# -*- coding: utf-8; -*-
import gherkin
from gherkin import Lexer, Parser, Ast
def test_lex_test_eof():
"lex_text() Should be able to find EOF"
# Given a lexer that takes '' as the input string
lexer = gherkin.Lexer('')
# When we try to lex any text from ''
new_state = lexer.lex_text()
# T... | normal | {
"blob_id": "44649e44da4eb80e7f869ff906798d5db493b913",
"index": 4415,
"step-1": "<mask token>\n\n\ndef test_lex_comment_no_newline():\n lexer = gherkin.Lexer(' test comment')\n new_state = lexer.lex_comment_metadata_value()\n lexer.tokens.should.equal([(1, gherkin.TOKEN_META_VALUE, 'test comment')])\n ... | [
23,
35,
36,
40,
42
] |
from PIL import Image
source = Image.open("map4.png")
img = source.load()
map_data = {}
curr_x = 1
curr_y = 1
#Go over each chunk and get the pixel info
for x in range(0, 100, 10):
curr_x = x+1
for y in range(0, 100, 10):
curr_y = y+1
chunk = str(curr_x)+"X"+str(curr_y)
if chunk not in map_data:
map_data[... | normal | {
"blob_id": "297b2ff6c6022bd8aac09c25537a132f67e05174",
"index": 525,
"step-1": "from PIL import Image\n\nsource = Image.open(\"map4.png\")\nimg = source.load()\n\nmap_data = {}\n\ncurr_x = 1\ncurr_y = 1\n#Go over each chunk and get the pixel info\nfor x in range(0, 100, 10):\n\tcurr_x = x+1\n\tfor y in range(0,... | [
0
] |
from metricsManager import MetricsManager
def TestDrawGraphs():
manager = MetricsManager()
manager.displayMetricsGraph()
return
def main():
TestDrawGraphs()
if __name__ == "__main__":
main()
| normal | {
"blob_id": "4e8a5b0ba13921fb88d5d6371d50e7120ab01265",
"index": 737,
"step-1": "<mask token>\n\n\ndef TestDrawGraphs():\n manager = MetricsManager()\n manager.displayMetricsGraph()\n return\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef TestDrawGraphs():\n manager = MetricsManager()\n m... | [
1,
2,
3,
4,
5
] |
#!/usr/bin/python
# Find minimal distances between clouds in one bin, average these per bin
# Compute geometric and arithmetical mean between all clouds per bin
from netCDF4 import Dataset as NetCDFFile
from matplotlib import pyplot as plt
import numpy as np
from numpy import ma
from scipy import stats
from haversin... | normal | {
"blob_id": "1c6e6394a6bd26b152b2f5ec87eb181a3387f794",
"index": 5894,
"step-1": "#!/usr/bin/python\n\n# Find minimal distances between clouds in one bin, average these per bin\n# Compute geometric and arithmetical mean between all clouds per bin\n\nfrom netCDF4 import Dataset as NetCDFFile\nfrom matplotlib impo... | [
0
] |
import stockquote
import time
import datetime
from datetime import date
from connection import db
start_date='20100101'
def prices(symbol):
"""
Loads the prices from the start date for the given symbol
Only new quotes are downloaded.
"""
to = date.today().strftime("%Y%m%d")
c = db.cursor()
c.execute("SEL... | normal | {
"blob_id": "1b58d294f02ce85bf19da03f94100af87408081d",
"index": 1326,
"step-1": "import stockquote\nimport time\nimport datetime\nfrom datetime import date\nfrom connection import db\n\nstart_date='20100101'\ndef prices(symbol):\n \"\"\"\n Loads the prices from the start date for the given symbol\n Only new ... | [
0
] |
#题目014:将一个正整数分解质因数
#【编程思路】类似手算分解质因数的过程,找出因数后,原数字缩小
'''
找出质因数并不难,把他们打印出来有点小烦
'''
num = int(input('请输入一个整数:'))
original=num
a= []
while num > 1:
for i in range(2,num+1):
if num%i == 0:
a.append(i)
num = num//i
break
print("%d ="%(original),end='')
for i... | normal | {
"blob_id": "78e72bf3ac73113e2c71caf5aed70b53cafa9c46",
"index": 3413,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile num > 1:\n for i in range(2, num + 1):\n if num % i == 0:\n a.append(i)\n num = num // i\n break\nprint('%d =' % original, end='')\nfor i ... | [
0,
1,
2,
3
] |
import matplotlib.pyplot as plt
x_int = list(range(1, 5001))
y_int = [i**3 for i in x_int]
plt.scatter(x_int, y_int, c=y_int, cmap=plt.cm.Blues, s=40)
plt.show()
| normal | {
"blob_id": "40e2b695d8aaaa82cb90694b85d12061b4e6eca8",
"index": 8034,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.scatter(x_int, y_int, c=y_int, cmap=plt.cm.Blues, s=40)\nplt.show()\n",
"step-3": "<mask token>\nx_int = list(range(1, 5001))\ny_int = [(i ** 3) for i in x_int]\nplt.scatter(x_int, ... | [
0,
1,
2,
3,
4
] |
import urllib.request
from urllib.request import Request, urlopen
import json
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
"""
Web Scraper ======================================================================
"""
... | normal | {
"blob_id": "4c9a3983180cc75c39da41f7f9b595811ba0dc35",
"index": 8390,
"step-1": "<mask token>\n\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise retu... | [
5,
6,
7,
8,
9
] |
# -*- coding: utf-8 -*-
import csv
import datetime
from django.conf import settings
from django.contrib import admin
from django.http import HttpResponse
from django.utils.encoding import smart_str
from djforms.scholars.models import *
def export_scholars(modeladmin, request, queryset):
"""Export t... | normal | {
"blob_id": "1ae69eaaa08a0045faad13281a6a3de8f7529c7a",
"index": 9761,
"step-1": "<mask token>\n\n\nclass PresentationAdmin(admin.ModelAdmin):\n <mask token>\n model = Presentation\n actions = [export_scholars]\n raw_id_fields = 'user', 'updated_by', 'leader'\n list_max_show_all = 500\n list_pe... | [
7,
9,
11,
12,
13
] |
# - Generated by tools/entrypoint_compiler.py: do not edit by hand
"""
NGramHash
"""
import numbers
from ..utils.entrypoints import Component
from ..utils.utils import try_set
def n_gram_hash(
hash_bits=16,
ngram_length=1,
skip_length=0,
all_lengths=True,
seed=314489979,
... | normal | {
"blob_id": "fb1974ad7ac9ae54344812814cb95a7fccfefc66",
"index": 5880,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef n_gram_hash(hash_bits=16, ngram_length=1, skip_length=0, all_lengths=\n True, seed=314489979, ordered=True, invert_hash=0, **params):\n \"\"\"\n **Description**\n ... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
## File is released under public domain and you can use without limitations
#########################################################################
... | normal | {
"blob_id": "93c465f017542cfe9cbc55da0ae5a9e34663cf32",
"index": 1978,
"step-1": "# -*- coding: utf-8 -*-\n\n#########################################################################\n## This scaffolding model makes your app work on Google App Engine too\n## File is released under public domain and you can use w... | [
0
] |
from rest_framework import serializers
from dailytasks.models import Tasks
class TasksSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
class Meta:
model = Tasks
fields = ['id', 'created', 'title', 'description', 'status', 'user']
| normal | {
"blob_id": "3fa1736fd87448ec0da4649153521d0aba048ccf",
"index": 3689,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass TasksSerializer(serializers.ModelSerializer):\n <mask token>\n\n\n class Meta:\n model = Tasks\n fields = ['id', 'created', 'title', 'description', 'status',... | [
0,
1,
2,
3
] |
###############################################################################
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by ... | normal | {
"blob_id": "53909b750f259b67b061ba26d604e0c2556376df",
"index": 9560,
"step-1": "<mask token>\n\n\nclass CurationLists(object):\n <mask token>\n <mask token>\n\n def pseudo_tree(self, gids, out_tree):\n \"\"\"Create pseudo-tree with the specified genome IDs.\"\"\"\n pseudo_tree = '('\n ... | [
4,
5,
6,
9,
10
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from trest.utils import utime
from trest.logger import SysLogger
from trest.config import settings
from trest.exception import JsonError
from applications.common.models.user import User
class UserService(object):
@staticmethod
def page_list(where, page, per_page):... | normal | {
"blob_id": "d1ed43bab6171c876b2ad9ef9db834ab8f9026d5",
"index": 8411,
"step-1": "<mask token>\n\n\nclass UserService(object):\n <mask token>\n\n @staticmethod\n def get(id):\n \"\"\"获取单条记录\n\n [description]\n\n Arguments:\n id int -- 主键\n\n return:\n Us... | [
3,
4,
5,
6,
7
] |
import copy
import sys
import os
from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta
import numpy as np
import pandas
import tsprocClass as tc
import pestUtil as pu
#update parameter values and fixed/unfixed
#--since Joe is so pro-America...
tc.DATE_FMT = '%m/%d/%Y'
#--build ... | normal | {
"blob_id": "c060cdb7730ba5c4d2240b65331f5010cac222fa",
"index": 8721,
"step-1": "import copy\nimport sys\nimport os\nfrom datetime import datetime,timedelta\nfrom dateutil.relativedelta import relativedelta\nimport numpy as np\nimport pandas\n\nimport tsprocClass as tc \nimport pestUtil as pu \n\n#update param... | [
0
] |
import sys
sys.stdin = open('4828.txt', 'r')
sys.stdout = open('4828_out.txt', 'w')
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
l = list(map(int, input().split()))
min_v = 1000001
max_v = 0
i = 0
while i < N:
if l[i] < min_v:
min_v = l[i]
if l[... | normal | {
"blob_id": "2b5df70c75f2df174991f6b9af148bdcf8751b61",
"index": 4275,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor test_case in range(1, T + 1):\n N = int(input())\n l = list(map(int, input().split()))\n min_v = 1000001\n max_v = 0\n i = 0\n while i < N:\n if l[i] < min_v:... | [
0,
1,
2,
3
] |
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.db.models import Count
from django.db.models import QuerySet
from django.db import connection
from django.core.paginator import Paginator, PageNotAnInteger
from django.http import HttpResponse
from django.http import H... | normal | {
"blob_id": "bcc959dcdb60c55897158e85d73c59592b112c12",
"index": 6381,
"step-1": "<mask token>\n\n\nclass FastCountQuerySet:\n\n def __init__(self, queryset, tablename):\n self.queryset = queryset\n self.tablename = tablename\n\n def count(self):\n cursor = connection.cursor()\n ... | [
25,
26,
28,
29,
35
] |
import cachetools
cache = cachetools.LRUCache(maxsize = 3)
cache['PyCon'] = 'India'
cache['year'] = '2017'
print("Older: " + cache['year'])
cache['year'] = '2018'
print("Newer: " + cache['year'])
print(cache)
cache['sdate'] = '05/09/2018'
print(cache)
cache['edate'] = '09/09/2018'
print(cache) | normal | {
"blob_id": "aebc918d6a1d1d2473f74d77b8a915ac25548e3a",
"index": 443,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Older: ' + cache['year'])\n<mask token>\nprint('Newer: ' + cache['year'])\nprint(cache)\n<mask token>\nprint(cache)\n<mask token>\nprint(cache)\n",
"step-3": "<mask token>\ncache ... | [
0,
1,
2,
3,
4
] |
"""
USAGE:
o install in develop mode: navigate to the folder containing this file,
and type 'python setup.py develop --user'.
(ommit '--user' if you want to install for
all users)
"""
from setupt... | normal | {
"blob_id": "cfa862988edf9d70aa5e975cca58b4e61a4de847",
"index": 759,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='gromacsplotter', version='0.1', description=\n 'Read xvg files created with gromacs for plotting with matplotlib', url\n ='', author='Ilyas Kuhlemann', author_email='ilya... | [
0,
1,
2,
3
] |
import wikipedia
input_ = input("Type in your question ")
print(wikipedia.summary(input_))
| normal | {
"blob_id": "5eb5388ffe7a7c880d8fcfaa137c2c9a133a0636",
"index": 713,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(wikipedia.summary(input_))\n",
"step-3": "<mask token>\ninput_ = input('Type in your question ')\nprint(wikipedia.summary(input_))\n",
"step-4": "import wikipedia\ninput_ = input... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... | normal | {
"blob_id": "eb1737ac671129ed3459ce4feacb81d414eef371",
"index": 5667,
"step-1": "<mask token>\n\n\n@pytest.fixture(scope='module')\ndef module_scope_prefix(request, session_scope_prefix):\n \"\"\"\n Generate a name prefix to be shared by objects created during this pytest module\n Relies on pytest's bu... | [
17,
20,
21,
23,
45
] |
import numpy as np
# data I/O
data = open('input.txt', 'r').read() # should be simple plain text file
chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print("chars: ", chars)
#one-hot encoding
char_to_ix = { ch:i for i,ch in enumerate(chars) }
ix_to_char = { i:ch for i,ch in enumerate(chars) }
it... | normal | {
"blob_id": "d988cfebeec37df700f46bbb027a4980ba624d30",
"index": 6639,
"step-1": "<mask token>\n\n\ndef lossFun(inputs, targets, hprev):\n x, h, yprime = {}, {}, {}\n h[-1] = np.copy(hprev)\n loss = 0\n for t in range(len(inputs)):\n x[t] = np.zeros((vocab_size, 1))\n x[t][inputs[t]] = ... | [
1,
2,
3,
4,
5
] |
from pathlib import Path
from typing import Union
from archinst.cmd import run
def clone(url: str, dest: Union[Path, str]):
Path(dest).mkdir(parents=True, exist_ok=True)
run(
["git", "clone", url, str(dest)],
{
"GIT_SSH_COMMAND": "ssh -o UserKnownHostsFile=/dev/null -o StrictHostK... | normal | {
"blob_id": "d85261268d9311862e40a4fb4139158544c654b3",
"index": 2394,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef clone(url: str, dest: Union[Path, str]):\n Path(dest).mkdir(parents=True, exist_ok=True)\n run(['git', 'clone', url, str(dest)], {'GIT_SSH_COMMAND':\n 'ssh -o UserKno... | [
0,
1,
2,
3
] |
from django import forms
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import time
from page.models import Submit, Assignment
class UploadFileForm(forms.ModelForm):
class Meta:
model = Submit
fields = ['email', 'student_no', 'file']
@csrf_exempt
def up... | normal | {
"blob_id": "dabc38db6a5c4d97e18be2edc9d4c6203e264741",
"index": 3849,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass UploadFileForm(forms.ModelForm):\n\n\n class Meta:\n model = Submit\n fields = ['email', 'student_no', 'file']\n\n\n<mask token>\n",
"step-3": "<mask token>\n... | [
0,
1,
2,
3,
4
] |
"""
Schema management for various object types (publisher, dataset etc). Loads
the jsonschema and allows callers to validate a dictionary against them.
"""
import os
import json
import pubtool.lib.validators as v
from jsonschema import validate, validators
from jsonschema.exceptions import ValidationError
SCHEMA = ... | normal | {
"blob_id": "c4f39f9212fbe0f591543d143cb8f1721c1f8e1e",
"index": 7056,
"step-1": "<mask token>\n\n\nclass ObjectValidationErrors(Exception):\n\n def __init__(self, errors):\n self.errors = errors\n\n\ndef _get_directory():\n p = os.path.dirname(__file__)\n p = os.path.join(p, os.pardir, os.pardir... | [
3,
5,
6,
7,
8
] |
# coding: utf-8
# ## Estimating Travel Time
#
#
# The objective of this document is proposing a prediction model for estimating the travel time of two
# specified locations at a given departure time. The main idea here is predicting the velocity of the trip. Given the distance between starting and ending point of t... | normal | {
"blob_id": "c1bb7b579e6b251ddce41384aef1243e411c5d0e",
"index": 1018,
"step-1": "<mask token>\n\n\ndef distance(row):\n source = row['start_lat'], row['start_lng']\n dest = row['end_lat'], row['end_lng']\n return vincenty(source, dest).miles\n\n\n<mask token>\n\n\ndef dropoff_to_MH(row):\n \"\"\"fin... | [
8,
9,
11,
12,
15
] |
# -*- coding: utf-8 -*-
###############################################################################
# This file is part of metalibm (https://github.com/kalray/metalibm)
###############################################################################
# MIT License
#
# Copyright (c) 2018 Kalray
#
# Permission is here... | normal | {
"blob_id": "3a05ebee8e70321fe53637b4792f5821ce7044be",
"index": 4264,
"step-1": "<mask token>\n\n\ndef evaluate_comparison_range(node):\n \"\"\" evaluate the numerical range of Comparison node, if any\n else returns None \"\"\"\n return None\n\n\ndef is_comparison(node):\n \"\"\" test if node is... | [
14,
15,
16,
17,
18
] |
#!/usr/bin/env python
# -------------------------------------------------------------------------
# Copyright (c) Microsoft, Intel Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------... | normal | {
"blob_id": "a61132d2d504ed31d4e1e7889bde670853968559",
"index": 5739,
"step-1": "<mask token>\n\n\nclass CalibraterBase:\n\n def __init__(self, model_path: Union[str, Path], op_types_to_calibrate:\n Optional[Sequence[str]]=None, augmented_model_path=\n 'augmented_model.onnx', symmetric=False, u... | [
46,
56,
59,
60,
68
] |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 10:39:55 2019
@author: PC
"""
import pandas as pd
dictionary={"Name":["Ali","Buse","Selma","Hakan","Bülent","Yağmur","Ahmet"],
"Age":[18,45,12,36,40,18,63],
"Maas":[100,200,400,500,740,963,123]}
dataFrame1=pd.DataFrame(dictionary) ... | normal | {
"blob_id": "efa94f8442c9f43234d56a781d2412c9f7ab1bb3",
"index": 7910,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(dataFrame1.columns)\nprint(dataFrame1.info())\nprint(dataFrame1.dtypes)\nprint(dataFrame1.describe())\n",
"step-3": "<mask token>\ndictionary = {'Name': ['Ali', 'Buse', 'Selma', '... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
"""
app definition
"""
from django.apps import AppConfig
class CoopHtmlEditorAppConfig(AppConfig):
name = 'coop_html_editor'
verbose_name = "Html Editor"
| normal | {
"blob_id": "641cbe2f35925d070249820a2e3a4f1cdd1cf642",
"index": 8697,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass CoopHtmlEditorAppConfig(AppConfig):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass CoopHtmlEditorAppConfig(AppConfig):\n name = 'coop_html_edito... | [
0,
1,
2,
3,
4
] |
import ctypes
from game import GameWindow
import start_window as m_window
def start_button_callback(obj, w, h, amount):
_max = int(w.get()) * int(h.get())
if not (obj.validation_check(w) and obj.validation_check(h) and obj.validation_check(amount, _max)):
ctypes.windll.user32.MessageBoxW(0, "Wprowadź... | normal | {
"blob_id": "65eb7d01ccea137605d54d816b707c2cd3709931",
"index": 2067,
"step-1": "<mask token>\n\n\ndef start_button_callback(obj, w, h, amount):\n _max = int(w.get()) * int(h.get())\n if not (obj.validation_check(w) and obj.validation_check(h) and obj.\n validation_check(amount, _max)):\n ct... | [
1,
2,
3,
4,
5
] |
"""
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1, 2, 2, 3, 4, 4, 3]
Output: true
1
/ \
2 2
/ \ / \
3 4 4 3
Example 2:
Input: root = [1, 2, 2, None, 3, None, 3]
Output: false
1
/ ... | normal | {
"blob_id": "9cfbb06df4bc286ff56983d6e843b33e4da6ccf8",
"index": 7803,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef is_symmetric(root):\n\n def helper(left, right):\n if left is None and right is None:\n return True\n elif left and right:\n return helper(l... | [
0,
1,
2,
3,
4
] |
import tensorflow as tf
import cv2
img=cv2.imread('d:\st.jpg',0)
cv2.namedWindow('st',cv2.WINDOW_NORMAL)#可以调整图像窗口大小
cv2.imshow('st',img)
cv2.imwrite('mes.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows() | normal | {
"blob_id": "6b5399effe73d27eade0381f016cd7819a6e104a",
"index": 2466,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncv2.namedWindow('st', cv2.WINDOW_NORMAL)\ncv2.imshow('st', img)\ncv2.imwrite('mes.png', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n",
"step-3": "<mask token>\nimg = cv2.imread('d:\\... | [
0,
1,
2,
3,
4
] |
from graphics.rectangle import *
from graphics.circle import *
from graphics.DGraphics.cuboid import *
from graphics.DGraphics.sphere import *
print ("------rectangle-------")
l=int(input("enter length : "))
b=int(input("enter breadth : "))
print("area of rectangle : ",RectArea(1,b))
print("perimeter of rectang... | normal | {
"blob_id": "f275085a2e4e3efc8eb841b5322d9d71f2e43846",
"index": 7998,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('------rectangle-------')\n<mask token>\nprint('area of rectangle : ', RectArea(1, b))\nprint('perimeter of rectangle : ', Rectperimeter(1, b))\nprint()\nprint('-------circle-------... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
from http.client import HTTPConnection
import pytest
from circuits.web import Controller
from circuits.web.client import Client, request
from .helpers import urlopen
class Root(Controller):
def index(self):
return "Hello World!"
def request_body(self):
return self.r... | normal | {
"blob_id": "eb891341488e125ae8c043788d7264fff4018614",
"index": 6585,
"step-1": "<mask token>\n\n\nclass Root(Controller):\n\n def index(self):\n return 'Hello World!'\n\n def request_body(self):\n return self.request.body.read()\n\n def response_body(self):\n return 'ä'\n\n def... | [
8,
9,
11,
12,
15
] |
STATUS_DISCONNECT = 0
STATUS_CONNECTED = 1
STATUS_OPEN_CH_REQUEST = 2
STATUS_OPENED = 3
STATUS_EXITING = 4
STATUS_EXITTED = 5
CONTENT_TYPE_IMAGE = 0
CONTENT_TYPE_VIDEO = 1
STATUS_OK = 0
STATUS_ERROR = 1
class Point(object):
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
class ObjectDe... | normal | {
"blob_id": "0ceb9eac46e3182821e65a1ae3a69d842db51e62",
"index": 7879,
"step-1": "<mask token>\n\n\nclass ObjectDetectionResult(object):\n\n def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):\n self.object_class = 0\n self.confidence = 0\n self.lt = Point(ltx, lty)\n self.r... | [
3,
4,
5,
6,
7
] |
containerized: "docker://quay.io/snakemake/containerize-testimage:1.0"
rule a:
output:
"test.out"
conda:
"env.yaml"
shell:
"bcftools 2> {output} || true"
| normal | {
"blob_id": "6e0d09bd0c9d1d272f727817cec65b81f83d02f5",
"index": 6742,
"step-1": "containerized: \"docker://quay.io/snakemake/containerize-testimage:1.0\"\n\nrule a:\n output:\n \"test.out\"\n conda:\n \"env.yaml\"\n shell:\n \"bcftools 2> {output} || true\"\n",
"step-2": null,
... | [
0
] |
# Generated by Django 2.2.1 on 2019-05-05 18:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='divida',
name='id_cliente',
... | normal | {
"blob_id": "1ce7b292f89fdf3f978c75d4cdf65b6991f71d6f",
"index": 7499,
"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 = [('core', '000... | [
0,
1,
2,
3,
4
] |
from pyspark.sql import SparkSession, Row, functions, Column
from pyspark.sql.types import *
from pyspark.ml import Pipeline, Estimator
from pyspark.ml.feature import SQLTransformer, VectorAssembler
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.tuning import TrainValidationSplit, ParamGridBuild... | normal | {
"blob_id": "3852ff2f3f4ac889256bd5f4e36a86d483857cef",
"index": 6534,
"step-1": "<mask token>\n\n\ndef get_data(inputloc, tablename='data'):\n data = spark.read.csv(inputloc, schema=schema)\n data.createOrReplaceTempView(tablename)\n return data\n\n\n<mask token>\n\n\ndef resolved_max(df):\n df_max ... | [
4,
5,
6,
7,
8
] |
import pygame
from pygame.locals import *
import threading
from load import *
import time
import socket as sck
import sys
port=8767
grid=[[None,None,None],[None,None,None],[None,None,None]]
XO='X'
OX='X'
winner=None
coordinate1=600
coordinate2=20
begin=0
address=('localhost',port)
class TTTError(Exception):
def __i... | normal | {
"blob_id": "b6d9b6ec10271627b7177acead9a617520dec8f8",
"index": 5146,
"step-1": "import pygame\nfrom pygame.locals import *\n\nimport threading\nfrom load import *\nimport time\nimport socket as sck\nimport sys\n\nport=8767\ngrid=[[None,None,None],[None,None,None],[None,None,None]]\nXO='X'\nOX='X'\nwinner=None\... | [
0
] |
import numpy as np
import pandas as pd
import sklearn
import sklearn.preprocessing
import matplotlib.pyplot as plt
import tensorflow as tf
from enum import Enum
from pytalib.indicators import trend
from pytalib.indicators import base
class Cell(Enum):
BasicRNN = 1
BasicLSTM = 2
LSTMCellPeephole = 3
GR... | normal | {
"blob_id": "4379d89c2ada89822acbf523d2e364599f996f8c",
"index": 5456,
"step-1": "<mask token>\n\n\nclass Cell(Enum):\n BasicRNN = 1\n BasicLSTM = 2\n LSTMCellPeephole = 3\n GRU = 4\n\n\n<mask token>\n\n\ndef normalize_data(df):\n min_max_scaler = sklearn.preprocessing.MinMaxScaler()\n df['Open... | [
7,
8,
9,
10,
12
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-08-03 02:31
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... | normal | {
"blob_id": "cdd929ee041c485d2a6c1149ea1b1ced92d7b7ab",
"index": 5972,
"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
] |
import pandas as pd
df = pd.read_csv('~/Documents/data/tables.csv')
mdfile = open('tables_with_refs.md', 'w')
mdfile.write('# Tables with references\n')
for i, row in df.iterrows():
t = '\n```\n{% raw %}\n' + str(row['table']) + '\n{% endraw %}\n```\n'
r = '\n```\n{% raw %}\n' + str(row['refs']) + '\n{% endraw ... | normal | {
"blob_id": "8de6877f040a7234da73b55c8b7fdefe20bc0d6e",
"index": 9538,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmdfile.write('# Tables with references\\n')\nfor i, row in df.iterrows():\n t = '\\n```\\n{% raw %}\\n' + str(row['table']) + '\\n{% endraw %}\\n```\\n'\n r = '\\n```\\n{% raw %}\\n... | [
0,
1,
2,
3
] |
from setuptools import setup, find_packages
setup(
name='testspace-python',
version='',
packages=find_packages(include=['testspace', 'testspace.*']),
url='',
license="MIT license",
author="Jeffrey Schultz",
author_email='jeffs@s2technologies.com',
description="Module for interacting wit... | normal | {
"blob_id": "7bc2a02d85c3b1a2b7ed61dc7567d1097b63d658",
"index": 3559,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='testspace-python', version='', packages=find_packages(include=[\n 'testspace', 'testspace.*']), url='', license='MIT license', author=\n 'Jeffrey Schultz', author_email=... | [
0,
1,
2,
3
] |
import sqlite3 as lite
import sys
con = lite.connect("test.db")
with con:
cur = con.cursor()
cur.execute('''CREATE TABLE Cars(Id INT, Name TEXT, Price INT)''')
cur.execute('''INSERT INTO Cars VALUES(1, 'car1', 10)''')
cur.execute('''INSERT INTO Cars VALUES(2, 'car2', 20)''')
cur.execute('''INSERT INTO C... | normal | {
"blob_id": "db22e568c86f008c9882181f5c1d88d5bca28570",
"index": 5416,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith con:\n cur = con.cursor()\n cur.execute('CREATE TABLE Cars(Id INT, Name TEXT, Price INT)')\n cur.execute(\"INSERT INTO Cars VALUES(1, 'car1', 10)\")\n cur.execute(\"INSER... | [
0,
1,
2,
3,
4
] |
from __future__ import absolute_import
import sys
from apscheduler.executors.base import BaseExecutor, run_job
try:
import gevent
except ImportError: # pragma: nocover
raise ImportError('GeventExecutor requires gevent installed')
class GeventExecutor(BaseExecutor):
"""
Runs jobs as greenlets.
... | normal | {
"blob_id": "afcadc11d23fb921eb6f8038a908de02ee763ca4",
"index": 693,
"step-1": "<mask token>\n\n\nclass GeventExecutor(BaseExecutor):\n <mask token>\n\n def _do_submit_job(self, job, run_times):\n\n def callback(greenlet):\n try:\n events = greenlet.get()\n exce... | [
2,
3,
4,
5,
6
] |
from contextlib import contextmanager
from filecmp import cmp, dircmp
from shutil import copyfile, copytree, rmtree
import pytest
from demisto_sdk.commands.common.constants import PACKS_DIR, TEST_PLAYBOOKS_DIR
from demisto_sdk.commands.common.tools import src_root
TEST_DATA = src_root() / 'tests' / 'test_files'
TEST_... | normal | {
"blob_id": "8928c2ff49cbad2a54252d41665c10437a471eeb",
"index": 1404,
"step-1": "<mask token>\n\n\ndef same_folders(src1, src2):\n \"\"\"Assert if folder contains diffrent files\"\"\"\n dcmp = dircmp(src1, src2)\n if dcmp.left_only or dcmp.right_only:\n return False\n for sub_dcmp in dcmp.sub... | [
6,
8,
9,
12,
15
] |
import torch.nn as nn
from transformers import BertModel
class BertBasedTODModel(nn.Module):
def __init__(self, bert_type, num_intent_labels, num_slot_labels):
super(BertBasedTODModel, self).__init__()
self.bert_model = BertModel.from_pretrained(bert_type)
self.num_intent_labels = num_int... | normal | {
"blob_id": "74e70056ddfd8963a254f1a789a9058554c5489e",
"index": 2586,
"step-1": "<mask token>\n\n\nclass BertBasedTODModel(nn.Module):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass BertBasedTODModel(nn.Module):\n <mask token>\n\n def forward(self, input_ids, attention_mask, ... | [
1,
2,
3,
4
] |
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 9999))
clientsocket.send('hallooooo')
| normal | {
"blob_id": "7d3d4476343579a7704c4c2b92fafd9fa5da5bfe",
"index": 9294,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nclientsocket.connect(('localhost', 9999))\nclientsocket.send('hallooooo')\n",
"step-3": "<mask token>\nclientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclientsocket.con... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2021-04-09 06:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lkft', '0021_reportjob_finished_successfully'),
]
operations = [
migration... | normal | {
"blob_id": "787397473c431d2560bf8c488af58e976c1864d0",
"index": 6730,
"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 = [('lkft', '002... | [
0,
1,
2,
3,
4
] |
from .interface import AudioInterface
from .config import AudioConfig
from .buffer import CustomBuffer
| normal | {
"blob_id": "cc33d0cf1b922a6b48fb83be07acb35a62372f2e",
"index": 8260,
"step-1": "<mask token>\n",
"step-2": "from .interface import AudioInterface\nfrom .config import AudioConfig\nfrom .buffer import CustomBuffer\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
from gurobipy import *
import math
# params.NonConvex = 2
# K = 5
# R = {0: 1000, 1: 5000, 2: 10000, 3: 20000, 4: 69354} # imbalanced
# R = {0: 50, 1: 100, 2: 150, 3: 84, 4: 400} # imbalanced
# R = {0: 100, 1: 200, 2: 484} # imbalanced
# R = {0: 10, 1: 20, 2: 30, 3: 50, 4: 100} # imbalanced
# R = {0... | normal | {
"blob_id": "2ed9eafb6e26971f642d1e33cbb3d1f3df34990a",
"index": 3401,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef solve_model(K, R, N, L_max, G):\n print(\n 'parameters==| k=%d \\t |R=%s \\t |N=%d \\t |eta=%f \\t |L_max=%f \\t |G=%f'\n % (K, R, N, eta, L_max, G))\n R_sum ... | [
0,
1,
2,
3,
4
] |
from django.db import models
# Create your models here.
class person(models.Model):
name=models.CharField(max_length=20,unique=True)
age=models.IntegerField()
email=models.CharField(max_length=20,unique=True)
phone=models.CharField(max_length=10, unique=True)
gender=models.CharField(max_length=10)
... | normal | {
"blob_id": "efe5df4005dbdb04cf4e7da1f350dab483c94c92",
"index": 4459,
"step-1": "<mask token>\n\n\nclass person(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask ... | [
1,
2,
3,
4,
5
] |
from tkinter import *
from math import *
#Raiz
root=Tk()
root.title('Calculadora LE-1409')
root.iconbitmap('calculadora.ico')
root.geometry('510x480')
root.config(bg='gray42')
root.resizable(False, False)
#Pantalla
screen=Entry(root, font=("arial",20, "bold"), width=22, borderwidth=10, background="CadetBlue1", justi... | normal | {
"blob_id": "1a42892095d820f1e91ba5e7f2804b5a21e39676",
"index": 2107,
"step-1": "<mask token>\n\n\ndef click(valor):\n global i\n screen.insert(i, valor)\n i += 1\n\n\n<mask token>\n\n\ndef hacer_operacion():\n ecuacion = screen.get()\n try:\n result = eval(ecuacion)\n screen.delete... | [
2,
4,
5,
6,
7
] |
#!/usr/bin/env python
from math import *
import numpy as np
import matplotlib.pyplot as plt
import Input as para
data = np.loadtxt("eff-proton.dat")
#data = np.loadtxt("eff-electron.dat")
show_time = data[0]
show_eff = data[1]
#print show_turn, show_eff
#x_lower_limit = min(show_time)
#x_upper_limit = max(show_time)... | normal | {
"blob_id": "bee96e817dd4d9462c1e3f8eb525c22c2117140a",
"index": 9942,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.figure()\nplt.xlabel('Time (ms)', fontsize=30)\nplt.ylabel('Capture rate (%)', fontsize=30)\nplt.xticks(fontsize=25)\nplt.yticks(fontsize=25)\nplt.xlim(x_lower_limit, x_upper_limit)\n... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
#借鉴的扫码单文件
import qrcode
from fake_useragent import UserAgent
from threading import Thread
import time, base64
import requests
from io import BytesIO
import http.cookiejar as cookielib
from PIL import Image
import os
requests.packages.urllib3.disable_warnings()
ua = UserAgent(pa... | normal | {
"blob_id": "c268c61e47698d07b7c1461970dc47242af55777",
"index": 1637,
"step-1": "<mask token>\n\n\nclass showpng(Thread):\n\n def __init__(self, data):\n Thread.__init__(self)\n self.data = data\n\n def run(self):\n img = Image.open(BytesIO(self.data))\n img.show()\n\n\ndef isl... | [
4,
5,
7,
8,
9
] |
# lesson 4 Mateush Vilen
my_information = {
'name': 'Vilen',
'last_name': 'Mateush',
'how_old': 31,
'born_town': 'Khmelniysky'
}
dict_test = {key: key**2 for key in range(7)}
print('dict_test: ', dict_test)
elem_dict = 0
elem_dict = input('input number of elements:')
user_input_dict = {}
for key in ... | normal | {
"blob_id": "b000f293b50970233d5b71abc3e10e2ad57a3fc7",
"index": 1767,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('dict_test: ', dict_test)\n<mask token>\nfor key in range(0, int(elem_dict)):\n key = input('dict key: ')\n user_input_dict[key] = input('dict value:')\nprint(user_input_dict)... | [
0,
1,
2,
3
] |
try:
alp="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
idx=eval(input("请输入一个整数"))
print(alp[idx])
except NameError:
print("输入错误,请输入一个整数")
except:
print("其他错误")
else:
print("没有发生错误")
finally:
print("程序执行完毕,不知道是否发生了异常")
| normal | {
"blob_id": "99a6b450792d434e18b8f9ff350c72abe5366d95",
"index": 153,
"step-1": "<mask token>\n",
"step-2": "try:\n alp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n idx = eval(input('请输入一个整数'))\n print(alp[idx])\nexcept NameError:\n print('输入错误,请输入一个整数')\nexcept:\n print('其他错误')\nelse:\n print('没有发生错误')\... | [
0,
1,
2
] |
class Handlers():
change_store = "/change_store"
change_status = "/change_status"
mail = "/mail"
get_status = "/get_status"
create_order = "/create_order"
ask_store = "/ask_store"
check = "/check"
test = "/test"
| normal | {
"blob_id": "32e3eed2e279706bca2925d3d9d897a928243b4c",
"index": 4518,
"step-1": "<mask token>\n",
"step-2": "class Handlers:\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",
"step-3": "class Handlers:\n cha... | [
0,
1,
2,
3
] |
# Generated by Django 3.0.1 on 2020-03-20 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('page', '0004_auto_20200320_1521'),
]
operations = [
migrations.AddField(
model_name='menu',
name='level',
... | normal | {
"blob_id": "807b20f4912ab89bf73966961536a4cd4367f851",
"index": 6468,
"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 = [('page', '000... | [
0,
1,
2,
3,
4
] |
import io
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/')
def index():
buf = io.BytesIO()
buf.write('hello world')
buf.seek(0)
return send_file(buf,
attachment_filename="testing.txt",
as_attachment=True)
| normal | {
"blob_id": "362c4e572f0fe61b77e54ab5608d4cd052291da4",
"index": 4043,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@app.route('/')\ndef index():\n buf = io.BytesIO()\n buf.write('hello world')\n buf.seek(0)\n return send_file(buf, attachment_filename='testing.txt', as_attachment=True\n... | [
0,
1,
2,
3,
4
] |
import json
import yaml
import argparse
import sys
def json2yaml(json_input, yaml_input):
json_data = json.load(open(json_input, 'r'))
yaml_file = open(yaml_input, 'w')
yaml.safe_dump(json_data, yaml_file, allow_unicode=True, default_flow_style=False)
yaml_data = yaml.load_all(open(yaml_input, 'r'), L... | normal | {
"blob_id": "5c15252611bee9cd9fbb5d91a19850c242bb51f1",
"index": 4940,
"step-1": "<mask token>\n\n\ndef json2yaml(json_input, yaml_input):\n json_data = json.load(open(json_input, 'r'))\n yaml_file = open(yaml_input, 'w')\n yaml.safe_dump(json_data, yaml_file, allow_unicode=True,\n default_flow_s... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/env python
# Copyright (c) 2016, SafeBreach
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of cond... | normal | {
"blob_id": "278f0ece7cc2c7bb2ec1a3a2a7401bf3bc09611d",
"index": 2659,
"step-1": "#!/usr/bin/env python\n# Copyright (c) 2016, SafeBreach\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n#... | [
0
] |
#!/usr/bin/env python
# encoding: utf-8
import os
import argparse
import coaddBatchCutout as cbc
def run(args):
min = -0.0
max = 0.5
Q = 10
if os.path.isfile(args.incat):
cbc.coaddBatchCutFull(args.root, args.incat,
filter=args.filter,
... | normal | {
"blob_id": "c0503536672aa824eaf0d19b9d4b5431ef910432",
"index": 1028,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run(args):\n min = -0.0\n max = 0.5\n Q = 10\n if os.path.isfile(args.incat):\n cbc.coaddBatchCutFull(args.root, args.incat, filter=args.filter,\n id... | [
0,
1,
2,
3,
4
] |
naam = raw_input("Wat is je naam?")
getal = raw_input("Geef me een getal?")
if naam == "Barrie":
print "Welkom " * int(getal)
else:
print "Helaas, tot ziens" | normal | {
"blob_id": "c48d5d9e088acfed0c59e99d3227c25689d205c6",
"index": 7848,
"step-1": "naam = raw_input(\"Wat is je naam?\")\ngetal = raw_input(\"Geef me een getal?\")\nif naam == \"Barrie\":\n\tprint \"Welkom \" * int(getal)\nelse:\n\tprint \"Helaas, tot ziens\"",
"step-2": null,
"step-3": null,
"step-4": null... | [
0
] |
__author__ = 'lei'
import unittest
from ch3.node import TreeNode as t
import ch3.searchRange as sr
class MyTestCase(unittest.TestCase):
def test_1(self):
a = t(2)
b = t(1)
a.left = b
self.assertEqual(sr.searchRange(a, 0, 4), [1, 2])
def test_2(self):
a = t(20)
... | normal | {
"blob_id": "c63e5a2178e82ec6e0e1e91a81145afb735bf7bf",
"index": 216,
"step-1": "<mask token>\n\n\nclass MyTestCase(unittest.TestCase):\n <mask token>\n\n def test_2(self):\n a = t(20)\n b = t(1)\n a.left = b\n c = t(40)\n a.right = c\n d = t(35)\n c.left = ... | [
2,
4,
5,
6
] |
listtuple = [(1, 2), (2, 3), (3, 4), (4, 5)]
dictn = dict(listtuple)
print(dictn)
| normal | {
"blob_id": "85bc304c69dac8bb570f920f9f12f558f4844c49",
"index": 8644,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(dictn)\n",
"step-3": "listtuple = [(1, 2), (2, 3), (3, 4), (4, 5)]\ndictn = dict(listtuple)\nprint(dictn)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
... | [
0,
1,
2
] |
import torch
import torch.nn as nn
class MLPNet(nn.Module):
def __init__(self, num_classes):
super(MLPNet, self).__init__()
self.fc1 = nn.Linear(32 * 32 * 3, 512)
self.fc2 = nn.Linear(512, num_classes)
def forward(self, x):
x = x.view(x.size(0), -1)
x = self.fc1(x)
... | normal | {
"blob_id": "eff8b6a282ac73a116587e7ed04f386927c9f826",
"index": 9089,
"step-1": "<mask token>\n\n\nclass MLPNet(nn.Module):\n <mask token>\n\n def forward(self, x):\n x = x.view(x.size(0), -1)\n x = self.fc1(x)\n x = torch.sigmoid(x)\n x = self.fc2(x)\n return x\n <ma... | [
2,
3,
4,
5
] |
import numpy as np
import scipy.sparse as sparse
from .world import World
from . import util
from . import fem
from . import linalg
def solveFine(world, aFine, MbFine, AbFine, boundaryConditions):
NWorldCoarse = world.NWorldCoarse
NWorldFine = world.NWorldCoarse * world.NCoarseElement
NpFine = np.prod(NWo... | normal | {
"blob_id": "1b3493322fa85c2fe26a7f308466c4a1c72d5b35",
"index": 4637,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef solveCoarse(world, aFine, MbFine, AbFine, boundaryConditions):\n NWorldCoarse = world.NWorldCoarse\n NWorldFine = world.NWorldCoarse * world.NCoarseElement\n NCoarseEleme... | [
0,
1,
2,
3
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 20:47:28 2019
@author: jaco
"""
| normal | {
"blob_id": "d806d1b31712e3d8d60f4bfbc60c6939dfeeb357",
"index": 9579,
"step-1": "<mask token>\n",
"step-2": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 16 20:47:28 2019\n\n@author: jaco\n\"\"\"\n\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
... | [
0,
1
] |
class Sala:
def __init__(self, sala):
self.Turmas = []
self.numero = sala
def add_turma(self, turma):
# do things
self.Turmas.append(turma)
def __str__(self):
return str(self.numero)
| normal | {
"blob_id": "e41df44db92e2ef7f9c20a0f3052e1c8c28b76c7",
"index": 6174,
"step-1": "class Sala:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Sala:\n <mask token>\n <mask token>\n\n def __str__(self):\n return str(self.numero)\n",
"step-3": "class Sala:\n <mask t... | [
1,
2,
3,
4,
5
] |
#!/usr/bin/env python
from pymongo import MongoClient
import serial
import sys, os, datetime
os.system('sudo stty -F /dev/ttyS0 1200 sane evenp parenb cs7 -crtscts')
SERIAL = '/dev/ttyS0'
try:
ser = serial.Serial(
port=SERIAL,
baudrate = 1200,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ON... | normal | {
"blob_id": "d0997f5001090dd8925640cd5b0f3eb2e6768113",
"index": 3862,
"step-1": "#!/usr/bin/env python\n\n\nfrom pymongo import MongoClient\nimport serial\nimport sys, os, datetime\n\nos.system('sudo stty -F /dev/ttyS0 1200 sane evenp parenb cs7 -crtscts')\n\nSERIAL = '/dev/ttyS0'\ntry:\n ser = serial.Serial(\... | [
0
] |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: swensun
@github:https://github.com/yunshuipiao
@software: python
@file: encode_decode.py
@desc: 字符串编解码
@hint:
"""
def encode(strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ''
... | normal | {
"blob_id": "2561db1264fe399db85460e9f32213b70ddf03ff",
"index": 1864,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef encode(strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n :rtype: str\n \"\"\"\n res = ''\n for string in strs.split(... | [
0,
1,
2,
3,
4
] |
import scipy.sparse
from multiprocessing.sharedctypes import Array
from ctypes import c_double
import numpy as np
from multiprocessing import Pool
import matplotlib.pyplot as plt
from time import time
import scipy.io as sio
import sys
# np.random.seed(1)
d = 100
n = 100000
k=10
learning_rate = 0.4
T_freq = 100
num_t... | normal | {
"blob_id": "bf04bf41f657a6ada4777fe5de98d6a68beda9d3",
"index": 9769,
"step-1": "<mask token>\n\n\ndef getSyntheticData(n, d, k):\n mean = np.array([0] * d)\n alpha = 0.8\n cov_diag = [(alpha ** i) for i in range(d)]\n covariance = np.diag(cov_diag)\n truth = np.sum(cov_diag[:k])\n samples = n... | [
2,
5,
8,
9,
10
] |
import itertools
import numpy as np
SAMPLER_CACHE = 10000
def cache_gen(source):
values = source()
while True:
for value in values:
yield value
values = source()
class Sampler:
"""Provides precomputed random samples of various distribution."""
randn_gen = cache_gen(lambda... | normal | {
"blob_id": "ddeff852e41b79fb71cea1e4dc71248ddef85d79",
"index": 7033,
"step-1": "<mask token>\n\n\nclass Sampler:\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def standard_normal(cls, size=1):\n return list(itertools.islice(cls.randn_gen, size))\n\n @classmethod\n ... | [
4,
7,
9,
10
] |
from django.test import TestCase, Client
from django.contrib.auth.models import User
from blog.factories import BlogPostFactory, TagFactory
from blog.models import BlogPost
from faker import Factory
faker = Factory.create()
class ServicesTests(TestCase):
def setUp(self):
self.tag = TagFactory()
... | normal | {
"blob_id": "c9d25460022bb86c821600dfaed17baa70531c9f",
"index": 7125,
"step-1": "<mask token>\n\n\nclass ServicesTests(TestCase):\n\n def setUp(self):\n self.tag = TagFactory()\n self.blog_post = BlogPostFactory()\n self.client = Client()\n self.user = User.objects.create_user(use... | [
4,
5,
6,
7,
8
] |
from pymoo.model.duplicate import ElementwiseDuplicateElimination
class ChrDuplicates(ElementwiseDuplicateElimination):
"""Detects duplicate chromosome, which the base ElementwiseDuplicateElimination then removes."""
def is_equal(self, a, b):
"""
Checks whether two character chromosome elemen... | normal | {
"blob_id": "9276c4106cbe52cf0e2939b5434d63109910a45c",
"index": 8801,
"step-1": "<mask token>\n\n\nclass ChrDuplicates(ElementwiseDuplicateElimination):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass ChrDuplicates(ElementwiseDuplicateElimination):\n <mask token>\n\n def is_eq... | [
1,
2,
3,
4
] |
# File for the information gain feature selection algorithm
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_selection import mutual_info_classif
# The function which will be called
def get_features(raw_data, raw_ids):
"""
Calculate the in... | normal | {
"blob_id": "ca403e8820a3e34e0eb11b2fdd5d0fc77e3ffdc4",
"index": 9394,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_features(raw_data, raw_ids):\n \"\"\"\n Calculate the information gain of a dataset. This function takes three parameters:\n 1. data = The dataset for whose feature t... | [
0,
1,
2,
3
] |
#calss header
class _PULPIER():
def __init__(self,):
self.name = "PULPIER"
self.definitions = pulpy
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['pulpy']
| normal | {
"blob_id": "a1d1056f302cf7bc050537dd8cc53cdb2da7e989",
"index": 5507,
"step-1": "<mask token>\n",
"step-2": "class _PULPIER:\n <mask token>\n",
"step-3": "class _PULPIER:\n\n def __init__(self):\n self.name = 'PULPIER'\n self.definitions = pulpy\n self.parents = []\n self.c... | [
0,
1,
2,
3
] |
'''
Run from the command line with arguments of the CSV files you wish to convert.
There is no error handling so things will break if you do not give it a well
formatted CSV most likely.
USAGE: python mycsvtomd.py [first_file.csv] [second_file.csv] ...
OUTPUT: first_file.md second_file.md ...
'''
import sys
import cs... | normal | {
"blob_id": "28851979c8f09f3cd1c0f4507eeb5ac2e2022ea0",
"index": 8362,
"step-1": "'''\nRun from the command line with arguments of the CSV files you wish to convert.\nThere is no error handling so things will break if you do not give it a well\nformatted CSV most likely.\n\nUSAGE: python mycsvtomd.py [first_file... | [
0
] |
from kafka import KafkaProducer
import json
msg_count = 50
producer = KafkaProducer(bootstrap_servers=['localhost:9092'])
for i in range(0, msg_count):
msg = {'id': i + 20, 'payload': 'Here is test message {}'.format(i + 20)}
sent = producer.send('test-topic2', bytes(json.dumps(msg), 'utf-8'))
| normal | {
"blob_id": "d763485e417900044d7ce3a63ef7ec2def115f05",
"index": 7263,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(0, msg_count):\n msg = {'id': i + 20, 'payload': 'Here is test message {}'.format(i + 20)}\n sent = producer.send('test-topic2', bytes(json.dumps(msg), 'utf-8'))\n",
... | [
0,
1,
2,
3
] |
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
settings=config['Settings']
colors=config['Colors']
import logging
logger = logging.getLogger(__name__)
logLevel = settings.getint('log-level')
oneLevelUp = 20
#I don't know if this will work before loading the transformers module?
#s... | normal | {
"blob_id": "e4fb932c476ca0222a077a43499bf9164e1f27d0",
"index": 8896,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nconfig.read('config.ini')\n<mask token>\nlogging.getLogger('transformers.tokenization_utils').setLevel(logLevel +\n oneLevelUp)\nlogging.getLogger('transformers.modeling_utils').setLev... | [
0,
1,
2,
3,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.