code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
"""
get poly data(face center, face id, etc), select face, create object by face data
setPosition for vertex (random)
import sys
module_path = '/home/shrimo/Desktop/course/git/vfx_dev/maya/general_lesson'
if module_path not in sys.path:
sys.path.append(module_path)
import lesson_v01
reload(lesson_v01)
lesson... | normal | {
"blob_id": "723d8819b5341f1397163533f59c17ba1a74b77d",
"index": 1310,
"step-1": "\"\"\"\nget poly data(face center, face id, etc), select face, create object by face data\nsetPosition for vertex (random)\n\nimport sys\nmodule_path = '/home/shrimo/Desktop/course/git/vfx_dev/maya/general_lesson'\nif module_path n... | [
0
] |
from .factories import *
| normal | {
"blob_id": "c036e6a0a9f06b08ee3eb43655dd833b46fd1e76",
"index": 3690,
"step-1": "<mask token>\n",
"step-2": "from .factories import *\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
from DataStructures.BST.util import *
def storeInorder(root, inorder):
if root is None:
return
storeInorder(root.left, inorder)
inorder.append(root.data)
storeInorder(root.right, inorder)
def arrayToBST(arr, root):
# Base Case
if root is None:
return
# First update the ... | normal | {
"blob_id": "d2af2b25a1ba2db93c977a13fe0273919bc2e6e0",
"index": 7768,
"step-1": "<mask token>\n\n\ndef storeInorder(root, inorder):\n if root is None:\n return\n storeInorder(root.left, inorder)\n inorder.append(root.data)\n storeInorder(root.right, inorder)\n\n\n<mask token>\n",
"step-2": ... | [
1,
3,
4,
5,
6
] |
#
# Copyright John Reid 2009
#
"""
Code to handle bootstrap analyses.
"""
from itertools import cycle
import random
import bisect
def generate_bootstrap_samples(num_samples, test_universe, test_set_sizes):
"""
Yield samples that match the sizes given in test_set_sizes
"""
for sample_idx, sample_siz... | normal | {
"blob_id": "752affdfa1481b9a19a9b7dfe76f9d5d11c80073",
"index": 4678,
"step-1": "<mask token>\n\n\ndef bootstrap_p_value(bootstrap_stats, stat_value):\n \"\"\"\n Calculate the p-value for the statistic's value given the bootstrap values.\n \"\"\"\n return 1.0 - bisect.bisect_left(bootstrap_stats, st... | [
1,
2,
3,
4,
5
] |
## adapted from https://matplotlib.org/examples/api/radar_chart.html
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.spines import Spine
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
def radar_factory(num... | normal | {
"blob_id": "ddf64ea5ecbd3aa737cd788924035cccb5544fec",
"index": 5544,
"step-1": "<mask token>\n\n\ndef radar_factory(num_vars, frame='circle'):\n theta = np.linspace(0, 2 * np.pi, num_vars, endpoint=False)\n theta += np.pi / 2\n\n def draw_poly_patch(self):\n verts = unit_poly_verts(theta)\n ... | [
2,
3,
4,
5,
6
] |
from db_connector import insert_item_details, insert_user_details
from Item_details import ItemDetails
def mechant_service(user_id):
print('================================')
print('Merchant Page')
print('================================')
heading='=============================================\nenter ... | normal | {
"blob_id": "d5dae7ab6eb34c82ae795730ecae666c4f81f10a",
"index": 4160,
"step-1": "<mask token>\n\n\ndef create_item(user_id):\n flag = False\n while flag == False:\n product_name = input('Enter the name of the product : ')\n flag = validate_product_name(product_name)\n flag = False\n wh... | [
2,
4,
5,
6,
7
] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .document import ParsedDocument,XmlDocument
from .corenlp import StanfordCoreNLP
from .annotation import KBPAnnMgr,ApfAnnMgr
import os
import codecs
import sys
from . import _list_files
def _sequence_tag_bio(doc):
outlines = u''
mentions= doc._... | normal | {
"blob_id": "80b8b77498f915a85185f829e8c7d5becdab8068",
"index": 9286,
"step-1": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom .document import ParsedDocument,XmlDocument\nfrom .corenlp import StanfordCoreNLP\nfrom .annotation import KBPAnnMgr,ApfAnnMgr\nimport os\nimport codecs\nimport ... | [
0
] |
"""
Urls for CAE_Web Audio_Visual app.
"""
from django.conf.urls import url
from . import views
app_name = 'cae_web_audio_visual'
urlpatterns = [
]
| normal | {
"blob_id": "5debc97e99bbd78b17e545896d718d4b0eac8519",
"index": 2430,
"step-1": "<mask token>\n",
"step-2": "<mask token>\napp_name = 'cae_web_audio_visual'\nurlpatterns = []\n",
"step-3": "<mask token>\nfrom django.conf.urls import url\nfrom . import views\napp_name = 'cae_web_audio_visual'\nurlpatterns = ... | [
0,
1,
2,
3
] |
# coding: utf-8
# # Read Bathy data from ERDDAP
# In[ ]:
get_ipython().system(u'conda install basemap --yes')
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
import urllib
import netCDF4
from mpl_toolkits.basemap import Basemap
# In[2]:
# Definine the domain of interest
minlat = 42
maxlat = 45
min... | normal | {
"blob_id": "6d0340a08701b0c4f34e9b833bca27cf455d682d",
"index": 827,
"step-1": "\n# coding: utf-8\n\n# # Read Bathy data from ERDDAP\n\n# In[ ]:\n\nget_ipython().system(u'conda install basemap --yes')\n\n\n# In[1]:\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport urllib\nimport netCDF4\nfrom mpl_t... | [
0
] |
import numpy as np
import sympy as sp
from copy import copy
from typing import Any, get_type_hints, Dict
from inspect import getclosurevars, getsource, getargs
import ast
from ast import parse, get_source_segment
from .numpy import NumPy
from .torch import torch_defs
defines = {}
defines.update(torch_defs)
def check_... | normal | {
"blob_id": "430b5ca7212983743cadc36a2ada987bb721174a",
"index": 3537,
"step-1": "<mask token>\n\n\ndef check_type(item, target):\n assert item == target\n\n\ndef exec_lines(source: str, body, loc: Dict[str, Any], glob: Dict[str, Any],\n ret: Any):\n\n def get_value(v):\n if isinstance(v, ast.Bin... | [
3,
4,
5,
6
] |
import sys, time
from machine import Pin
print('LOAD: blinker.py')
def blink_connected_to_wifi(pin=23):
_blink_pattern(pin, [[3, 0.5, 0.5], [4, 0.2, 0.2]])
def blink_not_connected_to_wifi(pin=23):
_blink_pattern(pin, [[2, 0.2, 0.2], [1, 0.5, 0.5], [2, 0.2, 0.2], [1, 0.5, 0.5]])
# pin - the pin, connected ... | normal | {
"blob_id": "c0bd060990d00ab50c9f2d3060b7f975ff16e1ab",
"index": 4105,
"step-1": "<mask token>\n\n\ndef blink_connected_to_wifi(pin=23):\n _blink_pattern(pin, [[3, 0.5, 0.5], [4, 0.2, 0.2]])\n\n\n<mask token>\n\n\ndef _blink_pattern(pin, pattern):\n p = Pin(pin, Pin.OUT)\n try:\n for item in patt... | [
2,
3,
4,
5,
6
] |
import itertools
import numpy as np
import pandas as pd
from scipy.sparse import coo_matrix
def merge_and_split(inputs, labels):
df = inputs.reset_index().merge(labels.reset_index(), on='utterance',
how='inner').set_index('utterance')
return df.feat, df.label
def list_to_sparse(inputs):
"""Conve... | normal | {
"blob_id": "912928cea0f96e601eecfcb6dba695ef26a3c6e2",
"index": 9618,
"step-1": "<mask token>\n\n\nclass BatchGenerator(object):\n\n def __init__(self, data, batch_size=1):\n self.inputs, self.labels = data\n self.batch_size = batch_size\n self.data_length = len(self.inputs)\n sel... | [
5,
6,
7,
8
] |
"""
Created on Fri Jan 07 20:53:58 2022
@author: Ankit Bharti
"""
from unittest import TestCase, main
from cuboid_volume import *
class TestCuboid(TestCase):
def test_volume(self):
self.assertAlmostEqual(cuboid_volume(2), 8)
self.assertAlmostEqual(cuboid_volume(1), 1)
self.assertAlmostE... | normal | {
"blob_id": "394f835064d070a30040b6f01b25b6f0e005827d",
"index": 5010,
"step-1": "<mask token>\n\n\nclass TestCuboid(TestCase):\n <mask token>\n\n def test_input_value(self):\n self.assertRaises(TypeError, cuboid_volume, 'ank')\n <mask token>\n\n def test_addition_input_value(self):\n s... | [
3,
5,
6,
7,
8
] |
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats")
elif people > cats:
print("Not many cats")
else:
print("we cannnot decide") | normal | {
"blob_id": "0465e33d65c2ce47ebffeec38db6908826bf4934",
"index": 299,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif people < cats:\n print('Too many cats')\nelif people > cats:\n print('Not many cats')\nelse:\n print('we cannnot decide')\n",
"step-3": "people = 20\ncats = 30\ndogs = 15\nif... | [
0,
1,
2,
3
] |
AuthorPath = 'data/Author.csv'
PaperPath = 'buff/Paper.TitleCut.csv'
PaperAuthorPath = 'data/PaperAuthor.csv'
AffilListPath = 'buff/AffilList2.csv'
StopwordPath = 'InternalData/en.lst'
| normal | {
"blob_id": "690e7cc9047b3a445bf330524df52e2b359f1f13",
"index": 958,
"step-1": "<mask token>\n",
"step-2": "AuthorPath = 'data/Author.csv'\nPaperPath = 'buff/Paper.TitleCut.csv'\nPaperAuthorPath = 'data/PaperAuthor.csv'\nAffilListPath = 'buff/AffilList2.csv'\nStopwordPath = 'InternalData/en.lst'\n",
"step-3... | [
0,
1
] |
# (1) Obtain your values here (https://core.telegram.org/api/obtaining_api_id)
api_id = 000000
api_hash = '00000000000000000000000'
phone = '+000000000000'
username = 'theone'
project_id = 000000000
| normal | {
"blob_id": "a5646a5d42dbf6e70e9d18f28513ee2df68a28b1",
"index": 6886,
"step-1": "<mask token>\n",
"step-2": "api_id = 0\napi_hash = '00000000000000000000000'\nphone = '+000000000000'\nusername = 'theone'\nproject_id = 0\n",
"step-3": "# (1) Obtain your values here (https://core.telegram.org/api/obtaining_ap... | [
0,
1,
2
] |
import os
from flask import Flask, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename
import chardet as chardet
import pandas as pd
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file_... | normal | {
"blob_id": "eb17de8828a600832253c4cfeeb91503b6876dd7",
"index": 9963,
"step-1": "<mask token>\n\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower(\n ) in ALLOWED_EXTENSIONS\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == ... | [
5,
6,
7,
8,
9
] |
import zipfile, re
f = zipfile.ZipFile("channel.zip")
num = '90052'
comments = []
while True:
content = f.read(num + ".txt").decode("utf-8")
print(content)
comments.append(f.getinfo(num + ".txt").comment.decode("utf-8"))
match = re.search("Next nothing is (\d+)", content)
if match == None:
... | normal | {
"blob_id": "b883e63c70f3dfeac3294989fab93c1331b6329c",
"index": 7990,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n content = f.read(num + '.txt').decode('utf-8')\n print(content)\n comments.append(f.getinfo(num + '.txt').comment.decode('utf-8'))\n match = re.search('Next noth... | [
0,
1,
2,
3,
4
] |
import turtle
red = range(4);
for i in red:
turtle.forward(200)
turtle.left(90)
turtle.done() | normal | {
"blob_id": "38fceb57977cb792be1a63e8571cd222facdf656",
"index": 1142,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in red:\n turtle.forward(200)\n turtle.left(90)\nturtle.done()\n",
"step-3": "<mask token>\nred = range(4)\nfor i in red:\n turtle.forward(200)\n turtle.left(90)\nturt... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from dynamic_rest import viewsets
from django.shortcuts import render
import os
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework.decorators import api_vi... | normal | {
"blob_id": "8c6b7f29b8dca61a5218b51c85149c9642af5649",
"index": 6665,
"step-1": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom dynamic_rest import viewsets\nfrom django.shortcuts import render\nimport os\nfrom rest_framework import permissions\nfrom rest_framework.response import Respon... | [
0
] |
import world
import items
class Quest:
def __init__(self):
raise NotImplementedError("Do not create raw quest classes")
def __str__(self):
return self.quest_name
def give_reward(self, player):
print("You receive: \n{} gold\n{} exp".format(self.reward_gold, self.reward_exp))
for item in self.reward_it... | normal | {
"blob_id": "4d31985cf1266619406d79a7dbae269c10f21bda",
"index": 5510,
"step-1": "<mask token>\n\n\nclass Quest:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass NoobQuest(Quest):\n\n def __init__(self):\n self.quest_status = 0\n self.quest_name = 'Kill the Rat!'\n self.re... | [
5,
6,
8,
9,
10
] |
# -*- coding: utf-8 -*-
"""
Created on Thu May 3 09:12:11 2018
@author: shen1994
"""
import codecs
import numpy as np
def create_documents():
""" 按标点符号或是空格存储文件 """
documents_length = 0
chars,labels = [],[]
chars_file = codecs.open("data/data.data", 'w', 'utf-8')
labels_file = codecs.open("data/... | normal | {
"blob_id": "f22836fc4fed22d833755db0ff34502170260766",
"index": 9260,
"step-1": "<mask token>\n\n\ndef create_documents():\n \"\"\" 按标点符号或是空格存储文件 \"\"\"\n documents_length = 0\n chars, labels = [], []\n chars_file = codecs.open('data/data.data', 'w', 'utf-8')\n labels_file = codecs.open('data/lab... | [
4,
7,
8,
10,
11
] |
"""This module provides constants for locale-dependent providers."""
import typing as t
from mimesis.enums import Locale
from mimesis.exceptions import LocaleError
__all__ = ["Locale", "validate_locale"]
def validate_locale(locale: t.Union[Locale, str]) -> Locale:
if isinstance(locale, str):
try:
... | normal | {
"blob_id": "779445aa22145d5076940ea5b214c25ad233dd0e",
"index": 3087,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef validate_locale(locale: t.Union[Locale, str]) ->Locale:\n if isinstance(locale, str):\n try:\n return Locale(locale)\n except ValueError:\n ... | [
0,
1,
2,
3,
4
] |
"""
TODO
Chess A.I.
"""
import os, pygame, board, math, engine, sys, gSmart
from pygame.locals import *
import engine, board, piece, copy
class gSmart:
def __init__(self):
self.e = engine.engine()
self.mtrlW = .75
self.dvlpW = 2
self.aggnW = 2
self.defnW = .5
self.thrndW = 2
sel... | normal | {
"blob_id": "7998c4e0ed2bb683f029342554730464f8ac2a09",
"index": 2366,
"step-1": "<mask token>\n\n\nclass gSmart:\n <mask token>\n\n def getNextMove(self, b, n):\n gt = gameTree(b, n)\n return gt.miniMax()\n\n def getAllNextMoves(self, b):\n pcs = b.getPieces(b.turn)\n nextMo... | [
4,
6,
7,
8,
9
] |
#!/usr/bin/env python
# encoding: utf-8
'''
1D2DCNN抽取特征,LSTM后提取特征,最后将提取的特征进行拼接,CNN与LSTM是交叉在一起的
'''
# 导入相关的包
import keras
# 导入相关层的结构
from keras.models import Sequential
from keras.layers import Conv1D, Conv2D, MaxPooling1D, MaxPooling2D, Flatten, Dense, Dropout,LSTM,Reshape
from keras import Model
# 可视化神经网络
from ... | normal | {
"blob_id": "cce1b6f8e4b3f78adfa2243fe49b4994d35c5a38",
"index": 9898,
"step-1": "<mask token>\n\n\ndef merge_model(model_1, model_2):\n \"\"\"\n keras将两个独立的模型融合起来\n :param model_1:\n :param model_2:\n :return:\n \"\"\"\n inp1 = model_1.input\n inp2 = model_2.input\n r1 = model_1.outpu... | [
2,
3,
4,
5,
6
] |
from abc import ABC
from rest_framework import serializers
from shopping_cars.models import Order, ShoppingCart
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
class OrderProductSerializer(serializers.ModelSerializer):
class Meta:
mode... | normal | {
"blob_id": "9c14f024b25c5014567405535dbe5a6c787cfe28",
"index": 6529,
"step-1": "<mask token>\n\n\nclass OrderProductSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = ShoppingCart\n fields = '__all__'\n\n def validate_quantity(self, value):\n if value <= 0:\n ... | [
2,
3,
5,
6,
7
] |
def test_number():
pass
| normal | {
"blob_id": "687ab41e9ce94c8d14154a941504845a8fa9f2d9",
"index": 8660,
"step-1": "<mask token>\n",
"step-2": "def test_number():\n pass\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
import csv
import boto3
import pytz
import time
from datetime import datetime, timedelta
# current_time = int(datetime.now())
from boto3.dynamodb.conditions import Key, Attr
def lambda_handler(event, context):
current_date = datetime.now(pytz.timezone('US/Central'))
yesterday_date = current_date - timedleta(... | normal | {
"blob_id": "64d955d568a6bfec50aad36c9c4f1e36998e4d74",
"index": 7467,
"step-1": "<mask token>\n\n\ndef lambda_handler(event, context):\n current_date = datetime.now(pytz.timezone('US/Central'))\n yesterday_date = current_date - timedleta(days=1)\n yesterday_date_string = yesterday_date.strftime('%Y-%m-... | [
1,
2,
3,
4,
5
] |
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='API')
from django.contrib.auth import views as auth_views
urlpatterns = [
path('django-admin/', admin.site.urls)... | normal | {
"blob_id": "987d6c769a4f593405e889ed2b0e3f9955900406",
"index": 856,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif settings.DEBUG and 'debug_toolbar' in settings.INSTALLED_APPS:\n import debug_toolbar\n urlpatterns = [path('__debug__/', include(debug_toolbar.urls))\n ] + urlpatterns\n",... | [
0,
1,
2,
3,
4
] |
import cv2,os
import sqlite3
cam = cv2.VideoCapture(0)
detector = cv2.CascadeClassifier('Classifiers/face.xml')
i = 0
offset = 50
def create_or_open_db(db_file):
db_is_new = not os.path.exists(db_file)
conn = sqlite3.connect(db_file)
if db_is_new:
print 'Creating schema'
sql = '''create ta... | normal | {
"blob_id": "3beaea1f2b1b085a60bdc5e53f4e6d9aff7e8b6f",
"index": 5538,
"step-1": "import cv2,os\nimport sqlite3\ncam = cv2.VideoCapture(0)\ndetector = cv2.CascadeClassifier('Classifiers/face.xml')\ni = 0\noffset = 50\n\n\ndef create_or_open_db(db_file):\n db_is_new = not os.path.exists(db_file)\n conn = sq... | [
0
] |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
r_data_df = pd.read_csv('./Shootout Data/Shootout_Mac2017.csv')
em_data_df = pd.read_csv('./Shootout Data/Shootout_Emily.csv')
aishah_data_df = pd.read_csv('./Shootout Data/Shootout_Aishah_Mac2011.csv')
agni_data_df = pd.read_csv('./Shootout Data/S... | normal | {
"blob_id": "467b919f6953737eedd3f99596df244bd1177575",
"index": 5411,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.bar(pos, df['Mersenne Twister'], width, alpha=0.5, color='#EE3224')\nplt.bar([(p + width) for p in pos], df['Xorshift 128+'], width, alpha=0.5,\n color='#F78F1E')\nplt.bar([(p + wi... | [
0,
1,
2,
3,
4
] |
#https://www.youtube.com/watch?v=CQ5kc_j4RjA
import pandas as pd
#import quandl
import math, datetime
import time
import numpy as np
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import cross_validation, preprocessing, svm
from sklearn.metrics import accuracy_s... | normal | {
"blob_id": "9c4676edbeef3748a4947f827fefa29e95674bfa",
"index": 121,
"step-1": "<mask token>\n\n\ndef Actual_Value():\n global df\n print('The Actual Closing Value is Displayed below')\n df = data.DataReader(stockTicker, 'yahoo', '2017-01-28', '2017-02-5')\n ao = df['Close']\n print(str(ao))\n ... | [
5,
12,
13,
14,
15
] |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, dataset.shape[1]-1].values
#Fitting the Decision Tree Regression
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(r... | normal | {
"blob_id": "c8565e1b5659dd0908aabf91e07738a798dc3232",
"index": 1366,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nregressor.fit(X, y)\n<mask token>\nplt.scatter(X, y, color='red')\nplt.plot(X_grid, regressor.predict(X_grid), color='blue')\nplt.scatter(6.5, y_pred, color='green')\nplt.title('Salary vs... | [
0,
1,
2,
3,
4
] |
import sys
import bisect
t = int(raw_input())
for i in xrange(1, t+1):
n, k = map(int, raw_input().strip().split())
s = [n]
for j in xrange(k):
num = s.pop()
if num % 2 != 0:
ls = num/2
lr = num/2
if ls != 0:
bisect.insort_left(s,ls)
bisect.insort_left(s,lr)
else:
... | normal | {
"blob_id": "488c111c051796b481794678cb04108fcf11ac39",
"index": 5778,
"step-1": "import sys\nimport bisect\n\nt = int(raw_input())\n\nfor i in xrange(1, t+1):\n n, k = map(int, raw_input().strip().split())\n s = [n]\n for j in xrange(k):\n num = s.pop()\n if num % 2 != 0:\n ls = num/2\n lr = ... | [
0
] |
from knox.models import AuthToken
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from accounts.serializers import UserSerializer, RegisterSerializer, LoginSerializer, ChangePasswordSerializer
# Register API
class RegisterAPI(generics.CreateAPIView):
permiss... | normal | {
"blob_id": "5d6ec1b23dcbc935fe80dd09a2e967eb7e37a363",
"index": 5645,
"step-1": "<mask token>\n\n\nclass LoginAPI(generics.GenericAPIView):\n <mask token>\n <mask token>\n\n\nclass ChangePasswordAPI(generics.UpdateAPIView):\n permission_classes = [permissions.IsAuthenticated]\n serializer_class = Ch... | [
8,
9,
10,
14,
15
] |
# Generated by Django 3.2 on 2021-04-21 13:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rate', '0003_auto_20210421_1316'),
]
operations = [
migrations.AlterField(
model_name='song',
name='overall_rating',
... | normal | {
"blob_id": "d46cda5354640e1c87432d39a2e949d6db034edc",
"index": 6413,
"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 = [('rate', '000... | [
0,
1,
2,
3,
4
] |
import os
import time
#if __name__ == "__main__":
# os.system('xterm -e "pwd ; cd ~ ; torcs -r ~/quickrace.xml ; echo press RETURN to close this window ; read" &') # delete the echo and the read to don't stop the process and make it run quickly
# os.system('xterm -e "pwd ; ./start.sh ; echo press RETURN to close... | normal | {
"blob_id": "c2cf74893c7f7515a95141bb10be6a446b45a0cc",
"index": 1447,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef train_once():\n os.system('xterm -e \"pwd ; cd ~ ; torcs -r ~/quickrace.xml \" &')\n os.system('xterm -e \"pwd ; ./start.sh \" &')\n return True\n",
"step-3": "import... | [
0,
1,
2,
3
] |
def myswap(a, b):
temp = a
a = b
b = temp
if a < b:
print(a, b)
else:
print(b, a)
a, b = map(int, input().split())
myswap(a, b)
| normal | {
"blob_id": "e6efd2de5f92d66f1b734a2173fc8681af3c4cc8",
"index": 8040,
"step-1": "<mask token>\n",
"step-2": "def myswap(a, b):\n temp = a\n a = b\n b = temp\n if a < b:\n print(a, b)\n else:\n print(b, a)\n\n\n<mask token>\n",
"step-3": "def myswap(a, b):\n temp = a\n a = ... | [
0,
1,
2,
3
] |
"""
db.集合.update()
"""
"""
实例 被替换了
> db.test1000.update({'name':'dapeng'},{'name':'大鹏'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test1000.find()
{ "_id" : ObjectId("5c35549d7ad0cf935d3c150d"), "name" : "大鹏" }
{ "_id" : ObjectId("5c3554f37ad0cf935d3c150e"), "nInserted" : 1 }
{ "_id" : Obj... | normal | {
"blob_id": "7d8c2aa5674704d4443034c29bbdc715da9fd567",
"index": 5022,
"step-1": "<mask token>\n",
"step-2": "\"\"\"\ndb.集合.update()\n\n\"\"\"\n\"\"\"\n实例 被替换了\n> db.test1000.update({'name':'dapeng'},{'name':'大鹏'})\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n> db.test1000.find()\n... | [
0,
1
] |
from django.urls import reverse_lazy
from django.views.generic import CreateView, edit, ListView
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from users.forms import CustomUserCreationForm, LoginForm
from users.models import CustomUser as Users
class SignUpView(CreateView):
... | normal | {
"blob_id": "6bd9c8e38373e696193c146b88ebf6601170cf0e",
"index": 9549,
"step-1": "<mask token>\n\n\nclass IndexView(edit.FormView):\n success_url = '/facilities'\n form_class = LoginForm\n template_name = 'users/index.html'\n\n def form_valid(self, form):\n username = form.cleaned_data['userna... | [
3,
4,
5,
6
] |
from packet import Packet
from packetConstructor import PacketConstructor
import threading
import time
class PacketSender:
"""
Packet represents a simulated UDP packet.
"""
# The next seq num for sent packets
seq_num = 0
# The next seq num for acks that we're waiting for
next_seq_num = 0
... | normal | {
"blob_id": "47c1ad4bd1ceffa38eef467ea8eb59dbd2fc2ebb",
"index": 262,
"step-1": "<mask token>\n\n\nclass PacketSender:\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 awa... | [
3,
5,
9,
10,
11
] |
ghj=input("enter your first name:")
print("Welcome to my Quiz:\nIf you go wrong once you lose but if you give all the answers correct then you win but no CHEATING.")
print("Q1:-Who is the president of India?")
winlist=("ramnath govind","multiple choice question","multiple choice questions","mumbai")
enter=input("en... | normal | {
"blob_id": "351421ef6a40e3a4bd4549a1851fbf4bed9ddf30",
"index": 5024,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(\n \"\"\"Welcome to my Quiz:\nIf you go wrong once you lose but if you give all the answers correct then you win but no CHEATING.\"\"\"\n )\nprint('Q1:-Who is the president of... | [
0,
1,
2,
3
] |
import hashlib
from ast import literal_eval
# import requests
# from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import render, redirect, HttpResponse,get_object_or_404
from django.views.decorators.csrf import csrf_exempt
fro... | normal | {
"blob_id": "a84920821982f04b9835391eb267707971f8f7c1",
"index": 3929,
"step-1": "import hashlib\nfrom ast import literal_eval\n# import requests\n# from rest_framework import generics\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.shortcuts import render, re... | [
0
] |
import pathlib
import shutil
import os
import glob
import pandas as pd
import sqlalchemy as sqla
"""
SCRIPT TO FILL THE DATABASE FROM CSV ON MEGA IF LOSE DATA IN PARTICULAR DATE
"""
PATH = "/home/thomas/Documents/TER/AJOUTER_CSV_BDD/"
folder = "test/"
files_used = []
totalFiles = 0
contents = pathlib.Path(PATH+folder... | normal | {
"blob_id": "795936dad7a9e51edf0df66207a43ac4d97e9023",
"index": 3781,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor path in sorted(contents):\n files_used.append(path.name)\n totalFiles += 1\nprint(files_used)\nprint(totalFiles)\n<mask token>\nfor filename in files_used:\n df = pd.read_csv... | [
0,
1,
2,
3,
4
] |
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
headline = "Hello world from a variable!"
# headline de la izq es el nombre de la variable en la vista
# headline de la der es el nombre de la variable en el server
return render_template("index.html", headline... | normal | {
"blob_id": "83bbb6433d1577be869bf840bdd42aa86e415da6",
"index": 9328,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@app.route('/')\ndef index():\n headline = 'Hello world from a variable!'\n return render_template('index.html', headline=headline)\n\n\n@app.route('/bye/')\ndef bye():\n hea... | [
0,
2,
3,
4,
5
] |
import json
import sys
import os
# Change to Singularity working directory.
os.chdir('/mnt/cwd')
# Take subset index as argument
subset_index = sys.argv[1]
# Open up subset matching this.
with open('/mnt/scripts/outputs/instcat_list_subset'+str(subset_index)+'.json', 'r') as f:
instcat_list_subset = json.load(f)... | normal | {
"blob_id": "e2e5ca388d67f2a13eaef6067fc19e2dfe284a55",
"index": 4469,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nos.chdir('/mnt/cwd')\n<mask token>\nwith open('/mnt/scripts/outputs/instcat_list_subset' + str(subset_index) +\n '.json', 'r') as f:\n instcat_list_subset = json.load(f)\nsys.path.a... | [
0,
1,
2,
3,
4
] |
import os
import imageio
import h5py
import numpy as np
def create_segmentation_test_data(data_path, raw_key, label_key, shape, chunks):
with h5py.File(data_path, 'a') as f:
f.create_dataset(raw_key, data=np.random.rand(*shape), chunks=chunks)
f.create_dataset(label_key, data=np.random.randint(0, ... | normal | {
"blob_id": "e3417980599448f1293b56cb95312088e7a8abe3",
"index": 9713,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef create_segmentation_test_data(data_path, raw_key, label_key, shape, chunks\n ):\n with h5py.File(data_path, 'a') as f:\n f.create_dataset(raw_key, data=np.random.rand... | [
0,
1,
2,
3,
4
] |
# Reference: https://docs.python.org/2/library/unittest.html
import unittest
import sys
sys.path.append('..')
from database_utils import DatabaseUtils
class Test_DatabaseUtils(unittest.TestCase):
def setUp(self):
self.db=DatabaseUtils()
def dataCount(self):
with self.db.connection.cursor()... | normal | {
"blob_id": "ff8e8af72a8eb97a392fcfec5960eed7a2e51f68",
"index": 9211,
"step-1": "<mask token>\n\n\nclass Test_DatabaseUtils(unittest.TestCase):\n\n def setUp(self):\n self.db = DatabaseUtils()\n <mask token>\n\n def test_getUser(self):\n count = self.dataCount()\n try:\n ... | [
9,
10,
13,
17,
18
] |
from django.apps import AppConfig
class StonewallConfig(AppConfig):
name = 'stonewall'
| normal | {
"blob_id": "8364264851895ccabeb74fd3fab1d4f39da717f8",
"index": 8398,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass StonewallConfig(AppConfig):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass StonewallConfig(AppConfig):\n name = 'stonewall'\n",
"step-4": "from django.apps impo... | [
0,
1,
2,
3
] |
# Generated by Django 3.1.6 on 2021-07-17 10:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0032_product_sex'),
]
operations = [
migrations.AddField(
model_name='product',
name='price_ret_sale',
... | normal | {
"blob_id": "09660cfcff7d5da0339da201cb18b6f63bec2df9",
"index": 1394,
"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 = [('shop', '003... | [
0,
1,
2,
3,
4
] |
import json
import joblib
import numpy as np
import datetime
import sqlalchemy as sa
import cx_Oracle
import pandas as pd
from flask import Flask, render_template, session, request, redirect, url_for
app = Flask(__name__)
oracle_engine = sa.create_engine('oracle://ft:1234@localhost:1522/xe')
@app.route("/")
def inde... | normal | {
"blob_id": "74aa93bf3731d4e3ddb920bedc7daced50b4f2c3",
"index": 1565,
"step-1": "<mask token>\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/survey', methods=['POST', 'GET'])\ndef survey():\n if request.method == 'GET':\n return render_template('survey.h... | [
2,
4,
5,
6,
7
] |
# #1
# def bi_search(l, r, arr, x):
# # Code Here
# if(l == r):
# return arr[r] == x
# mid = (l + r)//2 + 1
# if(arr[mid] > x):
# return bi_search(l,mid-1,arr,x)
# else:
# return bi_search(mid,r,arr,x)
# inp = input('Enter Input : ').split('/')
# arr, k = list(map(int, ... | normal | {
"blob_id": "883b4de18dddede97f850e3a184a0e1072bda99e",
"index": 814,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef solve(dpArr, list, box, i):\n global boxes\n global ans\n if box == boxes:\n s = 0\n for j in list:\n s += len(j)\n if s == len(dpArr):\n ... | [
0,
1,
2,
3,
4
] |
'''
Aluno: Lucas Airam Castro de Souza
Resumo: Programa para calcular a raiz com a precisão n de casas decimais
def raiz(numero, casas_decimais=0):
if ((numero == 0) or (numero == 1)):
return "O resultado eh: " + str(numero)
elif (numero<0):
return "A raiz nao existe no conjunto rea... | normal | {
"blob_id": "5c174dd514d0a7d9aa932fcb436f22d9a44d2327",
"index": 1486,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef raiz(numero):\n casas_decimais = 18\n if numero == 0 or numero == 1:\n return 'O resultado eh: ' + str(numero)\n elif numero < 0:\n return 'A raiz nao exist... | [
0,
1,
2
] |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Especialidade(models.Model):
def __str__(self):
return self.nome
# add unique=True?
nome = models.CharField(max_length=200, verbose_name=_('Especialidade'), unique=True, blank=False, null=False)
| normal | {
"blob_id": "9cc672702d960088f0230cbd1694b295216d8b5a",
"index": 4617,
"step-1": "<mask token>\n\n\nclass Especialidade(models.Model):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Especialidade(models.Model):\n\n def __str__(self):\n return self.nome\n <mask token>\n"... | [
1,
2,
3,
4,
5
] |
import time
import threading
lock_a = threading.Lock()
lock_b = threading.Lock()
def task1():
print('Task 1 is starting...')
print('Task 1 is waiting to acquire Lock A')
with lock_a:
print('Task 1 has acquired Lock A')
print('Task 1 is doing some calculations')
time.sleep(2)
... | normal | {
"blob_id": "c7d8a67587a6ca01c23ed922faabbaca8bbaf337",
"index": 6307,
"step-1": "<mask token>\n\n\ndef task1():\n print('Task 1 is starting...')\n print('Task 1 is waiting to acquire Lock A')\n with lock_a:\n print('Task 1 has acquired Lock A')\n print('Task 1 is doing some calculations')... | [
2,
3,
4,
5
] |
# TUPLE IMUTAVEL
# GERALMENTE HETEORGENEA
# tupla com 1 ou 0 elementos
#
# empty = ()
# singleton = 'breno',
# print(type(empty))
# print(singleton)
# tuplas podem ser aninhadas
# t = 12345, 54321, 'hello!'
# u = t, (1, 2, 3, 4, 5)
#imutaveis
# t[0] = 88888 | normal | {
"blob_id": "34e902fbced13629657494eedfe385d3b5ae3f55",
"index": 2489,
"step-1": "# TUPLE IMUTAVEL\n# GERALMENTE HETEORGENEA\n\n# tupla com 1 ou 0 elementos\n#\n# empty = ()\n# singleton = 'breno',\n# print(type(empty))\n# print(singleton)\n\n# tuplas podem ser aninhadas\n# t = 12345, 54321, 'hello!'\n# u = t, (... | [
1
] |
# __author__: Stanley
# date: 2018/10/22
class Foo:
def __init__(self, name, age):
self.name = name
self.age = age
def __getitem__(self, item):
return item + 10
def __setitem__(self, key, value):
print(key, value)
def __delitem__(self, key):
print(key)
obj =... | normal | {
"blob_id": "d4b9403366a16dfbb12a2161a996e641b3a785a5",
"index": 8027,
"step-1": "class Foo:\n <mask token>\n <mask token>\n\n def __setitem__(self, key, value):\n print(key, value)\n <mask token>\n\n\n<mask token>\n",
"step-2": "class Foo:\n\n def __init__(self, name, age):\n self... | [
2,
4,
6,
7,
8
] |
times = np.linspace(0.0, 10.0, 100)
result = mesolve(H, psi0, times, [np.sqrt(0.05) * sigmax()], [sigmaz(), sigmay()])
fig, ax = plt.subplots()
ax.plot(times, result.expect[0]) # doctest: +SKIP
ax.plot(times, result.expect[1]) # doctest: +SKIP
ax.set_xlabel('Time') # doctest: +SKIP
ax.set_ylabel('Expectation values') #... | normal | {
"blob_id": "8474205d49aef2d18755fc1a25a82718962f4120",
"index": 6912,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nax.plot(times, result.expect[0])\nax.plot(times, result.expect[1])\nax.set_xlabel('Time')\nax.set_ylabel('Expectation values')\nax.legend(('Sigma-Z', 'Sigma-Y'))\nplt.show()\n",
"step-3... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
# Copyright (c) 2018, University of Stuttgart
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright
# notice and this permission notice appear in all copies.
#
# THE ... | normal | {
"blob_id": "0d6177660a9b9c22bcf6eb11763e7fe1ee03b46a",
"index": 3454,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nworkspace.obstacles.append(box)\nworkspace.obstacles.append(segment)\nworkspace.obstacles.append(circle)\n<mask token>\nviewer.draw_ws_img(signed_distance_field)\nviewer.draw_ws_obstacles... | [
0,
1,
2,
3,
4
] |
from dataclasses import dataclass, field
from typing import List
@dataclass
class Root:
a: List[object] = field(
default_factory=list,
metadata={
"type": "Element",
"namespace": "",
"min_occurs": 2,
"max_occurs": 4,
"sequence": 1,
... | normal | {
"blob_id": "7e318ae7317eac90d6ce9a6b1d0dcc8ff65abef0",
"index": 9430,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@dataclass\nclass Root:\n a: List[object] = field(default_factory=list, metadata={'type':\n 'Element', 'namespace': '', 'min_occurs': 2, 'max_occurs': 4,\n 'sequence'... | [
0,
1,
2,
3
] |
def coroutine(func):
def start_coroutine(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr) #cr.send(None)
return cr
return start_coroutine
@coroutine
def grep(pattern):
print('start grep')
try:
while True:
line = yield
if pattern in line:
print(line)
except GeneratorExit:
print('stop grep'... | normal | {
"blob_id": "bebe098c5abb579eb155a1dc325347d100ddfa8f",
"index": 1805,
"step-1": "def coroutine(func):\n\n def start_coroutine(*args, **kwargs):\n cr = func(*args, **kwargs)\n next(cr)\n return cr\n return start_coroutine\n\n\n<mask token>\n",
"step-2": "def coroutine(func):\n\n d... | [
1,
2,
3,
4,
6
] |
from datetime import datetime
from app import db
class Vocabulary(db.Model):
_id = db.Column(db.Integer, primary_key=True)
language = db.Column(db.String(64), index=True)
word = db.Column(db.String(64), index=True, unique=True)
date = db.Column(db.DateTime, index=True, default=datetime.utcnow)
| normal | {
"blob_id": "834469f9c6e065fb29dfe1fd3e421fbb752f5094",
"index": 7708,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Vocabulary(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Vocabulary(db.Model):\n _id = db.Column... | [
0,
1,
2,
3
] |
from pyramid.request import Request
from pyramid.response import Response
from pyramid.view import view_config
from svc1_first_auto_service.data.repository import Repository
@view_config(route_name='autos_api',
request_method='GET',
renderer='json')
def all_autos(_):
cars = Repository.a... | normal | {
"blob_id": "cb903f3f7fd3c4f3ba5f8ff2ce12aac9c680aa15",
"index": 6116,
"step-1": "<mask token>\n\n\n@view_config(route_name='auto_api', request_method='GET', renderer='json')\ndef single_auto(request: Request):\n car_id = request.matchdict.get('car_id')\n car = Repository.car_by_id(car_id)\n if not car:... | [
1,
2,
3,
4,
5
] |
"""
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
"""
# O(n) TC and SC
class Solution:
... | normal | {
"blob_id": "5cfd7744f98c80483cb4dd318c17a7cd83ed3ae3",
"index": 758,
"step-1": "<mask token>\n\n\nclass Solution:\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n res = []\n for num in nums:\n if nums[ab... | [
1,
2,
3,
4,
5
] |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | normal | {
"blob_id": "883d2efeb6d7d43cf82eef2e0397110fd8e3ea03",
"index": 4368,
"step-1": "<mask token>\n\n\ndef parse_args():\n \"\"\"\n parse args\n \"\"\"\n parser = argparse.ArgumentParser(description='ternarybert evaluation')\n parser.add_argument('--device_target', type=str, default='Ascend',\n ... | [
2,
3,
4,
5,
6
] |
import csv
import os
import requests
from bs4 import BeautifulSoup
# open html file and parsing lxml
with open ('/Users/neeraj.joshi/Downloads/index.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')
#row = soup.find_all('tr')
#column = row.find_all('td')
#print(soup)
# create a file by any name and in o... | normal | {
"blob_id": "47be41bd5838b828acdc90c3ef5abdeec9da1e85",
"index": 1579,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('/Users/neeraj.joshi/Downloads/index.html') as html_file:\n soup = BeautifulSoup(html_file, 'lxml')\n<mask token>\nfor tree in soup.find_all('tr'):\n data = []\n for to... | [
0,
1,
2,
3,
4
] |
import pandas as pd
import sweetviz as sv
b = pd.read_csv("final_cricket_players.csv", low_memory=False)
b = b.replace(to_replace="-",value="")
b = b.replace(to_replace="[]",value="")
b = b.replace(to_replace="{}",value="")
b.drop(b.columns[b.columns.str.contains('unnamed',case = False)],axis = 1, inplace = Tru... | normal | {
"blob_id": "f93b7f2939bbee9b0cb5402d3e5f5d6c482d37c4",
"index": 6983,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nb.drop(b.columns[b.columns.str.contains('unnamed', case=False)], axis=1,\n inplace=True)\nb.to_csv('Cleaned_dataset.csv', index=False)\n<mask token>\nreport.show_html()\n",
"step-3":... | [
0,
1,
2,
3,
4
] |
import logging
from datetime import datetime
import boto3
from pytz import timezone
from mliyweb.api.v1.api_session_limiter import session_is_okay
from mliyweb.api.v1.json_view import JsonView
from mliyweb.dns import deleteDnsEntry
from mliyweb.models import Cluster
from mliyweb.resources.clusters import ClusterServi... | normal | {
"blob_id": "f882b73645c6a280a17f40b27c01ecad7e4d85ae",
"index": 5860,
"step-1": "<mask token>\n\n\nclass UserClusters(JsonView):\n logger = logging.getLogger('mliyweb.views.UserClusters')\n cluster_service = ClusterService()\n\n @log_enter_exit(logger)\n def get_data(self, context):\n usernam... | [
9,
11,
12,
13,
15
] |
# This script allows you to copy all files with a certain extention to a new folder without integrating the sub folders
# Created by Maurice de Kleijn Vrije Universiteit Amsterdam Spatial Information laboratory for the datamanagement of the the archaological project Barin Hoyuk
# 22062016 Python 2.7
import shutil
impo... | normal | {
"blob_id": "778cf8064fa45e3e25a66f2165dcf6885c72fb8a",
"index": 634,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nos.system('dir ' + org_GIS + '*' + ext + ' /s/d/b >' + org_GIS + 'tempext.txt')\n<mask token>\nfor line in lines:\n ln = line.rstrip('\\n')\n shutil.copy(ln, outputfolder)\nfile1.clo... | [
0,
1,
2,
3,
4
] |
# Differences between Python 2 and Python 3
print "hello world"
# become
print("hello world") # in Pyton 3
raw_input('What is your name?')
# become
input('What is your name?') # in Python 3
# the language of Python
# Reserved words
and
as
assert
break
class
continue
def
del
elif
else
except
finally
for
from
g... | normal | {
"blob_id": "40471bfcf05ef45fbb070bbb5bfd4c425fe59b1c",
"index": 7523,
"step-1": "# Differences between Python 2 and Python 3\n\nprint \"hello world\" \n # become \nprint(\"hello world\") # in Pyton 3\n\nraw_input('What is your name?') \n# become\ninput('What is your name?') # in Python 3\n\n\n# the language of... | [
0
] |
from fastapi import FastAPI
from app.router.routes import initRoutes
from app.cors.cors import initCors
app = FastAPI(debug=True,title="Recipe API")
initCors(app)
initRoutes(app)
| normal | {
"blob_id": "1857d76b8c68c58d2d721de529811a6aeb09fcbb",
"index": 5407,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ninitCors(app)\ninitRoutes(app)\n",
"step-3": "<mask token>\napp = FastAPI(debug=True, title='Recipe API')\ninitCors(app)\ninitRoutes(app)\n",
"step-4": "from fastapi import FastAPI\nf... | [
0,
1,
2,
3,
4
] |
string=input();
string=string.replace("(","");
string=string.replace(")","");
string=list(map(int,string.split(",")));
if(1 in string):
string.remove(1);
mid=[string[0]];
string.remove(string[0]);
result=0;
tar=0;
while(string!=[]):
tar=0;
length=len(string);
i=0
while(i<len(string)):
cout=0... | normal | {
"blob_id": "6a8cab1fceffa0d70441cc600137417a8b81d7b1",
"index": 6897,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif 1 in string:\n string.remove(1)\n<mask token>\nstring.remove(string[0])\n<mask token>\nwhile string != []:\n tar = 0\n length = len(string)\n i = 0\n while i < len(strin... | [
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
import unittest
from pycmbs import data4D
class TestPycmbsData4D(unittest.TestCase):
def setUp(self):
pass
def test_DummyTest(self):
pass
i... | normal | {
"blob_id": "87562ce2a957de3fa2eb84cbb0de18c6ce264c6b",
"index": 7676,
"step-1": "<mask token>\n\n\nclass TestPycmbsData4D(unittest.TestCase):\n\n def setUp(self):\n pass\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass TestPycmbsData4D(unittest.TestCase):\n\n def setUp(s... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/env python
from collections import defaultdict
from cluster.common import Cluster
from cluster.tools import print_table
def check_status(args):
""" Print node details
:param args: Arguments from argparse
:type args: argparse.Namespace
"""
cluster = Cluster(jobs_qstat=True, nodes=True,... | normal | {
"blob_id": "381b59ab9fa85561932a9bfb9ab8cef635901a35",
"index": 7249,
"step-1": "<mask token>\n\n\ndef main():\n \"\"\" Execute main program\n \"\"\"\n import argparse\n parser = argparse.ArgumentParser(description='Check nodes status.')\n parser.add_argument('-o', '--show-job-owners', action='st... | [
1,
2,
3,
4,
5
] |
import json
import sys
with open(sys.argv[1], 'r') as f:
x = json.load(f)
with open('my_wire_to_quartus_wire.json', 'r') as f:
wirenamemap = json.load(f)
print("----- There are {} muxes in the database".format(len(x)))
print("----- There are {} routing pairs in the database".format(sum((len(v) for k, v in x.i... | normal | {
"blob_id": "95163a28a35cc88240d9d6edc2e9b416e5493909",
"index": 6021,
"step-1": "<mask token>\n\n\ndef bits2str(bits):\n ret = ''\n for row in bits:\n rowstr = ''\n for bit in row:\n rowstr += '1' if bit else '0'\n ret += rowstr + '\\n'\n return ret\n\n\ndef parse_xyi(in... | [
6,
7,
9,
10,
11
] |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
self.mem = dict()
if root is None:
... | normal | {
"blob_id": "9e98a361ef20049cba488b86ad06eb92b3d29d11",
"index": 3584,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n <mask token>\n",
"step-3": "class Solution:\n\n def isBalanced(self, root: TreeNode) ->bool:\n self.mem = dict()\n if root is None:\n ... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
# @Project :experiment9
# @File :text1
# @Date :2020/10/28 09:13
# @Author :施嘉伟
# @Email :1138128021@qq.com
# @Software :PyCharm
-------------------------------------------------
"""
import urllib.request
# 发出请求,得到响应
response=ur... | normal | {
"blob_id": "b186ae7a48afbb70edf3be0d9697deed4f31e542",
"index": 2258,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(response.geturl())\n<mask token>\nwith open('bgdGW.html', 'w', encoding='utf-8') as fp:\n fp.write(html)\nprint(response.geturl())\n",
"step-3": "<mask token>\nresponse = urlli... | [
0,
1,
2,
3,
4
] |
def filter_long_words(word_lng, words_list):
return [word for word in words_list if len(word) > word_lng]
assert filter_long_words(5, ['piwo', 'wino', 'czasopisma', 'ubrania', 'napoje']
) == ['czasopisma', 'ubrania', 'napoje']
| normal | {
"blob_id": "e221b840239b6e9af735238760fd1157f333c1a4",
"index": 9014,
"step-1": "<mask token>\n",
"step-2": "def filter_long_words(word_lng, words_list):\n return [word for word in words_list if len(word) > word_lng]\n\n\n<mask token>\n",
"step-3": "def filter_long_words(word_lng, words_list):\n retur... | [
0,
1,
2
] |
# *Using Min & Max Exercise
def extremes(nums):
return (max(nums), min(nums))
| normal | {
"blob_id": "0577c274672bac333500535f21f568ade62100c7",
"index": 3580,
"step-1": "<mask token>\n",
"step-2": "def extremes(nums):\n return max(nums), min(nums)\n",
"step-3": "\n# *Using Min & Max Exercise\ndef extremes(nums):\n return (max(nums), min(nums))\n",
"step-4": null,
"step-5": null,
"st... | [
0,
1,
2
] |
# Generated by Django 2.2.2 on 2021-01-23 04:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('task', '0022_taskrecycle_create_date'),
]
operations = [
migrations.RemoveField(
model_name='ansibleextravars',
name='playbo... | normal | {
"blob_id": "d5beff74e3746c77cbaf6b8233b822ed1a86701e",
"index": 316,
"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 = [('task', '0022... | [
0,
1,
2,
3,
4
] |
import urlparse
import twitter
import oauth2 as oauth
import re
import urllib
url_checker = dict()
def twitter_auth():
consumer_key = 'IqsuEo5xfTdWwjD1GZNSA'
consumer_secret = 'dtYmqEekw53kia3MJhvDagdByWGxuTiqJfcdGkXw8A'
request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_... | normal | {
"blob_id": "afa20d7e9c7843a03090c00cc888d44a77fc29f3",
"index": 9205,
"step-1": "<mask token>\n\n\ndef twitter_auth():\n consumer_key = 'IqsuEo5xfTdWwjD1GZNSA'\n consumer_secret = 'dtYmqEekw53kia3MJhvDagdByWGxuTiqJfcdGkXw8A'\n request_token_url = 'https://api.twitter.com/oauth/request_token'\n acces... | [
4,
6,
8,
10,
11
] |
import simple_map
import pickle
import os
import argparse
import cv2
argparser = argparse.ArgumentParser()
argparser.add_argument("--src", type=str, required=True,
help="source directory")
argparser.add_argument("--dst", type=str, required=True,
help="destination directory")
ar... | normal | {
"blob_id": "a8c59f97501b3f9db30c98e334dbfcffffe7accd",
"index": 6557,
"step-1": "<mask token>\n\n\ndef get_reference():\n json = sorted([os.path.join(args.ref, file) for file in os.listdir(args\n .ref) if file.endswith('.json')])[0]\n smap = simple_map.SimpleMap(json)\n return smap.northing, sma... | [
2,
3,
5,
6,
7
] |
"""
定义函数,根据年、月、日计算星期。
0 星期一
1 星期二
....
"""
import time
def get_week(year, month, day):
str_time = "%d-%d-%d" % (year, month, day)
time_tuple = time.strptime(str_time, "%Y-%m-%d")
tuple_week = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日")
return tuple_week[time_tuple[6]]
... | normal | {
"blob_id": "012d9b5aa13c557ad958343cadf935b73c808a56",
"index": 4535,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_week(year, month, day):\n str_time = '%d-%d-%d' % (year, month, day)\n time_tuple = time.strptime(str_time, '%Y-%m-%d')\n tuple_week = '星期一', '星期二', '星期三', '星期四', '星期... | [
0,
1,
2,
3,
4
] |
class String:
def reverse(self, s):
return s[::-1]
s = input()
obj1 = String()
print(obj1.reverse(s))
| normal | {
"blob_id": "c27c29a5b4be9f710e4036f7f73a89c7d20acea5",
"index": 4317,
"step-1": "class String:\n <mask token>\n\n\n<mask token>\n",
"step-2": "class String:\n\n def reverse(self, s):\n return s[::-1]\n\n\n<mask token>\n",
"step-3": "class String:\n\n def reverse(self, s):\n return s[:... | [
1,
2,
3,
4
] |
# coding: utf-8
from __future__ import division, unicode_literals
import unittest
from monty.inspect import *
class LittleCatA(object):
pass
class LittleCatB(LittleCatA):
pass
class LittleCatC(object):
pass
class LittleCatD(LittleCatB):
pass
class InspectTest(unittest.TestCase):
def test_fu... | normal | {
"blob_id": "89605ff723d2f78e85cae458d576494718b5d456",
"index": 1193,
"step-1": "<mask token>\n\n\nclass InspectTest(unittest.TestCase):\n\n def test_func(self):\n self.assertTrue(find_top_pyfile())\n self.assertTrue(caller_name())\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask toke... | [
2,
5,
6,
9,
10
] |
'''
Author: Allen Chen
This is an example of entry point to CORE. Pay close attention to the import syntax - they're relative to this repo.
Don't try to run this by doing 'python3 main.py' under this directory. Try to add your Target in Makefile under the root dir,
and call './run YOUR_TARGET_NAME' from root.
'''
fr... | normal | {
"blob_id": "18eed41cbc419ecbb215f77235be99f15f86ea9a",
"index": 7468,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nlog_info(f'Just initialized a bot named {bot.name}')\nlog_ok(f'Bot is given cash: {bot.cash}')\nlog_error('Nothing else to do ! :(')\n",
"step-3": "<mask token>\nbot = TradeBot()\nlog_i... | [
0,
1,
2,
3,
4
] |
# Copyright (c) 2023 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... | normal | {
"blob_id": "cd1ada2d7979fffc17f707ed113efde7aa134954",
"index": 3036,
"step-1": "<mask token>\n\n\n@api(canonical_alias='nncf.torch.create_compressed_model')\n@tracked_function(NNCF_PT_CATEGORY, [CompressionStartedFromConfig(argname=\n 'config')])\ndef create_compressed_model(model: Module, config: NNCFConfi... | [
2,
3,
5,
6,
7
] |
from utilities.MatplotlibUtility import *
from utilities.PlotDefinitions.DrainSweep.OutputCurve import plot as importedOutputCurvePlot
plotDescription = {
'name':'Chip Output Curves',
'plotCategory': 'chip',
'priority': 40,
'dataFileDependencies': ['DrainSweep.json'],
'plotDefaults': {
'figsize':(2,2.5),
'co... | normal | {
"blob_id": "49ae9e90402d784fc3af3b47e96842fbfe842104",
"index": 9480,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef plot(identifiers, chipIndexes, firstRunChipHistory,\n recentRunChipHistory, specificRunChipHistory, groupedChipHistory,\n mode_parameters=None):\n if mode_parameters is N... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
import socket
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
from matplotlib import style
import pickle
# Create figure for plotting
time_list = []
gain_list = []
HOST = '127.0.0.1' # Standard loopba... | normal | {
"blob_id": "a4d5064decdc9963dae1712c7c6918b3e5902bf2",
"index": 9825,
"step-1": "<mask token>\n\n\ndef recieve_data():\n while True:\n data = conn.recv(1024)\n if not data:\n break\n conn.sendall(data)\n msg = pickle.loads(data)\n time = float(msg[0])\n ga... | [
2,
3,
4,
5,
6
] |
from field import print_field
from math_utilite import sign, col
def start_parameter_2(par):
global cell_king, castling_control, trans, take_on_aisle
cell_king = par[0]
castling_control = par[1]
trans = par[2]
take_on_aisle = par[3]
def det_cell_king(field):
global cell_king
cell_king... | normal | {
"blob_id": "90c9456bf22745d99fa76dbc752beae1a3835682",
"index": 7672,
"step-1": "<mask token>\n\n\ndef det_cell_king(field):\n global cell_king\n cell_king = {sign(fig): (x, y) for x, row in enumerate(field) for y,\n fig in enumerate(row) if abs(fig) == 6}\n return cell_king\n\n\n<mask token>\n\... | [
4,
8,
9,
10,
11
] |
import pandas as pd
import os
import openpyxl
from collections import defaultdict,deque
# 調節用パラメータ
filename = 'kaito7.xlsx' # 入力ファイル名
Output = 'output7.xlsx' # 出力ディレクトリ
wb = openpyxl.load_workbook(filename)
sheets = wb.sheetnames
days = []
names = []
dict = defaultdict(dict)
for sheet in sheets:
sh = wb[sheet]
... | normal | {
"blob_id": "37d5696c402737bfafe21b20b90a49e2753fdc4f",
"index": 7287,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor sheet in sheets:\n sh = wb[sheet]\n i = 3\n while True:\n tmp = sh.cell(row=1, column=i).value\n if tmp:\n days.append(tmp)\n else:\n ... | [
0,
2,
3,
4,
5
] |
"""
Iterations over :term:`hosts<host>`, :term:`roles<role>`,
:term:`components<component>` and config files.
"""
from contextlib import contextmanager
from fabric.api import env, settings, abort
from os.path import join
from pkg_resources import iter_entry_points
from warnings import warn
from fabric.network import s... | normal | {
"blob_id": "cc019c732003ed72db80a7893096a0bef0f12e47",
"index": 4168,
"step-1": "<mask token>\n\n\ndef _get_environmentdef():\n \"\"\"\n Retreive the EnvironmentDefinition from the fabric env.\n \"\"\"\n if 'environmentdef' not in env:\n abort('Environment needs to be configured')\n enviro... | [
5,
6,
7,
8,
9
] |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import re
def main():
s = input().strip()
s = s.replace('BC', 'X')
ans = 0
for ax in re.split(r'[BC]+', s):
inds = []
for i in range(len(ax)):
if ax[i] == 'A':
inds.append(i)
ans += sum([len(ax) - 1 - ind for ind in inds]) - sum(range(len(ind... | normal | {
"blob_id": "4100415b0df52e8e14b00dd66c7c53cd46c0ea6e",
"index": 2378,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n s = input().strip()\n s = s.replace('BC', 'X')\n ans = 0\n for ax in re.split('[BC]+', s):\n inds = []\n for i in range(len(ax)):\n ... | [
0,
1,
2,
3,
4
] |
INITIAL_B = 0.15062677711161448
B_FACTOR = 5.0
INITIAL_GE = 0.22581915788215678
GE_BOUNDS = [1.0 / 10.0, 1.0 / 4.0]
FIXED_P = 0.9401234488501574
INITIAL_GU = 0.2145066414796447
GU_BOUNDS = [1.0 / 15.0, 1.0 / 2.0]
INITIAL_GI = 0.19235137989123863
GI_BOUNDS = [1.0 / 15.0, 1.0 / 5.0]
INITIAL_GH = 0.044937075878220795... | normal | {
"blob_id": "47cf3045f2fa0f69759e09b1599e4afe953c06d8",
"index": 5138,
"step-1": "<mask token>\n",
"step-2": "INITIAL_B = 0.15062677711161448\nB_FACTOR = 5.0\nINITIAL_GE = 0.22581915788215678\nGE_BOUNDS = [1.0 / 10.0, 1.0 / 4.0]\nFIXED_P = 0.9401234488501574\nINITIAL_GU = 0.2145066414796447\nGU_BOUNDS = [1.0 /... | [
0,
1,
2
] |
# -*- coding: utf-8 -*- #
import time
from openerp.osv import osv, fields
import logging
import openerp.addons.decimal_precision as dp
logger = logging.getLogger(__name__)
class ebiz_supplier_account_create(osv.osv_memory):
_name = 'ebiz.supplier.account.create.wizard'
_description = "Ebiz Supplier Account"
... | normal | {
"blob_id": "309f8016dfebcc3595291b127edb4634f72298ec",
"index": 4387,
"step-1": "<mask token>\n\n\nclass ebiz_supplier_account_create(osv.osv_memory):\n <mask token>\n <mask token>\n\n def create_supplier_action(self, cr, uid, ids, context=None):\n active_ids = context.get('active_ids', False)\n... | [
2,
4,
5,
6,
7
] |
#!/usr/bin/env python
import fileinput
#open the file with the matched DNA short reads
#create a file with the modified version
f1 = open('CompleteDNAsequence.txt', 'r')
f2 = open('CompleteDNAsequence.txt.tmp', 'w')
for line in f1:
f2.write(line.replace('_', '\n')) #replaces _ with tab
f1.close()
f2.close()
#ope... | normal | {
"blob_id": "d02ef5fc27cde353e90dda4090905b89b5be5c49",
"index": 2897,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor line in f1:\n f2.write(line.replace('_', '\\n'))\nf1.close()\nf2.close()\n<mask token>\nopen('ANSWER.txt', 'w').writelines(lines[:+1])\n",
"step-3": "<mask token>\nf1 = open('Com... | [
0,
1,
2,
3,
4
] |
import os
from flask import Flask, jsonify, request, abort, make_response
from flask_sqlalchemy import SQLAlchemy
from .models import User
from .config import app_config
app = Flask(__name__)
app.config.from_object(app_config[os.getenv('FLASK_ENV', 'production')])
db = SQLAlchemy(app)
@app.route('/api/v1/users/<int:u... | normal | {
"blob_id": "f4519fa82ffc6bf945c7bb36d3761a708a06f641",
"index": 5933,
"step-1": "<mask token>\n\n\n@app.route('/api/v1/users/<int:user_id>', methods=['GET'])\ndef get_user(user_id):\n try:\n user = User.query.filter_by(id=user_id).first()\n return jsonify({'user': user.serialize})\n except:\... | [
4,
6,
7,
8
] |
import os
from django.conf import settings
from chamber.importers import BulkCSVImporter, CSVImporter
from .models import CSVRecord
class BulkCSVRecordImporter(BulkCSVImporter):
model_class = CSVRecord
fields = ('id', 'name', 'number')
csv_path = os.path.join(settings.PROJECT_DIR, 'data', 'all_fields_f... | normal | {
"blob_id": "559bd0c1821f405d21cdacba55f129ee5220bb5d",
"index": 3751,
"step-1": "<mask token>\n\n\nclass CSVRecordImporter(CSVImporter):\n model_class = CSVRecord\n fields = 'id', 'name', 'number'\n csv_path = os.path.join(settings.PROJECT_DIR, 'data',\n 'all_fields_filled.csv')\n\n def clean... | [
3,
4,
6,
7,
8
] |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: NVLGPSStatus.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _... | normal | {
"blob_id": "98d2196439a8dc3d511d176e61897aa67663a0b5",
"index": 4922,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n_sym_db.RegisterFileDescriptor(DESCRIPTOR)\n<mask token>\n_sym_db.RegisterMessage(NVLGPSStatus)\n",
"step-3": "<mask token>\n_b = sys.version_info[0] < 3 and (lambda x: x) or (lambda x:... | [
0,
1,
2,
3,
4
] |
# from django.urls import path,include
from django.conf.urls import include, url
from . import views
urlpatterns = [
url('buy',views.BuyPage,name='BuyPage'),
url('sell',views.SellPage,name='SellPage'),
url('',views.TradePage,name='TradePage'),
]
| normal | {
"blob_id": "5bbaffb35a89558b5cf0b4364f78d68ff2d69a01",
"index": 5726,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('buy', views.BuyPage, name='BuyPage'), url('sell', views\n .SellPage, name='SellPage'), url('', views.TradePage, name='TradePage')]\n",
"step-3": "from django.conf... | [
0,
1,
2,
3
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.