index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
3,800
781ce153d5053078ee11cecc13d055a67999a651
# -*- coding: utf-8 -*- from flask import jsonify from flask.views import MethodView class Users(MethodView): def get(self): return jsonify( { 'status': 'OK', 'users': [ {'name': 'Pepe', 'age': 35, 'ocupation': "Engineer"}, ...
[ "# -*- coding: utf-8 -*-\nfrom flask import jsonify\nfrom flask.views import MethodView\n\n\nclass Users(MethodView):\n\n def get(self):\n return jsonify(\n {\n 'status': 'OK',\n 'users': [\n {'name': 'Pepe', 'age': 35, 'ocupation': \"Engineer\"}...
false
3,801
50c7ce95f17cbd40a753d16d9f9fab349ad4f4ce
""" 100 4 200 1 3 2 100 4 200 1 3 2 6:35 """ class Solution: def longestConsecutive(self, nums: List[int]) -> int: numset = set(nums) ans = 0 # visited = set(nums) maxnum = float('-inf') if not nums: return 0 for n in numset: ...
[ "\"\"\"\n 100 4 200 1 3 2\n100 \n4\n200\n1\n3\n2\n\n6:35\n\"\"\"\n\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n numset = set(nums)\n ans = 0\n # visited = set(nums)\n maxnum = float('-inf')\n \n if not nums: \n return 0\n ...
false
3,802
15eed401728e07bfe9299edd12add43ad8b9cb71
# -*- coding: utf-8 -*- import luigi from luigi import * #from luigi import Task import pandas as pd from pset.tasks.embeddings.load_embeding import EmbedStudentData from pset.tasks.data.load_dataset import HashedStudentData import numpy as npy import pickle import os class NearestStudents(Task): github_id = Par...
[ "# -*- coding: utf-8 -*-\n\nimport luigi\nfrom luigi import *\n#from luigi import Task\nimport pandas as pd\nfrom pset.tasks.embeddings.load_embeding import EmbedStudentData\nfrom pset.tasks.data.load_dataset import HashedStudentData\nimport numpy as npy\nimport pickle\nimport os\n\nclass NearestStudents(Task):\n\n...
false
3,803
b713e38824db13f919484b071fb35afb29e26baa
import os,sys parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,parentdir) import xmind from xmind.core.markerref import MarkerId xmind_name="数据结构" w = xmind.load(os.path.dirname(os.path.abspath(__file__))+"\\"+xmind_name+".xmind") s2=w.createSheet() s2.setTitle("二叉树——递归套路")...
[ "import os,sys \nparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) \nsys.path.insert(0,parentdir) \n\nimport xmind\nfrom xmind.core.markerref import MarkerId\nxmind_name=\"数据结构\"\nw = xmind.load(os.path.dirname(os.path.abspath(__file__))+\"\\\\\"+xmind_name+\".xmind\") \ns2=w.createSheet()\ns2...
false
3,804
9f479ad2acf4f6deb0ca4db606c3d804979c10bd
from rllab.algos.trpo import TRPO from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline from rllab.envs.gym_env import GymEnv from rllab.envs.normalized_env import normalize from rllab.misc.instrument import run_experiment_lite from rllab.policies.gaussian_mlp_policy import GaussianMLPPolicy from rl...
[ "from rllab.algos.trpo import TRPO\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.envs.gym_env import GymEnv\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import run_experiment_lite\nfrom rllab.policies.gaussian_mlp_policy import GaussianMLPPoli...
false
3,805
e807cef534226f3efb4a8df471598727fa068f02
# -*- python -*- # ex: set syntax=python: # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # See master.experimental/slaves.cfg for documentation. slaves = [ #########################################...
[ "# -*- python -*-\n# ex: set syntax=python:\n\n# Copyright (c) 2012 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n# See master.experimental/slaves.cfg for documentation.\n\n\nslaves = [\n#########################...
false
3,806
f561846c943013629e417d16f4dae77df43b25c4
from flask_sqlalchemy import SQLAlchemy from flask_security import UserMixin, RoleMixin db = SQLAlchemy() roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): ...
[ "from flask_sqlalchemy import SQLAlchemy\nfrom flask_security import UserMixin, RoleMixin\n\ndb = SQLAlchemy()\n\nroles_users = db.Table('roles_users',\n db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),\n db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))\n\nclass Role(db.Model...
false
3,807
a4697f0a0d0cc264b28a58bcc28528c221b4cb49
import os import datetime from classifier import Classification class PersistableClassificationModel(Classification): """ Classification classifier with ability to persist trained classifier on the disk. """ def __init__(self, output_dir, origin): self.originModel = origin if not os...
[ "import os\nimport datetime\n\nfrom classifier import Classification\n\n\nclass PersistableClassificationModel(Classification):\n\n \"\"\"\n Classification classifier with ability to persist trained classifier on the disk.\n \"\"\"\n def __init__(self, output_dir, origin):\n self.originModel = or...
false
3,808
167c36627c7c3377266bde266e610792ba29b3e4
import re #lines = open("input.1").read() lines = open("input.2").read() lines = lines.splitlines() moves = {} moves["nw"] = [-1, -1] moves["ne"] = [ 0, -1] moves["w"] = [-1, 0] moves["e"] = [ 1, 0] moves["sw"] = [ 0, 1] moves["se"] = [ 1, 1] tiles = {} def fliptile(tile): if tile == "B": tile = "...
[ "import re\n\n#lines = open(\"input.1\").read()\nlines = open(\"input.2\").read()\nlines = lines.splitlines()\n\nmoves = {}\nmoves[\"nw\"] = [-1, -1]\nmoves[\"ne\"] = [ 0, -1]\nmoves[\"w\"] = [-1, 0]\nmoves[\"e\"] = [ 1, 0]\nmoves[\"sw\"] = [ 0, 1]\nmoves[\"se\"] = [ 1, 1]\n\ntiles = {}\n\ndef fliptile(tile):...
true
3,809
1a8c9be389aad37a36630a962c20a0a36c449bdd
def func(i): if(i % 2 != 0): return False visited = [0,0,0,0,0,0,0,0,0,0] temp = i while(i): x = i%10 if (visited[x] == 1) or (x == 0): break visited[x] = 1; i = (int)(i / 10); if(i == 0): for y in str(temp): if(temp % int(y) != 0): return False else: return False...
[ "def func(i):\r\n if(i % 2 != 0): return False\r\n visited = [0,0,0,0,0,0,0,0,0,0]\r\n temp = i\r\n while(i):\r\n x = i%10\r\n if (visited[x] == 1) or (x == 0): break\r\n visited[x] = 1; \r\n i = (int)(i / 10); \r\n\r\n if(i == 0):\r\n for y in str(temp):\r\n if(temp % int(y) != 0): return ...
false
3,810
dae8529aa58f1451d5acdd6607543c202c3c0c66
#### #Some more on variables #### #Variables are easily redefined. #Let's start simple. x=2 #x is going to start at 2 print (x) x=54 #we are redefining x to equal 54 print (x) x= "Cheese" #x is now the string 'cheese' print (x) #Try running this program to see x #printed at each point #Clearly variables can be...
[ "####\n#Some more on variables\n####\n\n#Variables are easily redefined. \n\n#Let's start simple.\n\nx=2 #x is going to start at 2\nprint (x) \nx=54 #we are redefining x to equal 54\nprint (x) \nx= \"Cheese\" #x is now the string 'cheese'\nprint (x)\n#Try running this program to see x \n#printed at each point\n\n#...
false
3,811
ae6cbb181e024b8c0b222d14120b910919f8cc81
"""Restaurant""" def main(): """Restaurant""" moeny = int(input()) service = moeny*0.1 vat = moeny*0.07 print("Service Charge : %.2f Baht" %service) print("VAT : %.2f Baht" %vat) print("Total : %.2f Baht" %(moeny+vat+service)) main()
[ "\"\"\"Restaurant\"\"\"\ndef main():\n \"\"\"Restaurant\"\"\"\n moeny = int(input())\n service = moeny*0.1\n vat = moeny*0.07\n print(\"Service Charge : %.2f Baht\" %service)\n print(\"VAT : %.2f Baht\" %vat)\n print(\"Total : %.2f Baht\" %(moeny+vat+service))\nmain()\n", "<docstring token>\n...
false
3,812
e15524d7ae87cbf0b10c54ee0bdc613ba589c1a9
from Cars import Bmw from Cars import Audi from Cars import Nissan # Press the green button in the gutter to run the script. if __name__ == '__main__': print('In Sample.py........') # Import classes from your brand new package # Create an object of Bmw class & call its method ModBMW = Bmw.Bmw() ...
[ "from Cars import Bmw\nfrom Cars import Audi\nfrom Cars import Nissan\n\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n print('In Sample.py........')\n\n # Import classes from your brand new package\n\n # Create an object of Bmw class & call its method\n ModB...
false
3,813
9081d0f75ac53ab8d0bafb39cd46a2fec8a5135f
from django import forms from .models import Profile class ImageForm(forms.ModelForm): userimage = forms.ImageField(required=False, error_messages={'invalid':("Image file only")}, widget=forms.FileInput) class Meta: model = Profile fields = ['userimage',]
[ "from django import forms\nfrom .models import Profile\n\n\n\n\n \nclass ImageForm(forms.ModelForm):\n userimage = forms.ImageField(required=False, error_messages={'invalid':(\"Image file only\")}, widget=forms.FileInput)\n class Meta:\n model = Profile\n fields = ['userimage',]\n\n\n", "fro...
false
3,814
9725c4bfea1215e2fb81c31cbb8948fd1656aca9
from airbot import resolvers from airbot import utils import unittest from grapher import App import pprint OPENID_CONFIG = { 'ISSUER_URL': 'https://dev-545796.oktapreview.com', 'CLIENT_ID': '0oafvba1nlTwOqPN40h7', 'REDIRECT_URI': 'http://locahost/implicit/callback' } class TestEndToEnd(unittest.TestCas...
[ "from airbot import resolvers\nfrom airbot import utils\nimport unittest\nfrom grapher import App\nimport pprint\n\n\nOPENID_CONFIG = {\n 'ISSUER_URL': 'https://dev-545796.oktapreview.com',\n 'CLIENT_ID': '0oafvba1nlTwOqPN40h7',\n 'REDIRECT_URI': 'http://locahost/implicit/callback'\n}\n\n\nclass TestEndToE...
true
3,815
aea92827753e12d2dc95d63ddd0fe4eb8ced5d14
#!/usr/bin/env python # coding: utf-8 # In[2]: from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU'))) # In[1]: import numpy as np import pandas as pd import matplotlib.pypl...
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nprint(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd...
false
3,816
e03290746d6520fde63836e917f6af0c76596704
# find the 12-digit number formed by concatenating a series of 3 4-digit # numbers who are permutations of each other and are all prime from itertools import permutations, dropwhile from pe_utils import prime_sieve prime_set = set(prime_sieve(10000)) def perm(n, inc): perm_set = set(map(lambda x: int("".join(x))...
[ "# find the 12-digit number formed by concatenating a series of 3 4-digit\n# numbers who are permutations of each other and are all prime\n\nfrom itertools import permutations, dropwhile\nfrom pe_utils import prime_sieve\n\nprime_set = set(prime_sieve(10000))\n\ndef perm(n, inc):\n perm_set = set(map(lambda x: i...
false
3,817
8ce2e9cd9ceed6c79a85682b8bc03a3ffb5131c4
""" This module provides an optimizer class that is based on an evolution strategy algorithm. """ import copy, random, math from time import time from xml.dom import minidom from extra.schedule import Schedule from extra.printer import pprint, BLUE class Optimizer(object): """ This class is the implementation of the...
[ "\"\"\"\nThis module provides an optimizer class that is based on an evolution\nstrategy algorithm.\n\"\"\"\nimport copy, random, math\nfrom time import time\nfrom xml.dom import minidom\nfrom extra.schedule import Schedule\nfrom extra.printer import pprint, BLUE\n\nclass Optimizer(object):\n\t\"\"\"\n\tThis class ...
false
3,818
f379092cefe83a0a449789fbc09af490081b00a4
from igbot import InstaBot from settings import username, pw from sys import argv def execute_script(InstaBot): InstaBot.get_unfollowers() #InstaBot.unfollow() #InstaBot.follow() #InstaBot.remove_followers() def isheadless(): if len(argv) > 1: if argv[1] == 'head': return False else: raise ValueError("...
[ "from igbot import InstaBot\nfrom settings import username, pw\nfrom sys import argv\n\ndef execute_script(InstaBot):\n\tInstaBot.get_unfollowers()\n\t#InstaBot.unfollow()\n\t#InstaBot.follow()\n\t#InstaBot.remove_followers()\n\ndef isheadless():\n\tif len(argv) > 1:\n\t\tif argv[1] == 'head':\n\t\t\treturn False\n...
false
3,819
2b8b502381e35ef8e56bc150114a8a4831782c5a
class Solution(object): def maxDistToClosest(self, seats): """ :type seats: List[int] :rtype: int """ start = 0 end = 0 length = len(seats) max_distance = 0 for i in range(len(seats)): seat = seats[i] if seat ==...
[ "class Solution(object):\n def maxDistToClosest(self, seats):\n \"\"\"\n :type seats: List[int]\n :rtype: int\n \"\"\"\n start = 0\n end = 0\n length = len(seats)\n max_distance = 0\n \n for i in range(len(seats)):\n seat = seats[i]...
false
3,820
a5559ff22776dee133f5398bae573f515efb8484
# MINISTを読み込んでレイヤーAPIでCNNを構築するファイル import tensorflow as tf import numpy as np import os import tensorflow as tf import glob import numpy as np import config as cf from data_loader import DataLoader from PIL import Image from matplotlib import pylab as plt dl = DataLoader(phase='Train', shuffle=True) X...
[ "# MINISTを読み込んでレイヤーAPIでCNNを構築するファイル\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport os\r\n\r\nimport tensorflow as tf\r\nimport glob\r\nimport numpy as np\r\n\r\nimport config as cf\r\nfrom data_loader import DataLoader\r\nfrom PIL import Image\r\nfrom matplotlib import pylab as plt\r\n\r\ndl = DataLoade...
false
3,821
3acbb37809462ee69ff8792b4ad86b31dba5d630
#!/usr/bin/env python2.7 from __future__ import print_function, division import numpy as np import matplotlib import os #checks if there is a display to use. if os.environ.get('DISPLAY') is None: matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors as clr import dtk import sys import ti...
[ "#!/usr/bin/env python2.7\n\nfrom __future__ import print_function, division \nimport numpy as np\nimport matplotlib\nimport os\n#checks if there is a display to use.\nif os.environ.get('DISPLAY') is None:\n matplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as clr\nimport dtk\nim...
false
3,822
2ba5cb1265090b42b9a4838b792a3e81b209ba1a
import unittest import A1 import part_manager import security class test_A1(unittest.TestCase): # ----------------------------------- set up the mock data for test cases ----------------------------------- def setUp(self): self.security1 = security.Security("XXX-1234-ABCD-1234", None) self...
[ "import unittest\nimport A1\nimport part_manager\nimport security\n\n\nclass test_A1(unittest.TestCase):\n \n# ----------------------------------- set up the mock data for test cases ----------------------------------- \n def setUp(self):\n self.security1 = security.Security(\"XXX-1234-ABCD-1234\", N...
false
3,823
726aaa0ef129f950e6da6701bb20e893d2f7373b
import os import numpy as np from argparse import ArgumentParser from tqdm import tqdm from models.networks import Perceptron from data.perceptron_dataset import Dataset, batchify from utils.utils import L1Loss, plot_line from modules.perceptron_trainer import Trainer if __name__ == '__main__': parser = Argumen...
[ "import os\nimport numpy as np\nfrom argparse import ArgumentParser\nfrom tqdm import tqdm\n\nfrom models.networks import Perceptron\nfrom data.perceptron_dataset import Dataset, batchify\nfrom utils.utils import L1Loss, plot_line\nfrom modules.perceptron_trainer import Trainer\n\n\nif __name__ == '__main__':\n ...
false
3,824
65d08fe1a3f6e5cc2458209706307513d808bdb2
#!/usr/bin/env python import os import sys #from io import open import googleapiclient.errors import oauth2client from googleapiclient.errors import HttpError from . import auth from . import lib debug = lib.debug # modified start def get_youtube_handler(): """Return the API Youtube object.""" ...
[ "#!/usr/bin/env python\n\n\nimport os\nimport sys\n#from io import open\n\nimport googleapiclient.errors\nimport oauth2client\nfrom googleapiclient.errors import HttpError\n\nfrom . import auth\nfrom . import lib\n\n\ndebug = lib.debug\n\n\n# modified start \ndef get_youtube_handler():\n \"\"\"Return the...
false
3,825
7531480f629c1b3d28210afac4ef84b06edcd420
# coding=utf-8 # __author__ = 'lyl' import json import csv import sys reload(sys) sys.setdefaultencoding('utf-8') def read_json(filename): """ 读取json格式的文件 :param filename: json文件的文件名 :return: [{}, {}, {}, {}, {},{} ......] """ return json.loads(open(filename).read()) def...
[ "# coding=utf-8\r\n# __author__ = 'lyl'\r\n\r\nimport json\r\nimport csv\r\n\r\nimport sys\r\nreload(sys)\r\nsys.setdefaultencoding('utf-8')\r\n\r\n\r\ndef read_json(filename):\r\n \"\"\"\r\n 读取json格式的文件\r\n :param filename: json文件的文件名\r\n :return: [{}, {}, {}, {}, {},{} ......]\r\n \"\"\"\r\n re...
false
3,826
68c9944c788b9976660384e5d1cd0a736c4cd0e6
import drawSvg import noise import random import math import numpy as np sizex = 950 sizey = 500 noisescale = 400 persistence = 0.5 lacunarity = 2 seed = random.randint(0, 100) actorsnum = 1000 stepsnum = 50 steplenght = 2 noisemap = np.zeros((sizex, sizey)) for i in range(sizex): for j in range(sizey): n...
[ "import drawSvg\nimport noise\nimport random\nimport math\nimport numpy as np\n\nsizex = 950\nsizey = 500\nnoisescale = 400\npersistence = 0.5\nlacunarity = 2\nseed = random.randint(0, 100)\nactorsnum = 1000\nstepsnum = 50\nsteplenght = 2\nnoisemap = np.zeros((sizex, sizey))\n\nfor i in range(sizex):\n for j in ...
false
3,827
d71ffd022d87aa547b2a379f4c92d767b91212fd
from channels.db import database_sync_to_async from django.db.models import Q from rest_framework.generics import get_object_or_404 from main.models import UserClient from main.services import MainService from .models import Message, RoomGroup, UsersRoomGroup class AsyncChatService: @staticmethod @database_s...
[ "from channels.db import database_sync_to_async\nfrom django.db.models import Q\nfrom rest_framework.generics import get_object_or_404\n\nfrom main.models import UserClient\nfrom main.services import MainService\nfrom .models import Message, RoomGroup, UsersRoomGroup\n\n\nclass AsyncChatService:\n @staticmethod\...
false
3,828
08ed57ffb7a83973059d62f686f77b1bea136fbd
from flask import Flask, request, render_template, redirect from stories import Story, stories # from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) # app.config['SECRET_KEY'] = "secret" # debug = DebugToolbarExtension(app) # my original approach involved using a global story variable to sto...
[ "from flask import Flask, request, render_template, redirect\nfrom stories import Story, stories\n# from flask_debugtoolbar import DebugToolbarExtension\n\napp = Flask(__name__)\t\n# app.config['SECRET_KEY'] = \"secret\"\n\n# debug = DebugToolbarExtension(app)\n\n\n# my original approach involved using a global sto...
false
3,829
6336b31e51f0565c6b34ab5148645748fe899541
import copy import pandas as pd import numpy as np from pandas import DataFrame from collections import Counter from sklearn.metrics import roc_auc_score, roc_curve from statsmodels.stats.outliers_influence import variance_inflation_factor class Get_res_DataFrame: ''' sheet1:数据概况 sheet2:变量的大小,效果,相关性 ok ...
[ "import copy\nimport pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\nfrom collections import Counter\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\n\nclass Get_res_DataFrame:\n '''\n sheet1:数据概况\n sheet2:变量的...
false
3,830
85e5bf57f7eba2cbee0fbb8a4d37b5180208f9b7
# -*- coding: utf-8 -*- from odoo import fields, models class LunchWizard(models.TransientModel): _name = "lunch.wizard" _description = "LunchWizard" lun_type = fields.Char(string="Set New Lunch Type") lunch_id = fields.Many2one('lunch.lunch', string="Lunch Id") def action_process_lunch(self):...
[ "# -*- coding: utf-8 -*-\n\n\nfrom odoo import fields, models\n\n\nclass LunchWizard(models.TransientModel):\n _name = \"lunch.wizard\"\n _description = \"LunchWizard\"\n\n lun_type = fields.Char(string=\"Set New Lunch Type\")\n lunch_id = fields.Many2one('lunch.lunch', string=\"Lunch Id\")\n\n def a...
false
3,831
53eb1dcd54ce43d9844c48eb1d79f122a87dca39
from selenium.webdriver import Chrome path=("/Users/karimovrustam/PycharmProjects/01.23.2020_SeleniumAutomation/drivers/chromedriver") driver=Chrome(executable_path=path) driver.maximize_window() driver.get("http://www.toolsqa.com/iframe-practice-page/") # driver.switch_to.frame("iframe2") # When working with few wi...
[ "from selenium.webdriver import Chrome\n\npath=(\"/Users/karimovrustam/PycharmProjects/01.23.2020_SeleniumAutomation/drivers/chromedriver\")\ndriver=Chrome(executable_path=path)\ndriver.maximize_window()\ndriver.get(\"http://www.toolsqa.com/iframe-practice-page/\")\n\n\n# driver.switch_to.frame(\"iframe2\") # When ...
false
3,832
99c12e925850fe7603831df5b159db30508f4515
from coarsegrainparams import * from inva_fcl_stab import * from Eq import * from Dynamics import * from sympy import Matrix,sqrt def construct_param_dict(params,K_RC,K_CP,m_P): """ Construct all the parameters from its relationships with body size and temperature, using the normalizing constants and scaling e...
[ "from coarsegrainparams import *\nfrom inva_fcl_stab import *\nfrom Eq import *\nfrom Dynamics import *\nfrom sympy import Matrix,sqrt\n\ndef construct_param_dict(params,K_RC,K_CP,m_P):\n \"\"\"\n Construct all the parameters from its relationships with body size and temperature, using the normalizing constan...
false
3,833
91eb0ae8e59f24aeefdabd46546bc8fb7a0b6f6c
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.feature_selection import SelectKBest, chi2 from sklearn import metrics, ensemble, linear_model, svm from numpy import log, ones, array, zeros, mean, std, repeat import numpy as np import scipy.sparse as sp import re import csv fro...
[ "from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.feature_selection import SelectKBest, chi2\nfrom sklearn import metrics, ensemble, linear_model, svm\nfrom numpy import log, ones, array, zeros, mean, std, repeat\nimport numpy as np\nimport scipy.sparse as sp\nimport re\nim...
false
3,834
7251d32918b16166e9b7c9613726e6dc51d6fea4
from sqlalchemy import (Column, Integer, Float, String, ForeignKey) from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship from .meta import Base, BaseModel class Stock(Base, BaseModel): __tablename__ = 'stock' name = Column(String(255), nullable=False) starting_price = ...
[ "from sqlalchemy import (Column, Integer, Float, String, ForeignKey)\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.orm import relationship\n\nfrom .meta import Base, BaseModel\n\n\nclass Stock(Base, BaseModel):\n __tablename__ = 'stock'\n\n name = Column(String(255), nullable=False)\n s...
false
3,835
429af603bf8f1c003799c3d94c0ce9a2c2f80dfc
class Solution(object): def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ i = 0 for j in range(1, len(A), 2): if A[j] % 2 == 1: continue else: while i + 2 < len(A) and A[i] % 2 == 0:...
[ "class Solution(object):\n def sortArrayByParityII(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n i = 0\n\n for j in range(1, len(A), 2):\n if A[j] % 2 == 1:\n continue\n else:\n while i + 2 < le...
false
3,836
b07073a7f65dbc10806b68729f21a8bc8773a1ab
#!/usr/bin/env python from math import ceil, floor, sqrt def palindromes(n: int) -> int: """yield successive palindromes starting at n""" # 1 -> 2 -> 3 ... 9 -> 11 -> 22 -> 33 -> 44 .. 99 -> 101 # 101 -> 111 -> 121 -> 131 -> ... -> 191 -> 202 -> 212 # 989 -> 999 -> 1001 -> 1111 -> 1221 # 9889 -> 9...
[ "#!/usr/bin/env python\n\nfrom math import ceil, floor, sqrt\n\ndef palindromes(n: int) -> int:\n \"\"\"yield successive palindromes starting at n\"\"\"\n # 1 -> 2 -> 3 ... 9 -> 11 -> 22 -> 33 -> 44 .. 99 -> 101\n # 101 -> 111 -> 121 -> 131 -> ... -> 191 -> 202 -> 212\n # 989 -> 999 -> 1001 -> 1111 -> 1...
false
3,837
2539411c7b348662dbe9ebf87e26faacc20f4c5e
import numpy as np import math import os if os.getcwd().rfind('share') > 0: topsy = True import matplotlib as mpl mpl.use('Agg') else: topsy = False from matplotlib import rc import matplotlib.pyplot as plt from matplotlib import rc from matplotlib import cm from scipy.optimize import curve_fit import sys import h...
[ "import numpy as np\nimport math\nimport os\nif os.getcwd().rfind('share') > 0:\n\ttopsy = True\n\timport matplotlib as mpl\n\tmpl.use('Agg')\nelse:\n\ttopsy = False\n\tfrom matplotlib import rc\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nfrom matplotlib import cm\nfrom scipy.optimize import curve_...
true
3,838
63a2c8b0c2eba2d5f9f82352196ef2b67d4d63b5
inp = int(input()) print(bytes(inp))
[ "inp = int(input())\n\nprint(bytes(inp))\n", "inp = int(input())\nprint(bytes(inp))\n", "<assignment token>\nprint(bytes(inp))\n", "<assignment token>\n<code token>\n" ]
false
3,839
7bf81954bef81004b6c9838ed00c624d24fcf0c6
# Generated by Django 2.0.3 on 2018-07-05 04:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('application_manager', '0015_auto_20180705_0415'), ] operations = [ migrations.RemoveField( model_name='application', name='u...
[ "# Generated by Django 2.0.3 on 2018-07-05 04:16\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('application_manager', '0015_auto_20180705_0415'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='application',\n...
false
3,840
4d707e23f66e8b6bea05a5901d3d8e459247c6c1
import cv2 import sys # Load the Haar cascades face_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_frontalface_default.xml') eyes_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_eye.xml') capture = cv2.VideoCapture(0) _, image = capture.read() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ...
[ "import cv2\nimport sys\n\n# Load the Haar cascades\nface_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_frontalface_default.xml')\neyes_cascade = cv2.CascadeClassifier('./haar_cascades/haarcascade_eye.xml')\n\ncapture = cv2.VideoCapture(0)\n_, image = capture.read()\ngray = cv2.cvtColor(image, cv2.CO...
false
3,841
791df87235f5da634fc62ebc3a3741cea6e2deca
def summation(numbers): positive_numbers = [] normalized_numbers = [] numbers_list = numbers.split() for idx, arg in enumerate(numbers_list): int_arg = int(arg) if int_arg < 0: new_arg = abs(int_arg) * 2 else: new_arg = int_arg positive_numbers.app...
[ "def summation(numbers):\n positive_numbers = []\n normalized_numbers = []\n numbers_list = numbers.split()\n for idx, arg in enumerate(numbers_list):\n int_arg = int(arg)\n if int_arg < 0:\n new_arg = abs(int_arg) * 2\n else:\n new_arg = int_arg\n posit...
false
3,842
c179d27f1620414061d376d4f30d2ddd4fd2750e
import sys, serial, time, signal, threading from MFRC522 import MFRC522 from event import Event class Sensor(threading.Thread): # main program for reading and processing tags def __init__(self, name): threading.Thread.__init__(self) self.name = name self.continue_reading = False self.tag_reader = MFRC522() ...
[ "import sys, serial, time, signal, threading\nfrom MFRC522 import MFRC522\nfrom event import Event\n\nclass Sensor(threading.Thread):\n\n\t# main program for reading and processing tags\n\tdef __init__(self, name):\n\t\tthreading.Thread.__init__(self)\n\t\tself.name = name\n\t\tself.continue_reading = False\n\t\tse...
true
3,843
bee6ba1db608c1d9c8114f89d4b3abab795a6b86
from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import config import os db = SQLAlchemy() static_file_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static') def create_app(config_name): app = Flask(__name__, static_folder=static_file_dir) app.config.from_object...
[ "from flask import Flask\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom config import config\nimport os\n\ndb = SQLAlchemy()\n\nstatic_file_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static')\n\ndef create_app(config_name):\n app = Flask(__name__, static_folder=static_file_dir)\n app.c...
false
3,844
38abc4bc99f3b15b416c77481818464a6c7f11ef
import mysql.connector from mysql.connector import errorcode DB_NAME = 'PieDB' TABLES = {} # TABLES['pietweets'] = ( # "CREATE TABLE `pietweets` (" # " `id` int NOT NULL AUTO_INCREMENT," # " `tweet_id` bigint NOT NULL," # " `username` varchar(32) NOT NULL," # " `geo_lat` float(53) NOT NULL," # " `geo_lon...
[ "import mysql.connector\nfrom mysql.connector import errorcode\n\nDB_NAME = 'PieDB'\n\nTABLES = {}\n# TABLES['pietweets'] = (\n# \t\"CREATE TABLE `pietweets` (\"\n# \t\" `id` int NOT NULL AUTO_INCREMENT,\"\t\t\n# \t\" `tweet_id` bigint NOT NULL,\"\n# \t\" `username` varchar(32) NOT NULL,\"\n# \t\" `geo_lat` flo...
false
3,845
9f3b7d6dbf57157b5ebd6ad72f46befc94798a5f
def count_words(word): count = 0 count = len(word.split()) return count if __name__ == '__main__': print count_words("Boj is dope")
[ "def count_words(word):\n\tcount = 0\n\tcount = len(word.split())\n\treturn count\n\n\nif __name__ == '__main__':\n\tprint count_words(\"Boj is dope\")\n" ]
true
3,846
d0d86d8b5b276218add6dd11a44d5c3951cc4e14
from django.db.models import Q from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from carga_horaria.models import Profesor, Asignat...
[ "from django.db.models import Q\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\nfrom carga_horaria.models import Profeso...
false
3,847
ad1aa69f92f104ac8b82aca3c0a64ce3de48b36d
# Copyright (c) 2021 Koichi Sakata from pylib_sakata import init as init # uncomment the follows when the file is executed in a Python console. # init.close_all() # init.clear_all() import os import shutil import numpy as np from control import matlab from pylib_sakata import ctrl from pylib_sakata import plot prin...
[ "# Copyright (c) 2021 Koichi Sakata\n\n\nfrom pylib_sakata import init as init\n# uncomment the follows when the file is executed in a Python console.\n# init.close_all()\n# init.clear_all()\n\nimport os\nimport shutil\nimport numpy as np\nfrom control import matlab\nfrom pylib_sakata import ctrl\nfrom pylib_sakata...
false
3,848
599c5c02397f283eb00f7343e65c5cb977442e38
from django import forms from .models import Project from user.models import User from assets.models import Assets class CreateProjectForm(forms.ModelForm): project_name = forms.CharField( label='项目名', widget=forms.TextInput( attrs={"class": "form-control"} ) ) project_...
[ "from django import forms\nfrom .models import Project\nfrom user.models import User\nfrom assets.models import Assets\n\n\nclass CreateProjectForm(forms.ModelForm):\n project_name = forms.CharField(\n label='项目名',\n widget=forms.TextInput(\n attrs={\"class\": \"form-control\"}\n ...
false
3,849
dabc38db6a5c4d97e18be2edc9d4c6203e264741
from django import forms from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import time from page.models import Submit, Assignment class UploadFileForm(forms.ModelForm): class Meta: model = Submit fields = ['email', 'student_no', 'file'] @csrf_exempt def up...
[ "from django import forms\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport time\nfrom page.models import Submit, Assignment\n\n\nclass UploadFileForm(forms.ModelForm):\n class Meta:\n model = Submit\n fields = ['email', 'student_no', 'file']\n\n\n@...
false
3,850
2fd40f4d69223933d53d8ed2abd5f6d3ccd2f509
from django.shortcuts import render from django.views.generic.base import View from .models import Article, Tag, Category from pure_pagination import Paginator, EmptyPage, PageNotAnInteger class ArticleView(View): '''文章详情页''' def get(self, request, article_id): # 文章详情 article = Article.object...
[ "from django.shortcuts import render\nfrom django.views.generic.base import View\nfrom .models import Article, Tag, Category\nfrom pure_pagination import Paginator, EmptyPage, PageNotAnInteger\n\n\nclass ArticleView(View):\n '''文章详情页'''\n\n def get(self, request, article_id):\n # 文章详情\n article ...
false
3,851
5da61b4cd8e4faf135b49396d3b346a219bf73f6
import os from src.model_manager import ModelManager dir_path = os.path.dirname(os.path.realpath(__file__)) config_file = '{}/data/config/config_1.json'.format(dir_path) model_dir = '{}/data/models'.format(dir_path) def test_init(): mm = ModelManager(config_file, model_dir) def test_predict(): pass
[ "import os\n\nfrom src.model_manager import ModelManager\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nconfig_file = '{}/data/config/config_1.json'.format(dir_path)\nmodel_dir = '{}/data/models'.format(dir_path)\n\n\ndef test_init():\n mm = ModelManager(config_file, model_dir)\n\n\ndef test_predict(...
false
3,852
5a2106f5255493d2f6c8cb9e06a2666c8c55ed38
""" Suffix Arrays - Optimized O(n log n) - prefix doubling A suffix is a non-empty substring at the end of the string. A suffix array contains all the sorted suffixes of a string A suffix array provides a space efficient alternative to a suffix tree which itself is a compressed version of a trie. Suffix array can do ...
[ "\"\"\"\nSuffix Arrays - Optimized O(n log n) - prefix doubling\n\nA suffix is a non-empty substring at the end of the string. A suffix array\ncontains all the sorted suffixes of a string\n\nA suffix array provides a space efficient alternative to a suffix tree which\nitself is a compressed version of a trie. Suffi...
false
3,853
44e9fd355bfab3f007c5428e8a5f0930c4011646
from flask import Flask, jsonify, abort, make_response from matchtype import matchtyper from db import db_handle import sys api = Flask(__name__) @api.route('/get/<key_name>', methods=['GET']) def get(key_name): li = db_handle(key_name) if li[1] is None: abort(404) else: result = matchtype...
[ "from flask import Flask, jsonify, abort, make_response\nfrom matchtype import matchtyper\nfrom db import db_handle\nimport sys\n\napi = Flask(__name__)\n\n@api.route('/get/<key_name>', methods=['GET'])\ndef get(key_name):\n li = db_handle(key_name)\n if li[1] is None:\n abort(404)\n else:\n ...
false
3,854
f87d08f3bb6faa237cce8379de3aaaa3270a4a34
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from rasa_core.actions.action import Action from rasa_core.events import SlotSet from rasa_core.dispatcher import Button, Element, Dispatcher import json import pickle class ActionWeather(Action): def na...
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom rasa_core.actions.action import Action\nfrom rasa_core.events import SlotSet\nfrom rasa_core.dispatcher import Button, Element, Dispatcher\nimport json\nimport pickle\n\nclass ActionWeather(Acti...
false
3,855
309090167c2218c89494ce17f7a25bd89320a202
from google.appengine.api import users from google.appengine.ext import ndb from datetime import datetime from datetime import timedelta import os import logging import webapp2 import jinja2 JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2....
[ "from google.appengine.api import users\nfrom google.appengine.ext import ndb\nfrom datetime import datetime\nfrom datetime import timedelta\nimport os\nimport logging\n\nimport webapp2\nimport jinja2\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n ext...
false
3,856
6162911befc8ad37591f7c19b14b349c655ccac0
def generator(factor, modulus=-1, maxx=2147483647): def next(prev): nxt = (prev*factor) % maxx if modulus > 0: while nxt % modulus != 0: nxt = (nxt * factor) % maxx return nxt return next def main(a, b, a_mod=-1, b_mod=-1, N=40000000, a_fact=16807, b_fact=48...
[ "def generator(factor, modulus=-1, maxx=2147483647):\n def next(prev):\n nxt = (prev*factor) % maxx\n if modulus > 0:\n while nxt % modulus != 0:\n nxt = (nxt * factor) % maxx\n return nxt\n return next\n\n\ndef main(a, b, a_mod=-1, b_mod=-1, N=40000000, a_fact=1...
false
3,857
fc9742ceb3c38a5f8c1ad1f030d76103ba0a7a81
# Generated by Django 3.2.7 on 2021-09-23 07:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sms_consumer', '0006_auto_20210923_0733'), ] operations = [ migrations.RemoveField( model_name='smslogmodel', name='hello', ...
[ "# Generated by Django 3.2.7 on 2021-09-23 07:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sms_consumer', '0006_auto_20210923_0733'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='smslogmodel',\n ...
false
3,858
e6c7b15e5b42cfe6c5dec2eaf397b67afd716ebd
myfavoritenumber = 5 print(myfavoritenumber) x=5 x=x+1 print(x) x,y,z=1,2,3 print(x,y,z)
[ "myfavoritenumber = 5\nprint(myfavoritenumber)\nx=5\nx=x+1\nprint(x)\nx,y,z=1,2,3\nprint(x,y,z)\n", "myfavoritenumber = 5\nprint(myfavoritenumber)\nx = 5\nx = x + 1\nprint(x)\nx, y, z = 1, 2, 3\nprint(x, y, z)\n", "<assignment token>\nprint(myfavoritenumber)\n<assignment token>\nprint(x)\n<assignment token>\npr...
false
3,859
03e92eae4edb4bdbe9fa73e39e7d5f7669746fe5
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 ...
[ "from integral_image import calc_integral_image\n\nclass Region:\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n \n def calc_feature(self, cumul_sum):\n yy = self.y + self.height\n xx = self.x + sel...
false
3,860
921c45af3ba34a1b12657bf4189fc8dd66fa44a6
import tensorflow as tf import numpy as np import tensorflow_datasets as tfds print(tf.__version__) imdb, info = tfds.load("imdb_reviews", with_info=True, as_supervised=True) train_data = imdb['train'] test_data = imdb['test'] # 25000 in each set training_sentences = [] training_labels = [] testing_sentences = [] ...
[ "import tensorflow as tf\nimport numpy as np\nimport tensorflow_datasets as tfds\nprint(tf.__version__)\n\n\nimdb, info = tfds.load(\"imdb_reviews\", with_info=True, as_supervised=True)\n\ntrain_data = imdb['train']\ntest_data = imdb['test']\n# 25000 in each set\n\ntraining_sentences = []\ntraining_labels = []\n\nt...
false
3,861
88071df9367804b1c6e2b1c80da178ab7658e7a4
# Copyright (c) 2018, Raul Astudillo import numpy as np from copy import deepcopy class BasicModel(object): """ Class for handling a very simple model that only requires saving the evaluated points (along with their corresponding outputs) so far. """ analytical_gradient_prediction = True def __in...
[ "# Copyright (c) 2018, Raul Astudillo\n\nimport numpy as np\nfrom copy import deepcopy\n\nclass BasicModel(object):\n \"\"\"\n Class for handling a very simple model that only requires saving the evaluated points (along with their corresponding outputs) so far.\n \"\"\"\n analytical_gradient_prediction ...
false
3,862
d0997f5001090dd8925640cd5b0f3eb2e6768113
#!/usr/bin/env python from pymongo import MongoClient import serial import sys, os, datetime os.system('sudo stty -F /dev/ttyS0 1200 sane evenp parenb cs7 -crtscts') SERIAL = '/dev/ttyS0' try: ser = serial.Serial( port=SERIAL, baudrate = 1200, parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ON...
[ "#!/usr/bin/env python\n\n\nfrom pymongo import MongoClient\nimport serial\nimport sys, os, datetime\n\nos.system('sudo stty -F /dev/ttyS0 1200 sane evenp parenb cs7 -crtscts')\n\nSERIAL = '/dev/ttyS0'\ntry:\n ser = serial.Serial(\n port=SERIAL,\n baudrate = 1200,\n parity=serial.PARITY_EVEN,\n stopbit...
true
3,863
f2abb7ea3426e37a10e139d83c33011542e0b3d1
from .menu import menu from .create_portfolio import create_portfolio from .search import search from .list_assets import list_assets from .add_transaction import add_transaction from .stats import stats from .info import info
[ "from .menu import menu\nfrom .create_portfolio import create_portfolio\nfrom .search import search\nfrom .list_assets import list_assets\nfrom .add_transaction import add_transaction\nfrom .stats import stats\nfrom .info import info", "from .menu import menu\nfrom .create_portfolio import create_portfolio\nfrom ...
false
3,864
0402096f215ae600318d17bc70e5e3067b0a176b
from django.core.paginator import Paginator, EmptyPage from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from logging import getLogger from django_redis import get_redis_connection from decimal import Decimal import json from django import http f...
[ "from django.core.paginator import Paginator, EmptyPage\nfrom django.shortcuts import render\nfrom django.views import View\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom logging import getLogger\nfrom django_redis import get_redis_connection\nfrom decimal import Decimal\nimport json\nfrom django ...
false
3,865
62d0818395a6093ebf2c410aaadeb8a0250707ab
# This is a generated file, do not edit from typing import List import pydantic from ..rmf_fleet_msgs.DockParameter import DockParameter class Dock(pydantic.BaseModel): fleet_name: str = "" # string params: List[DockParameter] = [] # rmf_fleet_msgs/DockParameter class Config: orm_mode = True...
[ "# This is a generated file, do not edit\n\nfrom typing import List\n\nimport pydantic\n\nfrom ..rmf_fleet_msgs.DockParameter import DockParameter\n\n\nclass Dock(pydantic.BaseModel):\n fleet_name: str = \"\" # string\n params: List[DockParameter] = [] # rmf_fleet_msgs/DockParameter\n\n class Config:\n ...
false
3,866
47cee0c659976a2b74e2bb07f6c4d622ceab7362
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
[ "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); y...
false
3,867
3b4799f43ec497978bea3ac7ecf8c6aaeb2180b4
# coding: utf8 from __future__ import absolute_import import numpy as np def arr2str(arr, sep=", ", fmt="{}"): """ Make a string from a list seperated by ``sep`` and each item formatted with ``fmt``. """ return sep.join([fmt.format(v) for v in arr]) def indent_wrap(s, indent=0, wrap=80): "...
[ "# coding: utf8\n\nfrom __future__ import absolute_import\n\nimport numpy as np\n\n\ndef arr2str(arr, sep=\", \", fmt=\"{}\"):\n \"\"\"\n Make a string from a list seperated by ``sep`` and each item formatted\n with ``fmt``.\n \"\"\"\n return sep.join([fmt.format(v) for v in arr])\n\n\ndef indent_wra...
false
3,868
4c3a27bf1f7e617f4b85dc2b59efa184751b69ac
import os from redis import Redis try: if os.environ.get('DEBUG'): import settings_local as settings else: import settings_prod as settings except ImportError: import settings redis_env = os.environ.get('REDISTOGO_URL') if redis_env: redis = Redis.from_url(redis_env) elif getattr(se...
[ "import os\n\nfrom redis import Redis\n\ntry:\n if os.environ.get('DEBUG'):\n import settings_local as settings\n else:\n import settings_prod as settings\nexcept ImportError:\n import settings\n\n\nredis_env = os.environ.get('REDISTOGO_URL')\n\nif redis_env:\n redis = Redis.from_url(redis...
false
3,869
0588aad1536a81d047a2a2b91f83fdde4d1be974
from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), path('about/', views.about, name='about'), path('contact/', views.contact, name= 'contact'), path('category/', views.category, name='category'), path('product/<str:id>/<slug:slug>',views.product...
[ "from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.index, name = 'index'),\n path('about/', views.about, name='about'),\n path('contact/', views.contact, name= 'contact'),\n path('category/', views.category, name='category'),\n path('product/<str:id>/<slug:slug>'...
false
3,870
bd2a5c2dd3eef5979c87a488fb584dce740ccb05
import io import os import sys import whwn from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand here = os.path.abspath(os.path.dirname(__file__)) with open('README.md') as readme: long_description = readme.read() with open('requirements.txt') as reqs: install_re...
[ "import io\nimport os\nimport sys\nimport whwn\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test as TestCommand\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nwith open('README.md') as readme:\n long_description = readme.read()\n\nwith open('requirements.txt') as req...
false
3,871
e5e460eb704e2ab5f747d1beee05e012ea95fbd2
class UnknownResponseFormat(Exception): pass
[ "class UnknownResponseFormat(Exception):\n pass\n", "<class token>\n" ]
false
3,872
283b93437072f0fd75d75dab733ecab05dc9e1f3
#!/usr/bin/env python3 import logging import datetime import os import time import json import prod import secret from logging.handlers import RotatingFileHandler import requests import sns from kafka import KafkaProducer logger = logging.getLogger() logger.setLevel('INFO') log_path = os.path.basename(__file__).split...
[ "#!/usr/bin/env python3\nimport logging\nimport datetime\nimport os\nimport time\nimport json\n\nimport prod\nimport secret\nfrom logging.handlers import RotatingFileHandler\nimport requests\nimport sns\nfrom kafka import KafkaProducer\n\nlogger = logging.getLogger()\nlogger.setLevel('INFO')\nlog_path = os.path.bas...
false
3,873
d90aeaaa682b371afb4771ecfbf1077fc12520b4
from django.contrib import admin # Register your models here. from django.contrib import admin from practice_app.models import Person class PersonAdmin(admin.ModelAdmin): pass admin.site.register(Person)
[ "from django.contrib import admin\n\n# Register your models here.\nfrom django.contrib import admin\nfrom practice_app.models import Person\n\n\nclass PersonAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(Person)", "from django.contrib import admin\nfrom django.contrib import admin\nfrom practice_app.mo...
false
3,874
2ae953d1d53c47da10ea4c8aace186eba0708ad0
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np import pylab as pb from .. import kern from ..core import model from ..util.linalg import pdinv,mdot from ..util.plot import gpplot,x_frame1D,x_frame2D, Tango from ..likelihoods import E...
[ "# Copyright (c) 2012, GPy authors (see AUTHORS.txt).\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\n\nimport numpy as np\nimport pylab as pb\nfrom .. import kern\nfrom ..core import model\nfrom ..util.linalg import pdinv,mdot\nfrom ..util.plot import gpplot,x_frame1D,x_frame2D, Tango\nfrom ..likel...
true
3,875
55a392d63838cbef027f9cf525999c41416e3575
import torch from torch import nn from torch.nn import functional as F from models.blocks import UnetConv3, MultiAttentionBlock, UnetGridGatingSignal3, UnetUp3_CT, UnetDsv3 class AttentionGatedUnet3D(nn.Module): """ Attention Gated Unet for 3D semantic segmentation. Args: config: Mus...
[ "import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom models.blocks import UnetConv3, MultiAttentionBlock, UnetGridGatingSignal3, UnetUp3_CT, UnetDsv3\n\n\nclass AttentionGatedUnet3D(nn.Module):\n \"\"\"\n Attention Gated Unet for 3D semantic segmentation.\n\n Args:\n ...
false
3,876
bd2c327915c1e133a6e7b7a46290369440d50347
#import fungsi_saya as fs # from fungsi_saya import kalkulator as k # hasil = k(10,5,'+') # print(hasil) from kelas import Siswa siswa_1 = Siswa('Afif', "A.I.", 17, 'XII IPA') siswa_2 = Siswa('Bayu', 'Sudrajat', 20, 'XII IPS') siswa_3 = Siswa('Bayu', 'Sudrajat', 20, 'XII IPS') siswa_4 = Siswa('Bayu', 'Sudrajat', 20,...
[ "#import fungsi_saya as fs\n# from fungsi_saya import kalkulator as k\n\n# hasil = k(10,5,'+')\n# print(hasil)\n\nfrom kelas import Siswa\n\nsiswa_1 = Siswa('Afif', \"A.I.\", 17, 'XII IPA')\nsiswa_2 = Siswa('Bayu', 'Sudrajat', 20, 'XII IPS')\nsiswa_3 = Siswa('Bayu', 'Sudrajat', 20, 'XII IPS')\nsiswa_4 = Siswa('Bayu...
false
3,877
a7f348b258e1d6b02a79c60e4fe54b6d53801f70
# coding=utf-8 """ author: wlc function: 百科检索数据层 """ # 引入外部库 import json import re from bs4 import BeautifulSoup # 引入内部库 from src.util.reptile import * class EncyclopediaDao: @staticmethod def get_key_content (key: str) -> list: """ 获取指定关键字的百科内容检索内容 :param key: :return: """ # 1.参数设置 url = 'https://...
[ "# coding=utf-8\n\n\"\"\"\nauthor: wlc\nfunction: 百科检索数据层\n\"\"\"\n\n# 引入外部库\nimport json\nimport re\nfrom bs4 import BeautifulSoup\n\n# 引入内部库\nfrom src.util.reptile import *\n\n\nclass EncyclopediaDao:\n\t@staticmethod\n\tdef get_key_content (key: str) -> list:\n\t\t\"\"\"\n\t\t获取指定关键字的百科内容检索内容\n\t\t:param key:\n\...
false
3,878
03da813650d56e7ab92885b698d4af3a51176903
import datetime with open('D:\Documents\PythonDocs\ehmatthes-pcc-f555082\chapter_10\programming.txt') as f_obj: lines = f_obj.readlines() m_lines = [] for line in lines: m_line = line.replace('python', 'C#') m_lines.append(m_line) with open('D:\Documents\PythonDocs\ehmatthes-pcc-f555082\chapter_10\prog...
[ "import datetime\n\n\nwith open('D:\\Documents\\PythonDocs\\ehmatthes-pcc-f555082\\chapter_10\\programming.txt') as f_obj:\n lines = f_obj.readlines()\n\nm_lines = []\n\nfor line in lines:\n m_line = line.replace('python', 'C#')\n m_lines.append(m_line)\n\nwith open('D:\\Documents\\PythonDocs\\ehmatthes-pc...
false
3,879
a85d06d72b053b0ef6cb6ec2ba465bfb8975b28e
def sum_numbers(numbers=None): sum = 0 if numbers == None: for number in range(1,101): sum += number return sum for number in numbers: sum += number return sum
[ "def sum_numbers(numbers=None):\n sum = 0\n if numbers == None:\n for number in range(1,101):\n sum += number\n return sum\n\n for number in numbers:\n sum += number\n return sum\n\n\n", "def sum_numbers(numbers=None):\n sum = 0\n if numbers == None:\n for ...
false
3,880
1b645ab0a48b226e26009f76ea49fd3f10f5cc7b
#デフォルト引数の破壊 #以下、破壊的な操作 def sample(x, arg=[]): arg.append(x) return arg print(sample(1)) print(sample(2)) print(sample(3)) #対策・・・デフォルト引数にはイミュータブルなものを使用する def sample(x, arg=None): if arg is None: arg = [] arg.append(x) return arg print(sample(1)) print(sample(2)) pr...
[ "#デフォルト引数の破壊\r\n#以下、破壊的な操作\r\ndef sample(x, arg=[]):\r\n arg.append(x)\r\n return arg\r\n\r\nprint(sample(1))\r\nprint(sample(2))\r\nprint(sample(3))\r\n\r\n#対策・・・デフォルト引数にはイミュータブルなものを使用する\r\ndef sample(x, arg=None):\r\n if arg is None:\r\n arg = []\r\n \r\n arg.append(x)\r\n return arg\r\n\...
false
3,881
d724b4f57cf7683d6b6385bf991ed23a5dd8208f
"""added Trail.Geometry without srid Revision ID: 56afb969b589 Revises: 2cf6c7c1f0d7 Create Date: 2014-12-05 18:13:55.512637 """ # revision identifiers, used by Alembic. revision = '56afb969b589' down_revision = '2cf6c7c1f0d7' from alembic import op import sqlalchemy as sa import flask_admin import geoalchemy2 de...
[ "\"\"\"added Trail.Geometry without srid\n\nRevision ID: 56afb969b589\nRevises: 2cf6c7c1f0d7\nCreate Date: 2014-12-05 18:13:55.512637\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '56afb969b589'\ndown_revision = '2cf6c7c1f0d7'\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport flask_admi...
false
3,882
84e84d9f35702c2572ad5e7daa92a271674986dc
#Coded by J. Prabhath #14th April, 2020 #Released under GNU GPL import numpy as np import matplotlib.pyplot as plt from scipy import signal K = 96 Kp = 1 Td = 1.884 s1 = signal.lti([-1/Td],[0,-2,-4,-6], K) s2 = signal.lti([],[0,-2,-4,-6], K) w,mag1,phase1 = signal.bode(s1) _,mag2,phase2 = signal.bode(s2) plt.xlabel...
[ "#Coded by J. Prabhath\n#14th April, 2020\n#Released under GNU GPL\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import signal\n\nK = 96\nKp = 1\nTd = 1.884\n\ns1 = signal.lti([-1/Td],[0,-2,-4,-6], K)\ns2 = signal.lti([],[0,-2,-4,-6], K)\nw,mag1,phase1 = signal.bode(s1)\n_,mag2,phase2 = signal....
false
3,883
e2948c0ad78ce210b08d65b3e0f75d757e286ad9
# 在写Python爬虫的时候,最麻烦的不是那些海量的静态网站,而是那些通过JavaScript获取数据的站点。Python本身对js的支持就不好,所以就有良心的开发者来做贡献了,这就是Selenium,他本身可以模拟真实的浏览器,浏览器所具有的功能他一个都不拉下,加载js更是小菜了 # https://zhuanlan.zhihu.com/p/27115580 # C:\Users\hedy\AppData\Local\Programs\Python\Python36\Scripts\;C:\Users\hedy\AppData\Local\Programs\Python\Python36\ # pip 换源 # http://...
[ "# 在写Python爬虫的时候,最麻烦的不是那些海量的静态网站,而是那些通过JavaScript获取数据的站点。Python本身对js的支持就不好,所以就有良心的开发者来做贡献了,这就是Selenium,他本身可以模拟真实的浏览器,浏览器所具有的功能他一个都不拉下,加载js更是小菜了\n# https://zhuanlan.zhihu.com/p/27115580\n# C:\\Users\\hedy\\AppData\\Local\\Programs\\Python\\Python36\\Scripts\\;C:\\Users\\hedy\\AppData\\Local\\Programs\\Python\\Python...
false
3,884
7e71c97070285b051b23448c755e3d41b2909dda
class Solution(object): def removeNthFromEnd(self, head, n): dummy = ListNode(-1) dummy.next = head first, second = dummy, dummy for i in range(n): first = first.next while first.next: first = first.next second = second.next second....
[ "class Solution(object):\n def removeNthFromEnd(self, head, n):\n dummy = ListNode(-1)\n dummy.next = head\n first, second = dummy, dummy\n for i in range(n):\n first = first.next\n while first.next:\n first = first.next\n second = second.next\n...
false
3,885
b0a51877b59e14eefdd662bac468e8ce12343e6b
from django.db import models # Create your models here. class Glo_EstadoPlan(models.Model): descripcion_estado = models.CharField(max_length=100) def __str__(self): return '{}'.format(self.descripcion_estado)
[ "from django.db import models\r\n\r\n# Create your models here.\r\nclass Glo_EstadoPlan(models.Model):\r\n descripcion_estado = models.CharField(max_length=100)\r\n\r\n def __str__(self):\r\n return '{}'.format(self.descripcion_estado)", "from django.db import models\n\n\nclass Glo_EstadoPlan(models....
false
3,886
22b9868063d6c5fc3f8b08a6e725fff40f4a1a03
from __future__ import annotations import math from abc import abstractmethod from pytown_core.patterns.behavioral import Command from pytown_core.serializers import IJSONSerializable from .buildings import BuildingProcess, BuildingTransaction from .buildings.factory import BuildingFactory from .check import ( A...
[ "from __future__ import annotations\n\nimport math\nfrom abc import abstractmethod\n\nfrom pytown_core.patterns.behavioral import Command\nfrom pytown_core.serializers import IJSONSerializable\n\nfrom .buildings import BuildingProcess, BuildingTransaction\nfrom .buildings.factory import BuildingFactory\nfrom .check...
false
3,887
cc1b3c3c65e8832316f72cbf48737b21ee4a7799
########################################################################### # This file provides maintenance on the various language files # 1. Create new "xx/cards_xx.json" files that have entries ordered as: # a. the card_tag entries in "cards_db.json" # b. the group_tag entries as found in "cards_db.json" # ...
[ "###########################################################################\n# This file provides maintenance on the various language files\n# 1. Create new \"xx/cards_xx.json\" files that have entries ordered as:\n# a. the card_tag entries in \"cards_db.json\"\n# b. the group_tag entries as found in \"car...
false
3,888
263347d1d445643f9c84e36a8cbb5304581ebaf6
from django.urls import path from django.views.decorators.csrf import csrf_exempt from .views import TestView, index, setup_fraud_detection, verify_testing_works urlpatterns = [ path('test/<str:name>/', index, name='index'), path('ml/setup/', setup_fraud_detection, name='fraud_detection_setup'), path('ml/...
[ "from django.urls import path\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .views import TestView, index, setup_fraud_detection, verify_testing_works\n\nurlpatterns = [\n path('test/<str:name>/', index, name='index'),\n path('ml/setup/', setup_fraud_detection, name='fraud_detection_setup'),\n...
false
3,889
8c458d66ab2f9a1bf1923eecb29c3c89f2808d0b
''' 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...
[ "'''\nwww.autonomous.ai\nPhan Le Son\nplson03@gmail.com\n'''\nimport speech_recognition as sr\nimport pyaudio\nfrom os import listdir\nfrom os import path\nimport time\nimport wave\nimport threading\nimport numpy as np\nimport BF.BeamForming as BF\nimport BF.Parameter as PAR\nimport BF.asr_wer as wer\nimport BF.mic...
false
3,890
606a6e7ecc58ecbb11aa53602599e671514bc537
import torch.utils.data import torch import math from util.helpers import * from collections import defaultdict as ddict class _Collate: def __init__(self, ): pass def collate(self, batch): return torch.squeeze(torch.from_numpy(np.array(batch))) class PR: dataset = None eval_data = N...
[ "import torch.utils.data\nimport torch\nimport math\nfrom util.helpers import *\nfrom collections import defaultdict as ddict\n\nclass _Collate:\n def __init__(self, ):\n pass\n\n def collate(self, batch):\n return torch.squeeze(torch.from_numpy(np.array(batch)))\n\n\nclass PR:\n dataset = No...
false
3,891
d133a07f69d2dadb5559d881b01050abb2a9602b
#!/usr/bin/env python # ! -*- coding: utf-8 -*- ''' @Time : 2020/6/4 16:33 @Author : MaohuaYang @Contact : maohuay@hotmail.com @File : pinganFudan-GUI.py @Software: PyCharm ''' import time import requests import tkinter as tk from login import Ehall def set_win_center(root, curWidth='', curHight=''): """ ...
[ "#!/usr/bin/env python\n# ! -*- coding: utf-8 -*-\n'''\n@Time : 2020/6/4 16:33\n@Author : MaohuaYang\n@Contact : maohuay@hotmail.com\n@File : pinganFudan-GUI.py\n@Software: PyCharm\n'''\n\nimport time\nimport requests\nimport tkinter as tk\nfrom login import Ehall\n\ndef set_win_center(root, curWidth='', cur...
false
3,892
1dab0084666588f61d0f9f95f88f06ed9d884e5b
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'KEY.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_KEY(object): def setupUi(self, KEY): KEY.setObjectName("KEY") ...
[ "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'KEY.ui'\n#\n# Created by: PyQt5 UI code generator 5.11.3\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_KEY(object):\n def setupUi(self, KEY):\n KEY.setOb...
false
3,893
bfd8385e8f4886b91dde59c04785134b9cd6a2b6
# Generated by Django 3.1 on 2020-08-28 14:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api_rest', '0004_auto_20200828_0749'), ] operations = [ migrations.RemoveField( model_name='event', name='user_id', ...
[ "# Generated by Django 3.1 on 2020-08-28 14:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api_rest', '0004_auto_20200828_0749'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='event',\n ...
false
3,894
e4a0f26afe8c78e4abbd85834c96ed5ba84e1f0b
import tensorflow as tf import numpy as np import math import sys import os import numpy as np BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '../utils')) import tf_util # from transform_nets import input_transform_net, feature_transform_net import...
[ "import tensorflow as tf\nimport numpy as np\nimport math\nimport sys\nimport os\nimport numpy as np\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(BASE_DIR, '../utils'))\nimport tf_util\n# from transform_nets import input_transform_net, feature_trans...
false
3,895
c8d27965df83eb3e673b3857ee700a8474826335
#!/usr/bin/python debug = 0 if debug == 1: limit = [8,20] n = 3 p = [[2,10],[10,12],[8,30],[1,5]] #n = 1 # p = [[8,30]] print limit print n print p def isIn(arr): if arr[0] > limit[1] or arr[1] < limit[0] or \ arr[1] == 0: return False else: return True ...
[ "#!/usr/bin/python\n\n\ndebug = 0\n\nif debug == 1:\n limit = [8,20]\n n = 3\n p = [[2,10],[10,12],[8,30],[1,5]]\n #n = 1\n # p = [[8,30]] \n print limit\n print n\n print p\n\ndef isIn(arr):\n\n if arr[0] > limit[1] or arr[1] < limit[0] or \\\n arr[1] == 0:\n return False\n ...
true
3,896
0f3e12f35cc29a71be5b8e6d367908e31c200c38
from numpy import * from numpy.linalg import* preco = array(eval(input("Alimentos: "))) alimento = array([[ 2, 1 ,4 ], [1 , 2 , 0], [2 , 3 , 2 ]]) r = dot(inv(alimento),preco.T) # print("estafilococo: ", round(r[0] , 1)) print("salmonela: ", round(r[1], 1)) print("coli: ", round(r[2], 1)) if r[0] ...
[ "from numpy import *\nfrom numpy.linalg import*\n\npreco = array(eval(input(\"Alimentos: \")))\nalimento = array([[ 2, 1 ,4 ],\n\t\t\t\t\t\t[1 , 2 , 0], \n\t\t\t\t\t\t[2 , 3 , 2 ]])\n\nr = dot(inv(alimento),preco.T) # \n\n\nprint(\"estafilococo: \", round(r[0] , 1))\nprint(\"salmonela: \", round(r[1], 1))\nprint(...
false
3,897
bc1aefd0b0a87b80a10cecf00407b4608a6902b5
# # cuneiform_python.py # # Example showing how to create a custom Unicode set for parsing # # Copyright Paul McGuire, 2021 # from typing import List, Tuple import pyparsing as pp class Cuneiform(pp.unicode_set): """Unicode set for Cuneiform Character Range""" _ranges: List[Tuple[int, ...]] = [ (0x10...
[ "#\n# cuneiform_python.py\n#\n# Example showing how to create a custom Unicode set for parsing\n#\n# Copyright Paul McGuire, 2021\n#\nfrom typing import List, Tuple\nimport pyparsing as pp\n\n\nclass Cuneiform(pp.unicode_set):\n \"\"\"Unicode set for Cuneiform Character Range\"\"\"\n\n _ranges: List[Tuple[int...
false
3,898
2874e05d6d5e0f13924e5920db22ea3343707dfa
_base_ = [ '../models/cascade_rcnn_r50_fpn.py', #'coco_instance.py', '../datasets/dataset.py', '../runtime/valid_search_wandb_runtime.py', '../schedules/schedule_1x.py' ] pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' # noqa model...
[ "_base_ = [\n '../models/cascade_rcnn_r50_fpn.py',\n #'coco_instance.py',\n '../datasets/dataset.py',\n '../runtime/valid_search_wandb_runtime.py',\n '../schedules/schedule_1x.py'\n]\npretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth' ...
false
3,899
4d7696c832f9255fbc68040b61fde12e057c06fa
import numpy as np import mysql.connector from mysql.connector import Error import matplotlib.pyplot as plt def readData(): connection = mysql.connector.connect(host='localhost',database='cad_ultrasound',user='root',password='') sql_select_Query = "SELECT id_pasien,nama,pathdata FROM datasets" cu...
[ "import numpy as np\r\nimport mysql.connector\r\nfrom mysql.connector import Error\r\nimport matplotlib.pyplot as plt\r\n\r\ndef readData():\r\n connection = mysql.connector.connect(host='localhost',database='cad_ultrasound',user='root',password='')\r\n\r\n sql_select_Query = \"SELECT id_pasien,nama,pathdata ...
false