code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
import csv
import io
import pickle
import os
import pip
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
import cv2
import numpy as np
SCOPES = ['https:/... | normal | {
"blob_id": "f32b9dc36b2452fea8c8f284fbf800f22608c3ae",
"index": 8541,
"step-1": "<mask token>\n\n\ndef install(package):\n if hasattr(pip, 'main'):\n pip.main(['install', package])\n else:\n pip._internal.main(['install', package])\n\n\n<mask token>\n\n\ndef get_gdrive_service():\n creds ... | [
9,
11,
12,
13,
19
] |
# phase 3 control unit
#Dennis John Salewi,Olaniyi Omiwale, Nobert Kimario
from MIPSPhase1 import BoolArray
class RegisterFile:
def __init__(self):
# The register file is a list of 32 32-bit registers (BoolArray)
# register 29 is initialized to "000003E0" the rest to "00000000"
# an instanc... | normal | {
"blob_id": "1913bbffd8c3c9864a8eeba36c6f06e30d2dd2c8",
"index": 4740,
"step-1": "<mask token>\n\n\nclass RegisterFile:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Memory:\n\n def __init__(self):\n self.dicti = {}\n for i in range(0, 1021)... | [
7,
10,
11,
13,
15
] |
import binascii
import collections
import enum
Balance = collections.namedtuple("Balance", ["total", "available", "reward"])
Balance.__doc__ = "Represents a balance of asset, including total, principal and reward"
Balance.total.__doc__ = "The total balance"
Balance.available.__doc__ = "The principal, i.e. the total m... | normal | {
"blob_id": "5762271de166994b2f56e8e09c3f7ca5245b7ce0",
"index": 6249,
"step-1": "<mask token>\n\n\nclass AssetID(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '{:s}:{:s}'.format(self.asset_name, self.policy_id)\n\n ... | [
4,
5,
7,
8,
10
] |
from __future__ import print_function, absolute_import, division
import os
import h5py
import glob
import copy
import numpy as np
from tqdm import tqdm
# from utils.pose import draw_skeleton
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import poseutils.camera_utils as cameras
from pose... | normal | {
"blob_id": "cf6dffb28e37003212d3e3402dee58a57a7d9869",
"index": 5192,
"step-1": "<mask token>\n\n\nclass TDPWDataset(object):\n\n def __init__(self, path, center_2d=False, load_metrics=None, skel_norm=\n False):\n super(TDPWDataset, self).__init__()\n self.cameras = None\n self._d... | [
5,
8,
10,
11,
15
] |
# -*- coding: utf-8 -*-
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
import urllib
from django.http import HttpResponse, Http404
from django.utils.dateparse import parse_datetime
from urllib.parse import urlencode
from matplotlib import pyplot
from decimal import Decimal
fr... | normal | {
"blob_id": "1a46752a2d1c72ec6084e7af3694a3969e2d1b4c",
"index": 1772,
"step-1": "<mask token>\n\n\ndef estacionamiento_reserva(request, _id):\n _id = int(_id)\n try:\n estacionamiento = Estacionamiento.objects.get(id=_id)\n except ObjectDoesNotExist:\n raise Http404\n if estacionamient... | [
5,
7,
9,
10,
11
] |
class CUtil:
# Returns a dictionary containing the cell UID as they key and the data for the cell as the value
# Ex: 'AA': 2, 'AB': 4 ....
@staticmethod
def generate_board(initial_board, grid_size):
board_dictionary = dict()
iterator = 0
board_identifiers = CUtil.__generate_boar... | normal | {
"blob_id": "929e6deeb017fd338c63439f689d05331b016d0f",
"index": 1951,
"step-1": "class CUtil:\n\n @staticmethod\n def generate_board(initial_board, grid_size):\n board_dictionary = dict()\n iterator = 0\n board_identifiers = CUtil.__generate_board_identifiers(grid_size)\n for r... | [
6,
7,
8,
10,
11
] |
from Smooth import smoothing
def n_grams(unigramsFile, bigramsFile, parameterization, sentences):
words = []
param = []
unigrams = []
bigrams = []
with open(parameterization) as p: #Parametrization file
data = p.read().split()
word = data[0]
param.append(data[1])
pa... | normal | {
"blob_id": "87c200796e1fac508a43e899c0ed53878b8c1d88",
"index": 5244,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef n_grams(unigramsFile, bigramsFile, parameterization, sentences):\n words = []\n param = []\n unigrams = []\n bigrams = []\n with open(parameterization) as p:\n ... | [
0,
1,
2,
3
] |
from .ast import *
# noinspection PyPep8Naming
def addToClass(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def print_intended(to_print, intend):
print(intend * "| " + to_print)
# noinspection PyPep8Naming,PyUnresolvedReferences
class TreeP... | normal | {
"blob_id": "1084478226777b9259274e053984ac34d461198d",
"index": 42,
"step-1": "<mask token>\n\n\nclass TreePrinter:\n\n @addToClass(Node)\n def printTree(self, indent=0):\n raise Exception('printTree not defined in class ' + self.__class__.\n __name__)\n\n @addToClass(Instruction)\n ... | [
18,
21,
22,
24,
26
] |
#!/usr/bin/env python2
from Crypto.PublicKey import RSA
from Crypto.Util.number import *
from timeit import default_timer as timer
import os
import gmpy2
import itertools as it
def extract2(inp):
two = 0
while inp % 2 == 0:
inp //= 2
two += 1
return inp, two
def genkey():
while 1:
... | normal | {
"blob_id": "b29f85ccf396640c2a63bf634b549a3eaa0dbb1b",
"index": 1830,
"step-1": "<mask token>\n\n\ndef extract2(inp):\n two = 0\n while inp % 2 == 0:\n inp //= 2\n two += 1\n return inp, two\n\n\n<mask token>\n\n\ndef solve():\n x = RSA.importKey(open('pub.pem', 'rb').read())\n d0 =... | [
2,
3,
4,
5,
6
] |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Module test_measured_model - Contains the unit tests for the classes
in the datamodels.miri_measured_model module.
:History:
15 Jan 2013: Created.
21 Jan 2013: Warning messages controlled with Python warnings module.
05 Feb 2013: File closing problem solved by using ... | normal | {
"blob_id": "644b4a2f0e8ce95e669c9c01df111c943e0c4af2",
"index": 3417,
"step-1": "<mask token>\n\n\nclass TestMiriMeasuredModel(unittest.TestCase):\n <mask token>\n <mask token>\n\n def test_creation(self):\n dq_def_names = list(MiriMeasuredModel.dq_def_names)\n schema_names = list(self.da... | [
19,
23,
27,
28,
31
] |
from torchsummary import summary
import torch
import torch.nn as nn
import torch.nn.functional as F
from eva4modeltrainer import ModelTrainer
class Net(nn.Module):
"""
Base network that defines helper functions, summary and mapping to device
"""
def conv2d(self, in_channels, out_channels, ker... | normal | {
"blob_id": "f925b3b2f55c3f8daf57438d8d20b60446ae39af",
"index": 6111,
"step-1": "<mask token>\n\n\nclass Net(nn.Module):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def create_depthwise_conv2d(self, in_channels, out_channels,\n kernel_size=(3, 3), dila... | [
6,
7,
11,
14,
17
] |
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
class Instruction(QWidget):
def __init__(self):
super().__init__()
# Set UI file
uic.loadUi('../ui/instruction.ui', self)
# Connect handlers of buttons... | normal | {
"blob_id": "da30cea4cfb1ffccabe708fe15e5a633b06d299f",
"index": 2265,
"step-1": "<mask token>\n\n\nclass Instruction(QWidget):\n <mask token>\n\n def set_background_instruction(self):\n img = QPixmap('../images/background_instruction.jpg')\n self.background_instruction.setPixmap(img)\n <m... | [
2,
3,
4,
5,
6
] |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/about.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtG... | normal | {
"blob_id": "25b3defc8410c72c7c6f25288af91bd0c826f2ed",
"index": 6051,
"step-1": "<mask token>\n\n\nclass Ui_aboutDialog(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Ui_aboutDialog(object):\n\n def setupUi(self, aboutDialog):\n aboutDialog.setObjectName('aboutDi... | [
1,
2,
3,
4,
5
] |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth.models import User, Group
class UserTests(APITestCase):
def test_user_list(self):
# must be rejected without validation
response = self.client.get('/api/us... | normal | {
"blob_id": "ca7b0553e55e1c5e6cd23139a158101e72456a50",
"index": 8844,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass UserTests(APITestCase):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass UserTests(APITestCase):\n\n def test_user_list(self):\n response = self.client.get('... | [
0,
1,
2,
3,
4
] |
from google.cloud import pubsub_v1
import os
from flask import Flask, request, jsonify
from google.cloud import pubsub_v1
import os
from gcloud import storage
import json
import datetime
import time
app = Flask(__name__)
os.environ[
"GOOGLE_APPLICATION_CREDENTIALS"] = "/home/vishvesh/Documents/Dal/serverless/api-... | normal | {
"blob_id": "a76a0631c97ba539019790e35136f6fd7573e461",
"index": 5469,
"step-1": "<mask token>\n\n\n@app.route('/publish', methods=['GET', 'POST'])\ndef publish():\n topic_user = request.args.get('touser')\n sub_user = request.args.get('fromuser')\n subscription_id = sub_user\n msg = request.args.get... | [
2,
3,
4,
5,
6
] |
#Copyright (c) 2020 Ocado. All Rights Reserved.
import vptree, itertools
import numpy as np
class _ExtendedVPTree(vptree.VPTree):
"""
VPTree class extended to include the list of points within the tree
"""
def __init__(self, points, dist_fn):
"""
:param points: List of points to add t... | normal | {
"blob_id": "22e6616fb98ecfb256587c3767c7c289decc6bf6",
"index": 3049,
"step-1": "<mask token>\n\n\nclass DynamicVPTree:\n <mask token>\n\n def __init__(self, dist_fn, min_tree_size=4):\n \"\"\"\n :param dist_fn: Metric distance function used for vp-trees\n :param min_tree_size: Minimu... | [
4,
6,
9,
11,
12
] |
# filename: cycle_break.py
# for i in range(1, 101):
# if i % 3 == 0 and i % 8 == 0:
# print(i)
# break
num = 1
while num <= 100:
if num % 4 == 0 and num % 6 == 0:
print(num)
break
num += 1 | normal | {
"blob_id": "d04506e67071abf36d43a828d90fbe0f14230103",
"index": 3208,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile num <= 100:\n if num % 4 == 0 and num % 6 == 0:\n print(num)\n break\n num += 1\n",
"step-3": "num = 1\nwhile num <= 100:\n if num % 4 == 0 and num % 6 == 0... | [
0,
1,
2,
3
] |
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import backref
db = SQLAlchemy()
def connect_db(app):
"""Connect to database."""
db.app = app
db.init_app(app)
"""Models for Blogly."""
class User(db.Model):
__tablename__= "users"
id = db.Column(db.Integer, primary_key=True, autoincre... | normal | {
"blob_id": "9ae92d6ee4b82f7ed335c47d53567b817140a51c",
"index": 8922,
"step-1": "<mask token>\n\n\nclass User(db.Model):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n first_name = db.Column(db.String(50), nullable=False)\n last_name = db.Column(db.Str... | [
4,
5,
6,
7,
8
] |
import cv2
def movemouse(event, x, y, flags, param):
global img
img2 = img.copy()
# img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
if event == cv2.EVENT_MOUSEMOVE:
font = cv2.FONT_HERSHEY_SIMPLEX
message = '{}'.format(img2[y, x])
cv2.putText(img2, message, (int(w / 2.5), int(h /... | normal | {
"blob_id": "cae0aeea2ebd0a429cf6ecc9acab8f5f103e9669",
"index": 1989,
"step-1": "<mask token>\n\n\ndef main():\n cv2.namedWindow('image')\n cv2.setMouseCallback('image', movemouse)\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef movemouse(event, x, ... | [
1,
2,
3,
4,
5
] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from flask import jsonify
from flask import make_response
from MultipleInterfaceManager.settings import STATUS_CODE
def _render(resp):
response = make_response(jsonify(resp))
# response.headers["Access-Control-Allow-Origin"] = "*"
return ... | normal | {
"blob_id": "a87ab07bb1502a75a7e705cd5c92db829ebdd966",
"index": 8689,
"step-1": "<mask token>\n\n\ndef _render(resp):\n response = make_response(jsonify(resp))\n return response\n\n\n<mask token>\n\n\ndef json_detail_render(code, data=[], message=None):\n if message is None:\n message = STATUS_C... | [
2,
3,
5,
6,
7
] |
# -*- coding: utf-8 -*-
import time
import re
from config import allowed_users, master_users, chat_groups
from bs4 import BeautifulSoup
import requests
import urllib.request, urllib.error, urllib.parse
import http.cookiejar
import json
import os
import sys
#from random import randint, choice
from random import uniform,... | normal | {
"blob_id": "98dd7446045f09e6d709f8e5e63b0a94341a796e",
"index": 3158,
"step-1": "<mask token>\n\n\ndef fetch_images_from_db(chat_id, keyword_id, keyword_n, db, shared_dict):\n search = False\n if str(chat_id) + str(keyword_id) + 'db' in shared_dict:\n print('%s for group %s already in progress, sle... | [
4,
5,
7,
8,
9
] |
"""
Cores no terminal
"""
a = 3
b = 5
print('Os valores são \033[32m{}\033[m e \033[31m{}\033[m !!!'.format(a, b))
# Dicionário de cores:
nome = 'Kátia'
cores = {'limpa':'\033]m',
'azul':'\033[34m',
'amarelo':'\033[33m',
'pretoebranco':'\033[7;30m'}
print('Prazer em te conhe... | normal | {
"blob_id": "7bbbd30ba1578c1165ccf5c2fff22609c16dfd64",
"index": 393,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Os valores são \\x1b[32m{}\\x1b[m e \\x1b[31m{}\\x1b[m !!!'.format(a, b))\n<mask token>\nprint('Prazer em te conhecer, {}{}{}!!!'.format(cores['azul'], nome, cores[\n 'amarelo'])... | [
0,
1,
2,
3
] |
import os
import sqlite3 as db
os.system('clear')
persons = []
class Person:
def __init__(self, name, surname, job, salary):
self.name = name
self.surname = surname
self.job = job
self.salary = salary
def create(name):
conn = db.connect(name + '.db')
c = conn.cursor()
c.execute("""CREATE TABLE first(
... | normal | {
"blob_id": "7ff19ee35422395f78dca1e17a736df20a40ea98",
"index": 7569,
"step-1": "<mask token>\n\n\nclass Person:\n\n def __init__(self, name, surname, job, salary):\n self.name = name\n self.surname = surname\n self.job = job\n self.salary = salary\n\n\ndef create(name):\n conn... | [
4,
6,
7,
8,
9
] |
"""added personal collection
Revision ID: 43eabda1d630
Revises: 9cad4dfb5125
Create Date: 2018-03-28 13:55:03.557872
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '43eabda1d630'
down_revision = '9cad4dfb5125'
branch_labels = None
depends_on = None
def upgra... | normal | {
"blob_id": "21bdf315c98a4cf69482cc7db41bc30d44781596",
"index": 816,
"step-1": "<mask token>\n\n\ndef upgrade():\n op.add_column('Gifs', sa.Column('personal_collections', sa.Integer(),\n nullable=True))\n op.create_foreign_key(None, 'Gifs', 'PersonalGifCollections', [\n 'personal_collections... | [
1,
2,
3,
4,
5
] |
import random
a=input("enter 'r' to roll the dice and 'q' to quit")
while True:
if (a=="r"):
print(random.randint(1,6))
elif(a=="q"):
print("bye!")
exit()
else:
print("give either 'r' or 'q'")
| normal | {
"blob_id": "7e1f77210b3beb4e496ff95686d65bd7d79561a3",
"index": 170,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n if a == 'r':\n print(random.randint(1, 6))\n elif a == 'q':\n print('bye!')\n exit()\n else:\n print(\"give either 'r' or 'q'\")\n",
"s... | [
0,
1,
2,
3,
4
] |
import numpy as np
class nearest(svm):
name="MLLKM2"
def __init__(self):
svm.__init__(self)
def fit(self,x,y):
self.x=x
self.y=y
def predict(self,x):
diff=np.subtract(x,self.x)
distance=np.linalg.norm(diff,axis=1)
dmin= np.argmin( distance )
... | normal | {
"blob_id": "7d1ca15129b1bf6b713e1d5eda4436d4a8539ad1",
"index": 5939,
"step-1": "<mask token>\n\n\nclass nearest(svm):\n <mask token>\n\n def __init__(self):\n svm.__init__(self)\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass nearest(svm):\n <mask token>\n\n def ... | [
2,
3,
5,
6,
7
] |
"""Module just for fun game"""
# -*- coding: utf-8 -*-
from __future__ import print_function
from itertools import chain
import tabulate
import numpy
class Game(object):
"""Класс игры"""
def __init__(self):
self.field = numpy.array([(-10, -10, -10), (-10, -10, -10), (-10, -10, -10)])
self.rende... | normal | {
"blob_id": "23ba9e498dd153be408e973253d5f2a858d4771b",
"index": 6922,
"step-1": "<mask token>\n\n\nclass Game(object):\n <mask token>\n <mask token>\n\n def render_field(self):\n \"\"\"Метод отрисовки поля\"\"\"\n print(tabulate.tabulate(self.rendered_field, tablefmt='grid'))\n\n def c... | [
5,
6,
9,
11,
12
] |
# -*- coding: utf-8 -*-
from route4me import Route4Me
API_KEY = "11111111111111111111111111111111"
def main():
r4m = Route4Me(API_KEY)
route = r4m.route
response = route.get_routes(limit=1, offset=0)
if isinstance(response, dict) and 'errors' in response.keys():
print('. '.join(response['err... | normal | {
"blob_id": "bc4684d255a46427f708d8ce8bda2e12fb8c8ffe",
"index": 238,
"step-1": "<mask token>\n\n\ndef main():\n r4m = Route4Me(API_KEY)\n route = r4m.route\n response = route.get_routes(limit=1, offset=0)\n if isinstance(response, dict) and 'errors' in response.keys():\n print('. '.join(respo... | [
1,
2,
3,
4,
5
] |
def sum_string(string):
list_chars = [zerone for zerone in string if zerone in ["0", "1"]]
return list_chars
def check_triads(trio, final_str):
list_occur_zero = [i for i in range(len(final_str)) if final_str.startswith(trio + '0', i)]
list_occur_one = [i for i in range(len(final_str)) if final_str.st... | normal | {
"blob_id": "29304bdbf93b0b1308025db1d35a92346c6dcbe0",
"index": 3799,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef check_triads(trio, final_str):\n list_occur_zero = [i for i in range(len(final_str)) if final_str.\n startswith(trio + '0', i)]\n list_occur_one = [i for i in range(l... | [
0,
1,
2,
3,
5
] |
print ("hello")
print ("===================================================")
print ("Nama Lengkap : Agung Dharmawan")
print ("Kelas : Teknik Informatika 2018 A")
print ("Kampus : Universitas Nahdlatul Ulama Sidoarjo")
print ("===================================================")
| normal | {
"blob_id": "4e10bc876797d0939c91cff5eff497b36af35dcb",
"index": 1932,
"step-1": "<mask token>\n",
"step-2": "print('hello')\nprint('===================================================')\nprint('Nama Lengkap : Agung Dharmawan')\nprint('Kelas : Teknik Informatika 2018 A')\nprint('Kampus : Universit... | [
0,
1,
2
] |
'''
Exercício 1: Estenda a classe Stack , que escrevemos durante as explicações do
conteúdo, adicionando uma nova função chamada min_value() que irá retornar o
menor valor inteiro presente na pilha.
'''
from stack import Stack
class Other_Operations_Stack(Stack):
def min_value(self):
min_value = self.pee... | normal | {
"blob_id": "0b2fd671b99b7012a14b132db2322318873b826c",
"index": 1345,
"step-1": "<mask token>\n\n\nclass Other_Operations_Stack(Stack):\n\n def min_value(self):\n min_value = self.peek()\n for value in self._data:\n if value < min_value:\n min_value = value\n ... | [
2,
3,
4,
5,
6
] |
from concurrent.futures import ProcessPoolExecutor
from nltk import PorterStemmer, RegexpTokenizer
from stop_words import get_stop_words
class Preprocessor(object):
def __init__(self, max_workers=4):
self.max_workers = max_workers
self.tokenizer = RegexpTokenizer(r"\w+")
self.en_stopwords... | normal | {
"blob_id": "8cd50e1f0e0feb4d753443220f9fa9065e80e0ef",
"index": 6358,
"step-1": "<mask token>\n\n\nclass Preprocessor(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass WithUrlPreprocessor(Preprocessor):\n\n def __init__(self, max_workers=4):\n ... | [
4,
6,
7,
10,
11
] |
#!/usr/bin/env python
from pymongo import GEO2D
from GlobalConfigs import eateries
eateries.create_index([("eatery_coordinates", GEO2D)])
eateries.ensure_index([("eatery_coordinates", pymongo.GEOSPHERE)])
for e in eateries.find({"eatery_coordinates": {"$near": [latitude, longitude]}}).limit(5):
print e.get... | normal | {
"blob_id": "59de17ea4e714e17e3a7dd966bd0d93ba73f4503",
"index": 5306,
"step-1": "#!/usr/bin/env python\n\nfrom pymongo import GEO2D\nfrom GlobalConfigs import eateries\n\neateries.create_index([(\"eatery_coordinates\", GEO2D)]) \neateries.ensure_index([(\"eatery_coordinates\", pymongo.GEOSPHERE)])\n\nfor e in ... | [
0
] |
"""Activate coverage at python startup if appropriate.
The python site initialisation will ensure that anything we import
will be removed and not visible at the end of python startup. However
we minimise all work by putting these init actions in this separate
module and only importing what is needed when needed.
For... | normal | {
"blob_id": "243794d36a1c6861c2c3308fe6a52ec19b73df72",
"index": 7820,
"step-1": "<mask token>\n\n\ndef multiprocessing_start(obj):\n cov = init()\n if cov:\n multiprocessing.util.Finalize(None, multiprocessing_finish, args=(\n cov,), exitpriority=1000)\n\n\n<mask token>\n\n\ndef init():\... | [
2,
3,
4,
5,
6
] |
import urllib.request
import io
import cv2
import numpy as np
img_url = 'http://192.168.0.2:7079/hi'
while True:
data = urllib.request.urlopen(img_url)
raw_data = data.read()
nparr = np.frombuffer(raw_data, np.byte)
image_raw = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
cv2.imshow("test", image_raw)... | normal | {
"blob_id": "c120db53e1ea5a5b865b891cf602a13113fb1e41",
"index": 4113,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n data = urllib.request.urlopen(img_url)\n raw_data = data.read()\n nparr = np.frombuffer(raw_data, np.byte)\n image_raw = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)... | [
0,
1,
2,
3,
4
] |
'''
这部分理解参考:
https://www.bilibili.com/video/BV1QA411H7tK?from=search&seid=17305042509580602672
图文代码地址: https://blog.csdn.net/qq_30758629/article/details/112527763
'''
import threading
import time
data=0
lock=threading.Lock() #创建一个锁对象
def func():
global data
print("%s is acquire lock..\n" %threading.curr... | normal | {
"blob_id": "7aa426723f5311b5abec4a7ace9d3ec1e5e31d9a",
"index": 5966,
"step-1": "<mask token>\n\n\ndef func():\n global data\n print('%s is acquire lock..\\n' % threading.current_thread().getName())\n if lock.acquire():\n print('%s get lock ' % threading.current_thread().getName())\n data... | [
1,
2,
3,
4,
5
] |
#------------------------------------------------------------------------------
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
import wx
from .wx_control import WXControl
from ...components.image_view import AbstractTkImag... | normal | {
"blob_id": "d4198c2c3706e03ba1bce3e31c5139f01248a184",
"index": 5161,
"step-1": "<mask token>\n\n\nclass wxBitmapWidget(wx.Panel):\n <mask token>\n\n def __init__(self, parent):\n \"\"\" Initialize a wxBitmapWidget.\n\n Parameters\n ----------\n parent : wx.Window\n ... | [
18,
20,
25,
28,
31
] |
from django import forms
from .models import HhRequest
class WorkRequestForm(forms.ModelForm):
"""Форма заявки на премию"""
class Meta:
model = HhRequest
fields = ('profile', 'sphere', 'experience', 'work_request', 'resume')
widgets = {
'profile': forms.Select(
... | normal | {
"blob_id": "3887516e4222504defe439e62bd24b12db3cdd84",
"index": 695,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass WorkRequestForm(forms.ModelForm):\n <mask token>\n\n\n class Meta:\n model = HhRequest\n fields = 'profile', 'sphere', 'experience', 'work_request', 'resume'\... | [
0,
1,
2,
3,
4
] |
#-*- coding: utf-8 -*-
import re
import sys
import os
import pandas as pd
import jieba
import logging
import argparse
from sklearn.externals import joblib
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import f1_score,accuracy_score
from sklearn.feature_extraction.text im... | normal | {
"blob_id": "c879230efe12bde9042159da221a2b9b4c1d8349",
"index": 198,
"step-1": "<mask token>\n\n\ndef load_data_from_csv(file_name, header=0, encoding='utf-8'):\n data_df = pd.read_csv(file_name, header=header, encoding=encoding)\n return data_df\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef lo... | [
1,
2,
3,
4,
5
] |
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import *
from django.views.decorators.csrf import csrf_exempt
def index(request):
notes = Note.objects.all().order_by('-created_at')
context = {
"notes" : notes
}
return render(request, 'notes/index.h... | normal | {
"blob_id": "e983db4b99e73929c02eb84fab1ee56138048052",
"index": 8221,
"step-1": "<mask token>\n\n\ndef index(request):\n notes = Note.objects.all().order_by('-created_at')\n context = {'notes': notes}\n return render(request, 'notes/index.html', context)\n\n\ndef add(request):\n if request.method ==... | [
2,
3,
4,
5,
6
] |
from plone import api
from plone.app.robotframework.testing import AUTOLOGIN_LIBRARY_FIXTURE
from plone.app.testing import applyProfile
from plone.app.testing import FunctionalTesting
from plone.app.testing import IntegrationTesting
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import PloneSandboxL... | normal | {
"blob_id": "eec2b818ea9d50161bad60e8bf83dcb7ce9bf9fa",
"index": 7428,
"step-1": "<mask token>\n\n\nclass OiRAFixture(PloneSandboxLayer):\n <mask token>\n\n def setUpZope(self, app, configurationContext):\n z2.installProduct(app, 'Products.membrane')\n z2.installProduct(app, 'Products.statusm... | [
3,
4,
5,
6,
7
] |
def isSubsetSum(set, n, sum):
subset =([[False for i in range(sum + 1)] for i in range(n + 1)])
for i in range(n + 1):
subset[i][0] = True
for i in range(1, sum + 1):
subset[0][i]= False
for i in range(1, n + 1):
for j in range(1, sum + 1):
if j<set[i-1]:
... | normal | {
"blob_id": "830e7e84eebd6a4adb411cc95c9e9c8ff7bdac30",
"index": 778,
"step-1": "<mask token>\n",
"step-2": "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n s... | [
0,
1,
2,
3,
4
] |
from pyzabbix import ZabbixMetric, ZabbixSender, ZabbixAPI
from datetime import datetime
from re import findall
# current_time = datetime.now().strftime("%H:%M:%S %d.%m.%Y")
class ZabbixItem():
def __init__(self, user, password, ext_group, ext_template, zabbix_host):
self.user = user
self.passwor... | normal | {
"blob_id": "14826b5b121ba2939519492c1e1d8700c32396d2",
"index": 8963,
"step-1": "<mask token>\n\n\nclass ZabbixItem:\n\n def __init__(self, user, password, ext_group, ext_template, zabbix_host):\n self.user = user\n self.password = password\n self.zabbix_host = zabbix_host\n self.... | [
6,
8,
9,
11,
12
] |
import fnmatch
import hashlib
from .mplog import MachopLog
from .utils import MachopProcess, wait_for_interrupt
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class MachopWatchCommand(MachopProcess):
class MachopHandler(PatternMatchingEventHandler):
"""... | normal | {
"blob_id": "4e30f0a9b420123c28858aad2a71040dcc952829",
"index": 1391,
"step-1": "<mask token>\n\n\nclass MachopWatchCommand(MachopProcess):\n\n\n class MachopHandler(PatternMatchingEventHandler):\n \"\"\" watcher for a file system event \"\"\"\n\n def on_modified(self, event):\n if e... | [
4,
5,
7,
8,
9
] |
# System import
import os
# Docutils import
from docutils import nodes
from docutils.parsers.rst.directives.admonitions import BaseAdmonition
from docutils.statemachine import ViewList
# Add node
class link_to_block(nodes.Admonition, nodes.Element):
""" Node for inserting a link to button."""
pass
# Add di... | normal | {
"blob_id": "63cce356b792949b90b215e0a5826f7b33d2d375",
"index": 8064,
"step-1": "<mask token>\n\n\nclass link_to_block(nodes.Admonition, nodes.Element):\n <mask token>\n pass\n\n\nclass LinkToBlock(BaseAdmonition):\n \"\"\" Hidden technical block\"\"\"\n node_class = link_to_block\n has_content =... | [
5,
6,
7,
9,
11
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Beach',
fields=[
('id', models.AutoField(verbos... | normal | {
"blob_id": "9555e5f75e3045afff6da9228764fca542caf539",
"index": 2448,
"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 = []\n operat... | [
0,
1,
2,
3,
4
] |
import pytest
from a3 import *
from test_utils import *
from numpy import allclose
def test_problem_7_1_8():
assert(check_linalg())
assert(abs(problem_7_1_8(5000)-84.8)<1)
| normal | {
"blob_id": "c7553cadb49c9c7e80a7800b9bff4d5f64796494",
"index": 7568,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_problem_7_1_8():\n assert check_linalg()\n assert abs(problem_7_1_8(5000) - 84.8) < 1\n",
"step-3": "import pytest\nfrom a3 import *\nfrom test_utils import *\nfrom n... | [
0,
1,
2,
3
] |
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, Sequential, optimizers
import numpy as np
from tensorflow.compat.v1.keras.backend import set_session
config = tf.compat.v1.ConfigProto()
config.gpu_optio... | normal | {
"blob_id": "e626a7f3f9241db8684c3b8c1bd79ea49e03490d",
"index": 8141,
"step-1": "<mask token>\n\n\nclass BasicBlock(layers.Layer):\n <mask token>\n\n def call(self, inputs, training=None):\n out = self.conv1(inputs)\n out = self.bn1(out)\n out = self.relu1(out)\n out = self.con... | [
6,
7,
8,
9,
11
] |
class Donkey(object):
def manzou(self):
print('走路慢……')
def jiao(self):
print('驴在欢叫%……')
class Horse(object):
def naili(self):
print('马力足,持久强……')
def jiao(self):
print('马在嘶鸣')
class Mule(Donkey,Horse):
pass
def jiao(self):
print('骡子在唱歌')
骡子一号 = Mule()
骡... | normal | {
"blob_id": "5d4ef436c4ee5c31496977a5ae9b55db9ff34e79",
"index": 4082,
"step-1": "<mask token>\n\n\nclass Horse(object):\n\n def naili(self):\n print('马力足,持久强……')\n <mask token>\n\n\nclass Mule(Donkey, Horse):\n pass\n\n def jiao(self):\n print('骡子在唱歌')\n\n\n<mask token>\n",
"step-2":... | [
4,
7,
8,
9,
11
] |
# Bengisu Ayan - 2236974
# Ceren Gürsoy - 2237485
import numpy as np
import cv2
B1 = "THE3-Images/B1.jpg"
B2 = "THE3-Images/B2.jpg"
B3 = "THE3-Images/B3.jpg"
B4 = "THE3-Images/B4.jpg"
B5 = "THE3-Images/B5.jpg"
def segmentation_function(image, name, blue_mask=False, white_mask=False, yellow_mask=False):
# Smo... | normal | {
"blob_id": "1614157c57b3d1b30087c42cb840d617dc91eecb",
"index": 493,
"step-1": "<mask token>\n\n\ndef segmentation_function(image, name, blue_mask=False, white_mask=False,\n yellow_mask=False):\n image = cv2.GaussianBlur(image, (11, 11), 0)\n hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n low_... | [
1,
2,
3,
4,
5
] |
from find import Solution
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
solution = Solution.Find(6, array)
| normal | {
"blob_id": "d4361b169bf75d3af82eca3d26609961ccc2f27e",
"index": 2405,
"step-1": "<mask token>\n",
"step-2": "<mask token>\narray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nsolution = Solution.Find(6, array)\n",
"step-3": "from find import Solution\narray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nsolution = Solution.Fi... | [
0,
1,
2
] |
#!/usr/bin/env python
import rospy
from std_msgs.msg import *
__print__ = ''
def Print(msg):
global __print__
target = int(msg.data.split(';')[0]) * 2
if target == 0:
__print__ = msg.data.split(';')[-1] + '\n' + '\n'.join(__print__.split('\n')[1:])
else:
__print__ = '\n'.join(__print... | normal | {
"blob_id": "007caece16f641947043faa94b8a074efe8ebadb",
"index": 6994,
"step-1": "#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import *\n\n__print__ = ''\n\ndef Print(msg):\n global __print__\n\n target = int(msg.data.split(';')[0]) * 2\n if target == 0:\n __print__ = msg.data.split('... | [
0
] |
# Generated by Django 3.0.7 on 2020-12-16 15:29
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('play', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='playerA',
... | normal | {
"blob_id": "ea414835554ea3dcac2017036692cf178526f91b",
"index": 5641,
"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 = [('play', '000... | [
0,
1,
2,
3,
4
] |
from typing import Tuple, Union
from webdnn.graph.graph import Graph
from webdnn.graph.operators.zero_padding_2d import ZeroPadding2D
from webdnn.graph.operators.convolution2d import Convolution2D
from webdnn.graph.operators.max_pooling_2d import MaxPooling2D
from webdnn.graph.operators.average_pooling_2d import Avera... | normal | {
"blob_id": "687f7f4908e8a5448335f636edf74a627f03c306",
"index": 9110,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass ConcatZeroPadding(OptimizeRule):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass ConcatZeroPadding(OptimizeRule):\n\n def optimize(self, graph: Graph) ->Tuple[Grap... | [
0,
1,
2,
3,
4
] |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django.db import models
SERVICE_RANGE_CHOISE = {(1, '1年'), (2, '2年'), (3, '3年'), (4, '4年'), (5, '5年'), (6, '6年'), (7, '7年'), (8, '8年'), (0, '长期')}
USER_STATUS_CHOISE = {(1, '停用'), (2, '正常'), (3, '锁定')}
DBSERVER_POS_CHOISE = {(1, '8层机房'), (2, '11层机房')... | normal | {
"blob_id": "c2490c3aacfa3ce22c3f47a69dbc44b695c2a2e5",
"index": 9509,
"step-1": "<mask token>\n\n\nclass Odbserver(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n ... | [
13,
14,
16,
17,
19
] |
from abc import ABC, abstractmethod, abstractproperty
from pytz import timezone
class EngageScraper(ABC):
def __init__(self, tz_string):
super().__init__()
self._agenda_locations = []
self._tz = timezone(tz_string)
@property
def agenda_locations(self):
return self._agenda... | normal | {
"blob_id": "ec224924206c41cf8203c6aa8002ddf6b0e70e9b",
"index": 1116,
"step-1": "<mask token>\n\n\nclass EngageScraper(ABC):\n\n def __init__(self, tz_string):\n super().__init__()\n self._agenda_locations = []\n self._tz = timezone(tz_string)\n\n @property\n def agenda_locations(s... | [
8,
10,
11,
12
] |
"""Plotting functionality for ab_test_model."""
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from itertools import combinations
from ._ab_test_model_utils import _ab_test_utils
# pylint: disable=no-member
class _ab_test_plotting(_ab_test_utils):
"""Provide Funcs for class to plot Baye... | normal | {
"blob_id": "3eaa898d1428e48aeb0449c7216d0a994262f76a",
"index": 9107,
"step-1": "<mask token>\n\n\nclass _ab_test_plotting(_ab_test_utils):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def plot_positive_lift(self, variant_on... | [
2,
5,
7,
10,
12
] |
import ujson as json
import platform
import socket
import os
from pathlib import Path
def test_json(text):
jobj = json.loads(text)
l = len(jobj['coordinates'])
x = 0
y = 0
z = 0
for coord in jobj['coordinates']:
x += coord['x']
y += coord['y']
z += coord['z']
print(x / l... | normal | {
"blob_id": "6f99b4e4204e85c78f9c02a5cd53cd76f52c022c",
"index": 617,
"step-1": "<mask token>\n\n\ndef notify(msg):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n if not s.connect_ex(('localhost', 9001)):\n s.sendall(bytes(msg, 'utf8'))\n\n\n<mask token>\n",
"step-2": "<m... | [
1,
2,
3,
4,
5
] |
from django.conf.urls import url
from .views import LoginView, logout_user, delete_user
from .views import NewUserView
urlpatterns = [
url(r'newuser/', NewUserView.as_view(), name='newuser'),
url(r'login/', LoginView.as_view(), name='login'),
url(r'logout/', logout_user, name='logout'),
url(r'delete/$'... | normal | {
"blob_id": "9b4bc7f8f9c96f503a5ed79827430963e21718c4",
"index": 3733,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('newuser/', NewUserView.as_view(), name='newuser'), url(\n 'login/', LoginView.as_view(), name='login'), url('logout/',\n logout_user, name='logout'), url('delete... | [
0,
1,
2,
3
] |
import os.path
from flask import url_for
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey
from sqlalchemy.orm import relationship
from tuneful import app
from .database import Base, engine, session
class Song(Base):
__tablename__ = 'songs'
id = Column(Integer, primary_key=True)
file_i... | normal | {
"blob_id": "d5c2b73c202c9944cd64798ef5ddc08ce68a4a9a",
"index": 3446,
"step-1": "<mask token>\n\n\nclass Song(Base):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass File(Base):\n __tablename__ = 'files'\n id = Column(Integer, primary_key=True)\n filename = Column(Stri... | [
4,
5,
6,
7,
8
] |
#!/usr/bin/env python
def get_attachment_station_coords(station):
if (station == "gripper1"):
coords = [0.48, 0.05, 0.161]
elif (station == "gripper2"):
coords = [0.28, 0.05, 0.13]
elif (station == "syringe"):
coords = [0.405, 0.745, 0.213]
else:
coords = [0.0, 0.0, 0.0]... | normal | {
"blob_id": "86c03fa85ac405a148be13325efeaaf691d9ec26",
"index": 5223,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_station_coords(station):\n if station == 'steaks':\n coords = [0.4625, 0.375, 0.14]\n elif station == 'griddle':\n coords = [0.73, 0.375, 0.05]\n elif s... | [
0,
1,
2,
3
] |
import os, glob, argparse, json, re
from collections import defaultdict
import numpy as np
import pandas as pd
from utils.CONSTANTS import output_dir, all_chromosomes, BINNED_CHRSZ, dataset_expts
def extract_chrom_num(s):
m = re.search('\d+', s)
if m is None:
return 24
else:
return int(m.group(0))
de... | normal | {
"blob_id": "c6d61a0159073304309cd4b1534ed5aed666bab5",
"index": 3666,
"step-1": "<mask token>\n\n\ndef main(expt_set, chrom, checkpoint_code, dataset='val', model_list=[],\n directory=None):\n if directory is None:\n directory = output_dir\n model_list = sorted(model_list, key=extract_chrom_num)... | [
1,
2,
3,
4,
5
] |
# this is the example code from the t0p-level README..d
from spatialmath import SE3
import roboticstoolbox as rtb
import swift
robot = rtb.models.DH.Panda()
print(robot)
T = robot.fkine(robot.qz)
print(T)
# IK
T = SE3(0.7, 0.2, 0.1) * SE3.OA([0, 1, 0], [0, 0, -1])
sol = robot.ikine_LMS(T) # solve IK, ignore additio... | normal | {
"blob_id": "cc1a1491ffbcf470705aeea079faac290dbaa25e",
"index": 5965,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(robot)\n<mask token>\nprint(T)\n<mask token>\nprint(sol.q)\nprint(robot.fkine(sol.q))\n<mask token>\nrobot.plot(qtraj.q, movie='panda1.gif')\n<mask token>\nprint(robot)\n<mask token... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
## https://atcoder.jp/contests/abs/tasks/abc083_b
import sys
def gets(input):
return input.readline().strip()
def run(input):
n, a, b = gets(input).split()
N, A, B = int(n), int(a), int(b)
#
total = 0
for i in range(1, N+1):
x = sum( int(ch) for ch in str(i) )... | normal | {
"blob_id": "a1ea0f269a20ff608d10ee01804eeee7e7232b1d",
"index": 7650,
"step-1": "<mask token>\n\n\ndef gets(input):\n return input.readline().strip()\n\n\n<mask token>\n\n\ndef main():\n result = run(sys.stdin)\n print(result)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef gets(input):\n r... | [
2,
3,
4,
5,
6
] |
# Generated by Django 3.0.6 on 2020-06-23 10:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('printer', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='printers_stat',
name='type_printers',
... | normal | {
"blob_id": "e7bb5e9a91ec6a1644ddecd52a676c8136087941",
"index": 4719,
"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 = [('printer', '... | [
0,
1,
2,
3,
4
] |
class Solution:
def jump(self, nums: List[int]) ->int:
l = len(nums)
jump = 0
curEnd = 0
curFarthest = 0
for i in range(l - 1):
curFarthest = max(curFarthest, i + nums[i])
if i == curEnd:
jump += 1
curEnd = curFarthest
... | normal | {
"blob_id": "763d448bc447b88d5f2de777a475a1dd50906527",
"index": 7491,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def jump(self, nums: List[int]) ->int:\n l = len(nums)\n jump = 0\n curEnd = 0\n curFarthest = 0\n ... | [
0,
1,
2
] |
import server.wsgi as flask
import server.grunner as gunicorn
from utils.cfgreader import EnvReader, BoolVar
def use_flask() -> bool:
env_var = BoolVar('USE_FLASK', False)
return EnvReader().safe_read(env_var)
if __name__ == '__main__':
if use_flask(): # dev mode, run the WSGI app in Flask dev server
... | normal | {
"blob_id": "ffe10ee8b2ebaad565e9aef5047440a067d4e239",
"index": 7528,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef use_flask() ->bool:\n env_var = BoolVar('USE_FLASK', False)\n return EnvReader().safe_read(env_var)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef use_flask() ->bo... | [
0,
1,
2,
3,
4
] |
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
import os
# caps = {'browserName': os.getenv('BROWSER', 'firefox')}
# browser = webdriver.Remo... | normal | {
"blob_id": "d84641ce2854d4af26cd46abbe9557d6006cfc2e",
"index": 681,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nbrowser.get('https://www.google.com')\ntime.sleep(3)\nbrowser.maximize_window()\n<mask token>\nprint(title)\nassert 'Google' == title\nbrowser.close()\n",
"step-3": "<mask token>\ncapabi... | [
0,
1,
2,
3,
4
] |
import socket
# Packet Sniffing
# It's All Binary
# Usage: python basic_sniffer.py
# create the sniffer raw socket object
sniffer = socket.socket(socket.AF_INET,socket.SOCK_RAW, socket.IPPROTO_ICMP)
#bind it to localhost
sniffer.bind(('0.0.0.0',0))
# make sure that the IP header is included
sniffer.setsockopt(soc... | normal | {
"blob_id": "9f2a8e78aa2e3eab8f74847443dec9083603da39",
"index": 3643,
"step-1": "import socket\n\n# Packet Sniffing\n# It's All Binary\n\n# Usage: python basic_sniffer.py \n\n# create the sniffer raw socket object\nsniffer = socket.socket(socket.AF_INET,socket.SOCK_RAW, socket.IPPROTO_ICMP)\n\n#bind it to local... | [
0
] |
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.metrics import classification_report
from BlogTutorials.pyimagesearch.preprocessing.imagetoarraypreprocessor import ImageToArrayPreprocessor
from Bl... | normal | {
"blob_id": "28cdb59e97f3052dd80f8437574f9ffe09fc1e84",
"index": 6690,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nle.fit(labels)\n<mask token>\nprint('[info] compile model...')\n<mask token>\nmodel.compile(loss='categorical_crossentropy', optimizer=opt, metrics=[\n 'accuracy'])\n<mask token>\nprin... | [
0,
1,
2,
3,
4
] |
"""
* author - kajol
* date - 12/24/2020
* time - 1:24 PM
* package - com.bridgelabz.basicprograms
* Title - Print a table of the powers of 2 that are less than or equal to 2^N
"""
try:
number = int(input("Enter number: "))
#print power of 2 within given range
if number < 31:
for num... | normal | {
"blob_id": "b0f0bcfb5739d46de54cbe46614e82bf5a2d13fb",
"index": 9038,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n number = int(input('Enter number: '))\n if number < 31:\n for num in range(1, number + 1):\n print('2 ^', num, '=', 2 ** num)\n else:\n print('Ent... | [
0,
1,
2
] |
from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import style
style.use('ggplot')
# Create random data points whose centers are the following
centers = [[20, 0, 0], [0, 20, 0], [0, 0... | normal | {
"blob_id": "c0216dbd52be134eb417c20ed80b398b22e5d844",
"index": 6967,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nstyle.use('ggplot')\n<mask token>\nclf.fit(X)\n<mask token>\nprint(cluster_centers)\n<mask token>\nprint('Number of clusters found:', n_clusters)\n<mask token>\nfor i in range(len(X)):\n ... | [
0,
1,
2,
3,
4
] |
import torch.nn as nn
from torch.autograd import Variable
import torch
import string
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)
#Find letter index from all_letters, e.g. "a" = 0
def letterToIndex(letter):
return all_letters.find(letter)
#Only for demonstation
def letterToTensor(let... | normal | {
"blob_id": "aa24442624aebeb2777f16a826cf59859d7870ba",
"index": 8744,
"step-1": "<mask token>\n\n\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n\n<mask token>\n\n\nclass RNN(nn.Module):\n\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n ... | [
6,
7,
10,
11,
13
] |
import sys
import requests
def ggwave(message: str, protocolId: int = 1, sampleRate: float = 48000, volume: int = 50, payloadLength: int = -1):
url = 'https://ggwave-to-file.ggerganov.com/'
params = {
'm': message, # message to encode
'p': protocolId, # transmission protocol to use
... | normal | {
"blob_id": "f5d285b3a82151b5d7efdcd07d56cc5aaaac5836",
"index": 7213,
"step-1": "<mask token>\n\n\ndef ggwave(message: str, protocolId: int=1, sampleRate: float=48000, volume:\n int=50, payloadLength: int=-1):\n url = 'https://ggwave-to-file.ggerganov.com/'\n params = {'m': message, 'p': protocolId, 's... | [
1,
2,
3,
4,
5
] |
# 斐波那契数列(后一位=前两位之和)
# 又叫黄金分割数列,前/后 越来越接近0.618
# list1 = []
# for i in range(20):
# if i <= 1:
# list1.append(1)
# else:
# list1.append(list1[-2]+list1[-1])
# print(list1)
import random
dict1 = {'A': [], 'B': [], 'C': [], 'D': []}
for i in range(20):
re = random.randint(1, 100)
if re >=... | normal | {
"blob_id": "4a223cdd3c957af2f54e33c910ce70d2b5e6c963",
"index": 7705,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(20):\n re = random.randint(1, 100)\n if re >= 90:\n dict1['A'].append(re)\n elif re >= 80:\n dict1['B'].append(re)\nprint(dict1)\n",
"step-3": "<ma... | [
0,
1,
2,
3,
4
] |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data=pd.read_excel("data_SHA.xls")
fig,ax=plt.subplots()
ax.plot(data["Date"],data["HCHFI"],label="HCHFI")
ax.plot(data["Date"],data["SHA"]/2.67547,label="SSE Composite Index")
ax.plot(data["Date"],data["Hushen300 Index"]/3.20393,label="Hushen300 In... | normal | {
"blob_id": "91df15d6d89d070677704572d35218558317a6ec",
"index": 117,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nax.plot(data['Date'], data['HCHFI'], label='HCHFI')\nax.plot(data['Date'], data['SHA'] / 2.67547, label='SSE Composite Index')\nax.plot(data['Date'], data['Hushen300 Index'] / 3.20393, lab... | [
0,
1,
2,
3,
4
] |
with open('vocabulary.txt', 'r') as f:
for line in f:
information = line.strip().split(': ')
# print(information[0], information[1])
question = information[1]
answer = information[0]
my_answer = input(f'{question}:')
if my_answer == answer:
print('맞았습니다!'... | normal | {
"blob_id": "34009d1aa145f4f5c55d0c5f5945c3793fbc6429",
"index": 7823,
"step-1": "<mask token>\n",
"step-2": "with open('vocabulary.txt', 'r') as f:\n for line in f:\n information = line.strip().split(': ')\n question = information[1]\n answer = information[0]\n my_answer = input... | [
0,
1,
2
] |
# function to add two numbers
def add2nums(a,b):
return a+b
| normal | {
"blob_id": "6e2fb9d498294a580426ff408183f7beec135329",
"index": 5592,
"step-1": "<mask token>\n",
"step-2": "def add2nums(a, b):\n return a + b\n",
"step-3": "# function to add two numbers\ndef add2nums(a,b):\n return a+b\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
... | [
0,
1,
2
] |
import pyodbc
print("Primera consulta SQL Server")
servidor="LOCALHOST\SQLEXPRESS"
bbdd="HOSPITAL"
usuario="SA"
password="azure"
#CADENA CONEXION CON SEGURIDAD SQL SERVER (REMOTO)
cadenaconexion=("DRIVER={ODBC Driver 17 for SQL Server};SERVER=" + servidor
+ "; DATABASE=" + bbdd + "; UID=" + usuario + "; PWD=" + passw... | normal | {
"blob_id": "0438f92aa9a36eaf1059244ec3be4397381f7a86",
"index": 6703,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Primera consulta SQL Server')\n<mask token>\nprint('Intentando conectar...')\n<mask token>\nprint('Conectado!!!')\n<mask token>\ncursor.execute(sql)\n<mask token>\nprint(row)\n<mas... | [
0,
1,
2,
3,
4
] |
import os
import numpy as np
import scipy as sp
import sys
from sure import that
from itertools import combinations, permutations
input_file = open('input1.txt', 'r')
output_file = open('output1.txt', 'w')
T = int(input_file.readline().rstrip('\n'))
case_num = 1
while case_num - 1 < T:
# Parse data
data = ma... | normal | {
"blob_id": "10c8316aee2107dc84ce7c1427dd62f52a2ce697",
"index": 4549,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile case_num - 1 < T:\n data = map(int, input_file.readline().rstrip('\\n').split(' '))\n typed = data[0]\n length = data[1]\n probs = map(float, input_file.readline().rstri... | [
0,
1,
2,
3,
4
] |
# As variáveis abaixo estão recebendo uma função anônima
contador_letras = lambda lista: [len(x) for x in lista]
lista_animais = ['cachorro', 'pato', 'marreco']
print(contador_letras(lista_animais))
| normal | {
"blob_id": "d13957c3d3f4d34279dc660d80ca91ca84ba4a77",
"index": 4504,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(contador_letras(lista_animais))\n",
"step-3": "contador_letras = lambda lista: [len(x) for x in lista]\nlista_animais = ['cachorro', 'pato', 'marreco']\nprint(contador_letras(list... | [
0,
1,
2,
3
] |
# Copyright 2021 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": "1ea31a126417c2feb079339aa79f97ea9e38fa40",
"index": 6152,
"step-1": "<mask token>\n\n\nclass Focusv2(nn.Cell):\n\n def __init__(self, c1, c2, k=1, s=1, p=None, act=True):\n super(Focusv2, self).__init__()\n self.conv = Conv(c1 * 4, c2, k, s, p, act)\n\n def construct(self, x):\n ... | [
12,
21,
27,
28,
33
] |
"""
A web-page.
"""
import re
import pkg_resources
from .components import Link, Javascript, inject
class Page:
"""A web-page presenting container.
Args:
favicon (str): The file name for the favorite icon displayed in a
browser tab(default=None)
title (str): The page title, disp... | normal | {
"blob_id": "2c2ad4b6e8c5055afa3dfb3b540a44bda65fa004",
"index": 5991,
"step-1": "<mask token>\n\n\nclass Page:\n <mask token>\n <mask token>\n <mask token>\n\n def background(self, color=None, image=None, position=None, size=None,\n repeat=None, origin=None, clip=None, attachment=None):\n ... | [
3,
5,
6,
7,
8
] |
import requests
import json
import base64
import re
def main(targetsrting):
email="" #email
key="" #key
#targetsrting='ip="202.107.117.5/24"' #搜索关键字
target=base64.b64encode(targetsrting.encode('utf-8')).decode("utf-8")
url="https://fofa.so/api/v1/search/all?email={}&key={}&qbase64={}&fields=hos... | normal | {
"blob_id": "5f13866bd5c6d20e8ddc112fb1d1335e3fd46c3e",
"index": 1817,
"step-1": "<mask token>\n\n\ndef main(targetsrting):\n email = ''\n key = ''\n target = base64.b64encode(targetsrting.encode('utf-8')).decode('utf-8')\n url = (\n 'https://fofa.so/api/v1/search/all?email={}&key={}&qbase64={... | [
1,
2,
3,
4,
5
] |
from ui.pages import BasePage
from ui.locators.login_page_locators import LoginPageLocators
class LoginPage(BasePage, LoginPageLocators):
def __init__(self, driver=None):
super(LoginPage, self).__init__(driver=driver)
self.identifier = self.IDENTIFIER
def login(self, email=None, password=Non... | normal | {
"blob_id": "c1bcce809aa073ecd6e64dfa65ead9bd48aee3ff",
"index": 7406,
"step-1": "<mask token>\n\n\nclass LoginPage(BasePage, LoginPageLocators):\n\n def __init__(self, driver=None):\n super(LoginPage, self).__init__(driver=driver)\n self.identifier = self.IDENTIFIER\n <mask token>\n\n def... | [
3,
4,
5,
6
] |
for t in range(int(input())):
st = list(input())
N, j = len(st), 1
for i in range(N // 2):
if st[i] == '*' or st[-i - 1] == '*':
break
elif st[i] != st[-i - 1]:
j = 0
break
print('#{} Exist'.format(t + 1)) if j else print('#{} Not exist'.format
... | normal | {
"blob_id": "21d499555b4bc4944996a57ae544a56aa317b00b",
"index": 4386,
"step-1": "<mask token>\n",
"step-2": "for t in range(int(input())):\n st = list(input())\n N, j = len(st), 1\n for i in range(N // 2):\n if st[i] == '*' or st[-i - 1] == '*':\n break\n elif st[i] != st[-i ... | [
0,
1
] |
import math as m
import functions_by_alexandra as fba
import funs
from functions_by_alexandra import User, a
from pkg import bps, geom
print(type(funs))
print(type(funs.add ))
#
# print(add(2,3))
print("Result: ", funs.add(10, 20))
print("Result: ", fba.add(10,20))
print(type(fba ))
print(a )
print(m... | normal | {
"blob_id": "b53b0e6ff14750bbba3c2e5e2ea2fc5bb1abccec",
"index": 3135,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(type(funs))\nprint(type(funs.add))\nprint('Result: ', funs.add(10, 20))\nprint('Result: ', fba.add(10, 20))\nprint(type(fba))\nprint(a)\nprint(m.pi)\n<mask token>\nprint(p)\nprint(b... | [
0,
1,
2,
3,
4
] |
from app.api import app
def main():
app.run(host='0.0.0.0', port=5001)
if __name__ == '__main__':
main()
| normal | {
"blob_id": "b49e5b40ce1e16f1b7c0bd9509daf94f36c51256",
"index": 6726,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n app.run(host='0.0.0.0', port=5001)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef main():\n app.run(host='0.0.0.0', port=5001)\n\n\nif __name__ == '__mai... | [
0,
1,
2,
3
] |
#########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | normal | {
"blob_id": "eed3ec2897d4da20b576cb4e2ce95331ae223f76",
"index": 7938,
"step-1": "<mask token>\n\n\nclass AgentInstallerLocalTest(BaseDaemonLiveTestCase):\n <mask token>\n\n @classmethod\n def setUpClass(cls):\n cls.logger = setup_logger(cls.__name__)\n cls.source_url = get_source_uri()\n ... | [
4,
6,
8,
10,
11
] |
import gym
import os
import sys
import numpy as np
import theano
import theano.tensor as T
import matplotlib.pyplot as plt
from gym import wrappers
from datetime import datetime
from mountain_car_v1_q_learning import Transformer
# so you can test different architectures
class Layer:
def __init__(self, m1, m2, f=... | normal | {
"blob_id": "63ee25791177ead5389c14990ce6da3e2c11b683",
"index": 6356,
"step-1": "<mask token>\n\n\nclass Layer:\n\n def __init__(self, m1, m2, f=T.nnet.relu, use_bias=True, zeros=False):\n if zeros:\n w = np.zeros((m1, m2))\n else:\n w = np.random.randn(m1, m2) * np.sqrt(2... | [
9,
11,
12,
13,
17
] |
#This models.py is under UserRegApp1 folder
from django.db import models
# Create your models here.
class UserRegModel(models.Model):
username = models.CharField(max_length=15)
emailid = models.EmailField()
password1= models.CharField(max_length=6)
password2= models.CharField(max_length=6)
mailse... | normal | {
"blob_id": "d0653dac8e7c8162070ed9fd191f7fb318f47c60",
"index": 1719,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass UserRegModel(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass UserRegModel(model... | [
0,
1,
2,
3,
4
] |
"""Command generator for running a script against a BigQuery cluster.
Contains the method to compile the BigQuery specific script execution command
based on generic arguments (sql script, output destination) and BigQuery
specific arguments (flag values).
"""
__author__ = 'p3rf@google.com'
from absl import flags
fla... | normal | {
"blob_id": "5e14eeaa3c79bfdd564f3bfd1575c9bbf1a3773d",
"index": 7881,
"step-1": "<mask token>\n\n\ndef generate_provider_specific_cmd_list(script, driver, output, error):\n \"\"\"Method to compile the BigQuery specific script execution command.\n\n Arguments:\n script: SQL script which contains the query... | [
1,
2,
3,
4,
5
] |
import cv2
import numpy as np
kernel = np.ones((3, 3), np.uint8)
def mask(image):
# define region of interest
green_frame = image[50:350, 50:350]
cv2.rectangle(image, (50, 50), (350, 350), (0, 255, 0), 0)
hsv = cv2.cvtColor(green_frame, cv2.COLOR_BGR2HSV)
# define range of skin color in HSV
lowe... | normal | {
"blob_id": "2286aa1581ca7d6282b35847505a904980da275e",
"index": 8659,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef mask(image):\n green_frame = image[50:350, 50:350]\n cv2.rectangle(image, (50, 50), (350, 350), (0, 255, 0), 0)\n hsv = cv2.cvtColor(green_frame, cv2.COLOR_BGR2HSV)\n ... | [
0,
1,
2,
3,
4
] |
from rest_framework import viewsets, mixins
from .models import Comment, Post
from .serializer import CommentSerializer, PostSerializer, AllCommentSerializer
class PostViewSet(viewsets.ModelViewSet):
serializer_class = PostSerializer
queryset = Post.objects.all()
class CommentViewSet(viewsets.GenericViewSet... | normal | {
"blob_id": "9bc13c608c079cbf23ed04f29edd1fd836214cde",
"index": 282,
"step-1": "<mask token>\n\n\nclass CommentViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins\n .RetrieveModelMixin):\n queryset = Comment.objects.all()\n\n def get_serializer_class(self):\n if self.action == 'retrie... | [
3,
4,
5,
6
] |
n=int(input("Digite um número"))
m=n-1
o=n+1
print("Seu número é {} seu antecessor é {} e seu sucessor é {}".format(n,m,o)) | normal | {
"blob_id": "47d72379b894826dad335f098649702ade195f78",
"index": 7337,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o)\n )\n",
"step-3": "n = int(input('Digite um número'))\nm = n - 1\no = n + 1\nprint('Seu número é {} se... | [
0,
1,
2,
3
] |
#! /bin/env python3
"""
Lane Emden Python interface.
Main routine:
lane_emden_int(dz, n)
"""
import numpy as np
from . import _solver
def test():
"""
A simple test.
"""
n = 3.
dz = 2.**(-14)
_solver.lane(dz,n)
out = _solver.laneout
n = out.ndata
t = out.theta
return t,n
d... | normal | {
"blob_id": "10723f703f40b5db2b7c9532cda520b2ae078546",
"index": 2175,
"step-1": "<mask token>\n\n\ndef lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):\n \"\"\"\n Interface to FORTRAN90 Lane-Emden Integrator.\n\n Call:\n ndata, data = laneemden.lane_emden_int(dz, n, w)\n\n INPUT:\n dz:\n ... | [
2,
3,
4,
5,
6
] |
from flask import Flask
app=Flask('__name__')
@app.route("/my/<name>/<age>")
def my(name,age):
name ="saral"
age="20"
return "my name is {} and age is {}".format(name,age) | normal | {
"blob_id": "3817770a80f8ab16322485522be18edd6b3f5516",
"index": 179,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@app.route('/my/<name>/<age>')\ndef my(name, age):\n name = 'saral'\n age = '20'\n return 'my name is {} and age is {}'.format(name, age)\n",
"step-3": "<mask token>\napp = ... | [
0,
1,
2,
3,
4
] |
include('f469-disco/manifest_f469.py')
freeze('src')
| normal | {
"blob_id": "3b29912788fa4cc76f34f52da7728e934ee96637",
"index": 7117,
"step-1": "<mask token>\n",
"step-2": "include('f469-disco/manifest_f469.py')\nfreeze('src')\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .tasks import read_all_models, update_a_model, delete_a_model, read_a_model, create_a_model
from .forms import MyModelForm
def home(request):
content = read_all_models()
sorted_list = sorted(content, key=lambda k: k['title'].title... | normal | {
"blob_id": "dc4de382ab16f036c6174e711f5c9fe52868ccc9",
"index": 8445,
"step-1": "<mask token>\n\n\ndef delete(request, pk):\n if delete_a_model(pk):\n return redirect('myapp:home')\n else:\n return HttpResponse('Error Occured')\n\n\ndef search(request):\n if request.method == 'POST':\n ... | [
2,
4,
5,
6,
7
] |
import requests
import json
import io
import sys
names = ['abc-news', 'abc-news-au', 'aftenposten','al-jazeera-english','ars-technica','associated-press','australian-financial-review','axios', 'bbc-news', 'bbc-sport','bleacher-report', 'bloomberg','breitbart-news','business-insider', 'business-insider-uk','buzzfeed','... | normal | {
"blob_id": "590baf17d9fdad9f52869fa354112d3aa5f7d5f0",
"index": 8943,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('[')\nsys.stdout.close()\nfor name in names:\n url = ('https://newsapi.org/v2/everything?sources=' + name +\n '&pageSize=100&language=en&from=2018-04-01&to=2018-04-01&apiK... | [
0,
1,
2,
3,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.