code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
print("gggg")
print("gggg")
print("gggg")
| normal | {
"blob_id": "b53294330a908f8a50d8fbb50b9c88e2bc6135a1",
"index": 4124,
"step-1": "<mask token>\n",
"step-2": "print('gggg')\nprint('gggg')\nprint('gggg')\n",
"step-3": "print(\"gggg\")\nprint(\"gggg\")\nprint(\"gggg\")\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
# Generated by Django 3.2.4 on 2021-06-18 01:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('eCom', '0014_auto_20210617_1503'),
]
operations = [
migrations.RemoveField(
model_name='order',... | normal | {
"blob_id": "ef57f0dfea261f022ced36ef9e27a07d63c21026",
"index": 2156,
"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 = [('eCom', '001... | [
0,
1,
2,
3,
4
] |
import abc
class Connector:
"""@abc.abstractmethod
def connect(self):
pass
"""
@abc.abstractmethod
def save(self, item):
pass
@abc.abstractmethod
def load_all(self):
pass
@abc.abstractmethod
def load_by_id(self, i... | normal | {
"blob_id": "ac46aa6f8f4f01b6f3c48532533b9dd41a8a1c1c",
"index": 7007,
"step-1": "<mask token>\n\n\nclass Connector:\n <mask token>\n\n @abc.abstractmethod\n def save(self, item):\n pass\n\n @abc.abstractmethod\n def load_all(self):\n pass\n\n @abc.abstractmethod\n def load_by_... | [
4,
5,
7,
8,
10
] |
import numpy as np
import sys
class NeuralNetworkClassifier():
def __init__(self, hidden_units, learning_rate, batch_size, epochs, l_1_beta_1, l_1_beta_2, l_2_alpha_1, l_2_alpha_2):
self._hidden_units = hidden_units
self._learning_rate = learning_rate
self._batch_size = batch_size
... | normal | {
"blob_id": "6199a2ac12e80395f4a7a54877c5b639315e64aa",
"index": 7702,
"step-1": "<mask token>\n\n\nclass NeuralNetworkClassifier:\n <mask token>\n\n def fit(self, X_train, Y_train):\n num_input_dimensions = X_train.shape[1]\n self._num_classes = Y_train.shape[1]\n training_set_size = ... | [
9,
15,
19,
21,
26
] |
from flask import (Flask,
render_template,
request,
url_for,
redirect,
flash,
jsonify)
app = Flask(__name__)
@app.route('/', methods=['GET'])
def showHomepage():
return render_template('home.html')
if __name__ == '__main__':
print('app started')
app.secret_key = 'secretkey'
app.run(debug=True)
| normal | {
"blob_id": "3001534be3364be1148cd51a4a943fd8c975d87e",
"index": 8384,
"step-1": "<mask token>\n\n\n@app.route('/', methods=['GET'])\ndef showHomepage():\n return render_template('home.html')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@app.route('/', methods=['GET'])\ndef showHomepage():\n return... | [
1,
2,
3,
4,
5
] |
import time
from junk.keyboard_non_blocking import NonBlockingKeyboard
TICK_DURATION = 0.05
INITIAL_FOOD_LEVEL = 100
FOOD_PER_TICK = -1
FOOD_PER_FEED = 10
MAX_FOOD_LEVEL = 100
INITIAL_ENERGY_LEVEL = 50
ENERGY_PER_TICK_AWAKE = -1
ENERGY_PER_TICK_ASLEEP = 5
MAX_ENERGY_LEVEL = 100
INITIAL_IS_AWAKE = False
INITIAL_PO... | normal | {
"blob_id": "1dd09a09f542099091d94d466ebd7cc149884eb4",
"index": 7385,
"step-1": "<mask token>\n\n\nclass UnknownCommand(Exception):\n pass\n\n\n<mask token>\n\n\nclass Tamagotchi:\n\n def __init__(self) ->None:\n self._age = 0\n self._food_level = INITIAL_FOOD_LEVEL\n self._energy_lev... | [
10,
11,
12,
13,
16
] |
my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1]
new_list = list(filter(lambda x: x != 0, my_list))
try:
new = list(map(lambda x: 2 / x, new_list))
except ZeroDivisionError:
pass
print(new)
# def devis(n, list):
# new_list = []
# for i, m_list in enumerate(list):
# try:
# new_list.a... | normal | {
"blob_id": "46f3d3681343d96889ddb073f17ff7f225486f35",
"index": 8005,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n new = list(map(lambda x: 2 / x, new_list))\nexcept ZeroDivisionError:\n pass\nprint(new)\n",
"step-3": "my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1]\nnew_list = list(filter(l... | [
0,
1,
2,
3
] |
############################## Import Modules ##################################
import pandas as pd
import numpy as np
import re
from scipy import stats
import matplotlib.pyplot as plt
############################## Define Functions ################################
# generate list containing data of standard curve
de... | normal | {
"blob_id": "19949b07c866d66b3ef00b6a386bf89f03e06294",
"index": 7984,
"step-1": "<mask token>\n\n\ndef process_std(standard_input_file):\n try:\n with open(standard_input_file, 'r') as in_handle:\n lin_reg_lst = []\n for line in in_handle:\n line = line.strip('\\n'... | [
3,
4,
5,
6,
8
] |
a = ['a', 'b', 'c', 'd', 'e']
print(';'.join(a))
| normal | {
"blob_id": "a10403d7809b97c1bcdfa73224b8c365519cc456",
"index": 7275,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(';'.join(a))\n",
"step-3": "a = ['a', 'b', 'c', 'd', 'e']\nprint(';'.join(a))\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
} | [
0,
1,
2
] |
from django import forms
from .models import Appointment, Prescription
from account.models import User
class AppointmentForm(forms.ModelForm):
class Meta:
model = Appointment
fields = '__all__'
widgets = {
'date': forms.DateInput(attrs={'type': 'date'}),
'time': for... | normal | {
"blob_id": "d3425017d4e604a8940997afd0c35a4f7eac1170",
"index": 6944,
"step-1": "<mask token>\n\n\nclass PrescriptionForm(forms.ModelForm):\n\n\n class Meta:\n model = Prescription\n exclude = ['doctor']\n widgets = {'prescription': forms.Textarea(attrs={'rows': 4})}\n\n def __init__(... | [
2,
3,
4,
5,
6
] |
class TestRawJob:
def __init__(self, parsedRow):
values = [string.strip().lower() for string in parsedRow]
keys = ["Id", "Title", "Description", "Raw Location", "Normalized Location",
"Contract Type", "Contract Time", "Company", "Category", "Source"]
self.data = dict(zip(keys, values))
| normal | {
"blob_id": "4eac468db955ca5ef5d2ec6ba67bd6c7f4d865f4",
"index": 2050,
"step-1": "<mask token>\n",
"step-2": "class TestRawJob:\n <mask token>\n",
"step-3": "class TestRawJob:\n\n def __init__(self, parsedRow):\n values = [string.strip().lower() for string in parsedRow]\n keys = ['Id', 'T... | [
0,
1,
2,
3
] |
import numpy as np
import math
import os
if os.getcwd().rfind('share') > 0:
topsy = True
import matplotlib as mpl
mpl.use('Agg')
else:
topsy = False
from matplotlib import rc
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib import cm
from scipy.optimize import curve_fit
import sys
import h... | normal | {
"blob_id": "2539411c7b348662dbe9ebf87e26faacc20f4c5e",
"index": 3837,
"step-1": "import numpy as np\nimport math\nimport os\nif os.getcwd().rfind('share') > 0:\n\ttopsy = True\n\timport matplotlib as mpl\n\tmpl.use('Agg')\nelse:\n\ttopsy = False\n\tfrom matplotlib import rc\nimport matplotlib.pyplot as plt\nfro... | [
0
] |
"""
Escreva um programa que leia as coordenadas x e y de um ponto R² e calcule
sua distância da origem(0,0).
"""
import math
print("Origem = 0")
x = int(input("X: "))
y = int(input("Y: "))
aux = (x*x)+(y*y)
dist = math.sqrt(aux)
print("Distância da origem {:.2f}".format(dist)) | normal | {
"blob_id": "69d48bc9ecd0f003d7b22c6fbaa532d28137b38e",
"index": 7713,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Origem = 0')\n<mask token>\nprint('Distância da origem {:.2f}'.format(dist))\n",
"step-3": "<mask token>\nprint('Origem = 0')\nx = int(input('X: '))\ny = int(input('Y: '))\naux =... | [
0,
1,
2,
3,
4
] |
import torch.utils.data
import torch
import math
from util.helpers import *
from collections import defaultdict as ddict
class _Collate:
def __init__(self, ):
pass
def collate(self, batch):
return torch.squeeze(torch.from_numpy(np.array(batch)))
class PR:
dataset = None
eval_data = N... | normal | {
"blob_id": "606a6e7ecc58ecbb11aa53602599e671514bc537",
"index": 3890,
"step-1": "<mask token>\n\n\nclass PR:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def init(self, d... | [
7,
8,
9,
11,
14
] |
print("This program calculates whether the year is a leap year or not")
year = input("Please enter the Year: ")
if year.isdecimal():
year=int(year)
if year%4==0 and year%100!=0 or year%400==0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
... | normal | {
"blob_id": "fdea48b6012b67327aea90e40eacbea5a1930d07",
"index": 9688,
"step-1": "<mask token>\n",
"step-2": "print('This program calculates whether the year is a leap year or not')\n<mask token>\nif year.isdecimal():\n year = int(year)\n if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:\n ... | [
0,
1,
2,
3
] |
#!/usr/bin/python3
print("content-type: text/html")
print()
import subprocess
import cgi
form=cgi.FieldStorage()
osname=form.getvalue("x")
command="sudo docker stop {}".format(osname)
output=subprocess.getstatusoutput(command)
status=output[0]
info=output[1]
if status==0:
print("{} OS is stopped succesfully....".form... | normal | {
"blob_id": "1d2dae7f1d937bdd9a6044b23f8f1897e61dac23",
"index": 6330,
"step-1": "<mask token>\n",
"step-2": "print('content-type: text/html')\nprint()\n<mask token>\nif status == 0:\n print('{} OS is stopped succesfully....'.format(osname))\nelse:\n print('some error: {}'.format(info))\n",
"step-3": "... | [
0,
1,
2,
3,
4
] |
water = 400
milk = 540
coffee = 120
cups = 9
money = 550
def buying():
global water
global coffee
global cups
global milk
global money
choice_coffee = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
if choice_coffee == "1":
... | normal | {
"blob_id": "4e98ebd040297cb9472368478452bc484e0aaa04",
"index": 3255,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef stats_print():\n print('The coffee machine has:')\n print(str(water) + ' of water')\n print(str(milk) + ' of milk')\n print(str(coffee) + ' of coffee beans')\n prin... | [
0,
2,
6,
7,
8
] |
#!/usr/bin/python
import wx
class test(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,"TestFrame",size=(500,500))
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = test(parent=None,id=-1,)
frame.show()
app.mainloop()
| normal | {
"blob_id": "e204cbbf36ac180eba0e95916345088c77bca7c0",
"index": 5001,
"step-1": "<mask token>\n\n\nclass test(wx.Frame):\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass test(wx.Frame):\n\n def __init__(self, parent, id):\n wx.Frame.__init__(self, parent, id, 'TestFrame', s... | [
1,
2,
3,
4,
5
] |
__author__ = 'christopher'
import fabio
import pyFAI
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from pims.tiff_stack import TiffStack_tifffile as TiffStack
from skxray.io.save_powder_output import save_output
from xpd_workflow.mask_tools import *
geo = pyFAI.load(
'/mnt/bulk-data/researc... | normal | {
"blob_id": "50f6bcb4d2223d864cca92778ab3483a2d2c3214",
"index": 5283,
"step-1": "__author__ = 'christopher'\nimport fabio\nimport pyFAI\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom pims.tiff_stack import TiffStack_tifffile as TiffStack\nfrom skxray.io.save_powder_output import s... | [
0
] |
# coding:utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing import Pool
"""
用户id,时间戳,浏览行为数据,浏览子行为编号
"""
names = ['userid','time','browser_behavior','browser_behavior_number']
browse_history_train = pd.read_csv("../../pcredit/train/browse_history_train.txt",header=None)
... | normal | {
"blob_id": "e6bd9391a5364e798dfb6d2e9b7b2b98c7b701ac",
"index": 6559,
"step-1": "# coding:utf-8\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Pool\n\n\"\"\"\n 用户id,时间戳,浏览行为数据,浏览子行为编号\n\"\"\"\nnames = ['userid','time','browser_behavior','browser_behavior... | [
0
] |
"""Plugin setup."""
import importlib
from qiime2.plugin import (
Plugin,
Str,
Choices,
Int,
Bool,
Range,
Float,
Metadata,
MetadataColumn,
Categorical,
Numeric,
Citations,
)
import q2_micom
from q2_micom._formats_and_types import (
SBML,
JSON,
Pickle,
SBM... | normal | {
"blob_id": "9a6f159d9208ee9e337de7b717e2e25c7e7f9f06",
"index": 4277,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplugin.register_formats(SBMLFormat, SBMLDirectory, JSONFormat,\n JSONDirectory, CommunityModelFormat, CommunityModelManifest,\n CommunityModelDirectory, GrowthRates, Fluxes, MicomRe... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python3
import argparse
import logging
import tango
def delete_devices():
"""."""
db = tango.Database()
class_list = db.get_class_list('*')
print('class list = ', class_list)
server_list = db.get_server_list('*')
print('server list = ', server_list)
# for index in range(nu... | normal | {
"blob_id": "f3dad6a474d5882beaac7d98f8f60c347730ee55",
"index": 8428,
"step-1": "<mask token>\n\n\ndef delete_devices():\n \"\"\".\"\"\"\n db = tango.Database()\n class_list = db.get_class_list('*')\n print('class list = ', class_list)\n server_list = db.get_server_list('*')\n print('server li... | [
1,
2,
3,
4,
5
] |
import itertools
from typing import Tuple, List, Dict, Optional, Hashable, Collection
class Hypergraph:
"""
Represents a hypergraph, consisting of nodes, directed edges,
hypernodes (each of which is a set of nodes) and hyperedges (directed edges
from hypernodes to hypernodes). Contains functionality to... | normal | {
"blob_id": "4a3611ecd70d80575f9f68bf45d67532a17b9c93",
"index": 7527,
"step-1": "<mask token>\n\n\nclass Hypergraph:\n <mask token>\n\n def __init__(self):\n self.nodes = dict()\n self.hypernodes = dict()\n self.adj_out = dict()\n self.adj_in = dict()\n <mask token>\n\n d... | [
8,
10,
15,
16,
20
] |
from sonosscripts import common
from sonosscripts.common import round_nearest
def run(_):
parser = common.get_argument_parser()
parser.add_argument("--step", help="volume step", type=int, default=5)
parsed_args = parser.parse_args()
sonos = common.get_sonos(parsed_args)
step = parsed_args.step
... | normal | {
"blob_id": "6e78dee46276f738197ba6796fe1a027ab743354",
"index": 1769,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run(_):\n parser = common.get_argument_parser()\n parser.add_argument('--step', help='volume step', type=int, default=5)\n parsed_args = parser.parse_args()\n sonos = ... | [
0,
1,
2,
3
] |
# coding: utf-8
import sys, os
sys.path.append(os.pardir)
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from common.util import smooth_curve
from common.multi_layer_net import MultiLayerNet
from common.optimizer import *
# 0. MNIST 데이터 로딩
(x_train, t_train), (x_test, t_test) = load... | normal | {
"blob_id": "85d40a49341c7bd7af7a5dc62e4bce0253eb25e6",
"index": 9944,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.append(os.pardir)\n<mask token>\nfor key in optimizers.keys():\n networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, \n 100, 100, 100], output_size=10)... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import tempfile
from functools import partial
import numpy as np
import torch
from ax.benchmark.benchmark_pr... | normal | {
"blob_id": "52eec56f7f5da8356f61301994f846ef7769f73b",
"index": 6189,
"step-1": "<mask token>\n\n\nclass JSONStoreTest(TestCase):\n\n def setUp(self):\n self.experiment = get_experiment_with_batch_and_single_trial()\n\n def testJSONEncodeFailure(self):\n self.assertRaises(JSONEncodeError, ob... | [
7,
10,
12,
14,
18
] |
import os
import location
import teamList
import pandas as pd
import csv
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
##adapted from code from this website:
## https://towardsdatascience.com/simple-little-tables-with-matplotlib-9780ef5d0bc4
year = "18-19"
team = "ARI"
seasonReportRaw =... | normal | {
"blob_id": "ba7db49ca7956fdc055702ffccba769485fd0046",
"index": 8915,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor row in data:\n cell_text.append([f'{x:1.2f}' for x in row])\n<mask token>\nplt.figure(linewidth=2, edgecolor=fig_border, facecolor=\n fig_background_color, tight_layout={'pad': ... | [
0,
1,
2,
3,
4
] |
def domain_name(url):
while "https://" in url or "http://" in url or "www." in url:
url = url.replace("https://", ' ') if "https://" in url else url.replace("http://", ' ') if "http://" in url else url.replace("www.", ' ')
url = list(url)
for i in range(len(url)):
if url[i] == ".":
... | normal | {
"blob_id": "2b9dfd0cfd62276330f1a4f983f318076f329437",
"index": 5026,
"step-1": "<mask token>\n",
"step-2": "def domain_name(url):\n while 'https://' in url or 'http://' in url or 'www.' in url:\n url = url.replace('https://', ' '\n ) if 'https://' in url else url.replace('http://', ' '\n... | [
0,
1,
2,
3
] |
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.minheap = []
self.maxheap = []
def addNum(self, num: int) -> None:
heapq.heappush (self.maxheap ,-heapq.heappushpop(self.minheap , num) )
if len(self.maxheap) > len... | normal | {
"blob_id": "e7699bb3f6080c78517f11445e2c48a0e40f3332",
"index": 3209,
"step-1": "class MedianFinder:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class MedianFinder:\n <mask token>\n <mask token>\n\n def findMedian(self) ->float:\n if len(self.maxheap) == len(self.minhe... | [
1,
2,
3,
4,
5
] |
def fun1(fun):
return "Hai!!!! "+fun
def message():
return "How are you"
res = fun1(message())
print(res)
| normal | {
"blob_id": "e9fff1fb0a79493d4d7f3417c7d554eb10a978a0",
"index": 6616,
"step-1": "<mask token>\n",
"step-2": "def fun1(fun):\n return 'Hai!!!! ' + fun\n\n\ndef message():\n return 'How are you'\n\n\n<mask token>\n",
"step-3": "def fun1(fun):\n return 'Hai!!!! ' + fun\n\n\ndef message():\n return ... | [
0,
2,
3,
4,
5
] |
def solution(record):
answer = []
arr = dict()
history = []
for i in record:
tmp = i.split()
if tmp[0] == "Enter" :
arr[tmp[1]] = tmp[2]
history.append([tmp[1], "님이 들어왔습니다."])
elif tmp[0] == "Leave" :
history.append([tmp[1], "님이 나갔습니다."])
... | normal | {
"blob_id": "d9f66cc3ba40292c49da08d7573d4c605a2771ae",
"index": 3730,
"step-1": "<mask token>\n",
"step-2": "def solution(record):\n answer = []\n arr = dict()\n history = []\n for i in record:\n tmp = i.split()\n if tmp[0] == 'Enter':\n arr[tmp[1]] = tmp[2]\n h... | [
0,
1,
2
] |
import numpy as np
import matplotlib.pyplot as plt
import math
filename = '/home/kolan/mycode/python/dektak/data/t10_1_1_normal.csv'
#filename = '/home/kolan/mycode/python/dektak/t10_1_3_normal.csv'
#filename = '/home/kolan/mycode/python/dektak/t10_1_6_normal.csv'
#filename = '/home/kolan/mycode/python/dektak/t10_1_7... | normal | {
"blob_id": "139d06497a44031f6414980ad54454477e3d0b2c",
"index": 4540,
"step-1": "import numpy as np \nimport matplotlib.pyplot as plt\nimport math\n\nfilename = '/home/kolan/mycode/python/dektak/data/t10_1_1_normal.csv'\n#filename = '/home/kolan/mycode/python/dektak/t10_1_3_normal.csv'\n#filename = '/home/kolan... | [
0
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
from typing import List, Dict, NamedTuple, Union, Optional
import codecs
import collections
import enum
import json
import re
import struct
from refinery.lib.structures import StructReader
from refinery.units.formats.office... | normal | {
"blob_id": "566dab589cdb04332a92138b1a1faf53cd0f58b8",
"index": 5419,
"step-1": "<mask token>\n\n\nclass MSITableColumnInfo(NamedTuple):\n <mask token>\n number: int\n attributes: int\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def length(self) ->int:\n... | [
14,
21,
22,
26,
27
] |
# -*- coding: utf-8 -*-
__all__ = ["kepler", "quad_solution_vector", "contact_points"]
import numpy as np
from .. import driver
def kepler(mean_anomaly, eccentricity):
mean_anomaly = np.ascontiguousarray(mean_anomaly, dtype=np.float64)
eccentricity = np.ascontiguousarray(eccentricity, dtype=np.float64)
... | normal | {
"blob_id": "ccd32a6ca98c205a6f5d4936288392251522db29",
"index": 4896,
"step-1": "<mask token>\n\n\ndef kepler(mean_anomaly, eccentricity):\n mean_anomaly = np.ascontiguousarray(mean_anomaly, dtype=np.float64)\n eccentricity = np.ascontiguousarray(eccentricity, dtype=np.float64)\n sinf = np.empty_like(m... | [
2,
3,
4,
5,
6
] |
#! /usr/bin/env python3
import os
import requests
# import json
external_ip = "xx"
data_path = "/data/feedback/"
url = "http://{}/feedback/".format(external_ip)
def read():
# read file
file_list = os.listdir(data_path)
result_list = []
for file in file_list:
with open(data_path + file) as f:... | normal | {
"blob_id": "6f1bb9fde9ed9667ab81baa9e8ec965d711a0556",
"index": 9853,
"step-1": "<mask token>\n\n\ndef read():\n file_list = os.listdir(data_path)\n result_list = []\n for file in file_list:\n with open(data_path + file) as f:\n content = f.readlines()\n dict = {}\n ... | [
4,
5,
6,
7,
8
] |
from threading import Thread
import time
def sleeping():
time.sleep(5)
print('Ended')
Thread(target=sleeping, daemon=True).start()
print('Hello world')
time.sleep(5.5)
| normal | {
"blob_id": "628fdf848079d0ecf5bf4f5bd46e07ad6cd10358",
"index": 5070,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef sleeping():\n time.sleep(5)\n print('Ended')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef sleeping():\n time.sleep(5)\n print('Ended')\n\n\nThread(target=s... | [
0,
1,
2,
3
] |
import nltk
import spacy
import textacy
from keras.layers import Embedding, Bidirectional, Dense, Dropout, BatchNormalization
from keras_preprocessing.sequence import pad_sequences
from keras_preprocessing.text import Tokenizer
from nltk import word_tokenize, re
from rasa import model
import pandas as pd
from spacy imp... | normal | {
"blob_id": "707855a4e07b68d9ae97c2e1dc8bfd52f11c314c",
"index": 1812,
"step-1": "<mask token>\n\n\ndef load_dataset(filename):\n df = pd.read_csv(filename, encoding='latin1', names=['Sentence', 'Intent'])\n intent = df['Intent']\n unique_intent = list(set(intent))\n sentences = list(df['Sentence'])\... | [
7,
9,
10,
11,
12
] |
import scrapy
from yijing64.items import Yijing64Item
# import pymysql
class ZhouyiSpider(scrapy.Spider):
name = 'zhouyi'
allowed_domains = ['m.zhouyi.cc']
start_urls = ['https://m.zhouyi.cc/zhouyi/yijing64/']
def parse(self, response):
li_list = response.xpath("//div[@class='gualist1 tip_tex... | normal | {
"blob_id": "cd9f25a2810b02f5588e4e9e8445e7aaec056bf8",
"index": 7704,
"step-1": "<mask token>\n\n\nclass ZhouyiSpider(scrapy.Spider):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def parse_detail(self, response):\n item = response.meta['item']\n item['hexagram1'] ... | [
2,
3,
4,
5,
6
] |
from .base import GnuRecipe
class CAresRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(CAresRecipe, self).__init__(*args, **kwargs)
self.sha256 = '45d3c1fd29263ceec2afc8ff9cd06d5f' \
'8f889636eb4e80ce3cc7f0eaf7aadc6e'
self.name = 'c-ares'
self.ve... | normal | {
"blob_id": "bf7676dc2c47d9cd2f1ce2d436202ae2c5061265",
"index": 8634,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass CAresRecipe(GnuRecipe):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass CAresRecipe(GnuRecipe):\n\n def __init__(self, *args, **kwargs):\n super(CAresRecipe... | [
0,
1,
2,
3,
4
] |
# Copyright (c) 2015, the Fletch project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE.md file.
{
'variables': {
'mac_asan_dylib': '<(PRODUCT_DIR)/libclang_rt.asan_osx_dynamic.dylib',
},
... | normal | {
"blob_id": "84b98ebf6e44d03d16f792f3586be1248c1d0221",
"index": 6957,
"step-1": "<mask token>\n",
"step-2": "{'variables': {'mac_asan_dylib':\n '<(PRODUCT_DIR)/libclang_rt.asan_osx_dynamic.dylib'}, 'targets': [{\n 'target_name': 'fletch-vm', 'type': 'none', 'dependencies': [\n 'src/vm/vm.gyp:fletch-v... | [
0,
1,
2
] |
from django.core.exceptions import ValidationError
from django.utils import timezone
def year_validator(value):
if value < 1 or value > timezone.now().year:
raise ValidationError(
('%s is not a correct year!' % value)
)
def raiting_validator(value):
if value < 1 or value > 10:
... | normal | {
"blob_id": "7a6d5309580b673413f57047e631a08e61e837cf",
"index": 4447,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef raiting_validator(value):\n if value < 1 or value > 10:\n raise ValidationError('%s is not a caorrect raiting!' % value)\n",
"step-3": "<mask token>\n\n\ndef year_vali... | [
0,
1,
2,
3,
4
] |
import argparse
import gc
import gcsfs
import nibabel as nib
import nilearn
import nobrainer
import numpy as np
import os
import os.path as op
import pandas as pd
import tensorflow as tf
def interpolate_images(baseline, image, alphas):
alphas_x = alphas[:, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis]
basel... | normal | {
"blob_id": "848e4abcd0b4f118030fc62f1272a19bfce9db4e",
"index": 178,
"step-1": "<mask token>\n\n\ndef interpolate_images(baseline, image, alphas):\n alphas_x = alphas[:, tf.newaxis, tf.newaxis, tf.newaxis, tf.newaxis]\n baseline_x = tf.expand_dims(baseline, axis=0)\n input_x = tf.expand_dims(image, axi... | [
4,
5,
6,
7,
8
] |
#!/usr/bin/env python
"""
Calculate trigger efficiency error
"""
__author__ = "XIAO Suyu<xiaosuyu@ihep.ac.cn>"
__copyright__ = "Copyright (c) XIAO Suyu"
__created__ = "[2018-02-06 Tue 15:25]"
import math
n1 = 4212.0
n2 = 4237.0
N = 5000.0
eff = n1 / n2
err = math.sqrt(eff*(1-eff)/N)
print 'trig_eff = %.4f +- %f' ... | normal | {
"blob_id": "bac3f78b8eb9c4595bc9e8b85587819f92329729",
"index": 2295,
"step-1": "#!/usr/bin/env python\n\"\"\"\nCalculate trigger efficiency error\n\"\"\"\n\n__author__ = \"XIAO Suyu<xiaosuyu@ihep.ac.cn>\"\n__copyright__ = \"Copyright (c) XIAO Suyu\"\n__created__ = \"[2018-02-06 Tue 15:25]\"\n\nimport math\n\nn... | [
0
] |
class Order:
"""
Initiated a new order for the store
"""
def __init__(self, order_number, product_id, item_type, name, product_details, factory, quantity, holiday):
"""
Construct a new order
:param order_number: str
:param product_id: str
:param item_type: str
... | normal | {
"blob_id": "0dce4ea8ef21f2535194330b82ce5706ae694247",
"index": 4676,
"step-1": "class Order:\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def order_num(self):\n \"\"\"\n Return order num of the order.\n :return: str\n \"\"\"\n return self._order... | [
7,
10,
11,
15,
17
] |
# Bradley N. Miller, David L. Ranum
# Introduction to Data Structures and Algorithms in Python
# Copyright 2005
#
__all__=['BinaryTree', 'Stack']
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append... | normal | {
"blob_id": "5f48c7a68cb9734d84dee2cf8ff4d7be490cf328",
"index": 2888,
"step-1": "<mask token>\n\n\nclass BinaryTree:\n <mask token>\n\n def __init__(self, rootObj):\n self.key = rootObj\n self.leftChild = None\n self.rightChild = None\n self.parent = None\n\n def insertLeft(... | [
12,
19,
30,
31,
37
] |
from typing import Any
from typing import List
from xsdata.codegen.mixins import RelativeHandlerInterface
from xsdata.codegen.models import Attr
from xsdata.codegen.models import Class
from xsdata.models.enums import Tag
from xsdata.utils.namespaces import build_qname
class ClassEnumerationHandler(RelativeHandlerInt... | normal | {
"blob_id": "4d9064add28302fe173a8b0a81ee7d187db8aead",
"index": 6029,
"step-1": "<mask token>\n\n\nclass ClassEnumerationHandler(RelativeHandlerInterface):\n <mask token>\n <mask token>\n\n def process(self, target: Class):\n \"\"\"\n Process class receiver.\n\n Steps:\n ... | [
6,
7,
9,
10,
11
] |
import logging
import os
import callbacks
import commands
import dice
import echo
import inline
import keyboards
import mybot
import myenigma
import poll
import rocketgram
import send
import unknown
# avoid to remove "unused" imports by optimizers
def fix_imports():
_ = callbacks
_ = commands
_ = echo
... | normal | {
"blob_id": "fd904c70b350c650362c55ccb3b915371f24e267",
"index": 9623,
"step-1": "import logging\nimport os\n\nimport callbacks\nimport commands\nimport dice\nimport echo\nimport inline\nimport keyboards\nimport mybot\nimport myenigma\nimport poll\nimport rocketgram\nimport send\nimport unknown\n\n\n# avoid to ... | [
0
] |
import datetime
import traceback
import sys
import os
def getErrorReport():
errorReport = ErrorReport()
return errorReport
class ErrorReport():
def __init__(self):
return
def startLog(self):
timestamp = str(datetime.datetime.now())
fileName = 'Log_'+timestamp+'.txt.... | normal | {
"blob_id": "6abc8b97117257e16da1f7b730b09ee0f7bd4c6e",
"index": 4715,
"step-1": "<mask token>\n\n\nclass ErrorReport:\n <mask token>\n\n def startLog(self):\n timestamp = str(datetime.datetime.now())\n fileName = 'Log_' + timestamp + '.txt.'\n self.logFile = open(fileName, 'w')\n\n ... | [
4,
6,
7,
8,
9
] |
from datetime import datetime
import warnings
import numpy as np
import xarray as xr
from .common import HDF4, expects_file_info
pyhdf_is_installed = False
try:
from pyhdf import HDF, VS, V
from pyhdf.SD import SD, SDC
pyhdf_is_installed = True
except ImportError:
pass
__all__ = [
'CloudSat',
]
... | normal | {
"blob_id": "4328d526da14db756fad8d05457724a23e3e3ef6",
"index": 3939,
"step-1": "<mask token>\n\n\nclass CloudSat(HDF4):\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n @expects_file_info()\n def get_info(self, file_info, *... | [
4,
7,
8,
9,
11
] |
from dataclasses import dataclass
from models.user import User
class Customer(User):
def __init__(self, first_name: str, last_name: str, user_name: str, email: str, password: str):
super(Customer, self).__init__(first_name, last_name, user_name, email, password)
# def __str__(self):
# return... | normal | {
"blob_id": "254f34c923d49374e09b579c5bc1b17b8c69c0e4",
"index": 2661,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Customer(User):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Customer(User):\n\n def __init__(self, first_name: str, last_name: str, user_name: str,\n em... | [
0,
1,
2,
3,
4
] |
from collections import defaultdict, deque
N = int(input())
adj_list = defaultdict(list)
E = []
V_number = [None] * N
for _ in range(N - 1):
a, b = map(int, input().split())
E.append((a, b))
adj_list[a].append(b)
adj_list[b].append(a)
C = sorted(list(map(int, input().split())), reverse=True)
q = deque([... | normal | {
"blob_id": "b93f6c3192f8dd58b96dfdc6ea2b17e12cce34d0",
"index": 9752,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor _ in range(N - 1):\n a, b = map(int, input().split())\n E.append((a, b))\n adj_list[a].append(b)\n adj_list[b].append(a)\n<mask token>\nwhile q:\n v = q.popleft()\n ... | [
0,
1,
2,
3
] |
# encoding = utf-8
"""
A flask session memcached store
"""
from datetime import timedelta, datetime
from uuid import uuid4
__author__ = 'zou'
import memcache
import pickle
from flask.sessions import SessionMixin, SessionInterface
from werkzeug.datastructures import CallbackDict
class MemcachedSession(CallbackDict, S... | normal | {
"blob_id": "e4761c925643417f4fe906e8dd2c9356ae970d52",
"index": 3706,
"step-1": "<mask token>\n\n\nclass MemcachedSessionInterface(SessionInterface):\n <mask token>\n <mask token>\n\n def generate_sid(self):\n return str(uuid4())\n\n def get_memcache_expiration_time(self, app, session):\n ... | [
8,
10,
12,
14,
15
] |
from numpy import array, zeros, arange, concatenate, searchsorted, where, unique
from pyNastran.bdf.fieldWriter import print_card_8
from pyNastran.bdf.bdfInterface.assign_type import (integer, integer_or_blank,
double_or_blank, integer_double_or_blank, blank)
class PBAR(object):
type = 'PBAR'
def __init_... | normal | {
"blob_id": "8f960ad465d0a7bf48752db35c73169be6da27d8",
"index": 9092,
"step-1": "<mask token>\n\n\nclass PBAR(object):\n <mask token>\n\n def __init__(self, model):\n \"\"\"\n Defines the PCOMP object.\n\n :param self: the PCOMP object\n :param model: the BDF object\n :p... | [
3,
6,
7,
8,
9
] |
from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
import re
EMAIL_REGEX = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
app = Flask(__name__)
app.secret_key = "ThisIsSecret"
mysql = MySQLConnector(app,'mydb')
@app.route('/')
def ... | normal | {
"blob_id": "187cf160b520001b6fe3a8d343391de1c04b3acd",
"index": 1754,
"step-1": "<mask token>\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/process', methods=['POST'])\ndef process():\n if len(request.form['email']) < 1:\n flash('Email cannot be blank!'... | [
4,
5,
6,
7,
8
] |
from valuate.predict import *
def get_profit_rate(intent, popularity):
"""
获取畅销系数
"""
# 按畅销程度分级,各交易方式相比于标价的固定比例
profits = gl.PROFITS
profit = profits[popularity]
# 计算各交易方式的价格相比于标价的固定比例
if intent == 'sell':
# 商家收购价相比加权平均价的比例
profit_rate = 1 - profit[0] - profit[1]
el... | normal | {
"blob_id": "1f01989f10be5404d415d4abd1ef9ab6c8695aba",
"index": 6069,
"step-1": "<mask token>\n\n\ndef process_mile(price, use_time, mile):\n \"\"\"\n mile处理\n \"\"\"\n mile_per_month = mile / use_time\n if mile_per_month < gl.MILE_THRESHOLD_2_5:\n return price + 0.035 * (1 - mile_per_mont... | [
12,
15,
16,
18,
25
] |
import csv
from matplotlib import pyplot as plt
from datetime import datetime
file_one = 'data/dwifh_all_sales.csv'
file_two = 'data/dwifh_bc_sales.csv'
# create code to automatically build a dictionary for each album?
with open(file_one) as fo:
reader = csv.reader(fo)
header = next(reader)
album = {}
... | normal | {
"blob_id": "53380810a3d9787fe7c373cf1829f2d849a91c3c",
"index": 8456,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open(file_one) as fo:\n reader = csv.reader(fo)\n header = next(reader)\n album = {}\n dates, cd_income, dd_income, total_profit, artist_payout = [], [], [], [\n ]... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# staticbox.py
import wx
class StaticBox(wx.Dialog):
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size = (250, 230))
wx.StaticBox(self, -1, 'Personal Info', (5, 5), size = (240, 170))
wx.CheckBox(self, ... | normal | {
"blob_id": "96bf6220bfc884e3a19f70a63d9ecba449e2e7e2",
"index": 6108,
"step-1": "<mask token>\n\n\nclass StaticBox(wx.Dialog):\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass StaticBox(wx.Dialog):\n\n def __init__(self, parent, id, title):\n wx.Dialog.__i... | [
1,
3,
4,
5,
6
] |
from fractions import Fraction
import itertools
# With MOD
MOD = 10**9+7
def ncomb(n, r):
return reduce(lambda a, b: (a*b)%MOD, (Fraction(n-i, i+1) for i in range(r)), 1)
# No MOD
def ncomb(n, r):
return reduce(lambda a, b: (a*b), (Fraction(n-i, i+1) for i in range(r)), 1)
def comb(a, l):
return [subset ... | normal | {
"blob_id": "2bc0d76e17f2f52fce9cc1925a3a0e0f53f5b81d",
"index": 7953,
"step-1": "<mask token>\n\n\ndef ncomb(n, r):\n return reduce(lambda a, b: a * b % MOD, (Fraction(n - i, i + 1) for i in\n range(r)), 1)\n\n\n<mask token>\n\n\ndef comball(a):\n r = []\n for l in range(0, len(a) + 1):\n ... | [
2,
3,
4,
5,
7
] |
'''
Created on Nov 1, 2013
@author: hanchensu
'''
from numpy import *
import numpy as np
def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()
b = 0; m,n = shape(dataMatrix)
matrix = mat([[1,2],[3,4],[5,6]])
m,n= shape(matrix)
matA = mat... | normal | {
"blob_id": "9bf8834b12bcace0f6daf64adae1babe78bb04fa",
"index": 5553,
"step-1": "'''\nCreated on Nov 1, 2013\n\n@author: hanchensu\n'''\nfrom numpy import *\nimport numpy as np\n\ndef smoSimple(dataMatIn, classLabels, C, toler, maxIter):\n dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()\n ... | [
0
] |
'''
#조건문 예제
#fdragon50
#2016
'''
# 주석 : 도움말/덧글 / 미사용(추후 사용가능한) 코드 기록
# 여러줄의 문자열 표현은 ''' ''' 사이에 표현 가능하나 사용은 권장않음
# #으로 시작하는것은 문자열 자체가 아닌.. 무시되는 구간
# 주석은 누가봐도 이해할수있게 / 간결하게
# 더 좋은것은 누가봐도 이해할수 있는 코드임
# 가독성이 좋은 코드를 만들수 있도록..
#조건문 예제
#fdragon50
#2016
input = 11
real_fdragon50 = 11
#real_k8805 = "ab"
if real_fdr... | normal | {
"blob_id": "2da6debb1f9ae2c966a17fdfb3b668160a3ef8d7",
"index": 1384,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif real_fdragon50 == input:\n print('Hello!')\nelse:\n print('Who are you')\n",
"step-3": "<mask token>\ninput = 11\nreal_fdragon50 = 11\nif real_fdragon50 == input:\n print('H... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | normal | {
"blob_id": "ab5400f4b44a53cb5cc2f6394bcdb8f55fd218f0",
"index": 1813,
"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 = [migrations.sw... | [
0,
1,
2,
3,
4
] |
import os, subprocess
def greet(name):
hostname = subprocess.check_output("hostname").decode("utf-8")[:-1]
return "Hello, {}! I'm {}#{}.".format(name, hostname, os.getppid())
| normal | {
"blob_id": "9bd55a2f224acfa2cb34d0ca14a25e8864d644b3",
"index": 5250,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef greet(name):\n hostname = subprocess.check_output('hostname').decode('utf-8')[:-1]\n return \"Hello, {}! I'm {}#{}.\".format(name, hostname, os.getppid())\n",
"step-3": "i... | [
0,
1,
2,
3
] |
N, M = map(int, input().split()) # Nはスイッチの数、Mは電球の数
lights = [[0] * N for _ in range(M)]
for i in range(M):
temp = list(map(int, input().split())) # 0番目はスイッチの個数、1番目以降はスイッチを示す
k = temp[0]
switches = temp[1:]
for j in range(k):
lights[i][switches[j]-1] = 1
P = list(map(int, input().split())) # 個数を... | normal | {
"blob_id": "c4ac7ff5d45af9d325f65b4d454a48ca0d8f86df",
"index": 8808,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(M):\n temp = list(map(int, input().split()))\n k = temp[0]\n switches = temp[1:]\n for j in range(k):\n lights[i][switches[j] - 1] = 1\n<mask token>\nfor... | [
0,
1,
2,
3
] |
f=open('poem.txt')
for line in f:
print line,
| normal | {
"blob_id": "76348448a658736627efe8fa6b19c752191966e7",
"index": 5409,
"step-1": "f=open('poem.txt')\nfor line in f:\n\tprint line,\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test support for the various "EMPTY" WKT geometry representations.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#############################################... | normal | {
"blob_id": "1ef1dcc8fdf4d813dad70c860e33778715d51b0c",
"index": 1575,
"step-1": "<mask token>\n\n\nclass TestWktEmpty:\n\n def __init__(self, inString, expectedOutString):\n self.inString = inString\n self.expectedOutString = expectedOutString\n\n def isEmpty(self, geom):\n try:\n ... | [
5,
6,
7,
8,
9
] |
from cell import Cell
from tkinter import messagebox
import time
import fileTools
class Playground:
"""
The playground for the program. All cells are stored here. This object also import/export cells to the playground
:param screen: The screen object.
:param mouse: The mouse object.
... | normal | {
"blob_id": "80d5cc9871ec753fb9239df7680ac62809baa496",
"index": 8177,
"step-1": "<mask token>\n\n\nclass Playground:\n <mask token>\n\n def __init__(self, root, screen, mouse, keyboard):\n self.root = root\n self.screen = screen\n self.mouse = mouse\n self.keyboard = keyboard\n... | [
12,
16,
17,
18,
19
] |
# -*- coding: utf-8 -*-
import math
# 冒泡排序(Bubble Sort)
# 比较相邻的元素。如果第一个比第二个大,就交换它们两个;
# 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数;
# 针对所有的元素重复以上的步骤,除了最后一个;
# 重复步骤1~3,直到排序完成。
# 冒泡排序总的平均时间复杂度为:O(n^2)
def bubble_sort(input):
print("\nBubble Sort")
input_len = len(input)
print("length of input: %d" % i... | normal | {
"blob_id": "c967aa647a97b17c9a7493559b9a1577dd95263a",
"index": 7806,
"step-1": "<mask token>\n\n\ndef select_sort(input):\n print('\\nSelect Sort')\n input_len = len(input)\n for i in range(0, input_len):\n min_index = i\n for j in range(i + 1, input_len):\n if input[j] < inpu... | [
1,
6,
7,
8,
9
] |
import sys
from sklearn.svm import SVC
from sklearn.model_selection import KFold,cross_validate,GridSearchCV
from data_prepr import data_preprocessing
import numpy as np
def main():
#if dataset is not provided on call terminate
if len(sys.argv)<2:
print("usage: python svm_parameter_tuning.py <input_file> ")
sys... | normal | {
"blob_id": "c5842b17b2587149cd13448593a6ed31b091ba77",
"index": 4971,
"step-1": "import sys\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import KFold,cross_validate,GridSearchCV\nfrom data_prepr import data_preprocessing\nimport numpy as np\n\n\ndef main():\n\t#if dataset is not provided on call t... | [
0
] |
#!/usr/bin/python3
from optparse import OptionParser
from urllib import request, parse
from urllib.error import URLError, HTTPError
import ssl
import re
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.options &= ssl.CERT_NONE
class Settings:
SINGLETON = None
def __init__(self):
self.... | normal | {
"blob_id": "e92a738d3233450b255605619dafadd4d829604b",
"index": 9067,
"step-1": "<mask token>\n\n\nclass Settings:\n SINGLETON = None\n\n def __init__(self):\n self.url_pattern = (\n 'href=\"((http[s]?://|/)(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\\\(\\\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)\"'\n ... | [
14,
19,
20,
21,
25
] |
import os
import cv2
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from numpy import array
import tensorflow as tf
TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'
train_folder_list = array(os.listdir(TRAIN_DIR))
train_input = []
tr... | normal | {
"blob_id": "01339324ad1a11aff062e8b27efabf27c97157fb",
"index": 9908,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor index in range(len(train_folder_list)):\n path = os.path.join(TRAIN_DIR, train_folder_list[index])\n path = path + '/'\n img_list = os.listdir(path)\n for img in img_list:... | [
0,
1,
2,
3,
4
] |
import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
username=st.text_input ("username")
upload=st.file_uploader("uploadfile",type=['csv'])
button=st.button("submit")
if button==True:
df=pd.read_csv(upload)
st.write(df.head())
fig = plt.figu... | normal | {
"blob_id": "72f1547ea7de78a5fe4b583523e592fa25c0ee77",
"index": 2467,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif button == True:\n df = pd.read_csv(upload)\n st.write(df.head())\n fig = plt.figure()\n my = fig.add_subplot(1, 1, 1)\n my.scatter(df['sepal.length'], df['petal.length']... | [
0,
1,
2,
3,
4
] |
import numpy as np
import pandas as pd
from scipy.optimize import minimize
from datetime import datetime
import time
from functions import weather_scraper
def getData():
# # run weather_scraper.py to fetch new weather data
# weather_scraper.getData()
## Read in csv file "weather_data.csv"
weather_data... | normal | {
"blob_id": "7a1bd2b4734527a414c6173ea8edb150221f8042",
"index": 363,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef getData():\n weather_data = pd.read_csv('data/weather_data.csv')\n currentMonth = datetime.now().month\n currentHour = datetime.now().hour\n currentMonthGroup = current... | [
0,
1,
2,
3
] |
alias_macro = {
"class": "Application",
"method": "alias_macro",
"doc": """
Returns or modifies the macro of a command alias.
""",
"syntax": """
Rhino.AliasMacro (strAlias [, strMacro])
""",
"params": {
0: {
"name": "alias",
"... | normal | {
"blob_id": "1574f034ff9b6ddb785e4c54758b2057009198ed",
"index": 7587,
"step-1": "<mask token>\n",
"step-2": "alias_macro = {'class': 'Application', 'method': 'alias_macro', 'doc':\n \"\"\"\n Returns or modifies the macro of a command alias.\n \"\"\",\n 'syntax': \"\"\"\n Rhino.AliasMacr... | [
0,
1,
2
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from twython import Twython
import random
tweetStr = "None"
#twitter consumer and access information goes here
api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
timeline = api.get_user_timeline()
lastEntry = timeline[0]
sid = str(lastEntry['id']... | normal | {
"blob_id": "88e1eb4cbfe346c663cca23836c23346e18a8488",
"index": 7444,
"step-1": "\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nfrom twython import Twython\nimport random\n\ntweetStr = \"None\"\n\n#twitter consumer and access information goes here\n\n\napi = Twython(apiKey,apiSecret,accessToken,a... | [
0
] |
import numpy as np
class LinearRegressor():
def __init__(self, alpha=0.1, epochs=1):
self.alpha = alpha
self.epochs = epochs
self.costs = []
self.theta = None
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted wit... | normal | {
"blob_id": "d805a1290c107a8d768417a432e338b182b7cd6b",
"index": 5524,
"step-1": "<mask token>\n\n\nclass LinearRegressor:\n <mask token>\n\n def _cost_function(self, y_pred, y, m):\n \"\"\"\n Gets the cost for the predicted values when contrasted with the correct ones.\n y_pred: An (1... | [
4,
5,
6,
8,
9
] |
#!/bin/env python3
"""
https://www.hackerrank.com/challenges/triangle-quest-2
INPUT:
integer N
where 0 < N < 10
OUTPUT:
print palindromic triangle of size N
e.g.for N=5
1
121
12321
1234321
123454321
"""
for i in range(1, int(input()) + 1):
j = 1
while j < i:
print(j,end='')
j += 1
w... | normal | {
"blob_id": "94cbd9554e3326897147dc417d9fc8f91974786a",
"index": 5098,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(1, int(input()) + 1):\n j = 1\n while j < i:\n print(j, end='')\n j += 1\n while i > 0:\n print(i, end='')\n i -= 1\n print()\n",
... | [
0,
1,
2
] |
import torch
import torch.multiprocessing as mp
import random
class QManeger(object):
def __init__(self, opt, q_trace, q_batch):
self.traces_s = []
self.traces_a = []
self.traces_r = []
self.lock = mp.Lock()
self.q_trace = q_trace
self.q_batch = q_batch
sel... | normal | {
"blob_id": "b693cc63e2ee4c994ef7b5e44faea99f15a021f6",
"index": 68,
"step-1": "<mask token>\n\n\nclass QManeger(object):\n <mask token>\n <mask token>\n\n def listening(self):\n while True:\n traces = self.q_trace.get(block=True)\n for s, a, r in zip(traces[0], traces[1], t... | [
2,
4,
5,
6,
7
] |
#!/usr/bin/env python
# Core Library modules
import os
# Third party modules
import nose
# First party modules
import lumixmaptool.copy as copy
# Tests
def get_parser_test():
"""Check if the evaluation model returns a parser object."""
copy.get_parser()
def parse_mapdata_test():
current_folder = os.p... | normal | {
"blob_id": "4dfdbc692858a627248cbe47d19b43c2a27ec70e",
"index": 7373,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef parse_mapdata_test():\n current_folder = os.path.dirname(os.path.realpath(__file__))\n misc_folder = os.path.join(current_folder, 'misc')\n maplistdata_path = os.path.joi... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import xmlrunner
import os
import sys
import glob
import yaml
ASSETS_DIR = ""
class GenerateMachineConfig(unittest.TestCase):
def setUp(self):
self.machine_configs = []
for machine_config_path in glob.glob(
f'{ASSETS_D... | normal | {
"blob_id": "f0c082968e26d414b0dbb679d4e5077056e99979",
"index": 8653,
"step-1": "<mask token>\n\n\nclass GenerateMachineConfig(unittest.TestCase):\n\n def setUp(self):\n self.machine_configs = []\n for machine_config_path in glob.glob(\n f'{ASSETS_DIR}/openshift/99_openshift-machinec... | [
3,
4,
5,
6,
7
] |
from functools import wraps
from time import sleep
def retry(retry_count = 2, delay = 5, action_description = 'not specified', allowed_exceptions=()):
def decorator(func):
@wraps(func) # to preserve metadata of the function to be decorated
def wrapper(*args, **kwargs):
for _ in range(re... | normal | {
"blob_id": "79e4592d5ea84cc7c97d68a9390eb5d387045cf0",
"index": 4344,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef retry(retry_count=2, delay=5, action_description='not specified',\n allowed_exceptions=()):\n\n def decorator(func):\n\n @wraps(func)\n def wrapper(*args, **kw... | [
0,
1,
2,
3
] |
"""
This module provides an optimizer class that is based on an evolution
strategy algorithm.
"""
import copy, random, math
from time import time
from xml.dom import minidom
from extra.schedule import Schedule
from extra.printer import pprint, BLUE
class Optimizer(object):
"""
This class is the implementation of the... | normal | {
"blob_id": "8ce2e9cd9ceed6c79a85682b8bc03a3ffb5131c4",
"index": 3817,
"step-1": "<mask token>\n\n\nclass Optimizer(object):\n <mask token>\n <mask token>\n\n @staticmethod\n def fromXml(xmlDoc, plant, orderList, simulator, evaluator):\n \"\"\"\n\t\tLoads the optimizer configuration and parame... | [
10,
11,
12,
13,
16
] |
import math
class Solution:
# @param {integer} n
# @param {integer} k
# @return {string}
def getPermutation(self, n, k):
res = ''
k -= 1
nums = [str(i) for i in range(1, n+1)]
while n > 0:
tmp = math.factorial(n-1)
res += nums[k/tmp]
d... | normal | {
"blob_id": "d267bf82aee2eca29628fcd1d874a337adc1ae09",
"index": 8859,
"step-1": "import math\n\nclass Solution:\n # @param {integer} n\n # @param {integer} k\n # @return {string}\n def getPermutation(self, n, k):\n res = ''\n k -= 1\n nums = [str(i) for i in range(1, n+1)]\n ... | [
0
] |
#!/usr/bin/env python
#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================
"""
evaluate-gbvi.py
Evaluate the GBVI model on hydration free energies of small molec... | normal | {
"blob_id": "0ac9e757fa827b311487169d0dc822951ce8c4bb",
"index": 7167,
"step-1": "#!/usr/bin/env python\n\n#=============================================================================================\n# MODULE DOCSTRING\n#=========================================================================================... | [
0
] |
# 3번 반복하고 싶은 경우
# 별 10개를 한줄로
for x in range(0, 10, 3): # 3번째 숫자는 증감할 양을 정해줌.
# print(x)
print("★", end=" ")
print()
print("------------------------")
#이중 for문
for y in range(0, 10):
for x in range(0, 10):
# print(x)
print("★", end=" ")
print() | normal | {
"blob_id": "b360ba7412bd10e2818511cee81302d407f88fd1",
"index": 1895,
"step-1": "<mask token>\n",
"step-2": "for x in range(0, 10, 3):\n print('★', end=' ')\nprint()\nprint('------------------------')\nfor y in range(0, 10):\n for x in range(0, 10):\n print('★', end=' ')\n print()\n",
"step-... | [
0,
1,
2
] |
from django import forms
from .models import Recipe, Ingredient, Category, Tag
from blog.widgets import CustomClearableFileInput
class NewCategoriesForm(forms.ModelForm):
friendly_name = forms.CharField(label='... or add your own category',
required=False)
class Meta():
... | normal | {
"blob_id": "7484bd9012bc9952b679073ae036de4554d362be",
"index": 5175,
"step-1": "<mask token>\n\n\nclass IngredientForm(forms.ModelForm):\n\n\n class Meta:\n model = Ingredient\n exclude = 'recipe',\n labels = {'quantity': 'Qty'}\n\n def __init__(self, *args, **kwargs):\n super... | [
6,
7,
9,
12,
15
] |
from abc import ABC, abstractmethod
class DatasetFileManager(ABC):
@abstractmethod
def read_dataset(self):
pass
| normal | {
"blob_id": "5ef65ace397be17be62625ed27b5753d15565d61",
"index": 555,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass DatasetFileManager(ABC):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass DatasetFileManager(ABC):\n\n @abstractmethod\n def read_dataset(self):\n pass\n",... | [
0,
1,
2,
3
] |
# coding: utf-8
import logging
import uuid
import json
import xmltodict
import bottle
from bottle import HTTPError
from bottle.ext import sqlalchemy
from database import Base, engine
from database import JdWaybillSendResp, JdWaybillApplyResp
jd = bottle.Bottle(catchall=False)
plugin = sqlalchemy.Plugin(
engine, ... | normal | {
"blob_id": "a93884757069393b4d96de5ec9c7d815d58a2ea5",
"index": 935,
"step-1": "<mask token>\n\n\n@jd.get('/routerjson')\ndef apply_jd_waybill(db):\n query = bottle.request.query\n if query['method'] == 'jingdong.etms.waybillcode.get':\n jd_code, resp = jd_get_response_normal()\n logging.deb... | [
4,
5,
6,
7,
8
] |
list = input().split()
n = int(list[0])
k = int(list[1])
list.clear()
for i in range(0, n):
list.append("")
tmp = input().split()
list[i] = tmp[0] + list[int(tmp[1])-1]
for i in range(0, k):
start = input()
print(len([word for word in list if word.startswith(start)])) | normal | {
"blob_id": "1808be09c2730af5829bb0c7c0c7cfe9f80fe84c",
"index": 7546,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nlist.clear()\nfor i in range(0, n):\n list.append('')\n tmp = input().split()\n list[i] = tmp[0] + list[int(tmp[1]) - 1]\nfor i in range(0, k):\n start = input()\n print(le... | [
0,
1,
2,
3
] |
# -*- encoding:utf-8 -*-
from setuptools import setup, find_packages
setup(
name='pass-manager',
version='1.2.0',
author='petitviolet',
author_email='violethero0820@gmail.com',
packages=find_packages(),
description = 'Simple CLI Password Manager',
long_description = 'Please show help (pass-... | normal | {
"blob_id": "31664f1cc808ccc0dad230e2b955692c7ae12db1",
"index": 1792,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsetup(name='pass-manager', version='1.2.0', author='petitviolet',\n author_email='violethero0820@gmail.com', packages=find_packages(),\n description='Simple CLI Password Manager', l... | [
0,
1,
2,
3
] |
from .exceptions import InvalidUsage
class HTTPMethodView:
""" Simple class based implementation of view for the sanic.
You should implement methods (get, post, put, patch, delete) for the class
to every HTTP method you want to support.
For example:
class DummyView(HTTPMethodView):
... | normal | {
"blob_id": "4948fd2062bdbd32bfa32d2b0e24587f0872132d",
"index": 4686,
"step-1": "<mask token>\n\n\nclass HTTPMethodView:\n <mask token>\n <mask token>\n\n def dispatch_request(self, request, *args, **kwargs):\n handler = getattr(self, request.method.lower(), None)\n if handler:\n ... | [
2,
4,
5,
6
] |
import requests
def get(url):
return requests.get(url).text
| normal | {
"blob_id": "671ecf23df1da659d186014afa738d0608ad404d",
"index": 9251,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get(url):\n return requests.get(url).text\n",
"step-3": "import requests\n\n\ndef get(url):\n return requests.get(url).text\n",
"step-4": null,
"step-5": null,
"step... | [
0,
1,
2
] |
import ctypes
import time
from order_queue.order import Order
class stock(ctypes.Structure):
_fields_ = [('stock_id', ctypes.c_int), ('order_type',ctypes.c_int),('Time',ctypes.c_char * 40),('user_id',ctypes.c_int),('volume',ctypes.c_int),
('price',ctypes.c_double)
]
class exchange(ctypes.St... | normal | {
"blob_id": "7491a17256b9bc7af0953202e45f0fd9d5c34c40",
"index": 8376,
"step-1": "<mask token>\n\n\nclass exchange(ctypes.Structure):\n <mask token>\n\n\nclass TestSturcture(ctypes.Structure):\n _fields_ = [('a', ctypes.c_int), ('n', ctypes.c_int)]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass... | [
3,
5,
6,
8,
12
] |
# coding: utf-8
BOT_NAME = ['lg']
SPIDER_MODULES = ['lg.spiders']
NEWSPIDER_MODULE = 'lg.spiders'
DOWNLOAD_DELAY = 0.1 # 间隔时间
LOG_LEVEL = 'WARNING'
| normal | {
"blob_id": "bed3d83f682404719a95be360cdd74be9dc87991",
"index": 3718,
"step-1": "<mask token>\n",
"step-2": "BOT_NAME = ['lg']\nSPIDER_MODULES = ['lg.spiders']\nNEWSPIDER_MODULE = 'lg.spiders'\nDOWNLOAD_DELAY = 0.1\nLOG_LEVEL = 'WARNING'\n",
"step-3": "# coding: utf-8\n\nBOT_NAME = ['lg']\n\nSPIDER_MODULES ... | [
0,
1,
2
] |
#/usr/bin/env python3
def nth_prime(n):
ans = 2
known = []
for _ in range(n):
while not all(ans%x != 0 for x in known):
ans += 1
known.append(ans)
return ans
if __name__ == "__main__":
n = int(input("Which one? "))
print(nth_prime(n))
| normal | {
"blob_id": "21fb9622add4d19b2914118e3afd3867b2368a50",
"index": 4913,
"step-1": "<mask token>\n",
"step-2": "def nth_prime(n):\n ans = 2\n known = []\n for _ in range(n):\n while not all(ans % x != 0 for x in known):\n ans += 1\n known.append(ans)\n return ans\n\n\n<mask t... | [
0,
1,
2,
3
] |
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
negative = (dividend < 0) ^ (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
result = 0
while dividend >= divisor:
... | normal | {
"blob_id": "4a0213351f8e9dcb2c6e71317a5ff1064974652e",
"index": 3418,
"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 divide(self, dividend, divisor):\n \"\"\"\n :type dividend: int\n :type divisor: int... | [
0,
1,
2,
3,
4
] |
#! /usr/bin/env python
from taskHandler import Location, Task, TaskFactory
import roslib; roslib.load_manifest('smart_stool')
import rospy
from geometry_msgs.msg import PoseStamped, Twist, Vector3
from nav_msgs.msg import Odometry
from kobuki_msgs.msg import BumperEvent
from move_base_msgs.msg import MoveBaseActionRes... | normal | {
"blob_id": "234112ec16af39b79849dd08769597771fa2c38f",
"index": 3425,
"step-1": "#! /usr/bin/env python\n\nfrom taskHandler import Location, Task, TaskFactory\nimport roslib; roslib.load_manifest('smart_stool')\nimport rospy\nfrom geometry_msgs.msg import PoseStamped, Twist, Vector3\nfrom nav_msgs.msg import Od... | [
0
] |
###############################################################################
# Programming Essentials B8IT102 Assessment #
# Student: Barry Sheppard ID: 10387786 #
# Problem 1 #
... | normal | {
"blob_id": "77e985d94d3b47539f046a3a46cb1a197cef86f4",
"index": 3409,
"step-1": "<mask token>\n\n\ndef CheckNumber(userInput):\n \"\"\" This function returns True if userInput can be converted to a number and\n returns False if it cannot. \"\"\"\n try:\n float(userInput)\n return True\n ... | [
2,
3,
4,
5,
6
] |
import cv2
import numpy as np
import random
def main():
img = cv2.imread('test_image.png',0)
res = np.zeros((img.shape[0],img.shape[1],3),np.uint8)
thresh = cv2.threshold(img, 50, 255, 0)[1]
_, contours,_ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
... | normal | {
"blob_id": "1babf9f27e6792d2a1c2545a1e3bcd08fefa0975",
"index": 5639,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n img = cv2.imread('test_image.png', 0)\n res = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)\n thresh = cv2.threshold(img, 50, 255, 0)[1]\n _, contours,... | [
0,
1,
2,
3,
4
] |
# Random number guessing game.
# 10 July 20
# CTI-110 P5HW1 - Random Number
# Thelma Majette
import random
randomNumber = random.randint (1,100)
# main function
def main():
# Create a variable to control the loop.
keep_going = 'y'
while keep_going == 'y':
# Ask user fo... | normal | {
"blob_id": "c09c02a36a64e9522cfc8c0951bd6c98f404f09c",
"index": 367,
"step-1": "<mask token>\n\n\ndef main():\n keep_going = 'y'\n while keep_going == 'y':\n guess = int(input('\\nGuess a number between 1 and 100: '))\n if guess > randomNumber:\n print('\\nToo high, try again.')\n... | [
1,
2,
3,
4,
5
] |
class default_locations:
mc_2016_data_directory = "/afs/hephy.at/data/cms06/nanoTuples/"
mc_2016_postProcessing_directory = "stops_2016_nano_v0p23/dilep/"
data_2016_data_directory = "/afs/hephy.at/data/cms07/nanoTuples/"
data_2016_postProcessing_directory = "stops_2016_nan... | normal | {
"blob_id": "b6df9414f99294c7986d3eb5332d40288f059cd1",
"index": 1245,
"step-1": "class default_locations:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <ma... | [
1,
2,
3,
4,
5
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.