index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
1,200 | c4f437e6f5aaeccb6dd0948c3ed1f1d465bb29ce | import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
listner = sr.Recognizer()
engine = pyttsx3.init()
#change voices
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[10].id)
rate = engine.getProperty('rate')
engine.setProperty('rate', 150)
#for machine to say
def t... | [
"import speech_recognition as sr\nimport pyttsx3\nimport pywhatkit\nimport datetime\n\n\nlistner = sr.Recognizer()\nengine = pyttsx3.init()\n\n#change voices\nvoices = engine.getProperty('voices')\nengine.setProperty('voice',voices[10].id)\nrate = engine.getProperty('rate')\nengine.setProperty('rate', 150)\n\n#for ... | false |
1,201 | 4ed730369cf065936569a8515de44042829c2143 | import os
from test.test_unicode_file_functions import filenames
def writeUniquerecords(dirpath,filenames):
sourcepath=os.path.join(dirpath,filenames)
with open(sourcepath,'r') as fp:
lines= fp.readlines()
destination_lines=[]
for line in lines:
if line not in destination_l... | [
"import os\nfrom test.test_unicode_file_functions import filenames\n\n\ndef writeUniquerecords(dirpath,filenames):\n sourcepath=os.path.join(dirpath,filenames)\n with open(sourcepath,'r') as fp:\n lines= fp.readlines()\n destination_lines=[]\n for line in lines:\n if line not i... | false |
1,202 | b65d25198d55ab4a859b9718b7b225fa92c13a2b | from whylogs.core.annotation_profiling import Rectangle
def test_rect():
rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{"name": "test"}])
test = Rectangle([[0, 0], [5, 5]])
assert rect.area == 100
assert rect.intersection(test) == 25
assert rect.iou(test) == 25 / 100.0
def test_r... | [
"from whylogs.core.annotation_profiling import Rectangle\n\n\ndef test_rect():\n\n rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{\"name\": \"test\"}])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 100\n assert rect.intersection(test) == 25\n assert rect.iou(test) == 25 / ... | false |
1,203 | e78c4f65d84d5b33debb415005e22f926e14d7d4 | """Get pandas dataframes for a given data and month.
*get_dataframes(csvfile, spec=SPEC)* is a function to get dataframes
from *csvfile* connection under *spec* parsing instruction.
*Vintage* class addresses dataset by year and month:
Vintage(year, month).save()
Vintage(year, month).validate()
*Collecti... | [
"\"\"\"Get pandas dataframes for a given data and month.\n\n*get_dataframes(csvfile, spec=SPEC)* is a function to get dataframes\n from *csvfile* connection under *spec* parsing instruction.\n\n*Vintage* class addresses dataset by year and month:\n\n Vintage(year, month).save()\n Vintage(year, month).valid... | false |
1,204 | 5ab877ef15cdcd52463b1567c28327dc2eeea2de | from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
SELENIUM_TIMEOUT = 12
def get_browser_driver():
"""获取浏览器服务... | [
"from selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nSELENIUM_TIMEOUT = 12\n\ndef get_browser_driver():\n... | false |
1,205 | a21942a835f7b2ea70e9dd7b26285ea2dd411750 | class person(object):
population=50
def __init__(self,name,age):
self.name=name
self.age=age
@classmethod
def getpopulation(cls):
return cls.population
@staticmethod
def isadult(age=17):
return age>=18
def display(self):
print(self... | [
"class person(object):\r\n population=50\r\n\r\n def __init__(self,name,age):\r\n self.name=name\r\n self.age=age\r\n\r\n @classmethod\r\n def getpopulation(cls):\r\n return cls.population\r\n\r\n @staticmethod\r\n def isadult(age=17):\r\n return age>=18\r\n\r\n def... | false |
1,206 | 50ae47c88bbc0f281ef75784377fb65192e257b0 | import numpy as np
import cv2
import glob
from scipy.spatial.transform import Rotation
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.patches import Rectangle
import celluloid
from celluloid import Camera # couldn't save animation ... | [
"import numpy as np \nimport cv2 \nimport glob\nfrom scipy.spatial.transform import Rotation \nimport matplotlib.pyplot as plt \nfrom mpl_toolkits.mplot3d import Axes3D\nimport mpl_toolkits.mplot3d.art3d as art3d\nfrom matplotlib.patches import Rectangle\nimport celluloid \nfrom celluloid import Camera # couldn't s... | false |
1,207 | 480e6ae9eee70b2da58ca5624a43d8f5dcae1d33 | #!/usr/bin/env python
import unittest
from pyspark import SparkConf, SparkContext
from mmtfPyspark.io.mmtfReader import download_mmtf_files
from mmtfPyspark.datasets import secondaryStructureExtractor
from mmtfPyspark.filters import ContainsLProteinChain
from mmtfPyspark.mappers import StructureToPolymerChains
class... | [
"#!/usr/bin/env python\n\nimport unittest\nfrom pyspark import SparkConf, SparkContext\nfrom mmtfPyspark.io.mmtfReader import download_mmtf_files\nfrom mmtfPyspark.datasets import secondaryStructureExtractor\nfrom mmtfPyspark.filters import ContainsLProteinChain\nfrom mmtfPyspark.mappers import StructureToPolymerCh... | false |
1,208 | 3b959481f7c818ec35b8af174b1982954b4c72eb | """
Forms and validation code for user registration.
Note that all of these forms assume your user model is similar in
structure to Django's default User class. If your user model is
significantly different, you may need to write your own form class;
see the documentation for notes on custom user models with
django-re... | [
"\"\"\"\nForms and validation code for user registration.\n\nNote that all of these forms assume your user model is similar in\nstructure to Django's default User class. If your user model is\nsignificantly different, you may need to write your own form class;\nsee the documentation for notes on custom user models ... | false |
1,209 | cfa7dc295c635bbdf707f1e899c4fbf8ea91df9a | #!/usr/bin/python3
import sys
import csv
infile = sys.stdin
for line in infile:
line = line.strip()
my_list = line.split(',')
if my_list[0] != "ball":
continue
batsman = my_list[4]
bowler = my_list[6]
if my_list[9] == 'run out' or my_list[9] == '""' or my_list[9] == "retired hurt":
... | [
"#!/usr/bin/python3\nimport sys\nimport csv\ninfile = sys.stdin\n\nfor line in infile:\n line = line.strip()\n my_list = line.split(',')\n if my_list[0] != \"ball\":\n continue\n batsman = my_list[4]\n bowler = my_list[6]\n if my_list[9] == 'run out' or my_list[9] == '\"\"' or my_list[9] ==... | false |
1,210 | 7a01bffa5d7f0d5ecff57c97478f2cf5e9a27538 | import torch, torchvision
import torch.nn.functional as F
import transformers
from transformers import BertTokenizer, BertModel
from transformers.models.bert.modeling_bert import BertPreTrainingHeads
from utils import construct_bert_input, EvaluationDataset, save_json
from fashionbert_evaluator_parser import Evaluation... | [
"import torch, torchvision\nimport torch.nn.functional as F\nimport transformers\nfrom transformers import BertTokenizer, BertModel\nfrom transformers.models.bert.modeling_bert import BertPreTrainingHeads\nfrom utils import construct_bert_input, EvaluationDataset, save_json\nfrom fashionbert_evaluator_parser import... | false |
1,211 | 7c60ae58b26ae63ba7c78a28b72192373cc05a86 | import smtplib
import requests
import datetime
import json
import time
from datetime import date
from urllib.request import Request,urlopen
today = date.today().strftime("%d-%m-%y")
count = 0
pincodes = ["784164","781017","784161","787001"]
date = 0
temp = str(14) + "-05-21"
while True:
for... | [
"import smtplib\r\nimport requests\r\nimport datetime\r\nimport json\r\nimport time\r\nfrom datetime import date\r\nfrom urllib.request import Request,urlopen\r\n\r\ntoday = date.today().strftime(\"%d-%m-%y\")\r\ncount = 0\r\n\r\npincodes = [\"784164\",\"781017\",\"784161\",\"787001\"]\r\n\r\ndate = 0\r\ntemp = str... | false |
1,212 | 45a57fac564f23253f9d9cd5d0fd820e559c15b9 | import requests
from requests import Response
from auditlogging.Trail import Trail
from utils.Utils import is_empty
from auditlogging.agents.AuditAgent import AuditAgent
class APIAuditAgent(AuditAgent):
"""
Captures the audit trail using a REST endpoint URL (POST)
Add this agent to Auditor in order to cap... | [
"import requests\nfrom requests import Response\nfrom auditlogging.Trail import Trail\nfrom utils.Utils import is_empty\nfrom auditlogging.agents.AuditAgent import AuditAgent\n\n\nclass APIAuditAgent(AuditAgent):\n \"\"\"\n Captures the audit trail using a REST endpoint URL (POST)\n Add this agent to Audit... | false |
1,213 | 1e84b28580b97e77394be0490f3d8db3d62a2ccb | from django.contrib.auth.models import User
from rt.models import Movie_Suggestion, MovieDB, ActorDB, TVDB
def user_present(username):
if User.objects.filter(username=username).count():
return True
return False
#Takes in a list of MovieDB/TVDB objects
#Outputs a list of sorted titles
def sort_title(movies):
ti... | [
"from django.contrib.auth.models import User\nfrom rt.models import Movie_Suggestion, MovieDB, ActorDB, TVDB\n\ndef user_present(username):\n\tif User.objects.filter(username=username).count():\n\t\treturn True\t\n\treturn False\n\t\n#Takes in a list of MovieDB/TVDB objects\n#Outputs a list of sorted titles\ndef so... | false |
1,214 | f2e2ebd5b848cf3a01b7304e5e194beb3eec1c10 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
TileMapScalePlugin
A QGIS plugin
Let you add tiled datasets (GDAL WMS) and shows them in the correct scale.
-------------------
begin ... | [
"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n TileMapScalePlugin\n A QGIS plugin\n Let you add tiled datasets (GDAL WMS) and shows them in the correct scale.\n -------------------\n ... | false |
1,215 | 0deec9058c6f7b77ba4fa3bfc0269c8596ce9612 | '''
quarter = 0.25
dime = 0.10
nickel = 0.05
penny = 0.01
'''
#def poschg(dollar_amount,number):
| [
"'''\nquarter = 0.25\ndime = 0.10\nnickel = 0.05\npenny = 0.01\n'''\n\n#def poschg(dollar_amount,number):\n",
"<docstring token>\n"
] | false |
1,216 | eb9135c6bcf89a62534cfc8480e5d44a089fe5a8 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 7 17:42:18 2018
@author: Tim
"""
import music21 as m21
import music21.features.jSymbolic as jsym
import scipy.stats
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
# round all duration values t... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 7 17:42:18 2018\n\n@author: Tim\n\"\"\"\nimport music21 as m21\nimport music21.features.jSymbolic as jsym\nimport scipy.stats\nfrom collections import Counter\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom timeit import default_timer as timer\n\n# ro... | false |
1,217 | 918653cdeea8d91921f8b96779fcd3ebce491948 | #!/usr/bin/env python
class Problem1(object):
def sum_below(self, threshold):
current_number = 1
total = 0
while current_number < threshold:
if (current_number % 3 == 0) or (current_number % 5 == 0):
total += current_number
current_number += 1
... | [
"#!/usr/bin/env python\nclass Problem1(object):\n def sum_below(self, threshold):\n current_number = 1\n total = 0\n while current_number < threshold:\n if (current_number % 3 == 0) or (current_number % 5 == 0):\n total += current_number\n current_number ... | true |
1,218 | 2acfd0bbad68bb9d55aeb39b180f4326a225f6d5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 14:35:49 2019
@author: devinpowers
"""
# Lab 1 in CSE 231
#Quadratic Formula
# Find the roots in the Quadratic Formula
import math
a = float(input("Enter the coeddicient a: "))
b = float(input("Enter the coeddicient b: "))
c = float(input(... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 31 14:35:49 2019\n\n@author: devinpowers\n\"\"\"\n\n# Lab 1 in CSE 231\n#Quadratic Formula\n# Find the roots in the Quadratic Formula\n \nimport math\n\na = float(input(\"Enter the coeddicient a: \"))\nb = float(input(\"Enter the coeddi... | false |
1,219 | 0276181055f2c70562c1f557a16d00ba7107d003 |
import pyximport
pyximport.install(build_in_temp=False,inplace=True)
import Cython.Compiler.Options
Cython.Compiler.Options.annotate = True
import numpy as np
from test1 import c_test,c_test_result_workaround
a = np.ascontiguousarray(np.array([ [1,2,3],[1,2,3],[1,2,3] ], dtype=np.long), dtype=np.long)
print '\nStar... | [
"\n\nimport pyximport\npyximport.install(build_in_temp=False,inplace=True)\nimport Cython.Compiler.Options\nCython.Compiler.Options.annotate = True\nimport numpy as np\nfrom test1 import c_test,c_test_result_workaround\n\na = np.ascontiguousarray(np.array([ [1,2,3],[1,2,3],[1,2,3] ], dtype=np.long), dtype=np.long)... | true |
1,220 | 472a79767f5dc7dc3cd03d89999d322b3885dcbf | from django.contrib.auth import get_user_model
from rest_framework import generics
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from status.api.serializers import StatusInlineUserSerializer
from status.api.views import StatusAPIView
from status.models import Status
... | [
"from django.contrib.auth import get_user_model\nfrom rest_framework import generics\nfrom rest_framework.response import Response\nfrom rest_framework_jwt.settings import api_settings\n\nfrom status.api.serializers import StatusInlineUserSerializer\nfrom status.api.views import StatusAPIView\nfrom status.models im... | false |
1,221 | 6109efeb3462ac2c5a94a68fbfa4f2f0617dd927 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 19 09:31:20 2021
@author: dclabby
"""
import os
import cv2
import pickle
from utils import locateLetterRegions
# # Constants
# sourceFolder = '/home/dclabby/Documents/Springboard/HDAIML_SEP/Semester03/MachineLearning/Project/solving_captchas_code_e... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 19 09:31:20 2021\n\n@author: dclabby\n\"\"\"\nimport os\nimport cv2\nimport pickle\nfrom utils import locateLetterRegions\n\n# # Constants\n# sourceFolder = '/home/dclabby/Documents/Springboard/HDAIML_SEP/Semester03/MachineLearning/Project... | false |
1,222 | 2a92c47231b75a441660fed80a9bce9a35695af5 | from selenium import webdriver
import time
import math
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
try:
br = webdriver.Chrome();
lk = 'http://suninjuly.github.io/get_attribute.html'
br.get(lk)
#собираю
treasure=br.find_element_by_id('treasure')
valuex = treasure.get_attribute('valuex')
radio_... | [
"from selenium import webdriver\nimport time\nimport math\n\ndef calc(x):\n\treturn str(math.log(abs(12*math.sin(int(x)))))\n\n\ntry:\n\tbr = webdriver.Chrome();\n\tlk = 'http://suninjuly.github.io/get_attribute.html'\n\tbr.get(lk)\n\n#собираю\n\ttreasure=br.find_element_by_id('treasure')\n\tvaluex = treasure.get_a... | false |
1,223 | 92eaceb46974ba3a5944300139d5929d44673181 | from tqdm import trange
import numpy as np
class GPTD_fixedGrid:
def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]):
self.env = env
self.gamma = gamma
self.sigma0 = sigma0
self.kernel = kernel.kernel
if (not V_mu):
V_mu = lambda s: np.zeros((s.sh... | [
"from tqdm import trange\nimport numpy as np\n\nclass GPTD_fixedGrid:\n def __init__(self, env, sigma0, gamma, kernel, D, V_mu=[]):\n \n self.env = env\n self.gamma = gamma\n self.sigma0 = sigma0\n self.kernel = kernel.kernel\n if (not V_mu):\n V_mu = lambda s... | false |
1,224 | c926e16ef2daa5978b6c71e7794721d320bb9b1e | def tetrahedron_filled(tetrahedrons, water):
var=0
br=0
tetrahedrons.sort()
for numbers in tetrahedrons:
v=(tetrahedrons[var]**3*(2**0.5))/12000
if v<water:
br=br+1
water=water-v
var=var+1
print (br)
print (tetrahedron_filled([1000,10],10)) | [
"def tetrahedron_filled(tetrahedrons, water):\n\tvar=0\n\tbr=0\n\ttetrahedrons.sort()\n\tfor numbers in tetrahedrons:\n\t\tv=(tetrahedrons[var]**3*(2**0.5))/12000\n\t\tif v<water:\n\t\t\tbr=br+1\n\t\t\twater=water-v\n\t\tvar=var+1\n\tprint (br)\n\n\nprint (tetrahedron_filled([1000,10],10))",
"def tetrahedron_fill... | false |
1,225 | c349fa484476e3195e0932e425cbe93d7a7e5394 | #!/usr/bin/env python
import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from std_srvs.srv import Empty, EmptyResponse
import tf
from math import radians, degrees, fabs
class MovementNullifier:
def __init__(self):
rospy.Subscriber("odom", Odometry, self.OdomCallback)
... | [
"#!/usr/bin/env python\nimport rospy\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import Twist\nfrom std_srvs.srv import Empty, EmptyResponse\nimport tf\nfrom math import radians, degrees, fabs\n\nclass MovementNullifier:\n\n def __init__(self):\n rospy.Subscriber(\"odom\", Odometry, self.Od... | false |
1,226 | 3ffe16494eb45896563a2952f3bcf80fc19b2750 | def solution(record):
answer = []
db = {}
chatting = []
for log in record:
log_list = log.split()
if log_list[0] == 'Enter':
db[log_list[1]] = log_list[2]
chatting.append([True, log_list[1]])
elif log_list[0] == 'Leave':
chatting.append([Fals... | [
"def solution(record):\n answer = []\n db = {}\n chatting = []\n\n for log in record:\n log_list = log.split()\n\n if log_list[0] == 'Enter':\n db[log_list[1]] = log_list[2]\n chatting.append([True, log_list[1]])\n elif log_list[0] == 'Leave':\n chat... | false |
1,227 | 8c166dd4cb091dcd2d80b5ae3085b5dee77564e0 | from django.db import models
#from publicservants import models
from django.utils.encoding import smart_unicode
# Create your models here.
class Score(models.Model):
#score ID - publicservant ID plus score
#sID = models.ManyToOneRel(field=PublicServant.psID)
#PS Score at time t
pst = models.Inte... | [
"from django.db import models\n#from publicservants import models\nfrom django.utils.encoding import smart_unicode\n\n# Create your models here.\n\n\nclass Score(models.Model):\n #score ID - publicservant ID plus score\n #sID = models.ManyToOneRel(field=PublicServant.psID)\n \n #PS Score at time t\n ... | false |
1,228 | 9d3db4ca5bf964c68e9778a3625c842e74bf9dbd | import os
import z5py
from shutil import copytree, copyfile
ROOT = '/g/kreshuk/pape/Work/data/mito_em/data'
SCRATCH = '/scratch/pape/mito_em/data'
def create_file(out_path, ref_path):
os.makedirs(out_path, exist_ok=True)
copyfile(
os.path.join(ref_path, 'attributes.json'),
os.path.join(out_pa... | [
"import os\nimport z5py\nfrom shutil import copytree, copyfile\n\nROOT = '/g/kreshuk/pape/Work/data/mito_em/data'\nSCRATCH = '/scratch/pape/mito_em/data'\n\n\ndef create_file(out_path, ref_path):\n os.makedirs(out_path, exist_ok=True)\n copyfile(\n os.path.join(ref_path, 'attributes.json'),\n os... | false |
1,229 | 4e7cfbf51ec9bad691d8dd9f103f22728cf5e952 | # Copyright (c) 2016, the GPyOpt Authors
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from scipy.special import erfc
import time
from ..core.errors import InvalidConfigError
def compute_integrated_acquisition(acquisition,x):
'''
Used to compute the acquisition function when s... | [
"# Copyright (c) 2016, the GPyOpt Authors\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\nimport numpy as np\nfrom scipy.special import erfc\nimport time\nfrom ..core.errors import InvalidConfigError\n\ndef compute_integrated_acquisition(acquisition,x):\n '''\n Used to compute the acquisition ... | false |
1,230 | cb32aa6a1c42e7bb417999f3f6f74ec22209c5a0 | from django.core.cache import cache
from rest_framework import serializers
from thenewboston.constants.crawl import (
CRAWL_COMMAND_START,
CRAWL_COMMAND_STOP,
CRAWL_STATUS_CRAWLING,
CRAWL_STATUS_NOT_CRAWLING,
CRAWL_STATUS_STOP_REQUESTED
)
from v1.cache_tools.cache_keys import CRAWL_CACHE_LOCK_KEY, ... | [
"from django.core.cache import cache\nfrom rest_framework import serializers\nfrom thenewboston.constants.crawl import (\n CRAWL_COMMAND_START,\n CRAWL_COMMAND_STOP,\n CRAWL_STATUS_CRAWLING,\n CRAWL_STATUS_NOT_CRAWLING,\n CRAWL_STATUS_STOP_REQUESTED\n)\n\nfrom v1.cache_tools.cache_keys import CRAWL_C... | false |
1,231 | 7ef62e5545930ab13312f8ae1ea70a74386d8bfa | def ip_address(address):
new_address = ""
split_address = address.split(".")
seprator = "[.]"
new_address = seprator.join(split_address)
return new_address
if __name__ == "__main__":
ipaddress = ip_address("192.168.1.1")
print(ipaddress)
| [
"def ip_address(address):\n new_address = \"\"\n split_address = address.split(\".\")\n seprator = \"[.]\"\n new_address = seprator.join(split_address)\n return new_address\n\n\nif __name__ == \"__main__\":\n ipaddress = ip_address(\"192.168.1.1\")\n print(ipaddress)\n",
"def ip_address(addre... | false |
1,232 | 8f558593e516aa4a769b7c5e1c95c8bc23a36420 | import torch
import util
import numpy as np
import argparse
import losses
args = argparse.Namespace()
args.device = torch.device('cpu')
args.num_mixtures = 20
args.init_mixture_logits = np.ones(args.num_mixtures)
args.softmax_multiplier = 0.5
args.relaxed_one_hot = False
args.temperature = None
temp = np.arange(args.... | [
"import torch\nimport util\nimport numpy as np\nimport argparse\nimport losses\n\n\nargs = argparse.Namespace()\nargs.device = torch.device('cpu')\nargs.num_mixtures = 20\nargs.init_mixture_logits = np.ones(args.num_mixtures)\nargs.softmax_multiplier = 0.5\nargs.relaxed_one_hot = False\nargs.temperature = None\ntem... | false |
1,233 | c5bbfa1a86dbbd431566205ff7d7b941bdceff58 | #!/usr/bin/env python
# encoding: utf-8
"""
plot: regularization on x axis, number of k_best features on y
Created by on 2012-01-27.
Copyright (c) 2012. All rights reserved.
"""
import sys
import os
import json
import numpy as np
import pylab as plt
import itertools as it
from master.libs import plot_lib as plib
... | [
"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n plot: regularization on x axis, number of k_best features on y\n\nCreated by on 2012-01-27.\nCopyright (c) 2012. All rights reserved.\n\"\"\"\nimport sys\nimport os\nimport json\nimport numpy as np\nimport pylab as plt\nimport itertools as it\nfrom master.libs... | false |
1,234 | 2c4fa92b28fa46a26f21ada8826474baac204e00 | def mysum(*c):
print(sum([x for x in c]))
mysum(1,2,3,4,0xB) | [
"def mysum(*c):\n print(sum([x for x in c]))\n\nmysum(1,2,3,4,0xB)",
"def mysum(*c):\n print(sum([x for x in c]))\n\n\nmysum(1, 2, 3, 4, 11)\n",
"def mysum(*c):\n print(sum([x for x in c]))\n\n\n<code token>\n",
"<function token>\n<code token>\n"
] | false |
1,235 | af2aa236f6bfc582093faf868a374be1ebdfabf2 | """
"""
import os
import json
import csv
cutoff = float(input("Tolerance (decimal)? "))
docpath = "C:/Users/RackS/Documents/"
out = open("isosegmenter_scoring_error"+str(cutoff*100)+".csv", 'w', encoding='UTF-8')
summary = open("isosegmenter_score_summary_error"+str(cutoff*100)+".txt", 'w', encoding='UTF-8')
out.write... | [
"\"\"\"\n\"\"\"\nimport os\nimport json\nimport csv\n\ncutoff = float(input(\"Tolerance (decimal)? \"))\ndocpath = \"C:/Users/RackS/Documents/\"\nout = open(\"isosegmenter_scoring_error\"+str(cutoff*100)+\".csv\", 'w', encoding='UTF-8')\nsummary = open(\"isosegmenter_score_summary_error\"+str(cutoff*100)+\".txt\", ... | false |
1,236 | 2396f7acab95260253c367c62002392760157705 | import random
import numpy as np
import torch
from utils import print_result, set_random_seed, get_dataset, get_extra_args
from cogdl.tasks import build_task
from cogdl.datasets import build_dataset
from cogdl.utils import build_args_from_dict
DATASET_REGISTRY = {}
def build_default_args_for_node_classification(da... | [
"import random\nimport numpy as np\n\nimport torch\n\nfrom utils import print_result, set_random_seed, get_dataset, get_extra_args\nfrom cogdl.tasks import build_task\nfrom cogdl.datasets import build_dataset\nfrom cogdl.utils import build_args_from_dict\n\nDATASET_REGISTRY = {}\n\n\ndef build_default_args_for_node... | false |
1,237 | dace25428f48da633ee571b51565d15650782649 | #!/usr/bin/python
import os
import sys
import csv
import json
from time import sleep
from datetime import datetime
ShowProgress = False
ConvertTime = False
def print_welcome():
print("""
[*******************************************************************************************************]
... | [
"#!/usr/bin/python\nimport os\nimport sys\nimport csv\nimport json\nfrom time import sleep\nfrom datetime import datetime\n\nShowProgress = False\nConvertTime = False\n\n\ndef print_welcome():\n print(\"\"\"\n[*******************************************************************************************************... | true |
1,238 | 347627df4b08eca6e2137161472b4d31534cf81b | import pytz
import datetime
def apply_timezone_datetime(_local_tz: str, _time: datetime.time):
"""
set time zone + merge now().date() with time()
:param _local_tz:
:param _time:
:return:
"""
return pytz.timezone(_local_tz).localize(
datetime.datetime.combine(datetime.datetime.now()... | [
"import pytz\nimport datetime\n\n\ndef apply_timezone_datetime(_local_tz: str, _time: datetime.time):\n \"\"\"\n set time zone + merge now().date() with time()\n :param _local_tz:\n :param _time:\n :return:\n \"\"\"\n return pytz.timezone(_local_tz).localize(\n datetime.datetime.combine(... | false |
1,239 | a36a553342cfe605a97ddc0f636bbb73b683f6a6 | import re
def match_regex(filename, regex):
with open(filename) as file:
lines = file.readlines()
for line in reversed(lines):
match = re.match(regex, line)
if match:
regex = yield match.groups()[0]
def get_serials(filename):
ERROR_RE = 'XFS ERROR (\[sd[a-z]\])'
#... | [
"import re\n\ndef match_regex(filename, regex):\n with open(filename) as file:\n lines = file.readlines()\n\n for line in reversed(lines):\n match = re.match(regex, line)\n if match:\n regex = yield match.groups()[0]\n\ndef get_serials(filename):\n ERROR_RE = 'XFS ERROR (\\[... | false |
1,240 | 1ed7fb0dd5f0fa5e60c855eceaaf3259092918ef | x, y = [float(x) for x in raw_input().split(" ")]
print(x*y) | [
"x, y = [float(x) for x in raw_input().split(\" \")]\nprint(x*y)",
"x, y = [float(x) for x in raw_input().split(' ')]\nprint(x * y)\n",
"<assignment token>\nprint(x * y)\n",
"<assignment token>\n<code token>\n"
] | false |
1,241 | b1a1287c2c3b624eb02f2955760f6e9eca8cdcf9 | cars=100
drivers=30
passengers=70
print "There are",cars,"cars available."
print "There are only",drivers,"drivers available."
print "Each driver needs to drive",passengers/drivers-1,"passengers."
| [
"cars=100\ndrivers=30\npassengers=70\nprint \"There are\",cars,\"cars available.\"\nprint \"There are only\",drivers,\"drivers available.\"\nprint \"Each driver needs to drive\",passengers/drivers-1,\"passengers.\"\n"
] | true |
1,242 | e68d872232b3eab4c33cbbe4376be7dd788888e2 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-20 08:05
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depe... | [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.11.2 on 2017-07-20 08:05\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial... | false |
1,243 | df39a97db25f03aca8ebd501283fd6a7c486db8c | from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils import timezone
from timesheets.models import TimeSheet
from channels import Group
class ProjectTS(models.Model):
class Meta:
... | [
"from __future__ import unicode_literals\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.utils import timezone\nfrom timesheets.models import TimeSheet\nfrom channels import Group\n\n\nclass ProjectTS(models.Model):\n cla... | false |
1,244 | f80de2b069cf1dee2e665556262c6e84ce04b208 | """ Compiled: 2020-09-18 10:38:52 """
#__src_file__ = "extensions/AppWorkspaceTools/etc/FAppWorkspaceDesignerNodes.py"
""" Compiled: 2018-06-07 17:06:19 """
#__src_file__ = "extensions/AppWorkspaceTools/etc/FAppWorkspaceDesignerNodes.py"
import acm
import FUxCore
import Contracts_AppConfig_Messages_AppWorkspace as Ap... | [
"\"\"\" Compiled: 2020-09-18 10:38:52 \"\"\"\n\n#__src_file__ = \"extensions/AppWorkspaceTools/etc/FAppWorkspaceDesignerNodes.py\"\n\"\"\" Compiled: 2018-06-07 17:06:19 \"\"\"\n\n#__src_file__ = \"extensions/AppWorkspaceTools/etc/FAppWorkspaceDesignerNodes.py\"\nimport acm\nimport FUxCore\nimport Contracts_AppConfi... | false |
1,245 | b6df9414f99294c7986d3eb5332d40288f059cd1 | class default_locations:
mc_2016_data_directory = "/afs/hephy.at/data/cms06/nanoTuples/"
mc_2016_postProcessing_directory = "stops_2016_nano_v0p23/dilep/"
data_2016_data_directory = "/afs/hephy.at/data/cms07/nanoTuples/"
data_2016_postProcessing_directory = "stops_2016_nan... | [
"class default_locations:\n mc_2016_data_directory = \"/afs/hephy.at/data/cms06/nanoTuples/\" \n mc_2016_postProcessing_directory = \"stops_2016_nano_v0p23/dilep/\" \n data_2016_data_directory = \"/afs/hephy.at/data/cms07/nanoTuples/\" \n data_2016_postProcessing_directory = ... | false |
1,246 | 122c4f3a2949ee675b7dd64b9f9828e80cbe5610 | import cv2
import os
import re
class TestData:
def __init__(self, image_path= '../../data/test_images/'):
test_names = os.listdir(image_path)
self.images = []
self.numbers = []
self.treshold = .25
for name in test_names:
self.images.append(cv2.imread(... | [
"import cv2\nimport os\nimport re\n\n\nclass TestData:\n def __init__(self, image_path= '../../data/test_images/'):\n test_names = os.listdir(image_path)\n\n self.images = []\n self.numbers = []\n \n self.treshold = .25\n\n for name in test_names:\n self.image... | false |
1,247 | 23236cd8262eb414666db88215c01d973abf1d97 | decoded = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"... | [
"decoded = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \"a\", \"b\", ... | false |
1,248 | 7aa6bba8483082354a94ed5c465e59a0fc97fe23 | #https://codeforces.com/problemset/problem/1321/A
n=int(input())
r=list(map(int,input().split()))
b=list(map(int,input().split()))
l=[0]*n
x=0
y=0
for i in range(n):
if r[i]-b[i]==1:
x+=1
elif r[i]-b[i]==-1:
y+=1
if x==0:
print(-1)
else:
print(y//x+min(y%x+1,1))
| [
"#https://codeforces.com/problemset/problem/1321/A\n\nn=int(input())\nr=list(map(int,input().split()))\nb=list(map(int,input().split()))\nl=[0]*n\nx=0\ny=0\nfor i in range(n):\n if r[i]-b[i]==1:\n x+=1\n elif r[i]-b[i]==-1:\n y+=1\nif x==0:\n print(-1)\nelse:\n print(y//x+min(y%x+1,1))\n",... | false |
1,249 | 4c9f2b6fd119daa58b7f1dd7153c90df747e62cb | # Moving Averages Code
# Load the necessary packages and modules
import pandas as pd
import matplotlib.pyplot as plt
import data.stock as st
# Simple Moving Average
def SMA(data, ndays):
SMA = pd.Series(data['close'].rolling(ndays).mean(), name='SMA')
# SMA = pd.Series(pd.rolling_mean(data['close'], ndays),... | [
"# Moving Averages Code\n\n# Load the necessary packages and modules\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport data.stock as st\n\n\n# Simple Moving Average \ndef SMA(data, ndays):\n SMA = pd.Series(data['close'].rolling(ndays).mean(), name='SMA')\n # SMA = pd.Series(pd.rolling_mean(data['... | false |
1,250 | db55a603615c7d896569ada84f3110dd6c0ce45f | import shell
def executeUpgrade():
shell.executeCommand('pkg upgrade')
def executeInstall(pkg_name):
shell.executeCommand('pkg install ' + pkg_name)
def executeRemove(pkg_name):
shell.executeCommand('pkg remove ' + pkg_name)
shell.executeCommand('pkg autoremove')
def executeFindByName(name):
... | [
"import shell\n\n\ndef executeUpgrade():\n shell.executeCommand('pkg upgrade')\n\n\ndef executeInstall(pkg_name):\n shell.executeCommand('pkg install ' + pkg_name)\n\n\ndef executeRemove(pkg_name):\n shell.executeCommand('pkg remove ' + pkg_name)\n shell.executeCommand('pkg autoremove')\n\n\ndef execute... | false |
1,251 | 3078a0c7e2c711da88846ca3401c7924b1790dbc | #!/usr/bin/env python
#
# ConVirt - Copyright (c) 2008 Convirture Corp.
# ======
#
# ConVirt is a Virtualization management tool with a graphical user
# interface that allows for performing the standard set of VM operations
# (start, stop, pause, kill, shutdown, reboot, snapshot, etc...). It
# also attempts to s... | [
"#!/usr/bin/env python\n#\n# ConVirt - Copyright (c) 2008 Convirture Corp.\n# ======\n#\n# ConVirt is a Virtualization management tool with a graphical user\n# interface that allows for performing the standard set of VM operations\n# (start, stop, pause, kill, shutdown, reboot, snapshot, etc...). It\n# also ... | true |
1,252 | 64fd597918fe8133d53d1df741512cd2e49a111d | # -*- coding: utf8 -*-
from django.db import models
import custom_fields
import datetime
#import mptt
# Create your models here.
class Message(models.Model):
user = models.ForeignKey('User')
time = models.DateTimeField(auto_now=True,auto_now_add=True)
text = models.TextField()
#true если это ответ подд... | [
"# -*- coding: utf8 -*-\nfrom django.db import models\nimport custom_fields\nimport datetime\n#import mptt\n\n# Create your models here.\nclass Message(models.Model):\n user = models.ForeignKey('User')\n time = models.DateTimeField(auto_now=True,auto_now_add=True)\n text = models.TextField()\n #true есл... | false |
1,253 | 05aec07b94f3363e07d8740b102262d817e08e71 | # coding: utf-8
"""
Knetik Platform API Documentation latest
This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.
OpenAPI spec version: latest
Contact: support@knetik.com
Generated by: https://github.com/swagger-api/swagger-codeg... | [
"# coding: utf-8\n\n\"\"\"\n Knetik Platform API Documentation latest \n\n This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.\n\n OpenAPI spec version: latest \n Contact: support@knetik.com\n Generated by: https://github.com/swagger-... | true |
1,254 | dbb007af79b2da2b5474281759c2bcce2a836fb5 | from requests import get
from bs4 import BeautifulSoup, SoupStrainer
import httplib2
import re
from win32printing import Printer
def getLinks(url):
links = []
document = BeautifulSoup(response, "html.parser")
for element in document.findAll('a', href=re.compile(".pdf$")):
links.append(element.get(... | [
"from requests import get\nfrom bs4 import BeautifulSoup, SoupStrainer\nimport httplib2\nimport re\nfrom win32printing import Printer\n\ndef getLinks(url):\n links = []\n document = BeautifulSoup(response, \"html.parser\")\n\n for element in document.findAll('a', href=re.compile(\".pdf$\")):\n links... | false |
1,255 | 12f0eeeb81fe611d88e33fd2e8df407e289fb582 | # Error using ncdump - NetCDF4 Python
ncdump -h filename
| [
"# Error using ncdump - NetCDF4 Python\nncdump -h filename\n"
] | true |
1,256 | bbb3d27ce8f4c1943ecc7ab542346c9f41cbd30e | # Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module implements helpers for GN SDK e2e tests.
"""
# Note, this is run on bots, which only support python2.7.
# Be sure to only use python2.7 feature... | [
"# Copyright 2020 The Fuchsia 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\"\"\"This module implements helpers for GN SDK e2e tests.\n\"\"\"\n\n# Note, this is run on bots, which only support python2.7.\n# Be sure to only use... | false |
1,257 | ba483c7eaf2f2ced7f70a14b53c781f190585024 | from AStar import astar
def main():
grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0,... | [
"from AStar import astar\n\n\ndef main():\n grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n ... | false |
1,258 | b0fad3847519bb18365a8cd4226d06e9d96a8308 | from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path(r'', views.index, name='index'),
]
| [
"from django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url\nfrom . import views\nurlpatterns = [\n path('admin/', admin.site.urls),\n path(r'', views.index, name='index'),\n]\n",
"from django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls imp... | false |
1,259 | 68a776d7fccc8d8496a944baff51d2a862fc7d31 | # flush in poker
def IsContinuous(numbers):
if not numbers or len(numbers) < 1 :
return False
numbers.sort()
number_of_zero = 0
number_of_gap = 0
for i in range(len(numbers)):
if numbers[i] == 0:
number_of_zero += 1
small = number_of_zero
big = small + 1
whi... | [
"# flush in poker\ndef IsContinuous(numbers):\n if not numbers or len(numbers) < 1 :\n return False\n\n numbers.sort()\n number_of_zero = 0\n number_of_gap = 0\n for i in range(len(numbers)):\n if numbers[i] == 0:\n number_of_zero += 1\n\n small = number_of_zero\n big =... | false |
1,260 | d73491d6673abdabad85176c5f75a191995c806d | from . import views
from django.urls import path, re_path
app_name = "blogs"
urlpatterns = [
path('', views.index, name='index'),
re_path(r'^blogs/(?P<blog_id>\d+)/$', views.blog, name='blog'),
path('new_blog/', views.new_blog, name='new_blog'),
re_path(r'^edit_blog/(?P<blog_id>\d+)/$', views.edit_blog, name='edit_bl... | [
"from . import views\nfrom django.urls import path, re_path\n\napp_name = \"blogs\"\n\nurlpatterns = [\npath('', views.index, name='index'),\nre_path(r'^blogs/(?P<blog_id>\\d+)/$', views.blog, name='blog'),\npath('new_blog/', views.new_blog, name='new_blog'),\nre_path(r'^edit_blog/(?P<blog_id>\\d+)/$', views.edit_b... | false |
1,261 | 618b6c74133e181ce5cbaf4e969d9fc3aa44ce98 | # -*- mode: python; coding: utf-8 -*-
# Copyright 2019-2021 the AAS WorldWide Telescope project
# Licensed under the MIT License.
from __future__ import absolute_import, division, print_function
import numpy as np
import numpy.testing as nt
import os.path
import pytest
import sys
from xml.etree import ElementTree as ... | [
"# -*- mode: python; coding: utf-8 -*-\n# Copyright 2019-2021 the AAS WorldWide Telescope project\n# Licensed under the MIT License.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport numpy as np\nimport numpy.testing as nt\nimport os.path\nimport pytest\nimport sys\nfrom xml.etree import... | false |
1,262 | f5f9a1c7dcb7345e24f50db54649a1970fc37185 | from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
# are the lat/lon values of the lower left and upper right corners
# of the map.
# resolution = 'c' means use crude resolution coastlines.
m = Basemap(projection='cea',llcrnrlat=-90,urcr... | [
"from mpl_toolkits.basemap import Basemap\nimport numpy as np\nimport matplotlib.pyplot as plt\n# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon\n# are the lat/lon values of the lower left and upper right corners\n# of the map.\n# resolution = 'c' means use crude resolution coastlines.\nm = Basemap(projection='cea',llcrnr... | false |
1,263 | 76dd4d2b5f68683c77f9502a2298e65c97db7c8d | class ConfigError(ValueError):
pass
| [
"class ConfigError(ValueError):\n pass\n",
"class ConfigError(ValueError):\n pass\n",
"<class token>\n"
] | false |
1,264 | f16d43d9dfb3e9b9589fa92eb82aaa4c73fe48cd | from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from orders.models import Setting
def search(request):
return render(request, 'ui/search.html')
def search_printed(request):
print_url = ''
setting = Setting.objects.filter(name='printer').first()
if setting ... | [
"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom orders.models import Setting\n\ndef search(request):\n return render(request, 'ui/search.html')\n\ndef search_printed(request):\n print_url = ''\n setting = Setting.objects.filter(name='printer').first()\n... | false |
1,265 | dc81ab808720c3a2c76174264c9be9bcdd99c292 | A = []
ans = 0
def merge(left, mid, right):
global A
global ans
n1 = mid - left
n2 = right - mid
l = []
r = []
for i in range(n1):
l += [A[left + i]]
for i in range(n2):
r += [A[mid + i]]
l += [10**18]
r += [10**18]
i = 0
j = 0
ans += right - left
for k in range(left, right):
if l[i] <= r[j]:
A[... | [
"A = []\nans = 0\n\ndef merge(left, mid, right):\n\tglobal A\n\tglobal ans\n\tn1 = mid - left\n\tn2 = right - mid\n\tl = []\n\tr = []\n\tfor i in range(n1):\n\t\tl += [A[left + i]]\n\tfor i in range(n2):\n\t\tr += [A[mid + i]]\n\tl += [10**18]\n\tr += [10**18]\n\ti = 0\n\tj = 0\n\tans += right - left\n\tfor k in ra... | false |
1,266 | a6192e39d86005882d0bde040a99f364bf701c3b | # -*- coding: utf-8 -*-
def merge_sort(mlist):
if len(mlist) <= 1:
return mlist
mid = int(len(mlist) / 2)
# 使用递归将数组二分分解
left = merge_sort(mlist[:mid])
right = merge_sort(mlist[mid:])
return merge(left, right) # 将每次分解出来的数组各自排序,合并成一个大数组
def merge(left, right):
"""
... | [
"# -*- coding: utf-8 -*-\r\n\r\n\r\ndef merge_sort(mlist):\r\n if len(mlist) <= 1:\r\n return mlist\r\n mid = int(len(mlist) / 2)\r\n # 使用递归将数组二分分解\r\n left = merge_sort(mlist[:mid])\r\n right = merge_sort(mlist[mid:])\r\n return merge(left, right) # 将每次分解出来的数组各自排序,合并成一个大数组\r\n\r\n\r\ndef ... | false |
1,267 | 7cbf2082d530c315fdcfdb94f5c6ac4755ea2081 | #!/usr/bin/python3
"""
program of the command interpreter
"""
import cmd
import models
import re
from models.base_model import BaseModel
from models import storage
from models.user import User
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
... | [
"#!/usr/bin/python3\n\"\"\"\nprogram of the command interpreter\n\"\"\"\n\nimport cmd\nimport models\nimport re\nfrom models.base_model import BaseModel\nfrom models import storage\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom m... | false |
1,268 | 4db8b4403dd9064b7d5f935d4b9d111508c965fb | from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.db.models import Q
from cvmo import settings
from cvmo.context.models import ContextDefinition, Machines, ClusterDefinition, MarketplaceContextEntry
from cvmo.context.plugins im... | [
"from django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.db.models import Q\n\nfrom cvmo import settings\n\nfrom cvmo.context.models import ContextDefinition, Machines, ClusterDefinition, MarketplaceContextEntry\n\nfrom cvmo.cont... | false |
1,269 | 816c11717c4f26b9013f7a83e1dfb2c0578cbcf8 | from yama.record import Record
class MongoStorage(object):
_collection = None
_connection = None
_root_id = None
_roots = None
def __init__(self, connection):
self._connection = connection
self._collection = connection.objects
self._roots = connection.roots
root_... | [
"from yama.record import Record\n\n\nclass MongoStorage(object):\n\n _collection = None\n _connection = None\n _root_id = None\n\n _roots = None\n\n def __init__(self, connection):\n self._connection = connection\n self._collection = connection.objects\n self._roots = connection.... | false |
1,270 | ca5057a5fdfef0edf4cf0c3ff3e2a371907ca4ee | import tkinter as tk
import tkinter.ttk as ttk
import GUIForm
import sys
def main():
global window
global _form
print("You are using Python {}.{}.{}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro))
window=tk.Tk()
GUIForm.BuildInterface(window)
window.mainloop()... | [
"import tkinter as tk\nimport tkinter.ttk as ttk\nimport GUIForm\nimport sys\n\ndef main():\n global window\n global _form\n\n print(\"You are using Python {}.{}.{}\".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro))\n\n window=tk.Tk()\n GUIForm.BuildInterface(window)\n ... | false |
1,271 | 11a7ebac3dad1f91a6d46b62f557b51ded8e3d7a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ユークリッド距離
# http://en.wikipedia.org/wiki/Euclidean_space
# 多次元空間中での 2 点間の距離を探索する
def euclidean(p,q):
sumSq=0.0
# 差の平方を加算
for i in range(len(p)):
sumSq+=(p[i]-q[i])**2
# 平方根
return (sumSq**0.5)
#print euclidean([3,4,5],[4,5,6])
| [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ユークリッド距離\n# http://en.wikipedia.org/wiki/Euclidean_space\n\n# 多次元空間中での 2 点間の距離を探索する\n\ndef euclidean(p,q):\n sumSq=0.0\n # 差の平方を加算\n for i in range(len(p)):\n sumSq+=(p[i]-q[i])**2\n # 平方根\n return (sumSq**0.5)\n\n#print euclidean([3,4,5],[4... | false |
1,272 | ea8676a4c55bbe0ae2ff8abf924accfc0bd8f661 | from lib.utility import start_time, end_time
from lib.prime import read_primes
from bisect import bisect_left
start_time()
primes = read_primes(100)
# limit = 10 ** 16
import random
# limit = random.randint(1000, 10 ** 5)
limit = 43268
# limit = 10 ** 16
print('limit=', limit)
v1 = set()
v2 = set()
def version_100_i... | [
"from lib.utility import start_time, end_time\nfrom lib.prime import read_primes\nfrom bisect import bisect_left\nstart_time()\n\nprimes = read_primes(100)\n# limit = 10 ** 16\nimport random\n# limit = random.randint(1000, 10 ** 5)\nlimit = 43268\n# limit = 10 ** 16\nprint('limit=', limit)\nv1 = set()\nv2 = set()\n... | false |
1,273 | fa081ccd8081f5c3319f482b7d8abd7415d8e757 | '''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val... | [
"'''\nGiven a binary tree, find its maximum depth.\n\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\nNote: A leaf is a node with no children.\n\n'''\n\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x)... | true |
1,274 | af442d4a78930a0ebcd85a1cdfe4aa86461be5c1 | import re
from django import forms
from django.contrib.auth import password_validation
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.password_validation import validate_password
from .models import Account
class EditProfileModelForm(forms.ModelForm):
class Meta:
model... | [
"import re\n\nfrom django import forms\nfrom django.contrib.auth import password_validation\nfrom django.contrib.auth.forms import PasswordChangeForm\nfrom django.contrib.auth.password_validation import validate_password\n\nfrom .models import Account\n\n\nclass EditProfileModelForm(forms.ModelForm):\n class Met... | false |
1,275 | 07a546928df1acfedf7a7735dc813de9da8373e0 | ##This script looks at a path for a dated file, then parses it by row into two different files/folders based on fields being blank within each row.
import os.path
from datetime import date
##sets date variables/format
today = date.today()
todayFormatted = today.strftime("%m%d%Y")
print(todayFormatted)
##Se... | [
"##This script looks at a path for a dated file, then parses it by row into two different files/folders based on fields being blank within each row.\r\n\r\nimport os.path\r\nfrom datetime import date\r\n\r\n##sets date variables/format\r\ntoday = date.today()\r\ntodayFormatted = today.strftime(\"%m%d%Y\")\r\nprint(... | false |
1,276 | bd00644b9cf019fe8c86d52494389b7f0f03d3c3 | # !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... | [
"# !usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Licensed under a 3-clause BSD license.\n#\n# @Author: Brian Cherinka\n# @Date: 2018-08-16 11:43:42\n# @Last modified by: Brian Cherinka\n# @Last Modified time: 2018-08-16 11:58:06\n\nfrom __future__ import print_function, division, absolute_import\nimport py... | false |
1,277 | 34dd6966a971e3d32e82a17cd08c3b66bb88163b | def login():
usernameInput = input("Username : ")
passwordInput = input("Password : ")
if usernameInput == "admin" and passwordInput == "1234":
return (showMenu())
else:
print("User or Password Wrong.")
return login()
def showMenu():
print("---Please Choose Menu---")
prin... | [
"def login():\n usernameInput = input(\"Username : \")\n passwordInput = input(\"Password : \")\n if usernameInput == \"admin\" and passwordInput == \"1234\":\n return (showMenu())\n else:\n print(\"User or Password Wrong.\")\n return login()\ndef showMenu():\n print(\"---Please ... | false |
1,278 | 5461d50d3c06bc4276044cc77bd804f6e7c16b3b | #!/usr/bin/python3
''' FileStorage module '''
import json
from models.base_model import BaseModel
import models
from models.user import User
from models.place import Place
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.review import Review
class FileStorage:... | [
"#!/usr/bin/python3\n''' FileStorage module '''\nimport json\nfrom models.base_model import BaseModel\nimport models\nfrom models.user import User\nfrom models.place import Place\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.review import Review\n\n\n... | false |
1,279 | 8b671404228642f7ef96844c33ac3cee402bdb19 | import os, subprocess, time
from os.path import isfile, join
import shutil # to move files from af folder to another
import math
def GetListFile(PathFile, FileExtension):
return [os.path.splitext(f)[0] for f in os.listdir(PathFile) if isfile(join(PathFile, f)) and os.path.splitext(f)[1] == '.' + FileExtension]
d... | [
"import os, subprocess, time\nfrom os.path import isfile, join\nimport shutil # to move files from af folder to another\nimport math\n\ndef GetListFile(PathFile, FileExtension):\n return [os.path.splitext(f)[0] for f in os.listdir(PathFile) if isfile(join(PathFile, f)) and os.path.splitext(f)[1] == '.' + FileExt... | true |
1,280 | 33aa5c5ab75a26705875b55baf61f7f996cb69cd | from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='VitaminSHE-home'),
path('signup/', views.signup, name='VitaminSHE-signup'),
path('login/', views.login, name='VitaminSHE-login'),
path('healthcheck/', views.healthcheck, name='VitaminSHE-healthcheck'),
path('... | [
"from django.urls import path\nfrom . import views\nurlpatterns = [\n path('', views.home, name='VitaminSHE-home'),\n path('signup/', views.signup, name='VitaminSHE-signup'),\n path('login/', views.login, name='VitaminSHE-login'),\n path('healthcheck/', views.healthcheck, name='VitaminSHE-healthcheck'),... | false |
1,281 | 6b616f5ee0a301b76ad3f7284b47f225a694d33c | from plprofiler_tool import main
from plprofiler import plprofiler
| [
"from plprofiler_tool import main\nfrom plprofiler import plprofiler\n",
"<import token>\n"
] | false |
1,282 | 26ae44b5be1d78ed3fe9c858413ae47e163c5460 | from typing import List
"""
1. Generate an array containing the products of all elements to the left of current element
2. Similarly, start from the last element and generate an array containing the products to the right of each element
3. Multiply both arrays element-wise
"""
class Solution:
def productExceptS... | [
"from typing import List\n\n\"\"\"\n1. Generate an array containing the products of all elements to the left of current element\n2. Similarly, start from the last element and generate an array containing the products to the right of each element\n3. Multiply both arrays element-wise\n\n\"\"\"\n\n\nclass Solution:\n... | false |
1,283 | 284955a555ce1a727ba5041008cd0bac3c3bed49 | from django.db import models
# Create your models here.
class Covid(models.Model):
states= models.CharField(max_length=100, null=True, blank=True)
affected = models.IntegerField(null=True)
cured = models.IntegerField(null=True)
death = models.IntegerField(null=True)
| [
"from django.db import models\n\n# Create your models here.\nclass Covid(models.Model):\n states= models.CharField(max_length=100, null=True, blank=True)\n affected = models.IntegerField(null=True)\n cured = models.IntegerField(null=True)\n death = models.IntegerField(null=True)\n",
"from django.d... | false |
1,284 | 3aff6bdfd7c2ffd57af7bb5d0079a8a428e02331 | import tensorflow as tf
import numpy as np
from datetime import datetime
import os
from CNN import CNN
from LSTM import LSTM
from BiLSTM import BiLSTM
from SLAN import Attention
from HAN2 import HierarchicalAttention
import sklearn.metrics as metrics
import DataProcessor as dp
import matplotlib.pyplot as plt
import num... | [
"import tensorflow as tf\nimport numpy as np\nfrom datetime import datetime\nimport os\nfrom CNN import CNN\nfrom LSTM import LSTM\nfrom BiLSTM import BiLSTM\nfrom SLAN import Attention\nfrom HAN2 import HierarchicalAttention\nimport sklearn.metrics as metrics\nimport DataProcessor as dp\nimport matplotlib.pyplot a... | false |
1,285 | 6b2f10449909d978ee294a502a376c8091af06e0 | import tkinter as tk
from pickplace import PickPlace
import sys
import math
from tkinter import messagebox
import os
DEBUG = False
class GerberCanvas:
file_gto = False
file_gtp = False
units = 0
units_string = ('i', 'm')
"""
my canvas
"""
def __init__(self, frame):
self.x_fo... | [
"import tkinter as tk\nfrom pickplace import PickPlace\nimport sys\nimport math\nfrom tkinter import messagebox\nimport os\n\nDEBUG = False\n\n\nclass GerberCanvas:\n\n file_gto = False\n file_gtp = False\n units = 0\n units_string = ('i', 'm')\n\n \"\"\"\n my canvas\n \"\"\"\n def __init__(... | false |
1,286 | d56aa0f0b7c420e4021736cf8f80923121856d1c | import json
import requests
import time
class TRY():
rates = list()
def __init__(self, r):
# if(TRY.rates[-1] != r):
TRY.rates.append(r)
def ls(self):
# print("TRY: "+TRY.rates[e] for e in range(1, len(TRY.rates)))
print(f"TRY: {TRY.rates}")
class USD():
rates = lis... | [
"import json\nimport requests\nimport time\n\n\nclass TRY():\n rates = list()\n\n def __init__(self, r):\n # if(TRY.rates[-1] != r):\n TRY.rates.append(r)\n\n def ls(self):\n # print(\"TRY: \"+TRY.rates[e] for e in range(1, len(TRY.rates)))\n print(f\"TRY: {TRY.rates}\")\n\n\ncl... | false |
1,287 | f3789d70f784345881f705fc809c49ad4e3526bc | # -*- coding: utf-8 -*-
"""
======================
@author : Zhang Xu
@time : 2021/9/8:16:29
@email : zxreaper@foxmail.com
@content : tensorflow subclassing 复现 NPA
======================
"""
import tensorflow as tf
from tensorflow.keras import *
from tensorflow.keras.layers import *
from keras import ... | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n======================\r\n@author : Zhang Xu\r\n@time : 2021/9/8:16:29\r\n@email : zxreaper@foxmail.com\r\n@content : tensorflow subclassing 复现 NPA\r\n======================\r\n\"\"\"\r\nimport tensorflow as tf\r\nfrom tensorflow.keras import *\r\nfrom tensorflow.keras.la... | false |
1,288 | 4a17db6b65e1615b0d519581b3e63bc34ad16093 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 15 15:36:38 2021
@author: mav24
"""
import pandas as pd
import numpy as np
from sklearn.preprocessing import QuantileTransformer, StandardScaler, PowerTransformer, MaxAbsScaler
from sklearn.cross_decomposition import PLSRegression
from sklearn.en... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 15 15:36:38 2021\n\n@author: mav24\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import QuantileTransformer, StandardScaler, PowerTransformer, MaxAbsScaler\n\nfrom sklearn.cross_decomposition import PLSRe... | false |
1,289 | 563e534e4794aa872dcdc5319b9a1943d19f940f | import random
import time
class Cells:
UNDEFINED = 0
DEAD = 1
ALIVE = 2
def __init__(self, nx, ny, density = 5):
self.nx = nx
self.ny = ny
self._cells = [[Cells.UNDEFINED for y in range(ny)] for x in range(nx)]
self._nextCells = [[Cells.UNDEFINED for y in range(ny)] for... | [
"import random\nimport time\n\nclass Cells:\n UNDEFINED = 0\n DEAD = 1\n ALIVE = 2\n\n def __init__(self, nx, ny, density = 5):\n self.nx = nx\n self.ny = ny\n self._cells = [[Cells.UNDEFINED for y in range(ny)] for x in range(nx)]\n self._nextCells = [[Cells.UNDEFINED for y ... | false |
1,290 | 85dfb30a380dc73f5a465c8f4be84decccfbcb59 | /Users/sterlingbutters/anaconda3/lib/python3.6/encodings/cp037.py | [
"/Users/sterlingbutters/anaconda3/lib/python3.6/encodings/cp037.py"
] | true |
1,291 | 6192099bdecffd9ce3576f4034567478145115a0 | import queue
import copy
import heapq
import sys
sys.setrecursionlimit(100000)
dx =[1,0,0,-1]
dy=[0,1,-1,0]
class PriorityQueue:
pq=[]
elements={}
task=0
def insert(self , priority,x_val,y_val):
entry = [priority, self.task,x_val,y_val]
self.elements[self.task]=entry
heapq.hea... | [
"import queue\nimport copy\nimport heapq\nimport sys\nsys.setrecursionlimit(100000)\n\ndx =[1,0,0,-1]\ndy=[0,1,-1,0]\n\nclass PriorityQueue:\n pq=[]\n elements={}\n task=0\n\n def insert(self , priority,x_val,y_val):\n entry = [priority, self.task,x_val,y_val]\n self.elements[self.task]=en... | false |
1,292 | 94d296b5a13bfa59dba5812da31707f9db9080af | """
Implements a Neural Network
"""
from vectorflux import VectorFlux
from mnist import read, show, normalize
from vectorflux.layers import Dense
from vectorflux.layers.Dropout import Dropout
train = list(read('train'))
test = list(read('test'))
print("Train size: {}".format(len(train)))
print("Test size: {}".forma... | [
"\"\"\"\nImplements a Neural Network\n\n\"\"\"\nfrom vectorflux import VectorFlux\nfrom mnist import read, show, normalize\n\nfrom vectorflux.layers import Dense\nfrom vectorflux.layers.Dropout import Dropout\n\ntrain = list(read('train'))\ntest = list(read('test'))\n\nprint(\"Train size: {}\".format(len(train)))\n... | false |
1,293 | 0e337ce21450e0fdb7688183d0542ebf902a9614 |
import messages
import os
import requests
from bs4 import BeautifulSoup
URL = "https://mailman.kcl.ac.uk/mailman/"
ADMIN = "admin/"
ROSTER = "roster/"
OUTPUT_FOLDER = "../output/"
def makeoutput(path):
if os.path.exists(path):
pass
else:
os.mkdir(path)
def mailinglist_cookies(mailinglist, password): # this o... | [
"\nimport messages\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\n\nURL = \"https://mailman.kcl.ac.uk/mailman/\"\nADMIN = \"admin/\"\nROSTER = \"roster/\"\nOUTPUT_FOLDER = \"../output/\"\n\ndef makeoutput(path):\t\n\tif os.path.exists(path):\n\t\tpass\n\telse:\n\t\tos.mkdir(path)\n\ndef mailinglist_coo... | false |
1,294 | e6320bc1c344c87818a4063616db0c63b7b8be49 | from tkinter import *
global math
root = Tk()
root.title("Calculator")
e = Entry(root,width=60,borderwidth=5)
e.grid(columnspan=3)
def button_click(number):
#e.delete(0, END)
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(number))
def button_clear():
e.delete(0, END)
... | [
"from tkinter import *\r\n\r\nglobal math\r\n\r\nroot = Tk()\r\n\r\nroot.title(\"Calculator\")\r\n\r\ne = Entry(root,width=60,borderwidth=5)\r\ne.grid(columnspan=3)\r\n\r\ndef button_click(number):\r\n\t#e.delete(0, END)\r\n\tcurrent = e.get()\r\n\te.delete(0, END)\r\n\te.insert(0, str(current) + str(number))\r\n\r... | false |
1,295 | 13fa650557a4a8827c9fb2e514bed178df19a32c | """ Image Check / Compress Image"""
import re
import os
from PIL import Image
from common.constant import PATH
def check_image(file_type):
match = re.match("image/*", file_type)
return match
def compress_image(data):
with open(PATH.format(data['name']), 'wb+') as file:
file.write(data['binary'... | [
"\"\"\" Image Check / Compress Image\"\"\"\n\nimport re\nimport os\nfrom PIL import Image\n\nfrom common.constant import PATH\n\n\ndef check_image(file_type):\n match = re.match(\"image/*\", file_type)\n return match\n\n\ndef compress_image(data):\n with open(PATH.format(data['name']), 'wb+') as file:\n ... | false |
1,296 | 927b42326ad62f5e484fd7016c42a44b93609f83 | #!/usr/bin/python
# coding: utf-8
from os.path import dirname, abspath
PICKITEMSP = True
RAREP = True
REPAIRP = False
ITEMS = {
"legendary": ["#02CE01", # set
"#BF642F"], # legndary
"rare": ["#BBBB00"]
}
current_abpath = abspath(dirname(__file__)) + "/"
# Wi... | [
"#!/usr/bin/python\r\n# coding: utf-8\r\n\r\nfrom os.path import dirname, abspath\r\n\r\nPICKITEMSP = True\r\nRAREP\t = True\r\nREPAIRP = False\r\n\r\nITEMS = {\r\n \"legendary\": [\"#02CE01\", # set\r\n \"#BF642F\"], # legndary\r\n \"rare\":\t [\"#BBBB00\"]\r\n }\r\n\r\ncurrent_... | false |
1,297 | 65aa761110877bd93c2d2cb3d097fa3e126f72b1 | from application.processing_data.twitter import TwitterAPIv2
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
from .twitter import TwitterAPIv2
categories={
'Noise Complaints': {
'loud',
'party',
'noisy',
'noise',
'... | [
"from application.processing_data.twitter import TwitterAPIv2\nfrom azure.ai.textanalytics import TextAnalyticsClient\nfrom azure.core.credentials import AzureKeyCredential\nfrom .twitter import TwitterAPIv2\n\ncategories={\n 'Noise Complaints': {\n 'loud',\n 'party',\n 'noisy',\n 'no... | true |
1,298 | 0ee902d59d3d01b6ec8bb4cc8d5e8aa583644397 | from __future__ import print_function
import ot
import torch
import numpy as np
from sklearn.neighbors import KernelDensity
from torch.utils.data import Dataset
import jacinle.io as io
import optimal_transport_modules.pytorch_utils as PTU
import optimal_transport_modules.generate_data as g_data
from optimal_transport_m... | [
"from __future__ import print_function\nimport ot\nimport torch\nimport numpy as np\nfrom sklearn.neighbors import KernelDensity\nfrom torch.utils.data import Dataset\nimport jacinle.io as io\nimport optimal_transport_modules.pytorch_utils as PTU\nimport optimal_transport_modules.generate_data as g_data\nfrom optim... | false |
1,299 | de0d0588106ab651a8d6141a44cd9e286b0ad3a5 | """
采集端任务状态统计
直接在数据库查找数据
create by judy 2018/10/22
update by judy 2019/03/05
更改统一输出为output
"""
from datetime import datetime
import time
import traceback
import pytz
from datacontract import ETaskStatus
from datacontract.clientstatus.statustask import StatusTask
from idownclient.clientdbmanager import DbManager
from... | [
"\"\"\"\n采集端任务状态统计\n直接在数据库查找数据\ncreate by judy 2018/10/22\n\nupdate by judy 2019/03/05\n更改统一输出为output\n\"\"\"\nfrom datetime import datetime\nimport time\nimport traceback\n\nimport pytz\n\nfrom datacontract import ETaskStatus\nfrom datacontract.clientstatus.statustask import StatusTask\nfrom idownclient.clientdbma... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.