index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
5,500 | 1ccaedb6e79101764db1907634ba627a0f9f2bb2 | class Solution(object):
def maxSubArrayLen(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
sums = [0] * (len(nums) + 1)
seen = {}
seen[0] = -1
res = 0
for idx, n in enumerate(nums):
sums[idx +... | [
"class Solution(object):\n def maxSubArrayLen(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n sums = [0] * (len(nums) + 1)\n seen = {}\n seen[0] = -1\n res = 0\n \n for idx, n in enumerate(nums):... | false |
5,501 | 9539d2a4da87af1ff90b83bbcf72dfc8ab7b6db0 | """Unit tests for the `esmvalcore.preprocessor._rolling_window` function."""
import unittest
import iris.coords
import iris.exceptions
import numpy as np
from cf_units import Unit
from iris.cube import Cube
from numpy.testing import assert_equal
from esmvalcore.preprocessor._rolling_window import rolling_window_stati... | [
"\"\"\"Unit tests for the `esmvalcore.preprocessor._rolling_window` function.\"\"\"\nimport unittest\n\nimport iris.coords\nimport iris.exceptions\nimport numpy as np\nfrom cf_units import Unit\nfrom iris.cube import Cube\nfrom numpy.testing import assert_equal\n\nfrom esmvalcore.preprocessor._rolling_window import... | false |
5,502 | 1530f1711be6313b07df680721daf4cb0a84edc0 | # ------------------------------------------------------------
# calclex.py
#
# tokenizer for a simple expression evaluator for
# numbers and +,-,*,/
# ------------------------------------------------------------
import ply.lex as lex
# Regular expression rules for simple tokens
t_PLUS = r'\+'
t_MINUS = r'-'... | [
"# ------------------------------------------------------------\n# calclex.py\n#\n# tokenizer for a simple expression evaluator for\n# numbers and +,-,*,/\n# ------------------------------------------------------------\nimport ply.lex as lex\n\n\n\n\n\n\n# Regular expression rules for simple tokens\nt_PLUS = r'\... | true |
5,503 | 8e1de62f2490d2276a834ae1ab0f1958649fa821 | # 938. Range Sum of BST
# Share
# Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
# The binary search tree is guaranteed to have unique values.
# Example 1:
# Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
# Output: 32
# Example 2:
... | [
"# 938. Range Sum of BST\n\n\n# Share\n# Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).\n\n# The binary search tree is guaranteed to have unique values.\n\n \n\n# Example 1:\n\n# Input: root = [10,5,15,3,7,null,18], L = 7, R = 15\n# Output:... | false |
5,504 | d0f83e3b7eb5e1bc81a56e46043f394757437af8 | from django.db import models
# Create your models here.
class GeneralInformation(models.Model):
name = models.CharField(max_length=100)
address = models.TextField()
city = models.CharField(max_length=20)
class Meta:
ordering = ['name']
def __str__(self):
return "{} {} {}".format... | [
"from django.db import models\n\n\n# Create your models here.\n\nclass GeneralInformation(models.Model):\n name = models.CharField(max_length=100)\n address = models.TextField()\n city = models.CharField(max_length=20)\n\n class Meta:\n ordering = ['name']\n\n def __str__(self):\n retur... | false |
5,505 | 5251724656e1d971900fff3d8fa0210c6cfc27bb | n=int(0)
import random
def doubleEven(n):
if n % 2 == 0:
n = n*2
return (n)
else:
return "-1"
print(doubleEven(n = int(input("put in a number"))))
g=int(0)
def grade(g):
if g < 50:
return "F"
if g < 66:
return "C"
if g > 92:
return "A+"
else:
... | [
"n=int(0)\nimport random\ndef doubleEven(n):\n if n % 2 == 0:\n n = n*2\n return (n)\n else:\n return \"-1\"\n\n\nprint(doubleEven(n = int(input(\"put in a number\"))))\n\ng=int(0)\n\ndef grade(g):\n if g < 50:\n return \"F\"\n if g < 66:\n return \"C\"\n if g > 92:... | true |
5,506 | 53fd020946a2baddb1bb0463d2a56744de6e3822 | #List methods allow you to modify lists. The following are some list methods for you to practice with. Feel free to google resources to help you with this assignment.
#append(element) adds a single element to the list
#1. 'Anonymous' is also deserving to be in the hacker legends list. Add him in to the hacker legends ... | [
"#List methods allow you to modify lists. The following are some list methods for you to practice with. Feel free to google resources to help you with this assignment.\n\n#append(element) adds a single element to the list\n#1. 'Anonymous' is also deserving to be in the hacker legends list. Add him in to the hacker ... | false |
5,507 | a1d1056f302cf7bc050537dd8cc53cdb2da7e989 |
#calss header
class _PULPIER():
def __init__(self,):
self.name = "PULPIER"
self.definitions = pulpy
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['pulpy']
| [
"\n\n#calss header\nclass _PULPIER():\n\tdef __init__(self,): \n\t\tself.name = \"PULPIER\"\n\t\tself.definitions = pulpy\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.basic = ['pulpy']\n",
"class _PULPIER:\n\n def __init__(self):\n self.... | false |
5,508 | 4ae611ee8c019c76bb5d7c1d733ffb4bd06e2e8d | # import random module from Python standard library
# define a dictionary with image urls and number of flucks
# set the served img variable to be a random element from imgs
# hints:
# to put dict keys in a list: list(dict.keys())
# to choose a random item from a list: random.choice(lst)
# keep asking user if they ... | [
"# import random module from Python standard library\n\n# define a dictionary with image urls and number of flucks\n\n# set the served img variable to be a random element from imgs\n# hints: \n#\tto put dict keys in a list: list(dict.keys())\n#\tto choose a random item from a list: random.choice(lst)\n\n# keep aski... | false |
5,509 | 0470f98247f8f835c0c052b01ddd7f1f7a515ab5 | #-*- coding:utf-8 -*-
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
_exception = None
import os
class xmlSp:
def addNode(self,parentNode,childNode):
parentNode.append(childNode)
def createChildNode(self,key,value,propertyMap={}):
element... | [
"#-*- coding:utf-8 -*-\n\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element \n\n_exception = None\n\nimport os\nclass xmlSp: \n def addNode(self,parentNode,childNode): \n parentNode.append(childNode) \n \n def createChildNode(self,key,value,propertyMap={})... | false |
5,510 | 4d31985cf1266619406d79a7dbae269c10f21bda | import world
import items
class Quest:
def __init__(self):
raise NotImplementedError("Do not create raw quest classes")
def __str__(self):
return self.quest_name
def give_reward(self, player):
print("You receive: \n{} gold\n{} exp".format(self.reward_gold, self.reward_exp))
for item in self.reward_it... | [
"import world\nimport items\n\n\n\nclass Quest:\n\tdef __init__(self):\n\t\traise NotImplementedError(\"Do not create raw quest classes\")\n\t\t\n\tdef __str__(self):\n\t\treturn self.quest_name\n\t\n\tdef give_reward(self, player):\n\t\tprint(\"You receive: \\n{} gold\\n{} exp\".format(self.reward_gold, self.rewar... | false |
5,511 | 399097ef7cfdc061b307c3cc29615c9f50b1e6bf | from utils.gradient_strategy.dct_generator import DCTGenerator
from utils.gradient_strategy.random_generator import RandomGenerator
from utils.gradient_strategy.upsample_generator import UpSampleGenerator
from utils.gradient_strategy.centerconv_generator import CenterConvGenerator
from utils.attack_setting import *
fro... | [
"from utils.gradient_strategy.dct_generator import DCTGenerator\nfrom utils.gradient_strategy.random_generator import RandomGenerator\nfrom utils.gradient_strategy.upsample_generator import UpSampleGenerator\nfrom utils.gradient_strategy.centerconv_generator import CenterConvGenerator\nfrom utils.attack_setting imp... | false |
5,512 | 117b340b13b9b1c53d3df1646cd5924f0118ab5d | #Small enough? - Beginner
# You will be given an array and a limit value.
# You must check that all values in the array are
# below or equal to the limit value. If they are,
# return true. Else, return false.
def small_enough(array, limit):
counter = ""
for arr in array:
if arr <= limit:
... | [
"#Small enough? - Beginner\n# You will be given an array and a limit value. \n# You must check that all values in the array are \n# below or equal to the limit value. If they are, \n# return true. Else, return false.\n\ndef small_enough(array, limit):\n counter = \"\"\n for arr in array:\n if arr <= li... | false |
5,513 | 70b26052d9516fd067ff71074a6dc4c58ace7d80 | # ้ธๆ่ขใๆธใๆใใใใชใใใใซlistใงใฏใชใtupleใไฝฟใ
chose_from_two = ('A', 'B', 'C')
answer = []
answer.append('A')
answer.append('C')
print(chose_from_two)
# ('A', 'B', 'C')
print(answer)
# ['A', 'C'] | [
"# ้ธๆ่ขใๆธใๆใใใใชใใใใซlistใงใฏใชใtupleใไฝฟใ\nchose_from_two = ('A', 'B', 'C')\n\nanswer = []\nanswer.append('A')\nanswer.append('C')\nprint(chose_from_two)\n# ('A', 'B', 'C')\nprint(answer)\n# ['A', 'C']",
"chose_from_two = 'A', 'B', 'C'\nanswer = []\nanswer.append('A')\nanswer.append('C')\nprint(chose_from_two)\nprint(an... | false |
5,514 | 9928eaa32468453f405d8bb650f3e0e85a7933bf | import os
import cv2
import numpy as np
import torch
import torch.utils.data
import torchvision
from torchvision import transforms
from utils.utils import loadYaml
from .base_datalayer import BaseDataLayer
import albumentations as albu
class Datalayer(BaseDataLayer):
def __init__(self, config, augmentation=None,... | [
"import os\nimport cv2\nimport numpy as np\nimport torch\nimport torch.utils.data\nimport torchvision\nfrom torchvision import transforms\nfrom utils.utils import loadYaml\nfrom .base_datalayer import BaseDataLayer\nimport albumentations as albu\n\n\nclass Datalayer(BaseDataLayer):\n\n def __init__(self, config,... | false |
5,515 | 855bfc9420a5d5031cc673231cc7993ac67df076 | import numpy as np
import h5py
def rotate_z(theta, x):
theta = np.expand_dims(theta, 1)
outz = np.expand_dims(x[:, :, 2], 2)
sin_t = np.sin(theta)
cos_t = np.cos(theta)
xx = np.expand_dims(x[:, :, 0], 2)
yy = np.expand_dims(x[:, :, 1], 2)
outx = cos_t * xx - sin_t * yy
outy = sin_t * x... | [
"import numpy as np\nimport h5py\n\n\ndef rotate_z(theta, x):\n theta = np.expand_dims(theta, 1)\n outz = np.expand_dims(x[:, :, 2], 2)\n sin_t = np.sin(theta)\n cos_t = np.cos(theta)\n xx = np.expand_dims(x[:, :, 0], 2)\n yy = np.expand_dims(x[:, :, 1], 2)\n outx = cos_t * xx - sin_t * yy\n ... | false |
5,516 | 22792937415a8ee4cecff2a9683c435abe54bdab | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright ยฉ 2020- Spyder Project Contributors
#
# Released under the terms of the MIT License
# ----------------------------------------------------------------------------
"""Tests for the execution of pylint."""
... | [
"# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------------\n# Copyright ยฉ 2020- Spyder Project Contributors\n#\n# Released under the terms of the MIT License\n# ----------------------------------------------------------------------------\n\n\"\"\"Tests for the execution... | false |
5,517 | 520b9246c3c617b18ca57f31ff51051cc3ff51ca | from abc import ABC, abstractmethod
class Shape(ABC): # Shape is a child class of ABC
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, length):
self.length = length
square = Square(4)
# this will co... | [
"from abc import ABC, abstractmethod\n\n\nclass Shape(ABC): # Shape is a child class of ABC\n @abstractmethod\n def area(self):\n pass\n\n @abstractmethod\n def perimeter(self):\n pass\n\n\nclass Square(Shape):\n def __init__(self, length):\n self.length = length\n\n\nsquare = S... | false |
5,518 | c28d7fc45be9a6efa7b7ef00520898c3d238ac63 | a=raw_input("Enter the column\n")
b=raw_input("Enter the row\n")
i=0
k=0
m=0
c=""
d=""
while (m<int(b)):
while(i<int(a)):
c=c+" "
for j in xrange(1,4):
c=c+"-"
i=i+1
while(k<int(a)):
d=d+"|"
for l in xrange(1,4):
d=d+" "
k=k+1
m=m+1
... | [
"a=raw_input(\"Enter the column\\n\")\nb=raw_input(\"Enter the row\\n\")\ni=0\nk=0\nm=0\nc=\"\"\nd=\"\"\nwhile (m<int(b)):\n while(i<int(a)):\n c=c+\" \"\n for j in xrange(1,4):\n c=c+\"-\"\n i=i+1\n while(k<int(a)):\n d=d+\"|\"\n for l in xrange(1,4):\n ... | true |
5,519 | b573db8ea0845fb947636b8d82ed462904c6005d | import boto3
from app.models import *
from app.config import *
from app.lib.log import save_races_to_db, save_laptimes_to_db
from app.utils.utils import get_sec
import pandas as pd
def import_csv_from_aws():
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCE... | [
"import boto3\nfrom app.models import *\nfrom app.config import *\nfrom app.lib.log import save_races_to_db, save_laptimes_to_db\nfrom app.utils.utils import get_sec\nimport pandas as pd\n\ndef import_csv_from_aws():\n\n\tclient = boto3.client(\n\t\t's3',\n\t\taws_access_key_id=AWS_ACCESS_KEY_ID,\n\t\taws_secret_ac... | false |
5,520 | e58dbb4f67c93abf3564dc0f38df8852313338f0 | import time
import jax.numpy as jnp
def tick():
return time.perf_counter()
def tock(t0, dat=None):
if dat is not None:
try:
_ = dat.block_until_ready()
except AttributeError:
_ = jnp.array(dat).block_until_ready()
return time.perf_counter() - t0
| [
"import time\nimport jax.numpy as jnp\n\n\ndef tick():\n return time.perf_counter()\n\n\ndef tock(t0, dat=None):\n if dat is not None:\n try:\n _ = dat.block_until_ready()\n except AttributeError:\n _ = jnp.array(dat).block_until_ready()\n return time.perf_counter() - t0... | false |
5,521 | 083a9555f8db586fbb065d59e4e333bb16ee3d2a | import os
import sys
from subprocess import check_output
from charmhelpers.fetch import (
apt_install,
apt_update,
add_source,
)
from charmhelpers.core.templating import render
from charmhelpers.contrib.database.mysql import MySQLHelper
def install_mysql(package='mysql-server', sources=None, keys=None)... | [
"import os\nimport sys\n\nfrom subprocess import check_output\n\nfrom charmhelpers.fetch import (\n apt_install,\n apt_update,\n add_source,\n)\n\nfrom charmhelpers.core.templating import render\nfrom charmhelpers.contrib.database.mysql import MySQLHelper\n\n\ndef install_mysql(package='mysql-server', sour... | false |
5,522 | b2371f9c774c605a52ff1a4fae2dd44a856076aa | no=int(input("enter no:"))
rev=0
while no!=0:
r=no%10
no=no//10
rev=rev*10+r
print("reverse no is:",rev)
| [
"no=int(input(\"enter no:\"))\nrev=0\nwhile no!=0:\n r=no%10\n no=no//10\n rev=rev*10+r\nprint(\"reverse no is:\",rev)\n ",
"no = int(input('enter no:'))\nrev = 0\nwhile no != 0:\n r = no % 10\n no = no // 10\n rev = rev * 10 + r\nprint('reverse no is:', rev)\n",
"<assignment token>\nwhile ... | false |
5,523 | 2da10163a40c9720ca9deecd9afb0e39aa885546 | from tkinter import *
from PIL import ImageTk,Image
import sys, os
# This will display images and icon
root = Tk()
root.title("Expanding GUI")
# With ubuntu, it did not work the icon part
#root.iconbitmap('@/home/gxgarciat/Documents/Tkinter/gdrive.ico')
#root.iconphoto(True, PhotoImage(file="@/home/gxgarciat/Docume... | [
"from tkinter import *\nfrom PIL import ImageTk,Image\n\nimport sys, os\n\n# This will display images and icon\n\nroot = Tk()\nroot.title(\"Expanding GUI\")\n\n# With ubuntu, it did not work the icon part\n#root.iconbitmap('@/home/gxgarciat/Documents/Tkinter/gdrive.ico')\n#root.iconphoto(True, PhotoImage(file=\"@/h... | false |
5,524 | d805a1290c107a8d768417a432e338b182b7cd6b | import numpy as np
class LinearRegressor():
def __init__(self, alpha=0.1, epochs=1):
self.alpha = alpha
self.epochs = epochs
self.costs = []
self.theta = None
def _cost_function(self, y_pred, y, m):
"""
Gets the cost for the predicted values when contrasted wit... | [
"import numpy as np\n\n\nclass LinearRegressor():\n def __init__(self, alpha=0.1, epochs=1):\n self.alpha = alpha\n self.epochs = epochs\n self.costs = []\n self.theta = None\n\n def _cost_function(self, y_pred, y, m):\n \"\"\"\n Gets the cost for the predicted values... | false |
5,525 | 1fe6fab717a77f13ddf7059ef0a5aaef217f0fb0 | class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
left, right = 0, n-1
found = False
res = None
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
found = True
... | [
"class Solution:\n def search(self, nums: List[int], target: int) -> int:\n \n n = len(nums)\n left, right = 0, n-1\n found = False\n res = None\n\n while left <= right:\n mid = left + (right - left) // 2\n if nums[mid] == target:\n f... | false |
5,526 | 64bbf2e3b961a6e0b5d7e551278bb21990df2ed9 | import uuid
from fastapi import APIRouter, Depends, HTTPException, Form, Body
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
# dependency
from configs.config_sqlalchemy import get_db
# schema
from schema import store_schema
# define the url the clie... | [
"import uuid\n\nfrom fastapi import APIRouter, Depends, HTTPException, Form, Body\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\nfrom sqlalchemy.orm import Session\n\n# dependency\nfrom configs.config_sqlalchemy import get_db\n# schema\nfrom schema import store_schema \n\n\n\n# defin... | false |
5,527 | 4daab8b8db1e394e3132ab5550fe0236b67074d8 | from helper import *
tree_type = TREE_TYPE_SPLIT
file_name = ''
file_path = ''
split_scalars = {}
visited = {}
adjacency = {}
pairs = {}
index_map = {}
postorder_map = {}
preorder_map = {}
birth = {}
death = {}
string = ''
class Tree(object):
def __init__(self):
self.index = None
self.children = []
self.p... | [
"from helper import *\n\ntree_type = TREE_TYPE_SPLIT\n\nfile_name = ''\nfile_path = ''\n\nsplit_scalars = {}\nvisited = {}\nadjacency = {}\npairs = {}\n\nindex_map = {}\npostorder_map = {}\npreorder_map = {}\n\nbirth = {}\ndeath = {}\n\nstring = ''\n\nclass Tree(object):\n\tdef __init__(self):\n\t\tself.index = Non... | true |
5,528 | 6cc23a3e2fa3b1baddf05b30a1054a7faf0371a6 | # -*- coding: utf-8 -*-
from .base import BaseSchema
from marshmallow import fields
class BaseTickSchema(BaseSchema):
"""
Time ๏ผ ๆถ้ด
High ๏ผ ๆ้ซไปท
Low ๏ผ ๆไฝไปท
Volume ๏ผ ไบคๆ้
Last ๏ผ ๆๆฐไปท
"""
Time = fields.String()
High = fields.String()
Low = ... | [
"# -*- coding: utf-8 -*-\nfrom .base import BaseSchema\nfrom marshmallow import fields\n\n\nclass BaseTickSchema(BaseSchema):\n \"\"\"\n Time ๏ผ ๆถ้ด\n High ๏ผ ๆ้ซไปท\n Low ๏ผ ๆไฝไปท\n Volume ๏ผ ไบคๆ้\n Last ๏ผ ๆๆฐไปท\n \"\"\"\n\n Time = fields.String()\n High = ... | false |
5,529 | 530c2c185e57ffd3ac64628fc9f7f7985b0480fe | #!/usr/bin/env python
import numpy as np
import time, random
import sys, os, struct, socket
import psycopg2
import test_coords
import alex_random
import new_sim_utils
import sdr_kml_writer
from geo_utils import geo_utils
from beacon import beacon
from sim_data import data_utils
ENABLE_JITTER = False
ENABLE_DROPPED_... | [
"#!/usr/bin/env python\n\nimport numpy as np\nimport time, random\nimport sys, os, struct, socket\nimport psycopg2\n\nimport test_coords\nimport alex_random\nimport new_sim_utils\nimport sdr_kml_writer\n\nfrom geo_utils import geo_utils\nfrom beacon import beacon\nfrom sim_data import data_utils\n\nENABLE_JITTER = ... | true |
5,530 | 25ce31aee44c80ce4a5c1af7d1ca12c73c14df47 | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=timezone.now)
autho... | [
"from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.urls import reverse\n\n\nclass Post(models.Model):\n title = models.CharField(max_length=100)\n content = models.TextField()\n date_posted = models.DateTimeField(auto_now_add=timezone.... | false |
5,531 | 4df747b3ff254e0ccc4483acd7be12f3441bbcd8 |
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall, and %r heavy." % (age, height, weight)
#raw_input does not exist in Python 3.x while input() does. raw_input() returns a string, and inp... | [
"\nprint \"How old are you?\",\nage = raw_input()\nprint \"How tall are you?\",\nheight = raw_input()\nprint \"How much do you weigh?\",\nweight = raw_input()\n\nprint \"So, you're %r old, %r tall, and %r heavy.\" % (age, height, weight)\n\n#raw_input does not exist in Python 3.x while input() does. raw_input() re... | true |
5,532 | 505689803c8f4490619ab1a7579fde1e2c18c538 | from datetime import datetime
import struct
BEACON_LENGTH = 84
EPS_LENGTH = 20
COM_LENGTH = 10
# reverse engineered
ADCS1_LENGTH = 7
ADCS2_LENGTH = 6
AIS_LENGTH = 20
class EPS(object):
def __init__(self, eps_data):
if len(eps_data) != EPS_LENGTH:
raise InputException(len(eps_data), EPS_LENGTH... | [
"from datetime import datetime\nimport struct\n\nBEACON_LENGTH = 84\nEPS_LENGTH = 20\nCOM_LENGTH = 10\n\n# reverse engineered\nADCS1_LENGTH = 7\nADCS2_LENGTH = 6\nAIS_LENGTH = 20\n\nclass EPS(object):\n def __init__(self, eps_data):\n if len(eps_data) != EPS_LENGTH:\n raise InputException(len(e... | false |
5,533 | a99426c0751885f17078e709fd523cf3a26f5286 | '''
sin(x) = x^1/1! - x^3/3! + x^5/5! - x^7/7! + โฆ..
Input : x, n ( No. of terms I want in series )
Input : 3.14, 10
Output : sin(3.14) = sin(180) = 0
Radians vs Degrees
( 0, 30, 60, 90 โฆ.)
2pi = 360
Pi = 180
Pseudo code :
1.Take input variables radians,num
2. sin = 0
3. Indices = 1
4. odd = 1
4... | [
"'''\nsin(x) = x^1/1! - x^3/3! + x^5/5! - x^7/7! + โฆ..\n\nInput : x, n ( No. of terms I want in series )\n\nInput : 3.14, 10\n\nOutput : sin(3.14) = sin(180) = 0\n\nRadians vs Degrees\n\n\n( 0, 30, 60, 90 โฆ.)\n2pi = 360\nPi = 180\n\n\nPseudo code :\n1.Take input variables radians,num\n2. sin = 0\n3.... | false |
5,534 | 04b02931b749ad06a512b78ca5661ae1f5cb8a9c | from random import randint
from Ball import Ball
from Util import Vector, Rectangle
class Player:
RADIUS = 10
COLOR1 = "#80d6ff"
COLOR2 = "#ff867c"
OUTLINE = "#000000"
@property
def right(self):
return self.pos.sub(Vector(Player.RADIUS, 0))
@property
def left(self):
... | [
"from random import randint\n\nfrom Ball import Ball\nfrom Util import Vector, Rectangle\n\n\nclass Player:\n RADIUS = 10\n\n COLOR1 = \"#80d6ff\"\n COLOR2 = \"#ff867c\"\n OUTLINE = \"#000000\"\n\n @property\n def right(self):\n return self.pos.sub(Vector(Player.RADIUS, 0))\n\n @property... | false |
5,535 | be5a683309317f1f6ebc20ad3511fd2b2510e806 | from django.http.response import HttpResponse
from django.shortcuts import render , HttpResponse
import requests
from django.conf import settings
from .forms import WeatherForm
# Create your views here.
def get_weather(request):
form = WeatherForm()
error = ""
output = {}
if request.method == 'POST':
... | [
"from django.http.response import HttpResponse\nfrom django.shortcuts import render , HttpResponse\nimport requests\nfrom django.conf import settings\nfrom .forms import WeatherForm\n# Create your views here.\n\ndef get_weather(request):\n form = WeatherForm()\n error = \"\"\n output = {}\n if request.m... | false |
5,536 | ba94a69ac356969ab593afc922a2517f4713771f | __title__ = 'FUCKTHEINTRUDERS'
__description__ = 'Checking for Intruders in my locality'
__version__ = '0.0.1'
__author__ = 'Shivam Jalotra'
__email__ = 'shivam_11710495@nitkkr.ac.in'
__license__ = 'MIT 1.0'
| [
"__title__ = 'FUCKTHEINTRUDERS'\n__description__ = 'Checking for Intruders in my locality'\n__version__ = '0.0.1'\n__author__ = 'Shivam Jalotra'\n__email__ = 'shivam_11710495@nitkkr.ac.in'\n__license__ = 'MIT 1.0'\n",
"<assignment token>\n"
] | false |
5,537 | a638504737d0069d4fa40b0fc5026203904563e8 | from decimal import Decimal
from django.conf import settings
from blood.models import Bank, Blood
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SES... | [
"from decimal import Decimal\nfrom django.conf import settings\nfrom blood.models import Bank, Blood\n\n\nclass Cart(object):\n def __init__(self, request):\n self.session = request.session\n cart = self.session.get(settings.CART_SESSION_ID)\n if not cart:\n cart = self.session[se... | false |
5,538 | 3beaea1f2b1b085a60bdc5e53f4e6d9aff7e8b6f | import cv2,os
import sqlite3
cam = cv2.VideoCapture(0)
detector = cv2.CascadeClassifier('Classifiers/face.xml')
i = 0
offset = 50
def create_or_open_db(db_file):
db_is_new = not os.path.exists(db_file)
conn = sqlite3.connect(db_file)
if db_is_new:
print 'Creating schema'
sql = '''create ta... | [
"import cv2,os\nimport sqlite3\ncam = cv2.VideoCapture(0)\ndetector = cv2.CascadeClassifier('Classifiers/face.xml')\ni = 0\noffset = 50\n\n\ndef create_or_open_db(db_file):\n db_is_new = not os.path.exists(db_file)\n conn = sqlite3.connect(db_file)\n if db_is_new:\n print 'Creating schema'\n ... | true |
5,539 | 88542a18d98a215f58333f5dd2bf5c4b0d37f32f | x = 5
print(x , " "*3 , "5")
print("{:20d}".format(x))
| [
"x = 5\nprint(x , \" \"*3 , \"5\")\nprint(\"{:20d}\".format(x))\n",
"x = 5\nprint(x, ' ' * 3, '5')\nprint('{:20d}'.format(x))\n",
"<assignment token>\nprint(x, ' ' * 3, '5')\nprint('{:20d}'.format(x))\n",
"<assignment token>\n<code token>\n"
] | false |
5,540 | acf409f2e56cd16b7dc07476b49b9c18675f7775 | from PIL import Image
from flask_restplus import Namespace, Resource
from werkzeug.datastructures import FileStorage
from core.models.depthinthewild import DepthInTheWild
from core.utils import serve_pil_image
api = Namespace('nyudepth', description='Models Trained on NYUDepth')
upload_parser = api.parser()
upload_p... | [
"from PIL import Image\nfrom flask_restplus import Namespace, Resource\nfrom werkzeug.datastructures import FileStorage\n\nfrom core.models.depthinthewild import DepthInTheWild\nfrom core.utils import serve_pil_image\n\napi = Namespace('nyudepth', description='Models Trained on NYUDepth')\n\nupload_parser = api.par... | false |
5,541 | 0295d6ba962d099e76110c7a0e39748e3163e300 | #!/usr/bin/env python
###########################################################################
# 1) connect to the MQTT broker
# 2) subscribe to the available data streams
# 3) log to google sheets
# 4) notify on critical events on the telegram channel
###############################################################... | [
"#!/usr/bin/env python\n ###########################################################################\n# 1) connect to the MQTT broker\n# 2) subscribe to the available data streams\n# 3) log to google sheets\n# 4) notify on critical events on the telegram channel\n####################################################... | false |
5,542 | 0544c67cb14549e32b6ff8ea3215c6c65c8416ec | from typing import Any
from electionguard.ballot import CiphertextAcceptedBallot
from electionguard.decryption import compute_decryption_share_for_ballot
from electionguard.election import CiphertextElectionContext
from electionguard.scheduler import Scheduler
from electionguard.serializable import write_json_object
fr... | [
"from typing import Any\nfrom electionguard.ballot import CiphertextAcceptedBallot\nfrom electionguard.decryption import compute_decryption_share_for_ballot\nfrom electionguard.election import CiphertextElectionContext\nfrom electionguard.scheduler import Scheduler\nfrom electionguard.serializable import write_json... | false |
5,543 | 7e9efb267a5464a6e53f81f63d82c28acba8bc8c | # ToDo:
"""
965. Univalued Binary Tree
Easy
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
Note:
The number of nodes in the given tree will be in the range [1, 100].
Each node's value will be an integer in the range [0, 99].
... | [
"# ToDo:\n\n\"\"\"\n965. Univalued Binary Tree\nEasy\n\nA binary tree is univalued if every node in the tree has the same value.\n\nReturn true if and only if the given tree is univalued.\n\nNote:\n\n The number of nodes in the given tree will be in the range [1, 100].\n Each node's value will be an integer i... | true |
5,544 | ddf64ea5ecbd3aa737cd788924035cccb5544fec | ## adapted from https://matplotlib.org/examples/api/radar_chart.html
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.spines import Spine
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
def radar_factory(num... | [
"## adapted from https://matplotlib.org/examples/api/radar_chart.html\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.spines import Spine\nfrom matplotlib.projections.polar import PolarAxes\nfrom matplotlib.projections import register_projection\n\n\ndef r... | false |
5,545 | 225687729b64f455bcc841e83105c7444efdfad3 | import math as m
def calcula_elongacao(A, ฯ, ฯ, t):
x = A * m.cos(ฯ + ฯ * t )
return x | [
"import math as m\n\ndef calcula_elongacao(A, ฯ, ฯ, t):\n x = A * m.cos(ฯ + ฯ * t )\n return x",
"import math as m\n\n\ndef calcula_elongacao(A, ฯ, ฯ, t):\n x = A * m.cos(ฯ + ฯ * t)\n return x\n",
"<import token>\n\n\ndef calcula_elongacao(A, ฯ, ฯ, t):\n x = A * m.cos(ฯ + ฯ * t)\n return x\n",... | false |
5,546 | 54ed0683d0f8d907c27e2f3809f9533556593392 | import json
from pets.pet import Pet
from store_requests.store import Store
from user_requests.user import User
SUCCESS = 200
NotFound = 404
url_site = 'https://petstore.swagger.io/v2'
new_username = "Khrystyna"
new_id = 12345
invalid_new_id = 1234
error_message = "oops we have a problem!"
store_inventory = {
"1": ... | [
"import json\n\nfrom pets.pet import Pet\nfrom store_requests.store import Store\nfrom user_requests.user import User\n\nSUCCESS = 200\nNotFound = 404\nurl_site = 'https://petstore.swagger.io/v2'\nnew_username = \"Khrystyna\"\nnew_id = 12345\ninvalid_new_id = 1234\nerror_message = \"oops we have a problem!\"\nstore... | false |
5,547 | 918358f6e8e3f1c601b18a3c08fc6b7c024721ba | password = '#Garb1122' | [
"password = '#Garb1122'",
"password = '#Garb1122'\n",
"<assignment token>\n"
] | false |
5,548 | 04e57739e6fb98cd237fbe09caecd17c728c1797 | # terrascript/external/__init__.py
import terrascript
class external(terrascript.Provider):
pass | [
"# terrascript/external/__init__.py\n\nimport terrascript\n\nclass external(terrascript.Provider):\n pass",
"import terrascript\n\n\nclass external(terrascript.Provider):\n pass\n",
"<import token>\n\n\nclass external(terrascript.Provider):\n pass\n",
"<import token>\n<class token>\n"
] | false |
5,549 | 1396509f65d194eeaefa3841e152b7078abf0032 | import sys
class Bus:
def __init__(self):
self.seats=0
self.dict_seats={}
self.num_passenger = 0
def conctructor(self,seats):
self.seats=seats
for i in range(1,self.seats+1):
self.dict_seats.update({i:"Free"})
return self.dict_seats
def getOn(sel... | [
"import sys\nclass Bus:\n def __init__(self):\n self.seats=0\n self.dict_seats={}\n self.num_passenger = 0\n\n def conctructor(self,seats):\n self.seats=seats\n for i in range(1,self.seats+1):\n self.dict_seats.update({i:\"Free\"})\n return self.dict_seats\... | false |
5,550 | e77e0791ddf211807566528e9532eebb54db43b5 | from abc import ABC, abstractmethod
from datetime import datetime, timedelta, date
import os
import housekeeper
import yfinance as yf
import pandas as pd
class DataManager(ABC):
def __init__(self):
self.__myHousekeeper = housekeeper.instance_class()
self.__config_filename = "tickers... | [
"from abc import ABC, abstractmethod\nfrom datetime import datetime, timedelta, date\nimport os\n\nimport housekeeper\n\nimport yfinance as yf\nimport pandas as pd\n\nclass DataManager(ABC):\n \n def __init__(self):\n \n self.__myHousekeeper = housekeeper.instance_class()\n self.__config_... | false |
5,551 | 3e1c2d0c5bb30d093a99f10020af14db5436bf02 | # -*- coding: utf-8 -*-
"""microcms package, minimalistic flatpage enhancement.
THIS SOFTWARE IS UNDER BSD LICENSE.
Copyright (c) 2010-2012 Daniele Tricoli <eriol@mornie.org>
Read LICENSE for more informations.
"""
VERSION = (0, 2, 0)
| [
"# -*- coding: utf-8 -*-\n\"\"\"microcms package, minimalistic flatpage enhancement.\n\nTHIS SOFTWARE IS UNDER BSD LICENSE.\nCopyright (c) 2010-2012 Daniele Tricoli <eriol@mornie.org>\n\nRead LICENSE for more informations.\n\"\"\"\nVERSION = (0, 2, 0)\n",
"<docstring token>\nVERSION = 0, 2, 0\n",
"<docstring to... | false |
5,552 | 844b8e2d4f05a51282b356c995f2733d6935a5d6 | # We will try to implement add noise to audio file and filter it using Mean and Median Filters.
import numpy as np
import scipy
import matplotlib.pyplot as plt
from scipy.io.wavfile import read
from scipy.io.wavfile import write
rate,audio_original = read('Audio_Original.wav')
audio = audio_original[:,0]
write("Audi... | [
"# We will try to implement add noise to audio file and filter it using Mean and Median Filters.\n\nimport numpy as np\nimport scipy\nimport matplotlib.pyplot as plt\nfrom scipy.io.wavfile import read\nfrom scipy.io.wavfile import write\n\n\nrate,audio_original = read('Audio_Original.wav')\naudio = audio_original[:... | false |
5,553 | 9bf8834b12bcace0f6daf64adae1babe78bb04fa | '''
Created on Nov 1, 2013
@author: hanchensu
'''
from numpy import *
import numpy as np
def smoSimple(dataMatIn, classLabels, C, toler, maxIter):
dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()
b = 0; m,n = shape(dataMatrix)
matrix = mat([[1,2],[3,4],[5,6]])
m,n= shape(matrix)
matA = mat... | [
"'''\nCreated on Nov 1, 2013\n\n@author: hanchensu\n'''\nfrom numpy import *\nimport numpy as np\n\ndef smoSimple(dataMatIn, classLabels, C, toler, maxIter):\n dataMatrix = mat(dataMatIn); labelMat = mat(classLabels).transpose()\n b = 0; m,n = shape(dataMatrix)\n \nmatrix = mat([[1,2],[3,4],[5,6]])\nm,n= shape(m... | true |
5,554 | 92b24fe82929ed4590e5350188673c2245136d03 | from db import do_command, do_command_no_return, do_insert
def get_grocery(upc):
cmd = "SELECT name FROM grocery WHERE upc = ?"
rtVal = do_command(cmd, [upc])
length = len(rtVal)
if length > 0:
return {'success': bool(len(rtVal)), 'grocery': rtVal[0]}
return {'success': bool(len(rtVal))... | [
"from db import do_command, do_command_no_return, do_insert\n\n\ndef get_grocery(upc):\n cmd = \"SELECT name FROM grocery WHERE upc = ?\"\n rtVal = do_command(cmd, [upc])\n\n length = len(rtVal)\n\n if length > 0:\n return {'success': bool(len(rtVal)), 'grocery': rtVal[0]}\n\n return {'success... | false |
5,555 | b21796a9e10314f80cac3151d1fdbb139966303f | import numpy as np
import scipy.io as sio
import os
import torch
from torchvision.utils import save_image
from tools import *
def test(config, base, loaders, brief):
compute_and_save_features(base, loaders)
results = evalutate(config, base, brief)
return results
def evalutate(config, base, brief=False):
re... | [
"import numpy as np\nimport scipy.io as sio\nimport os\n\nimport torch\nfrom torchvision.utils import save_image\n\nfrom tools import *\n\n\n\ndef test(config, base, loaders, brief):\n\n\tcompute_and_save_features(base, loaders)\n\tresults = evalutate(config, base, brief)\n\treturn results\n\n\ndef evalutate(config... | false |
5,556 | 02381f28ef20aa0c2c235ef6563e1810a5931e35 | from qiskit import QuantumCircuit,execute,Aer
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
qc_ha=QuantumCircuit(4,2)
qc_ha.x(0)
qc_ha.x(1)
qc_ha.barrier()
qc_ha.cx(0,2)
qc_ha.cx(1,2)
qc_ha.ccx(0,1,3)
qc_ha.barrier()
qc_ha.measure(2,0)
qc_ha.measure(3,1)
#qc_ha.draw(output='mpl')
coun... | [
"from qiskit import QuantumCircuit,execute,Aer\nfrom qiskit.visualization import plot_histogram\nimport matplotlib.pyplot as plt\n\nqc_ha=QuantumCircuit(4,2)\nqc_ha.x(0)\nqc_ha.x(1)\nqc_ha.barrier()\nqc_ha.cx(0,2)\nqc_ha.cx(1,2)\nqc_ha.ccx(0,1,3)\nqc_ha.barrier()\nqc_ha.measure(2,0)\nqc_ha.measure(3,1)\n#qc_ha.draw... | false |
5,557 | 539726df0e631c7a8edabf50fd739ee0497e3e97 | from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Lasso, Ridge
from sklearn import tree
import pickle as pk
X = pk.load(file=open('../data/temp/train.pkl', 'rb'))
y = pk.load(file=open('../data/temp/label.pkl', 'rb'))
X_train, X_test, y_train, y_test = train_test_... | [
"from sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression, Lasso, Ridge\nfrom sklearn import tree\nimport pickle as pk\n\nX = pk.load(file=open('../data/temp/train.pkl', 'rb'))\ny = pk.load(file=open('../data/temp/label.pkl', 'rb'))\n\nX_train, X_test, y_train, y_test ... | false |
5,558 | ff358136bc96fa7f3eb41d019ddfd10fc4db8f0d | class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def GetName(self):
return (self.fname + ' ' + self.lname)
| [
"class Person:\n def __init__(self, fname, lname):\n self.fname = fname\n self.lname = lname\n\n def GetName(self):\n return (self.fname + ' ' + self.lname)\n",
"class Person:\n\n def __init__(self, fname, lname):\n self.fname = fname\n self.lname = lname\n\n def Get... | false |
5,559 | f6fe33e04ccdca1d9714caec412478d0cfc8b363 | from flask import Flask, request
from flask import render_template
import sqlite3
import datetime
app = Flask(__name__)
@app.route('/')
def index(date = ""):
date = request.args.get('date')
if not date:
now = datetime.datetime.now()
date = "%02d.%02d.%04d" % (now.day, now.month, now.year)
... | [
"from flask import Flask, request\n\nfrom flask import render_template\nimport sqlite3\nimport datetime\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index(date = \"\"):\n date = request.args.get('date')\n\n if not date:\n now = datetime.datetime.now()\n date = \"%02d.%02d.%04d\" % (now.day... | false |
5,560 | 89d0d5d13c5106c504c6727c7784f048a30495dc | # Generated by Django 3.2 on 2021-05-22 06:54
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Recuerdos',
fields=[
('id', models.BigAutoFie... | [
"# Generated by Django 3.2 on 2021-05-22 06:54\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Recuerdos',\n fields=[\n ('i... | false |
5,561 | c418b9b6903ebdad204a3a55f2384a94a3be0d09 | """
Pattern matching problem
Boyer Moore algorithm
First is my attempt, below is the code provided in the book
Idea:
Optimize brute force approach using 2 heuristics:
- Looking-Glass: start searches from last character of the
pattern and work backwards
- Character-Jump: During testing of a pattern P, a mismatch
in T[i... | [
"\"\"\"\nPattern matching problem\nBoyer Moore algorithm\n\nFirst is my attempt, below is the code provided in the book\nIdea:\nOptimize brute force approach using 2 heuristics:\n- Looking-Glass: start searches from last character of the\npattern and work backwards\n- Character-Jump: During testing of a pattern P, ... | false |
5,562 | af00c6f443426b1f61e1816d7d14ebc7e6871a82 | import csv
import us
from flask import abort, Flask, request, render_template
app = Flask(__name__) # pylint: disable=invalid-name
@app.route('/')
def root():
return render_template('index.html')
@app.route('/api')
def index():
return render_template('index.html')
@app.route('/api/total/counties')
def ... | [
"import csv\nimport us\n\nfrom flask import abort, Flask, request, render_template\n\napp = Flask(__name__) # pylint: disable=invalid-name\n\n\n@app.route('/')\ndef root():\n return render_template('index.html')\n\n\n@app.route('/api')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/ap... | false |
5,563 | ac1d38f550e548dff6ba226dbfc3dd1e5ff876a8 | from django.db import models
from django.contrib.gis.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Project(models.Model):
actual_developer = models.ForeignKey(User,null = True,blank=True, on_delete=models.CASCADE)
# actual_developer = models.CharField(User,null ... | [
"from django.db import models\nfrom django.contrib.gis.db import models\nfrom django.contrib.auth.models import User\n\nfrom django.urls import reverse\n\n\nclass Project(models.Model):\n\tactual_developer = models.ForeignKey(User,null = True,blank=True, on_delete=models.CASCADE)\n\t# actual_developer = models.Char... | false |
5,564 | 65ea40ad1c1bf6bf23aed5316b91862c9cdc353d | __author__ = "Rick Sherman"
__credits__ = "Jeremy Schulman, Nitin Kumar"
import unittest
from nose.plugins.attrib import attr
from jnpr.junos import Device
from jnpr.junos.utils.scp import SCP
from mock import patch
@attr('unit')
class TestScp(unittest.TestCase):
def setUp(self):
self.dev = Device(host... | [
"__author__ = \"Rick Sherman\"\n__credits__ = \"Jeremy Schulman, Nitin Kumar\"\n\nimport unittest\nfrom nose.plugins.attrib import attr\n\nfrom jnpr.junos import Device\nfrom jnpr.junos.utils.scp import SCP\n\nfrom mock import patch\n\n\n@attr('unit')\nclass TestScp(unittest.TestCase):\n def setUp(self):\n ... | false |
5,565 | 75ef5dd2b82cf79819f18045559f9850c74bb55a | from flask import Blueprint, request, make_response
from flask_expects_json import expects_json
from server.validation.schemas import guest_calendar_schema
from tools.for_db.work_with_booking_info import add_booking_info_and_get_uuid
from tools.for_db.work_with_links import get_link
from tools.build_response import bu... | [
"from flask import Blueprint, request, make_response\nfrom flask_expects_json import expects_json\n\nfrom server.validation.schemas import guest_calendar_schema\nfrom tools.for_db.work_with_booking_info import add_booking_info_and_get_uuid\nfrom tools.for_db.work_with_links import get_link\nfrom tools.build_respons... | false |
5,566 | 5261346f96e7520b6ef75a292b3d44a6f00d868c | # Imports
from __future__ import print_function
import numpy
from numpy.random import randint
from enum import Enum
__all__ = ["common", "plot"]
class result(Enum):
CRIT = 16
HIT = 8
EVADE = 4
FOCUS = 2
BLANK = 1
def result_str(res):
str = ""
if res & result.BLANK:
str += "BLANK"
i... | [
"# Imports\r\nfrom __future__ import print_function\r\n\r\nimport numpy\r\nfrom numpy.random import randint\r\nfrom enum import Enum\r\n\r\n__all__ = [\"common\", \"plot\"]\r\n\r\nclass result(Enum):\r\n\tCRIT = 16\r\n\tHIT = 8\r\n\tEVADE = 4\r\n\tFOCUS = 2\r\n\tBLANK = 1\r\n\t\r\ndef result_str(res):\r\n\tstr =... | false |
5,567 | 137842d50355563b2df6c2fc48864c01a22afa80 | # -*- coding:utf-8 -*-
# pylint: disable=line-too-long
_BASE_REPRESENTATIONS = [
"Primitive(field='f1', op='eq', value='value')",
"Primitive(field='f1', op='eq', value=42)",
"Primitive(field='f1', op='eq', value=3.14)",
"Primitive(field='f1', op='eq', value=True)",
"Condition(op=Operator.OR, values... | [
"# -*- coding:utf-8 -*-\n# pylint: disable=line-too-long\n\n_BASE_REPRESENTATIONS = [\n \"Primitive(field='f1', op='eq', value='value')\",\n \"Primitive(field='f1', op='eq', value=42)\",\n \"Primitive(field='f1', op='eq', value=3.14)\",\n \"Primitive(field='f1', op='eq', value=True)\",\n \"Condition(... | false |
5,568 | 1605396a6edb31dd6fe9238a0506f8cfeb794d07 | def play_43():
n=int(input('Enter n :'))
l=[]
for i in range(n):
l.append(int(input()))
for i in range(n-1):
for j in range(i+1,n):
if l[i]<l[j]:
continue
return "no"
return "Yes"
play_43()
| [
"def play_43():\n\tn=int(input('Enter n :'))\n\tl=[]\n\tfor i in range(n):\n\t\tl.append(int(input()))\n\tfor i in range(n-1):\n\t\tfor j in range(i+1,n):\n\t\t\tif l[i]<l[j]:\n\t\t\t\tcontinue\n\t\t\treturn \"no\"\n\treturn \"Yes\"\nplay_43()\n",
"def play_43():\n n = int(input('Enter n :'))\n l = []\n ... | false |
5,569 | 2de62c73507acac597d70557adfe8286e2f28a1f | def assert_number(arg):
if not isinstance(arg, (int, float)):
raise TypeError(f"Expected number, got {type(arg)}")
| [
"def assert_number(arg):\n if not isinstance(arg, (int, float)):\n raise TypeError(f\"Expected number, got {type(arg)}\")\n",
"def assert_number(arg):\n if not isinstance(arg, (int, float)):\n raise TypeError(f'Expected number, got {type(arg)}')\n",
"<function token>\n"
] | false |
5,570 | 788d9fa03c4311a8077d492b1a2b06d1f88826a3 | import numpy as np
import torch
def pad_sequences_1d(sequences, dtype=torch.long, device=torch.device("cpu"), fixed_length=None):
""" Pad a single-nested list or a sequence of n-d array (torch.tensor or np.ndarray)
into a (n+1)-d array, only allow the first dim has variable lengths.
Args:
sequence... | [
"import numpy as np\nimport torch\n\n\ndef pad_sequences_1d(sequences, dtype=torch.long, device=torch.device(\"cpu\"), fixed_length=None):\n \"\"\" Pad a single-nested list or a sequence of n-d array (torch.tensor or np.ndarray)\n into a (n+1)-d array, only allow the first dim has variable lengths.\n Args:... | false |
5,571 | dfc412acc9b69f50396680db1b9f6feafe162996 | import io
import os
from flask import Flask
from werkzeug.datastructures import FileStorage
import pytest
PNG_FILE = os.path.join(os.path.dirname(__file__), 'flask.png')
JPG_FILE = os.path.join(os.path.dirname(__file__), 'flask.jpg')
class TestConfig:
TESTING = True
MONGODB_DB = 'flask-fs-test'
MONGODB... | [
"import io\nimport os\n\nfrom flask import Flask\nfrom werkzeug.datastructures import FileStorage\n\nimport pytest\n\nPNG_FILE = os.path.join(os.path.dirname(__file__), 'flask.png')\nJPG_FILE = os.path.join(os.path.dirname(__file__), 'flask.jpg')\n\n\nclass TestConfig:\n TESTING = True\n MONGODB_DB = 'flask-f... | false |
5,572 | c80ecb97c8863b724169715b766024ce824b9225 | import numpy as np
# UM TRABALHO FEITO PELA GRANDE DUPLA PEQUENA Mag e Rud
def main():
a = int(input("Informe a sua opรงรฃo (Aleatรณrio = 0, Vocรช escolhe = outro numero): "))
if(a != 0):
linhas = int(input("Informe o nรบmero de linhas da matriz: "))
colunas = int(input("Informe o nรบmero de colunas... | [
"import numpy as np\n\n# UM TRABALHO FEITO PELA GRANDE DUPLA PEQUENA Mag e Rud\n\ndef main():\n a = int(input(\"Informe a sua opรงรฃo (Aleatรณrio = 0, Vocรช escolhe = outro numero): \"))\n if(a != 0):\n linhas = int(input(\"Informe o nรบmero de linhas da matriz: \"))\n colunas = int(input(\"Informe o... | false |
5,573 | 0f4bdaecef356e01cbef527d4886564d9ef840fa | from erlport.erlterms import Atom
from scipy.optimize import basinhopping
import numpy as np
import qsim
class Bounds(object):
'''Required for acceptance testing in scipy.optimize.basinhopping'''
def __init__(self, xmin, xmax, costs):
self.xmax = xmax
self.xmin = xmin
self.costs = costs... | [
"from erlport.erlterms import Atom\nfrom scipy.optimize import basinhopping\nimport numpy as np\nimport qsim\n\nclass Bounds(object):\n '''Required for acceptance testing in scipy.optimize.basinhopping'''\n def __init__(self, xmin, xmax, costs):\n self.xmax = xmax\n self.xmin = xmin\n sel... | false |
5,574 | aa801bc8398cdf69a15d04188dd8429e4624150e | import numpy as np
#read data from file
#read data from file
theFile = open('datapri.txt','r')
temp = []
#n la so phan tu cua mang mau
n = int(theFile.readline().format())
for val in theFile.read().split():
temp.append(int(val))
theFile.close()
arr = np.random.rand(n,n)
k = 0
for i in range(n):
for j in range... | [
"import numpy as np\n#read data from file\n#read data from file\n\ntheFile = open('datapri.txt','r')\ntemp = []\n#n la so phan tu cua mang mau\nn = int(theFile.readline().format())\nfor val in theFile.read().split():\n temp.append(int(val))\ntheFile.close()\n\narr = np.random.rand(n,n)\nk = 0\nfor i in range(n):... | false |
5,575 | 1284de6474e460f0d95f5c76d066b948bce59228 | #!usr/bin/env python3
from argoverse.map_representation.map_api import ArgoverseMap
from frame import Frame
import matplotlib.pyplot as plt
import pickle
import numpy as np
from argo import draw_local_map
# Frames in cluster visualization
def frame_in_pattern_vis(xmin, xmax, ymin, ymax):
dataset = 'ARGO'
if ... | [
"#!usr/bin/env python3\n\nfrom argoverse.map_representation.map_api import ArgoverseMap\nfrom frame import Frame\nimport matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\nfrom argo import draw_local_map\n\n\n# Frames in cluster visualization\ndef frame_in_pattern_vis(xmin, xmax, ymin, ymax):\n dataset... | false |
5,576 | 1b49cb59ebdb548cfc7567cd5cb4affe30f33aac | import pytest
@pytest.mark.usefixtures("driver")
class BaseClass:
"""BaseClass takes in driver fixture."""
| [
"import pytest\n\n\n@pytest.mark.usefixtures(\"driver\")\nclass BaseClass:\n \"\"\"BaseClass takes in driver fixture.\"\"\"\n",
"import pytest\n\n\n@pytest.mark.usefixtures('driver')\nclass BaseClass:\n \"\"\"BaseClass takes in driver fixture.\"\"\"\n",
"<import token>\n\n\n@pytest.mark.usefixtures('drive... | false |
5,577 | bc7a7b9ba4b3277c862aadb57b56661c24efc6e5 | from django.db import models
# Create your models here.
class Orders(models.Model):
customer_name = models.CharField(max_length=80)
customer_email = models.CharField(max_length=120)
customer_mobile = models.CharField(max_length=40)
status = models.CharField(max_length=20)
process_url = models.Cha... | [
"from django.db import models\n\n\n# Create your models here.\n\nclass Orders(models.Model):\n customer_name = models.CharField(max_length=80)\n customer_email = models.CharField(max_length=120)\n customer_mobile = models.CharField(max_length=40)\n status = models.CharField(max_length=20)\n process_u... | false |
5,578 | 9e37b728d8045726aef7625fccc14111ecb0e1c8 | # -*- coding: utf-8 -*-
# @Author: Lich_Amnesia
# @Email: alwaysxiaop@gmail.com
# @Date: 2016-11-17 11:00:33
# @Last Modified time: 2016-11-17 11:00:34
# @FileName: 346.py
class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
... | [
"# -*- coding: utf-8 -*-\n# @Author: Lich_Amnesia\n# @Email: alwaysxiaop@gmail.com\n# @Date: 2016-11-17 11:00:33\n# @Last Modified time: 2016-11-17 11:00:34\n# @FileName: 346.py\n\n\nclass MovingAverage(object):\n\n def __init__(self, size):\n \"\"\"\n Initialize your data structure here.\n ... | false |
5,579 | 888a5847beca2470f4063da474da1f05079abca9 | from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
from tweets.models import Tweet
from ..models import UserProfile
User = get_user_model()
class TestAccountsViews(TestCase):
def setUp(self):
self.username = 'masterbdx'
self.ema... | [
"from django.test import TestCase, Client\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\n\nfrom tweets.models import Tweet\nfrom ..models import UserProfile\nUser = get_user_model()\n\n\nclass TestAccountsViews(TestCase):\n def setUp(self):\n self.username = 'masterbdx'\... | false |
5,580 | 67e06b6dddbd3f26295eaff921d1ad4a8b0e5487 | import importlib
class Scrapper:
def get_pos(str_lf,str_rg,text):
left = text.find(str_lf)
right = text.rfind(str_rg)
return left, right
def scrapper(prov):
scrapper = importlib.import_module('scrappers.{}'.format(prov))
return scrapper.scrape()
| [
"import importlib\n\n\nclass Scrapper:\n\n def get_pos(str_lf,str_rg,text):\n left = text.find(str_lf)\n right = text.rfind(str_rg)\n\n return left, right\n\n def scrapper(prov):\n scrapper = importlib.import_module('scrappers.{}'.format(prov))\n return scrapper.scrape()\n\n... | false |
5,581 | fa825846c54ed32c2ede94128ac08f9d5e172c0f | # -*- coding: utf-8 -*-
import urllib2, json, traceback
from django.conf import settings
from django.db import models
from TkManager.order.models import User
from TkManager.juxinli.models import *
from TkManager.juxinli.error_no import *
from TkManager.common.tk_log import TkLog
from datetime import datetime
from djan... | [
"# -*- coding: utf-8 -*-\nimport urllib2, json, traceback\n\nfrom django.conf import settings\nfrom django.db import models\nfrom TkManager.order.models import User\nfrom TkManager.juxinli.models import *\nfrom TkManager.juxinli.error_no import *\nfrom TkManager.common.tk_log import TkLog\nfrom datetime import date... | true |
5,582 | a372289d15b55f43887a37bb78a9fc308ddd0371 | # Generated by Django 3.0.4 on 2020-03-24 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('students', '0002_auto_20200324_1635'),
]
operations = [
migrations.AddField(
model_name='student',
name='parent_mobi... | [
"# Generated by Django 3.0.4 on 2020-03-24 16:58\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('students', '0002_auto_20200324_1635'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='student',\n ... | false |
5,583 | 9da6bfa614d64956a302abbfeeea30c0339e9db3 | import tensorflow.contrib.slim as slim
import tensorflow as tf
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import init_ops
import numpy as np
WEIGHT_DECAY = 0.0005
class ScaledVarianceUniform(init_ops.Initializer):
"""Initializer that genera... | [
"import tensorflow.contrib.slim as slim\nimport tensorflow as tf\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import init_ops\nimport numpy as np\n\nWEIGHT_DECAY = 0.0005\n\nclass ScaledVarianceUniform(init_ops.Initializer):\n \"\"\"Initi... | false |
5,584 | e364a4e6e1c4e0fd6805515a1149adaf92e9c8fb | n = input()
n = list(n)
n.sort()
alph = []
num = []
for i in range(n) :
if i.isalpha() :
alpa.append(i)
else :
num.append(i)
result.append(str(alpa))
result.append(str(num))
print(n)
| [
"n = input()\n\nn = list(n)\nn.sort()\nalph = []\nnum = []\nfor i in range(n) :\n if i.isalpha() :\n alpa.append(i)\n else :\n num.append(i)\n\nresult.append(str(alpa))\nresult.append(str(num)) \nprint(n)\n\n",
"n = input()\nn = list(n)\nn.sort()\nalph = []\nnum = []\nfor i in range(n):\n ... | false |
5,585 | 8a6c9fa67c02d69444c9c3a2e6811b982c49eb4e | """Contains functionality for tokenizing, parsing, embedding language."""
from . import parsing
from . import cleaning
from .config import NATURAL_EMB_DIM
| [
"\"\"\"Contains functionality for tokenizing, parsing, embedding language.\"\"\"\n\nfrom . import parsing\nfrom . import cleaning\nfrom .config import NATURAL_EMB_DIM\n",
"<docstring token>\nfrom . import parsing\nfrom . import cleaning\nfrom .config import NATURAL_EMB_DIM\n",
"<docstring token>\n<import token>... | false |
5,586 | 5068336ca1a180e09a7efd41eea596cdcebb33ae | from flask import Blueprint, request, jsonify
from to_dict import *
from validacao import *
import sqlite3
from migration import conectar, create_database
from contextlib import closing
aluno = Blueprint("aluno", __name__)
@aluno.route("/hello")
def hello():
return "Hello, aluno"
@aluno.route("/reseta", methods ... | [
"from flask import Blueprint, request, jsonify\nfrom to_dict import *\nfrom validacao import *\nimport sqlite3\nfrom migration import conectar, create_database\nfrom contextlib import closing\n\naluno = Blueprint(\"aluno\", __name__)\n\n@aluno.route(\"/hello\")\ndef hello():\n return \"Hello, aluno\"\n\n@aluno.r... | false |
5,587 | 4bc9896847e4ab92a01dfcf674362140cc31ef4f | import ga.ga as ga
import os
import datetime
def ga_optimise(synth, param_count, target, output_dir, iterations = 10, pop_size = 500):
fs = ga.ga_optimise(compute_population_fitnesses = ga.compute_population_fitnesses,
target = target,
synth = synth,
param_count = param_count,
iterations = iterat... | [
"import ga.ga as ga\nimport os\nimport datetime\n\n\ndef ga_optimise(synth, param_count, target, output_dir, iterations = 10, pop_size = 500):\n\tfs = ga.ga_optimise(compute_population_fitnesses = ga.compute_population_fitnesses, \n\t\t\t\ttarget = target, \n\t\t\t\tsynth = synth, \n\t\t\t\tparam_count = param_coun... | true |
5,588 | a352768c2928cb7a33b9f1a31a0b3d8e56a8376a | # -*- coding: utf-8 -*-
# Scrapy settings for reddit_scraper project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'reddit_scraper'
SPIDER_MODULES = ['reddit_s... | [
"# -*- coding: utf-8 -*-\n\n# Scrapy settings for reddit_scraper project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n#\n\nBOT_NAME = 'reddit_scraper'\n\nSPIDER_MOD... | false |
5,589 | 012ab947f7a2c9d44f54464b3e477582ffcf3d77 | # -*- coding: utf-8 -*-
"""
current_models - library of ionic current models implemented in Python
Created on Mon Apr 10 16:30:04 2017
@author: Oliver Britton
"""
import os
import sys
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
" Voltage clamp generator function... | [
"# -*- coding: utf-8 -*-\n\"\"\"\ncurrent_models - library of ionic current models implemented in Python\n\nCreated on Mon Apr 10 16:30:04 2017\n\n@author: Oliver Britton\n\"\"\"\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\n\" Volt... | false |
5,590 | c005ae9dc8b50e24d72dbc99329bb5585d617081 | from rest_framework.serializers import ModelSerializer
from rest_framework.serializers import ReadOnlyField
from rest_framework.serializers import SlugField
from rest_framework.validators import UniqueValidator
from django.db import models
from illumidesk.teams.util import get_next_unique_team_slug
from illumidesk.us... | [
"from rest_framework.serializers import ModelSerializer\nfrom rest_framework.serializers import ReadOnlyField\nfrom rest_framework.serializers import SlugField\nfrom rest_framework.validators import UniqueValidator\n\nfrom django.db import models\n\nfrom illumidesk.teams.util import get_next_unique_team_slug\nfrom ... | false |
5,591 | ebd510bcd0caded03c5bcc36a11945710d5e644b | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import math
import re
import copy
from lcs import lcs
# Create your models here.
keywords=["int","long","for","while","if","else","break","continue","return","true","false","double","do","signed","unsigned"]
symbol=["[","]","{","}","(",")","&","|","^",... | [
"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta\nimport math\nimport re\nimport copy\nfrom lcs import lcs\n# Create your models here.\n\n\nkeywords=[\"int\",\"long\",\"for\",\"while\",\"if\",\"else\",\"break\",\"continue\",\"return\",\"true\",\"false\",\"double\",\"do\",\"signed\",\"unsigned\"]... | true |
5,592 | 6e2fb9d498294a580426ff408183f7beec135329 | # function to add two numbers
def add2nums(a,b):
return a+b
| [
"# function to add two numbers\ndef add2nums(a,b):\n return a+b\n",
"def add2nums(a, b):\n return a + b\n",
"<function token>\n"
] | false |
5,593 | 1bd1769f94b93e0bb674adfd1bb96c778708f6d8 | from django.urls import re_path
from .consumers import ChatConsumer, ChatLobbyConsumer
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_id>\w+)/$', ChatConsumer),
re_path(r'ws/lobby/$', ChatLobbyConsumer),
] | [
"from django.urls import re_path\n\nfrom .consumers import ChatConsumer, ChatLobbyConsumer\n\nwebsocket_urlpatterns = [\n re_path(r'ws/chat/(?P<room_id>\\w+)/$', ChatConsumer),\n re_path(r'ws/lobby/$', ChatLobbyConsumer),\n]",
"from django.urls import re_path\nfrom .consumers import ChatConsumer, ChatLobbyC... | false |
5,594 | cfba55505f3290a14b98d594bc871a74812c7c57 | """
Note: names of methods in this module, if seem weird, are the same as in Hunspell's ``suggest.cxx``
to keep track of them.
"""
from typing import Iterator, Union, List, Set
from spylls.hunspell.data import aff
MAX_CHAR_DISTANCE = 4
def replchars(word: str, reptable: List[aff.RepPattern]) -> Iterator[Union[str... | [
"\"\"\"\nNote: names of methods in this module, if seem weird, are the same as in Hunspell's ``suggest.cxx``\nto keep track of them.\n\"\"\"\n\nfrom typing import Iterator, Union, List, Set\n\nfrom spylls.hunspell.data import aff\n\n\nMAX_CHAR_DISTANCE = 4\n\n\ndef replchars(word: str, reptable: List[aff.RepPattern... | false |
5,595 | 53841ba56589955e09b03018af1d0ae79b3756c4 | #!/usr/bin/python
# coding=utf-8
import time
import atexit
# for signal handling
import signal
import sys
# ----------------------
# Encoder stuff
# ----------------------
import RPi.GPIO as GPIO
# init
GPIO.setmode(GPIO.BCM) # use the GPIO names, _not_ the pin numbers on the board
# Raspberry Pi pin configuratio... | [
"#!/usr/bin/python\n# coding=utf-8\n\nimport time\nimport atexit\n\n# for signal handling\nimport signal\nimport sys\n\n\n# ----------------------\n# Encoder stuff\n# ----------------------\nimport RPi.GPIO as GPIO\n\n# init\nGPIO.setmode(GPIO.BCM) # use the GPIO names, _not_ the pin numbers on the board\n\n# Raspb... | false |
5,596 | b739c1de6c008158ee3806bed9fa2865eb484b4f | import sys
sys.stdin = open("sample_input_17.txt","r")
T = int(input())
def code(N): # ์ํธ์ฝ๋๊ฐ ์๋ ์ด์ ์์น๋ฅผ ์ฐพ์
code = []
for i in range(N-4):
for j in range(49,53):
if S[i][j] == "1" :
code = S[i]
return code
def code_s(code): # ์ํธ์ฝ๋์ ํ ์์น๋ฅผ ์ฐพ์ ์ฌ๋ผ์ด์ฑ
for x in ... | [
"import sys\nsys.stdin = open(\"sample_input_17.txt\",\"r\")\n\nT = int(input())\n\ndef code(N): # ์ํธ์ฝ๋๊ฐ ์๋ ์ด์ ์์น๋ฅผ ์ฐพ์\n code = []\n for i in range(N-4):\n for j in range(49,53):\n if S[i][j] == \"1\" :\n code = S[i]\n return code\n\ndef code_s(code): # ์ํธ์ฝ๋์ ํ ์... | false |
5,597 | 430dccf1001af43c2a713b08dc05d8f04818aa1f | #Script to retrieve relevant files and paths, supply to cx_Freeze to compile into executeable
import os
# import cx_Freeze
files_list = []
dir_path = os.path.dirname(os.path.realpath(__file__))+str('/')
print(dir_path)
for root, directories, filenames in os.walk(str(dir_path)):
for file in filenames:
pat... | [
"#Script to retrieve relevant files and paths, supply to cx_Freeze to compile into executeable\nimport os\n# import cx_Freeze\nfiles_list = []\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__))+str('/')\nprint(dir_path)\nfor root, directories, filenames in os.walk(str(dir_path)):\n for file in filenames... | false |
5,598 | f6f0dcb806fbc1e14c0907dd500fdc6a609a19f7 | # -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
import ctypes
from py_dss_interface.models.Base import Base
class MonitorsS(Base):
"""
This interface can be used to read/write certain properties of the active DSS object.
The structure of the interface is as follows:
CStr Monit... | [
"# -*- encoding: utf-8 -*-\n\"\"\"\n Created by eniocc at 11/10/2020\n\"\"\"\nimport ctypes\n\nfrom py_dss_interface.models.Base import Base\n\n\nclass MonitorsS(Base):\n \"\"\"\n This interface can be used to read/write certain properties of the active DSS object.\n\n The structure of the interface is as ... | false |
5,599 | 85a3682f144f02aa412d45c901f76c65de2e816d | import graphics
from graphics import *
class Renderer():
def __init__(self, engine, width=700, height=600):
self.width = width
self.height = height
self.engine = engine
self.win = GraphWin("Game Board", width, height)
self.win.setBackground("blue")
def update(self):
... | [
"import graphics \nfrom graphics import *\n\nclass Renderer():\n def __init__(self, engine, width=700, height=600):\n self.width = width\n self.height = height\n self.engine = engine\n self.win = GraphWin(\"Game Board\", width, height)\n self.win.setBackground(\"blue\")\n\n ... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.