code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
import random
import datetime
import userval
import file
from getpass import getpass
#SORRY FOR THE REDUNDANT CODE, I RAN OUT OF OPTIONS
def register():
global first,last,email,pin,password,accountName #prepared_user_details
first=input("input firstname:")
last=input("input lastname:")
... | normal | {
"blob_id": "a8106c8f14e15706b12e6d157b889288b85bc277",
"index": 6789,
"step-1": "<mask token>\n\n\ndef genAcc():\n num = 1\n y = [3, 0]\n while num <= 8:\n x = random.randint(0, 9)\n y.append(x)\n num = num + 1\n accountNo = ''.join([str(i) for i in y])\n return accountNo... | [
7,
8,
9,
13,
15
] |
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
left, right = 0, n-1
found = False
res = None
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
found = True
... | normal | {
"blob_id": "1fe6fab717a77f13ddf7059ef0a5aaef217f0fb0",
"index": 5525,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n\n\n<mask token>\n",
"step-3": "class Solution:\n\n def search(self, nums: List[int], target: int) ->int:\n n = len(nums)\n left, right = 0, n - 1\... | [
0,
1,
2,
3
] |
from rest_framework.views import APIView
from rest_framework.response import Response
from drf_yasg.utils import swagger_auto_schema
from theme.models import UserProfile
from hs_core.views import serializers
class UserInfo(APIView):
@swagger_auto_schema(operation_description="Get information about the logged in ... | normal | {
"blob_id": "c45ffe8cba8d152e346182252dbc43e22eaf83e2",
"index": 3498,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass UserInfo(APIView):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass UserInfo(APIView):\n\n @swagger_auto_schema(operation_description=\n 'Get information abo... | [
0,
1,
2,
3,
4
] |
import argparse
import json
import os
import warnings
import numpy as np
import pandas as pd
import src.data_loaders as module_data
import torch
from sklearn.metrics import roc_auc_score
from src.data_loaders import JigsawDataBias, JigsawDataMultilingual, JigsawDataOriginal
from torch.utils.data import DataLoader
from... | normal | {
"blob_id": "58c7e81d1b3cf1cff7d91bf40641e5a03b9f19ac",
"index": 5730,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_classifier(config, dataset, checkpoint_path, device='cuda:0'):\n model = ToxicClassifier(config)\n checkpoint = torch.load(checkpoint_path, map_location=device)\n mo... | [
0,
1,
2,
3,
4
] |
import myThread
def main():
hosts={"127.0.0.1":"carpenter"}
myThread.messageListenThread(hosts)
if __name__ == '__main__':
main() | normal | {
"blob_id": "b0a49f5876bc3837b69a6dc274f9587a37351495",
"index": 8370,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef main():\n hosts = {'127.0.0.1'... | [
0,
1,
2,
3,
4
] |
import networkx as nx
import pytest
from caldera.utils.nx import nx_copy
def add_data(g):
g.add_node(1)
g.add_node(2, x=5)
g.add_edge(1, 2, y=6)
g.add_edge(2, 3, z=[])
def assert_graph_data(g1, g2):
assert g1 is not g2
assert g2.nodes[1] == {}
assert g2.nodes[2] == {"x": 5}
assert g... | normal | {
"blob_id": "7fe7ea89908f9d233dbdb9e46bf2d677406ab324",
"index": 1050,
"step-1": "<mask token>\n\n\ndef add_data(g):\n g.add_node(1)\n g.add_node(2, x=5)\n g.add_edge(1, 2, y=6)\n g.add_edge(2, 3, z=[])\n\n\ndef assert_graph_data(g1, g2):\n assert g1 is not g2\n assert g2.nodes[1] == {}\n as... | [
6,
7,
8,
9,
10
] |
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from models.nutrient import *
class SoilRecord(db.Model):
year=db.DateProperty(auto_now_add=True)
stats=NutrientProfile()
amendmen... | normal | {
"blob_id": "01a6283d2331590082cdf1d409ecdb6f93459882",
"index": 4861,
"step-1": "<mask token>\n\n\nclass CropRecord(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CropRecord(db.Model):\n year = db... | [
1,
5,
9,
10,
11
] |
name = input("Enter your name: ")
print("Hi buddy! Today we will play a game " + name + "!")
print("Are you ready?")
question = input("Are you ready ? Yes or no: ")
print(name + " we are starting!")
liste1 = ['My neighbor ', 'My girlfriend ', 'My boyfriend ', 'My dog ']
num = input("Enter a number: ")
... | normal | {
"blob_id": "4ef6002480fcaa514f41227978bae76f6e02c22d",
"index": 6401,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Hi buddy! Today we will play a game ' + name + '!')\nprint('Are you ready?')\n<mask token>\nprint(name + ' we are starting!')\n<mask token>\nprint(liste1 + liste2 + liste3 + liste4... | [
0,
1,
2,
3
] |
import heapq
class Solution: #priority queue
# def sortElemsByFrequency(self, arr):
# if arr:
# mydict = {}
# for k,v in enumerate(arr):
# mydict[v] = mydict.get(v, 0) + 1
# sorted_dict = sorted(mydict.items(), key = lambda x:x[1])
# return sorted_dict
def sortElemsByFrequen... | normal | {
"blob_id": "dcb12e282962c63f8e7de5d29c4c81ad177a387e",
"index": 7775,
"step-1": "<mask token>\n\n\nclass Solution:\n\n def sortElemsByFrequency(self, arr):\n if arr:\n x = []\n res = []\n mydict = {}\n for k, v in enumerate(arr):\n mydict[v] =... | [
2,
3,
4,
5,
6
] |
def is_prime(x):
divisor = 2
while divisor <= x**(1/2.0):
if x % divisor == 0:
return False
divisor += 1
return True
for j in range(int(raw_input())):
a, b = map(int, raw_input().split())
count = 0
if a == 2:
a += 1
count += 1
elif... | normal | {
"blob_id": "e3a59a1ae65dd86ff2f5dcc15d4df9e8dc451990",
"index": 8587,
"step-1": "def is_prime(x):\r\n divisor = 2\r\n while divisor <= x**(1/2.0):\r\n if x % divisor == 0:\r\n return False\r\n divisor += 1\r\n return True\r\n\r\nfor j in range(int(raw_input())):\r\n a, b = m... | [
0
] |
#coding=utf-8
'''
find words and count
By @liuxingpuu
'''
import re
fin= open("example","r")
fout = open("reuslt.txt","w")
str=fin.read()
reObj = re.compile("\b?([a-zA-Z]+)\b?")
words = reObj.findall(str)
word_dict={}
for word in words:
if(word_dict.has_key(word)):
word_dict[word.lower()]=max(word_dict[wor... | normal | {
"blob_id": "addab37cb23abead2d9f77a65336cd6026c52c68",
"index": 8559,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor word in words:\n if word_dict.has_key(word):\n word_dict[word.lower()] = max(word_dict[word.lower()], words.count(\n word.lower()) + words.count(word.upper()) + w... | [
0,
1,
2,
3,
4
] |
#pymongo and mongo DB search is like by line inside in a document then it moves to the other document
from enum import unique
import pymongo
from pymongo import MongoClient
MyClient = MongoClient() # again this is connecting to deault host and port
db = MyClient.mydatabase #db is a variable to store the database ... | normal | {
"blob_id": "31f302775ef19a07137622ef9d33495cc2a8eed2",
"index": 5775,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndb.users.create_index([('names', pymongo.ASCENDING)])\n",
"step-3": "<mask token>\nMyClient = MongoClient()\ndb = MyClient.mydatabase\nusers = db.users\ndb.users.create_index([('names',... | [
0,
1,
2,
3,
4
] |
# Generated by Django 2.2.2 on 2019-07-17 10:02
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('users', '0003_delete_userprofile'),
]
operations = [
migrations.CreateModel(
... | normal | {
"blob_id": "cf2c57dbb2c1160321bcd6de98691db48634d5d6",
"index": 5388,
"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 = [('users', '00... | [
0,
1,
2,
3,
4
] |
import ast
import datetime
from pathlib import Path
from typing import Any, Dict
import yaml
from .lemmatizer import LemmatizerPymorphy2, Preprocessor
def get_config(path_to_config: str) -> Dict[str, Any]:
"""Get config.
Args:
path_to_config (str): Path to config.
Returns:
Dict[str, An... | normal | {
"blob_id": "c85d7e799a652e82bfaf58e1e8bfa9c4606a8ecb",
"index": 917,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_config(path_to_config: str) ->Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Returns:\n Dict[str, Any]: Config... | [
0,
1,
2,
3
] |
from django.shortcuts import render, get_object_or_404, redirect
#from emailupdate.forms import emailupdate_form
from forms import EmailForm
from django.utils import timezone
def index(request):
if request.method == "POST":
form = EmailForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
po... | normal | {
"blob_id": "f2cdee7e5eebaeeb784cb901c3ac6301e90ac7b9",
"index": 866,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef index(request):\n if request.method == 'POST':\n form = EmailForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post... | [
0,
1,
2,
3,
4
] |
import time
from helpers.handler import port_handler
from helpers.functions import fetch_all
class ascii_handler(port_handler):
"""
Serve ASCII server list
"""
def handle_data(self):
"""
Show a nicely formatted server list and immediately close connection
"""
self.ls.... | normal | {
"blob_id": "cbf93eb96f40ff0aedc4b8d9238669da72934b27",
"index": 2400,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass ascii_handler(port_handler):\n <mask token>\n\n def handle_data(self):\n \"\"\"\n Show a nicely formatted server list and immediately close connection\n ... | [
0,
2,
3,
4,
5
] |
from omt.gui.abstract_panel import AbstractPanel
class SourcePanel(AbstractPanel):
def __init__(self):
super(SourcePanel, self).__init__()
def packagePath(self):
"""
This file holds the link to the active panels.
The structure is a dictionary, the key is the class name
... | normal | {
"blob_id": "aa0a69e3286934fcfdf31bd713eca1e8dd90aeaa",
"index": 6914,
"step-1": "<mask token>\n\n\nclass SourcePanel(AbstractPanel):\n\n def __init__(self):\n super(SourcePanel, self).__init__()\n\n def packagePath(self):\n \"\"\"\n This file holds the link to the active panels.\n ... | [
4,
5,
6,
7,
8
] |
#common method to delete data from a list
fruits=['orange','apple','mango','grapes','banana','apple','litchi']
#l=[]
#[l.append(i) for i in fruits if i not in l]
#print(l)
print(set(fruits))
print(fruits.count("orange"))
#pop method in a list used to delete last mathod from a lis... | normal | {
"blob_id": "158b39a64d725bdbfc78acc346ed8335613ae099",
"index": 8367,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(set(fruits))\nprint(fruits.count('orange'))\n",
"step-3": "fruits = ['orange', 'apple', 'mango', 'grapes', 'banana', 'apple', 'litchi']\nprint(set(fruits))\nprint(fruits.count('or... | [
0,
1,
2,
3
] |
from django.db import models
from django.utils import timezone
from accounts.models import AllUser
from profiles.models import Profile
### MODEL HOLDING MEMBER TO CLIENT RELATIONSHIPS. ###
class MemberClient(models.Model):
created = models.DateTimeField(auto_now_add=timezone.now())
client = models.ForeignKey(... | normal | {
"blob_id": "b419e26cbf5bbb746f897367ddaa829773a6860c",
"index": 7742,
"step-1": "<mask token>\n\n\nclass MemberClient(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass MemberClient(models.Model):\n <mask token>\n ... | [
1,
2,
3,
4,
5
] |
from binary_search_tree.gen_unique_bst import gen_unique_bst
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
def max_depth(root):
if not root:
return 0
return max(max_depth(root.left), max_depth(root.right)) + 1
# The minimum depth... | normal | {
"blob_id": "3e54d2ddddf6f8186137e5801ca4ba40d1061987",
"index": 2801,
"step-1": "from binary_search_tree.gen_unique_bst import gen_unique_bst\n\n\n# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\ndef max_depth(root):\n if not root:\n ... | [
0
] |
n=int(input())
k=[4,7,47,74,44,77,444,447,474,477,777,774,747,7444]
f=0
for i in k:
if(n%i==0):
f=1
print("YES")
break;
if(f==0):
print("NO")
| normal | {
"blob_id": "6161653fb789040d084e475e0ae25921e2e0676b",
"index": 2496,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in k:\n if n % i == 0:\n f = 1\n print('YES')\n break\nif f == 0:\n print('NO')\n",
"step-3": "n = int(input())\nk = [4, 7, 47, 74, 44, 77, 444, 447, 47... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
created by gjwei on 3/26/17
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
a = ListNode(1)
a.next = ListNode(3)
a.next = None
print a.val
print a.next
def main():
print "hello"
a = []
for i in r... | normal | {
"blob_id": "4a0cbd59ffae4fb5ba6e3bd871231e37065d1aed",
"index": 3464,
"step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\" \n created by gjwei on 3/26/17\n \n\"\"\"\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\na = ListNode(1)\na.next = L... | [
0
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'wenchao.hao'
"""
data.guid package.
"""
from .guid import Guid
| normal | {
"blob_id": "88a379747f955b0410ab2bb33c1165034c701673",
"index": 8597,
"step-1": "<mask token>\n",
"step-2": "__author__ = 'wenchao.hao'\n<mask token>\n",
"step-3": "__author__ = 'wenchao.hao'\n<mask token>\nfrom .guid import Guid\n",
"step-4": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = ... | [
0,
1,
2,
3
] |
#-*- coding: utf8 -*-
#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py
import shutil, time, logging
import torch
import torch.optim
import numpy as np
import visdom, copy
from datetime import datetime
from collections import defaultdict
from generic_models.yellowfin import YFOptimizer
logg... | normal | {
"blob_id": "be90dcb4bbb69053e9451479990e030cd4841e4a",
"index": 1620,
"step-1": "#-*- coding: utf8 -*-\n#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py\nimport shutil, time, logging\nimport torch\nimport torch.optim\nimport numpy as np\nimport visdom, copy\nfrom datetime import date... | [
0
] |
import re
def make_slug(string):
print(re.sub(^'\w','',string))
make_slug('#$gejcb#$evnk?.kjb')
| normal | {
"blob_id": "41e981e2192b600cdf9c9b515fe9f397cd1b8826",
"index": 5788,
"step-1": "import re\n\ndef make_slug(string):\n print(re.sub(^'\\w','',string))\n \nmake_slug('#$gejcb#$evnk?.kjb')\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
from typing import Dict, Any
from urllib import request
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from .models import Product
from cart.forms import CartAddProductForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout... | normal | {
"blob_id": "1d72a9882aea1e0f808969828ed2e69ecd79ac71",
"index": 7522,
"step-1": "<mask token>\n\n\nclass UserFormView(View):\n form_class = UserForm\n template_name = 'shop/signup.html'\n\n def get(self, request):\n form = self.form_class(None)\n return render(request, self.template_name,... | [
4,
6,
8,
9,
10
] |
from datetime import date
from django.test import TestCase
from model_mommy import mommy
from apps.debtors.models import Debtor
from apps.invoices.models import Invoice, InvoiceStatusChoices
from apps.invoices.services import InvoiceService
class InvoiceServiceTestCase(TestCase):
def setUp(self) ->None:
... | normal | {
"blob_id": "5f77e93d63c696363c30f019019acd22c694308b",
"index": 4529,
"step-1": "<mask token>\n\n\nclass InvoiceServiceTestCase(TestCase):\n <mask token>\n\n def test_create_invoice(self):\n invoice = self.invoice_service.create_invoice(amount=12.1, status=\n InvoiceStatusChoices.OVERDUE... | [
3,
4,
5,
6
] |
import numpy as np
import random
import argparse
import networkx as nx
from gensim.models import Word2Vec
from utils import read_node_label, plot_embeddings
class node2vec_walk():
def __init__(self, nx_G, is_directed, p, q):
self.G = nx_G
self.is_directed = is_directed
self.p = p
... | normal | {
"blob_id": "fc2748d766ebce8c9577f1eebc8435e2aa58ae25",
"index": 8605,
"step-1": "<mask token>\n\n\nclass node2vec_walk:\n\n def __init__(self, nx_G, is_directed, p, q):\n self.G = nx_G\n self.is_directed = is_directed\n self.p = p\n self.q = q\n\n def node2vec_walk(self, walk_l... | [
7,
8,
12,
13,
15
] |
from models import Person
from models import Skeleton
from models import Base_dolni
from models import Dolen_vrata
st = Person("Stoian")
Stoian = Person("Ivanov")
dolni = Skeleton(st, 900, 600, 2, 18, 28, 40)
dolni_st = Skeleton(Stoian, 900, 590, 2, 18, 28, 40)
dol_001 = Base_dolni(dolni_st, 550)
dol_001.set_descrip... | normal | {
"blob_id": "3d10f8810594303beb0ccabce3497de86149b2e5",
"index": 6666,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndol_001.set_description('dolen do mivkata')\ndol_001.rendModul()\n<mask token>\ndol_002.set_description('долен втори с 2 врати')\ndol_002.rendModul()\n",
"step-3": "<mask token>\nst = P... | [
0,
1,
2,
3,
4
] |
from nltk.tokenize import sent_tokenize
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
import networkx as nx
def summarize(text):
sentences_token = sent_tokenize(text)
#Feature Extraction
vectorizer = CountVectorizer(min_df=1,decode_error='replace')
sent_bow = v... | normal | {
"blob_id": "b75ebcd278ae92274bbbe8d1ce5cb3bb7fa14a2c",
"index": 9637,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef summarize(text):\n sentences_token = sent_tokenize(text)\n vectorizer = CountVectorizer(min_df=1, decode_error='replace')\n sent_bow = vectorizer.fit_transform(sentences_... | [
0,
1,
2,
3
] |
from pypc.a_primitives.nand import nand
# nand gates used: 5
def half_adder(a: bool, b: bool) -> (bool, bool):
"""Returns a + b in the form of a tuple of two bools representing the two
bits."""
nand_a_b = nand(a, b)
nand_c = nand(nand_a_b, a)
nand_d = nand(nand_a_b, b)
high = nand(na... | normal | {
"blob_id": "66f6639ae62fe8c0b42171cf3e3fb450d8eee2b2",
"index": 7671,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef full_adder(a: bool, b: bool, c: bool) ->(bool, bool):\n \"\"\"Returns a + b + c in the form of a tuple of two bools representing the two\n bits.\n \n Carried value is ... | [
0,
1,
2,
3,
4
] |
"""
k-element subsets of the set [n]
3-element subsets of the set [6]
123
"""
result = []
def get_subset(A, k, n):
a_list = [i for i in A]
if len(a_list) == k:
result.append(a_list)
return
s_num = max(a_list)+1 if a_list else 1
for i in range(s_num, n+1):
a_list.append(i)
... | normal | {
"blob_id": "d48353caa07d3bfa003ea9354b411fe0c79591db",
"index": 2725,
"step-1": "<mask token>\n\n\ndef get_subset(A, k, n):\n a_list = [i for i in A]\n if len(a_list) == k:\n result.append(a_list)\n return\n s_num = max(a_list) + 1 if a_list else 1\n for i in range(s_num, n + 1):\n ... | [
2,
3,
4,
5,
6
] |
def main():
x = float(input("Coordenada x: "))
y = float(input("Coordenada y: "))
if 1 <= y <= 2 and -3 <= x <= 3:
print("dentro")
elif (4 <= y <= 5 or 6 <= x <= 7) and ( -4 <= x <= -3 or -2 <= x <= -1 or 1 <= x <= 2 or 3 <= x <= 4):
print("dentro")
e... | normal | {
"blob_id": "06cb832c3adae95fcd1d1d2d0663641d3ac671ef",
"index": 9132,
"step-1": "<mask token>\n",
"step-2": "def main():\n x = float(input('Coordenada x: '))\n y = float(input('Coordenada y: '))\n if 1 <= y <= 2 and -3 <= x <= 3:\n print('dentro')\n elif (4 <= y <= 5 or 6 <= x <= 7) and (-4... | [
0,
1,
2,
3
] |
import os
import requests
from PIL import Image
from io import BytesIO
import csv
from typing import Iterable, List, Tuple, Dict, Callable, Union, Collection
# pull the image from the api endpoint and save it if we don't have it, else load it from disk
def get_img_from_file_or_url(img_format: str = 'JPEG') -> Callabl... | normal | {
"blob_id": "f2bb44600f011a205c71985ad94c18f7e058634f",
"index": 8,
"step-1": "<mask token>\n\n\ndef from_url(url: str) ->Image.Image:\n api_response = requests.get(url).content\n response_bytes = BytesIO(api_response)\n return Image.open(response_bytes)\n\n\ndef from_file(path: str) ->Union[Image.Image... | [
2,
3,
4,
5,
6
] |
import os
import math
from collections import defaultdict
__author__ = 'steven'
question='qb'
fs={'t1','small.in','large'}
def getmincost(n,c,f,x):
t=0.0
for i in range(0,n):
t+=1/(2+f*i)
t=t*c
t+=x/(2+f*n)
ct=getmincostnshift(n,c,f,x)
return min(t,ct);
def getmincostnshift(n,c,f,x):
... | normal | {
"blob_id": "8fee548466abf6d35ea180f8de4e52a9b8902d3f",
"index": 1025,
"step-1": "import os\nimport math\nfrom collections import defaultdict\n__author__ = 'steven'\n\nquestion='qb'\nfs={'t1','small.in','large'}\ndef getmincost(n,c,f,x):\n t=0.0\n\n for i in range(0,n):\n t+=1/(2+f*i)\n t=t*c\n ... | [
0
] |
#!/usr/bin/python3
import sys
import math
class parameter :
opt = 0
xp = 0
yp = 0
zp = 0
xv = 0
yv = 0
zv = 0
p = 0
def check_args() :
try :
int(sys.argv[1])
int(sys.argv[2])
int(sys.argv[3])
int(sys.argv[4])
int(sys.argv[5])
int(sys... | normal | {
"blob_id": "d1af148bc6b27d38052f2e57f1c610c86eccebef",
"index": 7757,
"step-1": "<mask token>\n\n\nclass parameter:\n opt = 0\n xp = 0\n yp = 0\n zp = 0\n xv = 0\n yv = 0\n zv = 0\n p = 0\n\n\n<mask token>\n\n\ndef help():\n if len(sys.argv) == 2 and sys.argv[1] == '-h':\n prin... | [
5,
7,
8,
11,
12
] |
# Python library import
import asyncio, asyncssh, logging
# Module logging logger
log = logging.getLogger(__package__)
# Debug level
# logging.basicConfig(level=logging.WARNING)
# logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.DEBUG)
asyncssh.set_debug_level(2)
# Declaration of constant v... | normal | {
"blob_id": "87baaf4a1b48fa248c65d26cc44e819a2ede1140",
"index": 3736,
"step-1": "<mask token>\n\n\nclass NetworkDevice:\n <mask token>\n\n def __init__(self, **kwargs):\n log.info('__init__')\n self.ip = ''\n self.username = ''\n self.password = ''\n self.device_type = '... | [
9,
10,
12,
14,
15
] |
#!/usr/bin/env python
# encoding: utf-8
"""
@description: 有序字典
(notice: python3.6 以后字典已经有序了)
@author: baoqiang
@time: 2019/11/28 1:34 下午
"""
from collections import OrderedDict
def run206_01():
print('Regular dict:')
# d = {'a':'A','b':'B','c':'C'}
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = ... | normal | {
"blob_id": "4a7d8db2bc3b753ea1a12120e1ad85f31d572dc7",
"index": 4237,
"step-1": "<mask token>\n\n\ndef run206_01():\n print('Regular dict:')\n d = {}\n d['a'] = 'A'\n d['b'] = 'B'\n d['c'] = 'C'\n for k, v in d.items():\n print(k, v)\n print('OrderedDict:')\n d = OrderedDict()\n ... | [
1,
2,
3,
4,
5
] |
import tensorflow as tf
import numpy as np
import tensorflow.contrib.layers as layers
class Model(object):
def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10, keep_prob=0.5, scope="model"):
self._batch_size = batch_size
self._learning_rate = learning_rate
self._num_labels ... | normal | {
"blob_id": "e9a1fd8464f6c1e65aa2c1af60becbfcbf050814",
"index": 7390,
"step-1": "<mask token>\n\n\nclass Model(object):\n\n def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10,\n keep_prob=0.5, scope='model'):\n self._batch_size = batch_size\n self._learning_rate = learn... | [
2,
3,
4,
5,
6
] |
import cv2
import numpy as np
import time
from dronekit import connect, VehicleMode
connection_string = "/dev/ttyACM0"
baud_rate = 115200
print(">>>> Connecting with the UAV <<<<")
vehicle = connect(connection_string, baud=baud_rate, wait_ready=True)
vehicle.wait_ready('autopilot_version')
print('ready')
cap = cv2.V... | normal | {
"blob_id": "8c11463e35fb32949abbb163a89f874040a33ad0",
"index": 5415,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('>>>> Connecting with the UAV <<<<')\n<mask token>\nvehicle.wait_ready('autopilot_version')\nprint('ready')\n<mask token>\nif cap.isOpened() == False:\n print('Unable to read cam... | [
0,
1,
2,
3,
4
] |
import numpy as np
import scipy.signal as sp
from common import *
class Processor:
def __init__(self, sr, **kwargs):
self.samprate = float(sr)
self.hopSize = kwargs.get("hopSize", roundUpToPowerOf2(self.samprate * 0.005))
self.olaFac = int(kwargs.get("olaFac", 2))
def analyze(self, x)... | normal | {
"blob_id": "e0075e4afafba9da70bbcb2ee073b5c1f7782d7d",
"index": 6032,
"step-1": "<mask token>\n\n\nclass Processor:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Processor:\n <mask token>\n <mask token>\n\n def synth(self, *args):\n nFrame, nBin =... | [
1,
2,
4,
5,
6
] |
t3 = float(input('Digite um numero: '))
print('o dobro deste numero é', t3 * 2)
print('O triplo deste numero é', t3 * 3)
print('E a raiz quadrada deste numero é', t3 ** (1 / 2))
| normal | {
"blob_id": "005ea8a1e75447b2b1c030a645bde5d0cdc8fb53",
"index": 3532,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('o dobro deste numero é', t3 * 2)\nprint('O triplo deste numero é', t3 * 3)\nprint('E a raiz quadrada deste numero é', t3 ** (1 / 2))\n",
"step-3": "t3 = float(input('Digite um nu... | [
0,
1,
2
] |
from scipy import misc
from math import exp
import tensorflow as tf
import timeit
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
IMAGE_WIDTH = 30
IMAGE_HEIGHT = 30
IMAGE_DEPTH = 3
IMAGE_PIXELS = IMAGE_WIDTH * IMAGE_HEIGHT
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], p... | normal | {
"blob_id": "8b4bd2d267f20775ee5d41f7fe9ef6f6eeab5bb0",
"index": 2516,
"step-1": "from scipy import misc\nfrom math import exp\nimport tensorflow as tf\nimport timeit\nimport os \n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n\nIMAGE_WIDTH = 30\nIMAGE_HEIGHT = 30\nIMAGE_DEPTH = 3\nIMAGE_PIXELS = ... | [
0
] |
import pytest
from dymopy.client import Dymo
from dymopy.client import make_xml, make_params
def test_url():
dymo = Dymo()
assert dymo.uri == "https://127.0.0.1:41951/DYMO/DLS/Printing"
def test_status():
dymo = Dymo()
status = dymo.get_status()
assert isinstance(status, dict)
assert statu... | normal | {
"blob_id": "766098753ec579e2d63893fcbd94e8819b46bc0b",
"index": 6867,
"step-1": "<mask token>\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict... | [
3,
4,
5,
6,
7
] |
import argparse
import subprocess
import os
def get_files(dir_path, ext='.png'):
relative_paths = os.listdir(dir_path)
relative_paths = list(filter(lambda fp: ext in fp, relative_paths))
return list(map(lambda rel_p: os.path.join(dir_path, rel_p), relative_paths))
def ipfs_add_local(file_path):
'Ret... | normal | {
"blob_id": "7ca88d451ad702e5a8e532da3e3f5939cfaa7215",
"index": 9571,
"step-1": "<mask token>\n\n\ndef ipfs_add_local(file_path):\n \"\"\"Returns CID\"\"\"\n proc = subprocess.run(['ipfs', 'add', file_path], capture_output=True,\n text=True)\n stdout = proc.stdout\n try:\n return stdou... | [
2,
3,
4,
5,
6
] |
x=input("Do you really want to run this program? (y/n) : ")
x=x.upper()
if x=="Y" or x=="N" or x=="Q":
while x=="Y" or x=="N" or x=="Q":
if x=="Q":
print("Exiting the Program")
import sys
sys.exit()
elif x=="N":
print("You decided to leave. See you ag... | normal | {
"blob_id": "7dff15a16ecc3ce3952f4b47290393ea3183807f",
"index": 4414,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif x == 'Y' or x == 'N' or x == 'Q':\n while x == 'Y' or x == 'N' or x == 'Q':\n if x == 'Q':\n print('Exiting the Program')\n import sys\n sys.... | [
0,
1,
2,
3
] |
from functools import reduce
with open("input.txt") as f:
numbers = f.read().split("\n")
n = sorted(list(map(lambda x: int(x), numbers)))
n.insert(0, 0)
n.append(n[-1] + 3)
target = n[-1]
memoize = {}
def part2(number):
if number == target:
return 1
if number in memoize.keys():
return ... | normal | {
"blob_id": "3179c13968f7bcdccbd00ea35b9f098dc49b42d8",
"index": 4450,
"step-1": "<mask token>\n\n\ndef part2(number):\n if number == target:\n return 1\n if number in memoize.keys():\n return memoize[number]\n paths = 0\n if number + 1 in n:\n paths += part2(number + 1)\n if ... | [
1,
2,
3,
4,
5
] |
from django.db import models
class IssueManager(models.Manager):
def open(self):
return self.filter(status__is_closed=False)
def closed(self):
return self.filter(status__is_closed=True)
| normal | {
"blob_id": "4c54cfefbaf90c1dd0648485e62bff1f2787ccfe",
"index": 2784,
"step-1": "<mask token>\n\n\nclass IssueManager(models.Manager):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass IssueManager(models.Manager):\n\n def open(self):\n return self.filter(status__is_closed=F... | [
1,
2,
3,
4
] |
cassandra = {'nodes': ['localhost'], 'keyspace': 'coffee'}
| normal | {
"blob_id": "0738fc48bc367f1df75567ab97ce20d3e747dc18",
"index": 8897,
"step-1": "<mask token>\n",
"step-2": "cassandra = {'nodes': ['localhost'], 'keyspace': 'coffee'}\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
# coding: utf-8
"""
login.py
~~~~~~~~
木犀官网登陆API
"""
from flask import jsonify, request
from . import api
from muxiwebsite.models import User
from muxiwebsite import db
@api.route('/login/', methods=['POST'])
def login():
email = request.get_json().get("email")
pwd = request.get_json().get("pass... | normal | {
"blob_id": "a0dbb374f803cb05a35f823f54ef5f14eaf328b2",
"index": 3688,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@api.route('/login/', methods=['POST'])\ndef login():\n email = request.get_json().get('email')\n pwd = request.get_json().get('password')\n user = User.query.filter_by(email... | [
0,
1,
2,
3
] |
class Solution:
def eventualSafeNodes(self, graph: List[List[int]]) ->List[int]:
res = []
d = {}
def dfs(node):
if graph[node] == []:
return True
if node in d:
return d[node]
if node in visit:
return False
... | normal | {
"blob_id": "b815f72e2cad351fd9411361a0e7cc75d39ae826",
"index": 9270,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def eventualSafeNodes(self, graph: List[List[int]]) ->List[int]:\n res = []\n d = {}\n\n def dfs(node):\n ... | [
0,
1,
2
] |
#!/usr/bin/env python
"""
Script that generates the photon efficiency curves and stores them in a root
file.
For the moment only the pT curves for the different eta bins are created
"""
import re
import json
import ROOT as r
r.PyConfig.IgnoreCommandLineOptions = True
import numpy as np
import sympy as sp
from utils... | normal | {
"blob_id": "fd450b5454b65ed69b411028788c587f9674760c",
"index": 966,
"step-1": "<mask token>\n\n\ndef eff_param_string():\n \"\"\"\n The parametrization of the efficiencies from AN-2015-11 as a string that can\n be used in a TF1 constructor.\n\n p0 * (1 - p1 * (Erf(pT + p2) - p1 / alpha * (pT - p3 *... | [
8,
9,
10,
12,
14
] |
# -*- coding: utf-8 -*-
"""
Editor de Spyder
Este es un archivo temporal.
"""
def largo (l, n):
i=0
cuenta=1
valor1=0
valor2=0
while cuenta < n+1 or cuenta==n+1:
a=l[i]
b=l[i+1]
if a==b:
cuenta+= 1
valor1=a
i+=1
cuenta=1
while cuenta ... | normal | {
"blob_id": "f3b697e20f60e51d80d655ddf4809aa9afdfcd69",
"index": 7495,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef largo(l, n):\n i = 0\n cuenta = 1\n valor1 = 0\n valor2 = 0\n while cuenta < n + 1 or cuenta == n + 1:\n a = l[i]\n b = l[i + 1]\n if a == b:\n... | [
0,
1,
2,
3,
4
] |
import os
from linkedin_scraper import get_jobs
chrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver')
df = get_jobs('Data Scientist', 40, False, chrome_driver_path)
df.to_csv('linkedin_jobs.csv', index=False)
| normal | {
"blob_id": "6ae529a5e5658ba409ec3e7284d8b2911c60dd00",
"index": 906,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndf.to_csv('linkedin_jobs.csv', index=False)\n",
"step-3": "<mask token>\nchrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver')\ndf = get_jobs('Data Scientist', ... | [
0,
1,
2,
3
] |
import json
from gamestate.gamestate_module import Gamestate
from time import time
from gamestate import action_getter as action_getter
def test_action_getter():
path = "./../Version_1.0/Tests/General/Action_1.json"
document = json.loads(open(path).read())
gamestate = Gamestate.from_document(document["gam... | normal | {
"blob_id": "b16691429d83f6909a08b10cc0b310bb62cd550d",
"index": 3985,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_action_getter():\n path = './../Version_1.0/Tests/General/Action_1.json'\n document = json.loads(open(path).read())\n gamestate = Gamestate.from_document(document['g... | [
0,
1,
2,
3
] |
def intersection(nums1, nums2):
return list(set(nums1)&set(nums2))
if __name__=="__main__":
print intersection([1, 2, 2, 1],[2, 2]) | normal | {
"blob_id": "0081ffc2a1de7fb71515fd0070aaebfef806f6ef",
"index": 4230,
"step-1": "def intersection(nums1, nums2):\n return list(set(nums1)&set(nums2))\n \n \nif __name__==\"__main__\":\n print intersection([1, 2, 2, 1],[2, 2])",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
... | [
0
] |
"""!
@brief Example 04
@details pyAudioAnalysis spectrogram calculation and visualization example
@author Theodoros Giannakopoulos {tyiannak@gmail.com}
"""
import numpy as np
import scipy.io.wavfile as wavfile
import plotly
import plotly.graph_objs as go
from pyAudioAnalysis import ShortTermFeatures as aF
layout = go.... | normal | {
"blob_id": "cb40141eddce9ce11fbd8475fc7c3d37438208a6",
"index": 6862,
"step-1": "<mask token>\n\n\ndef normalize_signal(signal):\n signal = np.double(signal)\n signal = signal / 2.0 ** 15\n signal = signal - signal.mean()\n return signal / (np.abs(signal).max() + 1e-10)\n\n\n<mask token>\n",
"step... | [
1,
2,
3,
4,
5
] |
# -*- coding: utf-8 -*-
# Copyright 2013, Achim Köhler
# All rights reserved, see accompanied file license.txt for details.
# $REV$
import argparse
import traylauncher
if __name__ == "__main__":
args = argparse.Namespace()
args.notray = False
traylauncher.start(args) | normal | {
"blob_id": "8faaf9eb2e78b7921dd1cac4772e2415671201c7",
"index": 8481,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n args = argparse.Namespace()\n args.notray = False\n traylauncher.start(args)\n",
"step-3": "import argparse\nimport traylauncher\nif __name__ == '_... | [
0,
1,
2,
3
] |
from django.urls import path,include
from . import views
urlpatterns = [
path('register_curier/',views.curier_register,name="register_curier"),
path('private_сurier/',views.private_сurier,name="private_сurier"),
path('private_сurier2/',views.private_сurier2,name="private_сurier2"),
path('private_curier... | normal | {
"blob_id": "c1a83c9551e83e395a365210a99330fee7877dff",
"index": 6881,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [path('register_curier/', views.curier_register, name=\n 'register_curier'), path('private_сurier/', views.private_сurier, name=\n 'private_сurier'), path('private_сur... | [
0,
1,
2,
3
] |
from . import *
from module import *
from transfer import *
from dataset import *
| normal | {
"blob_id": "94d992ef4b9015aa8f42071bb1409703d509c313",
"index": 9810,
"step-1": "<mask token>\n",
"step-2": "from . import *\nfrom module import *\nfrom transfer import *\nfrom dataset import *\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
# --------------------------------------------------------------------------------------------------
# Property of UAH
# IDS module for ladder logic monitoring
# This codes is Written by Rishabh Das
# Date:- 18th June 2018
# -----------------------------------------------------------------------------------------------... | normal | {
"blob_id": "6f8ce77dd45f555ca092482715b6ccaa33414fd8",
"index": 4176,
"step-1": "<mask token>\n\n\ndef Create_list():\n i = 0\n for file in os.listdir(os.getcwd()):\n if file.endswith('openplc'):\n Monitoredlist.append(file)\n i += 1\n if i == 0:\n print('No Files ar... | [
5,
6,
8,
9,
10
] |
import sys
sys.path.append("../")
import numpy as np
import tensorflow as tf
from utils import eval_accuracy_main_cdan
from models import mnist2mnistm_shared_discrepancy, mnist2mnistm_predictor_discrepancy
import keras
import argparse
import pickle as pkl
parser = argparse.ArgumentParser(description='Traini... | normal | {
"blob_id": "465d5baae8d5be77fbf3d550d10667da420a8fbe",
"index": 8608,
"step-1": "<mask token>\n\n\n@tf.function\ndef train_discrepancy_1(main_data, main_labels, target_data):\n with tf.GradientTape(persistent=True) as tape:\n shared_main = [shared[i](main_data, training=True) for i in range(\n ... | [
1,
3,
4,
5,
7
] |
def check_ip_or_mask(temp_str):
IPv4_regex = (r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}')
temp_list_ip_mask = re.findall(IPv4_regex, temp_str)
binary_temp_list_ip_mask = []
temp_binary_ip_mask = ''
for x in range(len(temp_list_ip_mask)):
split_ip_address = re.split(r'\.', temp_list_ip_mask[x])
... | normal | {
"blob_id": "fe597ad4462b1af3f3f99346c759c5fa8a7c14f4",
"index": 741,
"step-1": "<mask token>\n",
"step-2": "def check_ip_or_mask(temp_str):\n IPv4_regex = '(?:[0-9]{1,3}\\\\.){3}[0-9]{1,3}'\n temp_list_ip_mask = re.findall(IPv4_regex, temp_str)\n binary_temp_list_ip_mask = []\n temp_binary_ip_mask... | [
0,
1,
2
] |
#Author: AKHILESH
#This program illustrates the advanced concepts of inheritance
#Python looks up for method in following order: Instance attributes, class attributes and the
#from the base class
#mro: Method Resolution order
class Data(object):
def __init__(self, data):
self.data = data
def getData(s... | normal | {
"blob_id": "153a33b85cf8b3ef9c742f05b460e94e0c684682",
"index": 1000,
"step-1": "class Data(object):\n <mask token>\n <mask token>\n\n\nclass Time(Data):\n\n def getTime(self):\n print('Time:', self.data)\n\n\n<mask token>\n",
"step-2": "class Data(object):\n\n def __init__(self, data):\n ... | [
3,
4,
5,
6,
7
] |
# 上传文件
import os
from selenium import webdriver
# 获取当前路径的 “files” 文件夹
file_path = os.path.abspath("./files//")
# 浏览器打开文件夹的 upfile.html 文件
driver = webdriver.Firefox()
upload_page = "file:///" + file_path + "/upfile.html"
driver.get(upload_page)
# 定位上传按钮,添加本地文件
driver.find_element_by_id("inputfile").send_keys(file_p... | normal | {
"blob_id": "9e28fa1f221df13f9cc8e6b71586da961ebdc0e0",
"index": 4580,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndriver.get(upload_page)\ndriver.find_element_by_id('inputfile').send_keys(file_path + '\\\\test.txt')\n",
"step-3": "<mask token>\nfile_path = os.path.abspath('./files//')\ndriver = web... | [
0,
1,
2,
3,
4
] |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Rec1(object):
def setupUi(self, Rec1):
Rec1.setObjectName("Rec1")
Rec1.setFixedSize(450, 200)
ico = QtGui.QIcon("mylogo.png")
Rec1.setWindowIcon(ico)
font = QtGui.QFont()
font.setFamily("Times New Roman")
f... | normal | {
"blob_id": "c500ecaa66672ac960dc548c3f3882e4bc196745",
"index": 6870,
"step-1": "<mask token>\n\n\nclass Ui_Rec1(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Ui_Rec1(object):\n <mask token>\n\n def retranslateUi(self, Rec1):\n _translate = QtCore.QCoreApplic... | [
1,
2,
3,
4,
5
] |
#!/usr/bin/env python3
#coding=utf-8
import sys
import os
import tool
class BrandRegBasic(object):
def __init__(self, base_folder, log_instance):
if not os.path.exists(base_folder):
raise Exception("%s does not exists!" % base_folder)
self._real_brand_p = base_folder + "/real_brand.txt... | normal | {
"blob_id": "845d1251497df61dd2c23241016a049c695ad940",
"index": 9193,
"step-1": "<mask token>\n\n\nclass BrandReg(BrandRegBasic):\n\n def __init__(self, base_folder, log_instance, input_lst=None):\n super(BrandReg, self).__init__(base_folder, log_instance)\n input_file = base_folder + '/dp_bran... | [
6,
9,
12,
13,
15
] |
def somaSerie(valor):
soma = 0
for i in range(valor):
soma += ((i**2)+1)/(i+3)
return soma
a = int(input("Digite o 1º Numero :-> "))
result = somaSerie(a)
print(result) | normal | {
"blob_id": "8114d8162bab625854804d1df2b4a9c11818d35e",
"index": 3747,
"step-1": "<mask token>\n",
"step-2": "def somaSerie(valor):\n soma = 0\n for i in range(valor):\n soma += (i ** 2 + 1) / (i + 3)\n return soma\n\n\n<mask token>\n",
"step-3": "def somaSerie(valor):\n soma = 0\n for ... | [
0,
1,
2,
3,
4
] |
import re
def detectPeriod(data):
numWord = "[0-9,一二三四五六七八九十兩半]"
hourWord = "小時鐘頭"
minWord = "分鐘"
secWord = "秒鐘"
timePat = "["+numWord+"]+點?\.?["+numWord+"]*個?半?["+hourWord+"]*半?又?["+numWord+"]*["+minWord+"]*又?["+numWord+"]*["+secWord+"]*"
def main():
detectPeriod("我要去游泳一個小時")
if _... | normal | {
"blob_id": "397686964acbf640a5463a3a7095d85832545d9e",
"index": 6462,
"step-1": "<mask token>\n\n\ndef main():\n detectPeriod('我要去游泳一個小時')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef detectPeriod(data):\n numWord = '[0-9,一二三四五六七八九十兩半]'\n hourWord = '小時鐘頭'\n minWord = '分鐘'\n secWord =... | [
1,
2,
3,
4,
5
] |
"""
# listbinmin.py
# Sam Connolly 04/03/2013
#===============================================================================
# bin data according a given column in an ascii file of column data, such that
# each bin has a minimum number of points, giving the bin of each data point as
# a LIST. UNEVEN BINS.
#========... | normal | {
"blob_id": "496c58e68d3ac78a3eb1272d61ca3603c5d843b6",
"index": 4787,
"step-1": "\"\"\"\n# listbinmin.py\n# Sam Connolly 04/03/2013\n\n#===============================================================================\n# bin data according a given column in an ascii file of column data, such that\n# each bin has ... | [
0
] |
# Interprets the AST
class Program:
def __init__(self, code):
self.code = code
def eval(self, binding):
return self.code.eval(binding)
class Code:
def __init__(self, statements):
self.statements = statements
def eval(self, binding):
val = 0
for statement in ... | normal | {
"blob_id": "5fa91a5061a5e87a4a2b8fece0378299e87e5a48",
"index": 6694,
"step-1": "<mask token>\n\n\nclass Binding:\n\n def __init__(self, parent, binding):\n self.parent = parent\n self.binding = binding\n <mask token>\n\n def add(self, var_name, value):\n self.binding[var_name] = v... | [
42,
50,
56,
68,
73
] |
from paypalcheckoutsdk.core import PayPalHttpClient, SandboxEnvironment
from paypalcheckoutsdk.orders import OrdersCaptureRequest, OrdersCreateRequest
from django.conf import settings
import sys
class PayPalClient:
def __init__(self):
self.client_id = settings.PAYPAL_CLIENT_ID
self.client_secret ... | normal | {
"blob_id": "542bd52e3d5bc79077277034234419983005f78e",
"index": 2128,
"step-1": "<mask token>\n\n\nclass OrderClient(PayPalClient):\n \"\"\" This is the sample function to create an order. It uses the\n JSON body returned by buildRequestBody() to create an order.\"\"\"\n\n def create_order(self, order_... | [
4,
5,
6,
8,
11
] |
import numpy as np
import pandas as pd
import datetime
import time
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import cross_val_score
from sklearn import preprocessing
from sklearn.model... | normal | {
"blob_id": "5172819da135600d0764033a85a4175098274806",
"index": 7388,
"step-1": "<mask token>\n\n\nclass ModelSelection:\n\n def __init__(self, user_data, movie_data, aggregated_data, train_data,\n output_train):\n self.train = train_data\n self.users = user_data\n self.aggregated... | [
5,
7,
8,
9,
10
] |
# !/usr/bin/python
# coding:utf-8
import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
#紀錄檔PATH(建議絕對位置)
log_path='./log.txt'
#登入聯絡簿的個資
sid=''#學號(Ex. 10731187)
cid=''#生份證號(Ex. A123456789)
bir=''#生日(Ex. 2000/1/1)
#line or telegram module
#platform='telegram'
platform='line'
if plat... | normal | {
"blob_id": "77f37a80d160e42bb74017a55aa9d06b4c8d4fee",
"index": 4320,
"step-1": "<mask token>\n\n\ndef login_homework():\n res = requests.get('http://www.yphs.tp.edu.tw/tea/tu2.aspx')\n soup = BeautifulSoup(res.text, 'lxml')\n VIEWSTATE = soup.find(id='__VIEWSTATE')\n VIEWSTATEGENERATOR = soup.find(... | [
5,
8,
10,
11,
12
] |
from selenium import webdriver
import time
import datetime
import os
import openpyxl as vb
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
def deconnexion(Chrome):
"""登陆"""
"""初始化"""
global web, actions
web = webdriver.Chrome(Ch... | normal | {
"blob_id": "d2c31d9c3cc66b43966cfd852582539d4e4bea17",
"index": 321,
"step-1": "<mask token>\n\n\ndef deconnexion(Chrome):\n \"\"\"登陆\"\"\"\n \"\"\"初始化\"\"\"\n global web, actions\n web = webdriver.Chrome(Chrome)\n web.maximize_window()\n web.implicitly_wait(10)\n web.get(\n 'http://... | [
10,
14,
16,
18,
20
] |
# 내 풀이
with open("sequence.protein.2.fasta", "w") as fw:
with open("sequence.protein.fasta", "r") as fr:
for line in fr:
fw.write(line)
# 강사님 풀이
# fr = open('sequence.protein.fasta','r'):
# lines=fr.readlines()
# seq_list=list()
# for line in lines:
| normal | {
"blob_id": "84fb0e364ee3cd846148abfc9326f404f008c510",
"index": 7908,
"step-1": "<mask token>\n",
"step-2": "with open('sequence.protein.2.fasta', 'w') as fw:\n with open('sequence.protein.fasta', 'r') as fr:\n for line in fr:\n fw.write(line)\n",
"step-3": "# 내 풀이\nwith open(\"sequence... | [
0,
1,
2
] |
my_dict = {'one': '1', 'two': '2'}
for key in my_dict:
print('{} - {}'.format(key, my_dict[key]))
| normal | {
"blob_id": "1d524312cbd3b735850046131f31c03fdfa90bbc",
"index": 483,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor key in my_dict:\n print('{} - {}'.format(key, my_dict[key]))\n",
"step-3": "my_dict = {'one': '1', 'two': '2'}\nfor key in my_dict:\n print('{} - {}'.format(key, my_dict[key]))... | [
0,
1,
2
] |
from PIL import Image
from random import randrange
class PileMosaic:
def __init__(self):
self.width, self.height = 2380, 2800
self.filename = "pile_mosaic.png"
self.crema = (240, 233, 227)
self.choco = (89, 62, 53)
self.luna = (43, 97, 123)
self.latte = (195, 175, 14... | normal | {
"blob_id": "a484272ace089008e27f4e00d2e641118432665e",
"index": 4592,
"step-1": "<mask token>\n\n\nclass PileMosaic:\n\n def __init__(self):\n self.width, self.height = 2380, 2800\n self.filename = 'pile_mosaic.png'\n self.crema = 240, 233, 227\n self.choco = 89, 62, 53\n s... | [
7,
8,
12,
13,
14
] |
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
# are the lat/lon values of the lower left and upper right corners
# of the map.
# resolution = 'c' means use crude resolution coastlines.
m = Basemap(projection='cea',llcrnrlat=-90,urcr... | normal | {
"blob_id": "f5f9a1c7dcb7345e24f50db54649a1970fc37185",
"index": 1262,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nm.drawcoastlines()\nm.fillcontinents(color='coral', lake_color='aqua')\nm.drawparallels(np.arange(-90.0, 91.0, 30.0))\nm.drawmeridians(np.arange(-180.0, 181.0, 60.0))\nm.drawmapboundary(f... | [
0,
1,
2,
3,
4
] |
import functools
import requests
import time
import argparse
class TracePoint:
classes = []
funcs = []
flow = []
@staticmethod
def clear():
TracePoint.classes = []
TracePoint.funcs = []
TracePoint.flow = []
def __init__(self, cls, func, t):
if cls not ... | normal | {
"blob_id": "80bf208f1d658b639d650af8208a744ed2dd258f",
"index": 9355,
"step-1": "<mask token>\n\n\nclass TracePoint:\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n d... | [
6,
9,
11,
12,
14
] |
from apps.mastermind.core.domain.domain import Color, Game
from apps.mastermind.infrastructure.mongo_persistence.uow import MongoUnitOfWork
from composite_root.container import provide
class GameMother:
async def a_game(
self,
num_slots: int,
num_colors: int,
max_guesses: int,
... | normal | {
"blob_id": "8457cdde8f8ad069505c7729b8217e5d272be41e",
"index": 957,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass GameMother:\n\n async def a_game(self, num_slots: int, num_colors: int, max_guesses:\n int, secret_code: list[Color], reference: (str | None)=None) ->Game:\n asy... | [
0,
1,
2,
3
] |
import pymysql
def get_list(sql, args):
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd
='chen0918', db='web')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql, args)
result = cursor.fetchall()
cursor.close()
conn.close()
return res... | normal | {
"blob_id": "80819ec83572737c89044936fc269154b190751a",
"index": 2372,
"step-1": "<mask token>\n\n\ndef modify(sql, args):\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd\n ='chen0918', db='web')\n cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)\n cursor.execute(... | [
1,
2,
3,
4
] |
from random import randint
from Ball import Ball
from Util import Vector, Rectangle
class Player:
RADIUS = 10
COLOR1 = "#80d6ff"
COLOR2 = "#ff867c"
OUTLINE = "#000000"
@property
def right(self):
return self.pos.sub(Vector(Player.RADIUS, 0))
@property
def left(self):
... | normal | {
"blob_id": "04b02931b749ad06a512b78ca5661ae1f5cb8a9c",
"index": 5534,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Player:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def right(self):\n return self.pos.sub(Vector(Player.RADIUS, 0))\n\n... | [
0,
8,
9,
14,
15
] |
from collections import namedtuple
from weakref import ref
l = list()
_l = list()
# Point = namedtuple('Point', ['x', 'y'])
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def callback(ref):
print ('__del__', ref)
for x in range(10):
p = Point(x,x**2)
t = ref(p,callback)... | normal | {
"blob_id": "2542998c3a7decd6329856a31d8e9de56f82bae1",
"index": 3922,
"step-1": "<mask token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n ... | [
2,
3,
5,
6,
7
] |
try:
import RPi.GPIO as GPIO
import time
import numpy as np
import matplotlib.pyplot as plt
from os.path import dirname, join as pjoin
from scipy.io import wavfile
import scipy.io
except ImportError:
print ("Import error!")
raise SystemExit
try:
chan_list = (26, 19, 13, 6, 5, 1... | normal | {
"blob_id": "675d564ad60870f49b88dece480d5a50a30491df",
"index": 4907,
"step-1": "<mask token>\n\n\ndef decToBinList(decNumber):\n if decNumber < 0 or decNumber > 255:\n raise ValueError\n return [((int(decNumber) & 1 << i) >> i) for i in range(7, -1, -1)]\n\n\n<mask token>\n",
"step-2": "<mask to... | [
1,
2,
3,
4,
5
] |
/Users/medrine/anaconda/lib/python2.7/UserDict.py | normal | {
"blob_id": "8db90b0bfde61de1c4c1462bc3bcf05ef9056362",
"index": 9236,
"step-1": "/Users/medrine/anaconda/lib/python2.7/UserDict.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
from boxsdk import Client, OAuth2
import os
import sys
def ConfigObject(config_path):
"read a configuration file to retrieve access token"
configDict = {}
with open(config_path,'r') as config:
for line in config.readlines():
try:
configDict[line.split("=")[0]] = line.sp... | normal | {
"blob_id": "e76ebbe8dab2e5169ef40b559f783c49ba4de825",
"index": 1750,
"step-1": "<mask token>\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n ... | [
3,
4,
5,
6,
7
] |
import sys
from melody_types import *
import dataclasses
"""
Marks notes for grace notes
"""
# Mark grace notes on the peak note of every segment
def _peaks(song):
for phrase in song.phrases:
for pe in phrase.phrase_elements:
if type(pe) == Segment:
if pe.direction != SegmentDir... | normal | {
"blob_id": "ac83d7d39319c08c35302abfb312ebee463b75b2",
"index": 5130,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef _insert_grace_notes(song):\n for phrase in song.phrases:\n for pe in phrase.phrase_elements:\n if type(pe) != Segment:\n continue\n ... | [
0,
1,
3,
4,
6
] |
import requests
import re
from bs4 import BeautifulSoup
r = requests.get("https://terraria.fandom.com/wiki/Banners_(enemy)")
soup = BeautifulSoup(r.text, 'html.parser')
list_of_banners = soup.find_all('span', {'id': re.compile(r'_Banner')})
x_count = 1
y_count = 1
for banner_span in list_of_banners:
print(f"{banner... | normal | {
"blob_id": "e60d57e8884cba8ce50a571e3bd0affcd4dcaf68",
"index": 4056,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor banner_span in list_of_banners:\n print(f\"{banner_span['id']}, {x_count}, {y_count}\")\n x_count += 1\n if x_count == 51:\n x_count = 1\n y_count += 1\n ... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
# project: fshell
# author: s0nnet
# time: 2017-01-08
# desc: data_fuzzhash
import sys
sys.path.append("./dao")
from fss_data_fuzzhash_dao import *
class FssFuzzHash:
@staticmethod
def insert_node(agent_id, data):
return FssFuzzHashDao.insert_node(agent_id, data)
| normal | {
"blob_id": "398f9f52b83ffddfb452abbeaad2e83610580fee",
"index": 9763,
"step-1": "<mask token>\n\n\nclass FssFuzzHash:\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass FssFuzzHash:\n\n @staticmethod\n def insert_node(agent_id, data):\n return FssFuzzHashDao.insert_node(agent_id, data)\n",
... | [
1,
2,
3,
4,
5
] |
from enum import Enum
from app.utilities.data import Prefab
class Tags(Enum):
FLOW_CONTROL = 'Flow Control'
MUSIC_SOUND = 'Music/Sound'
PORTRAIT = 'Portrait'
BG_FG = 'Background/Foreground'
DIALOGUE_TEXT = 'Dialogue/Text'
CURSOR_CAMERA = 'Cursor/Camera'
LEVEL_VARS = 'Level-wide Unlocks and ... | normal | {
"blob_id": "c2dba981b0d628aebdf8cebfb890aad74a629b08",
"index": 7365,
"step-1": "<mask token>\n\n\nclass GiveExp(EventCommand):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Posit... | [
119,
154,
180,
218,
252
] |
from five import grok
from zope.formlib import form
from zope import schema
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from Products.Fi... | normal | {
"blob_id": "214585956e44ce006db0702fd23692b11459f9e1",
"index": 7664,
"step-1": "<mask token>\n\n\nclass Renderer(base.Renderer):\n render = ViewPageTemplateFile('twitterportlet.pt')\n\n def __init__(self, context, request, view, manager, data):\n self.context = context\n self.request = requ... | [
9,
10,
13,
15,
16
] |
from django.conf.urls import url
from tree import views
urlpatterns = [
url('/home', views.home),
url('/about', views.about),
] | normal | {
"blob_id": "3313f01ed98433f4b150c4d8e877ac09eb8403b4",
"index": 5652,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('/home', views.home), url('/about', views.about)]\n",
"step-3": "from django.conf.urls import url\nfrom tree import views\nurlpatterns = [url('/home', views.home), ur... | [
0,
1,
2,
3
] |
"""Test cases for the __main__ module."""
import pytest
from click.testing import CliRunner
from skimpy import __main__
from skimpy import generate_test_data
from skimpy import skim
@pytest.fixture
def runner() -> CliRunner:
"""Fixture for invoking command-line interfaces."""
return CliRunner()
def test_ma... | normal | {
"blob_id": "97a51d959ad642467c508cedc8786f636e4050bb",
"index": 1333,
"step-1": "<mask token>\n\n\n@pytest.fixture\ndef runner() ->CliRunner:\n \"\"\"Fixture for invoking command-line interfaces.\"\"\"\n return CliRunner()\n\n\ndef test_main_succeeds(runner: CliRunner) ->None:\n \"\"\"It exits with a s... | [
3,
6,
7,
8,
9
] |
# Generated by Django 3.2.6 on 2021-08-19 22:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat', '0005_user_image'),
]
operations = [
migrations.AlterField(
model_name='user',
name='first_name',
... | normal | {
"blob_id": "fac60a8967354e4f306b95fdb5c75d02dc2c1455",
"index": 2247,
"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 = [('chat', '000... | [
0,
1,
2,
3,
4
] |
from pymouse import PyMouse
m = PyMouse()
w,h = m.screen_size()
class base_controller:
def __init__(self):
pass
def move(self,xy:list):
'''
移动
'''
m.move(xy[0]*w,xy[1]*h)
def click(self, xy:list):
'''
点击
'''
m.click(xy[0]*w,xy... | normal | {
"blob_id": "b2f2f1e4b7070ac867b71e538f759e527eb1ffb9",
"index": 416,
"step-1": "<mask token>\n\n\nclass base_controller:\n <mask token>\n\n def move(self, xy: list):\n \"\"\"\n 移动\n \"\"\"\n m.move(xy[0] * w, xy[1] * h)\n\n def click(self, xy: list):\n \"\"\"\n ... | [
6,
8,
10,
11,
12
] |
def count_words(word):
count = 0
count = len(word.split())
return count
if __name__ == '__main__':
print count_words("Boj is dope")
| normal | {
"blob_id": "9f3b7d6dbf57157b5ebd6ad72f46befc94798a5f",
"index": 3845,
"step-1": "def count_words(word):\n\tcount = 0\n\tcount = len(word.split())\n\treturn count\n\n\nif __name__ == '__main__':\n\tprint count_words(\"Boj is dope\")\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"s... | [
0
] |
from superwires import games, color
import random
SCORE = 0
## pizza_image= games.load_image("images/pizza.png")
## pizza = games.Sprite(image = pizza_image, x=SW/2, y=SH/2,
## dx =1, dy = 1)
## games.screen.add(pizza)
games.init(screen_width = 640, screen_height = 480, fps = ... | normal | {
"blob_id": "ee16b91ce1c12ce78d23ff655304aebc39cb1639",
"index": 9693,
"step-1": "<mask token>\n\n\nclass Pan(games.Sprite):\n <mask token>\n\n def update(self):\n \"\"\" Move to mouse coordinates \"\"\"\n self.x = games.mouse.x\n self.check_collide()\n <mask token>\n\n\nclass Pizza... | [
7,
9,
10,
13,
14
] |
from collections import deque
'''
Big O
เวลาเรียก queue จะมี2operation 1deque 2enqueue เวลาเอาไปใช้
อยู่ที่การimplementation
โปรแกรมที่ดี 1.ทำงานถูกต้อง 2.ทันใจ 3.ทรัพยากรที่ใช้รันได้ทุกเครื่อง(specคอมกาก)
4.ทำงานได้ตามต้องการ5.ความเสถียรของระบบ 6.Bugs
แพง คือ memory expansive ใช้หน่วยความจำเยอะ
runtime exp... | normal | {
"blob_id": "c96a64573fc6cc207ee09be4f4b183d065736ff6",
"index": 5442,
"step-1": "<mask token>\n\n\nclass Queue:\n\n def __init__(self):\n self.items = deque()\n\n def enQueue(self, i):\n self.items.append(i)\n\n def deQueue(self):\n return self.items.popleft()\n\n def isEmpty(se... | [
5,
6,
7,
8,
9
] |
from flask import Flask, render_template, flash, request
import pandas as pd
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
df = pd.read_csv('data1.csv')
try:
row = df[df['District'] == 'Delhi'].index[0]
except:
print("now city found")
DEBUG = True
app = Flask(__name_... | normal | {
"blob_id": "8240e6483f47abbe12e7bef02493bd147ad3fec6",
"index": 6998,
"step-1": "from flask import Flask, render_template, flash, request\nimport pandas as pd\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\n\ndf = pd.read_csv('data1.csv')\ntry:\n row = df[df['Distri... | [
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.