index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
8,700 | 9c29f04746de6847ad1bbdf08964d14e6c3766db | from modeltranslation.translator import register, TranslationOptions
from .models import *
@register(PageTitleModel)
class TitleTranslationOptions(TranslationOptions):
fields = (
'name',
)
@register(NewsModel)
class ProjectTranslationOptions(TranslationOptions):
fields = (
'name',
... | [
"from modeltranslation.translator import register, TranslationOptions\nfrom .models import *\n\n\n@register(PageTitleModel)\nclass TitleTranslationOptions(TranslationOptions):\n fields = (\n 'name',\n )\n\n\n@register(NewsModel)\nclass ProjectTranslationOptions(TranslationOptions):\n fields = (\n ... | false |
8,701 | 3dc4e10145ad42c0168fec3462da0f87c1e661a5 | class Image:
def __init__(self, **kwargs):
self.ClientID = kwargs['ClientID']
self.DealerID = kwargs['DealerID']
self.VIN = kwargs['VIN']
self.UrlVdp = None
self.PhotoURL = kwargs['PhotoURL']
self.VdpActive = None
def __repr__(self):
return f"{se... | [
"class Image:\n\n def __init__(self, **kwargs):\n self.ClientID = kwargs['ClientID']\n self.DealerID = kwargs['DealerID']\n self.VIN = kwargs['VIN']\n self.UrlVdp = None\n self.PhotoURL = kwargs['PhotoURL']\n self.VdpActive = None\n \n def __repr__(self):\n ... | false |
8,702 | e8f090a02bfd5ee8a6832351357594af2d6692f9 | import calendar
import json
from datetime import datetime
from datapoller.download import download
from datapoller.settings import *
from messaging.Messaging import sendMessage
from messaging.settings import RABBIT_NOTIFY_QUEUE
from sessioncontroller.utils import is_level_interesting_for_kp
__author__ = 'arik'
shared... | [
"import calendar\nimport json\nfrom datetime import datetime\nfrom datapoller.download import download\nfrom datapoller.settings import *\nfrom messaging.Messaging import sendMessage\nfrom messaging.settings import RABBIT_NOTIFY_QUEUE\nfrom sessioncontroller.utils import is_level_interesting_for_kp\n\n__author__ = ... | false |
8,703 | e38be2890526c640ba8d9db5a376ff57ba9e0aa2 | import azure.functions as func
import json
from ..common import cosmos_client
def main(req: func.HttpRequest) -> func.HttpResponse:
return func.HttpResponse(
body = json.dumps(cosmos_client.DB.Goals),
mimetype="application/json",
charset="utf-8"
)
# [
# {'amoun... | [
"import azure.functions as func\nimport json\nfrom ..common import cosmos_client\n\ndef main(req: func.HttpRequest) -> func.HttpResponse:\n \n return func.HttpResponse(\n body = json.dumps(cosmos_client.DB.Goals),\n mimetype=\"application/json\",\n charset=\"utf-8\"\n )\n\n # [\... | false |
8,704 | 254afebcc909c805d1e4972a0910eb4451d1e64e | """Copied from http://svn.sourceforge.jp/svnroot/slothlib/CSharp/Version1/SlothLib/NLP/Filter/StopWord/word/Japanese.txt"""
STOP_WORDS = set(
"""
あそこ
あたり
あちら
あっち
あと
あな
あなた
あれ
いくつ
いつ
いま
いや
いろいろ
うち
おおまか
おまえ
おれ
がい
かく
かたち
かやの
から
がら
きた
くせ
ここ
こっち
こと
ごと
こちら
ごっちゃ
これ
これら
ごろ
さまざま
さらい
さん
しかた
しよう
すか
ずつ
すね
すべて
ぜんぶ
そう
そこ
そちら
そっち... | [
"\"\"\"Copied from http://svn.sourceforge.jp/svnroot/slothlib/CSharp/Version1/SlothLib/NLP/Filter/StopWord/word/Japanese.txt\"\"\"\nSTOP_WORDS = set(\n \"\"\"\nあそこ\nあたり\nあちら\nあっち\nあと\nあな\nあなた\nあれ\nいくつ\nいつ\nいま\nいや\nいろいろ\nうち\nおおまか\nおまえ\nおれ\nがい\nかく\nかたち\nかやの\nから\nがら\nきた\nくせ\nここ\nこっち\nこと\nごと\nこちら\nごっちゃ\nこれ\nこれら\nごろ\... | false |
8,705 | ceb714e949a72f621aec8b8728fbd1201e22afd1 | """
Copyright (c) Facebook, Inc. and its affiliates.
"""
# fmt: off
"""
Every template contains an ordered list of TemplateObjects.
TemplateObject is defined in template_objects.py
GetMemory templates are written for filters and have an answer_type
They represent the action of fetching from the memory using the filte... | [
"\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\"\"\"\n\n# fmt: off\n\"\"\"\nEvery template contains an ordered list of TemplateObjects.\nTemplateObject is defined in template_objects.py\n\nGetMemory templates are written for filters and have an answer_type\nThey represent the action of fetching from th... | false |
8,706 | 022c8d6c31ad5494b03bfe93d17396eac25b011e | '''
This program will simulate leveling a DnD character, showing their ending HP, and stats.
'''
import argparse
import csv
import json
import re
import time
from openpyxl import load_workbook
from pandas import DataFrame
from src import classes, util
def import_race_data(file_path):
'''
This method imports d... | [
"'''\nThis program will simulate leveling a DnD character, showing their ending HP, and stats.\n'''\nimport argparse\nimport csv\nimport json\nimport re\nimport time\nfrom openpyxl import load_workbook\nfrom pandas import DataFrame\nfrom src import classes, util\n\n\ndef import_race_data(file_path):\n '''\n T... | false |
8,707 | 2294dc21ede759e755e51471705fa8ef784528a7 | import requests
import json
import datetime
from bs4 import BeautifulSoup
from pymongo import MongoClient, UpdateOne
import sys
#usage: python freesound_crawler.py [from_page] [to_page]
SOUND_URL = "https://freesound.org/apiv2/sounds/"
SEARCH_URL = "https://freesound.org/apiv2/search/text/"
AUTORIZE_URL = "https://fr... | [
"import requests\nimport json\nimport datetime\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient, UpdateOne\nimport sys\n\n#usage: python freesound_crawler.py [from_page] [to_page]\n\nSOUND_URL = \"https://freesound.org/apiv2/sounds/\"\nSEARCH_URL = \"https://freesound.org/apiv2/search/text/\"\nAUTORI... | true |
8,708 | 45335fa5d4773bdd0ef3e6c340fe06e84169be5e |
from flask import Flask, send_file
import StringIO
app = Flask(__name__)
@app.route('/')
def index():
strIO = StringIO.StringIO()
strIO.write('Hello from Dan Jacob and Stephane Wirtel !')
strIO.seek(0)
return send_file(strIO,
attachment_filename="testing.txt",
... | [
"\nfrom flask import Flask, send_file\nimport StringIO\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n strIO = StringIO.StringIO()\n strIO.write('Hello from Dan Jacob and Stephane Wirtel !')\n strIO.seek(0)\n return send_file(strIO,\n attachment_filename=\"testing.txt\",\... | false |
8,709 | 11984027baf6d4c97b2976e4ac49a0e8ec62f893 | from math import sqrt
from numpy import concatenate
from matplotlib import pyplot
from pandas import read_csv
from pandas import DataFrame
from pandas import concat
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from tensorflo... | [
"from math import sqrt\nfrom numpy import concatenate\nfrom matplotlib import pyplot\nfrom pandas import read_csv\nfrom pandas import DataFrame\nfrom pandas import concat\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import mean_squared_error\n... | true |
8,710 | 077c596f71aae22e85589fdaf78d5cdae8085443 | from django.conf.urls import url
from . import views
from .import admin
urlpatterns = [
url(r'^$', views.showberanda, name='showberanda'),
url(r'^sentimenanalisis/$', views.showsentimenanalisis, name='showsentimenanalisis'),
url(r'^bantuan/$', views.showbantuan, name='showbantuan'),
url(r'^tweets/', vi... | [
"from django.conf.urls import url\nfrom . import views\nfrom .import admin\n\nurlpatterns = [\n url(r'^$', views.showberanda, name='showberanda'),\n url(r'^sentimenanalisis/$', views.showsentimenanalisis, name='showsentimenanalisis'),\n url(r'^bantuan/$', views.showbantuan, name='showbantuan'),\n url(r'... | false |
8,711 | 294b0dc7587ecd37887591da5a1afe96a4349f6b | # ?????
c=0
for i in range(12):
if 'r' in input():
c+=1
# ??
print(c) | [
"# ?????\r\nc=0\r\n\r\nfor i in range(12):\r\n if 'r' in input():\r\n c+=1\r\n\r\n# ??\r\nprint(c)",
"c = 0\nfor i in range(12):\n if 'r' in input():\n c += 1\nprint(c)\n",
"<assignment token>\nfor i in range(12):\n if 'r' in input():\n c += 1\nprint(c)\n",
"<assignment token>\n<code t... | false |
8,712 | 1ab690b0f9c34b1886320e1dfe8b54a5ec6cd4d1 | """Support for Deebot Vaccums."""
import logging
from typing import Any, Mapping, Optional
import voluptuous as vol
from deebot_client.commands import (
Charge,
Clean,
FanSpeedLevel,
PlaySound,
SetFanSpeed,
SetRelocationState,
SetWaterInfo,
)
from deebot_client.commands.clean import CleanAc... | [
"\"\"\"Support for Deebot Vaccums.\"\"\"\nimport logging\nfrom typing import Any, Mapping, Optional\n\nimport voluptuous as vol\nfrom deebot_client.commands import (\n Charge,\n Clean,\n FanSpeedLevel,\n PlaySound,\n SetFanSpeed,\n SetRelocationState,\n SetWaterInfo,\n)\nfrom deebot_client.comm... | false |
8,713 | b5dba7c1566721f8bb4ec99bc2f13cae4ade4f0a | #!/usr/bin/python3 -S
# -*- coding: utf-8 -*-
import netaddr
from cargo.fields import MacAddress
from unit_tests.fields.Field import TestField
from unit_tests import configure
class TestMacAddress(configure.NetTestCase, TestField):
@property
def base(self):
return self.orm.mac
def test___call__... | [
"#!/usr/bin/python3 -S\n# -*- coding: utf-8 -*-\nimport netaddr\nfrom cargo.fields import MacAddress\n\nfrom unit_tests.fields.Field import TestField\nfrom unit_tests import configure\n\n\nclass TestMacAddress(configure.NetTestCase, TestField):\n\n @property\n def base(self):\n return self.orm.mac\n\n ... | false |
8,714 | 5869669f1e3f648c0ddc68683f0b1d2754b40169 | import discord
from collections import Counter
from db import readDB, writeDB
INFO_DB_SUCCESS = 'Database updated successfully!'
ERROR_DB_ERROR = 'Error: Unable to open database for writing'
ERROR_DB_NOT_FOUND = 'Error: Database for specified game does not exist. Check your spelling or use !addgame first.'
ERROR_PLA... | [
"import discord\nfrom collections import Counter\nfrom db import readDB, writeDB\n\n\nINFO_DB_SUCCESS = 'Database updated successfully!'\nERROR_DB_ERROR = 'Error: Unable to open database for writing'\nERROR_DB_NOT_FOUND = 'Error: Database for specified game does not exist. Check your spelling or use !addgame first.... | false |
8,715 | 7c3798aa9cc5424656572dfaa87f7acb961613eb | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import unittest
import logging
from collections import Counter
from utility import token_util
class TestFileReadingFunctions(unittest.TestCase)... | [
"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport unittest\nimport logging\nfrom collections import Counter\n\nfrom utility import token_util\n\n\nclass TestFileReadingFunctio... | false |
8,716 | 50c274e0365f2556a46eb58edcd1f0a7301e89db | # -*- coding: utf-8 -*-
#
# RPi.Spark KeyButton Demo
#
# Author: Kunpeng Zhang
# 2018.6.6
#
# See LICENSE for details.
from time import sleep
import RPi.GPIO as GPIO
from JMRPiSpark.Drives.Key.RPiKeyButtons import RPiKeyButtons
from JMRPiSpark.Drives.Key.RPiKeyButtons import DEF_BOUNCE_TIME_SHORT_MON
from JMRPiSpark.... | [
"# -*- coding: utf-8 -*-\n#\n# RPi.Spark KeyButton Demo\n#\n# Author: Kunpeng Zhang\n# 2018.6.6\n#\n# See LICENSE for details.\n\nfrom time import sleep\nimport RPi.GPIO as GPIO\n\nfrom JMRPiSpark.Drives.Key.RPiKeyButtons import RPiKeyButtons\nfrom JMRPiSpark.Drives.Key.RPiKeyButtons import DEF_BOUNCE_TIME_SHORT_MO... | false |
8,717 | 1a6f84835ec2f5fbbb064aef2cd872c24eb3839d | prompt = "Enter a message and I will repeat it to you: "
message = " "
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# using the 'flag' variable
prompt = "Enter a message and I will repeat it to you: "
# active is the variable used in this case as flag
activ... | [
"prompt = \"Enter a message and I will repeat it to you: \"\n\nmessage = \" \"\n\nwhile message != 'quit':\n message = input(prompt)\n if message != 'quit':\n print(message)\n\n# using the 'flag' variable\n\nprompt = \"Enter a message and I will repeat it to you: \"\n\n# active is the variable used in ... | false |
8,718 | 6645887b25d75f4657fb231b80d8ebdec2bac7c9 | from django.shortcuts import render
from django.views.generic import TemplateView
from django.conf import settings
import os, csv
class InflationView(TemplateView):
template_name = 'inflation.html'
def get(self, request, *args, **kwargs):
# чтение csv-файла и заполнение контекста
context = {}... | [
"from django.shortcuts import render\nfrom django.views.generic import TemplateView\nfrom django.conf import settings\nimport os, csv\n\n\nclass InflationView(TemplateView):\n template_name = 'inflation.html'\n\n def get(self, request, *args, **kwargs):\n # чтение csv-файла и заполнение контекста\n ... | false |
8,719 | e0fc7e5771f6cb8e0638bc8c9549cfe1a92d3d82 | from django.urls import path
from redjit.post.views import MyPost, PostView
urlpatterns = [
path('newpost/', MyPost.as_view(), name='newpost')
path('subredjit/<subredjit>/<post_id>/', PostView.as_view(), name='post')
] | [
"from django.urls import path\nfrom redjit.post.views import MyPost, PostView\n\n\n\nurlpatterns = [\n path('newpost/', MyPost.as_view(), name='newpost')\n path('subredjit/<subredjit>/<post_id>/', PostView.as_view(), name='post')\n]"
] | true |
8,720 | f971302f39149bcdcbe4237cc71219572db600d4 | import numpy as np
from nn.feedforward_nn import Feed_Forward
class RMSprop(object):
def __init__(self,n_in,n_hid,n_out,regularization_coe):
self.nn = Feed_Forward(n_in,n_hid,n_out,regularization_coe)
def set_param(self,param):
if 'learning_rate' in param.keys():
self.learning_rat... | [
"import numpy as np\nfrom nn.feedforward_nn import Feed_Forward\nclass RMSprop(object):\n\n def __init__(self,n_in,n_hid,n_out,regularization_coe):\n self.nn = Feed_Forward(n_in,n_hid,n_out,regularization_coe)\n\n\n def set_param(self,param):\n if 'learning_rate' in param.keys():\n se... | false |
8,721 | c060cdb7730ba5c4d2240b65331f5010cac222fa | import copy
import sys
import os
from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta
import numpy as np
import pandas
import tsprocClass as tc
import pestUtil as pu
#update parameter values and fixed/unfixed
#--since Joe is so pro-America...
tc.DATE_FMT = '%m/%d/%Y'
#--build ... | [
"import copy\nimport sys\nimport os\nfrom datetime import datetime,timedelta\nfrom dateutil.relativedelta import relativedelta\nimport numpy as np\nimport pandas\n\nimport tsprocClass as tc \nimport pestUtil as pu \n\n#update parameter values and fixed/unfixed\n\n#--since Joe is so pro-America...\ntc.DATE_FMT = '%... | true |
8,722 | 0bce5d590b96e434cd8aee7531a321bc648c1981 | #!/usr/bin/python
try:
from Queue import Queue
except ImportError: # Python 3
from queue import Queue
class BFSWithQueue:
"""Breadth-First Search.
Attributes
----------
graph : input graph
color : dict with nodes, private
distance : dict with nodes (distances to source node)
... | [
"#!/usr/bin/python\n\ntry:\n from Queue import Queue\nexcept ImportError: # Python 3\n from queue import Queue\n\n\nclass BFSWithQueue:\n \"\"\"Breadth-First Search.\n \n Attributes\n ----------\n graph : input graph\n color : dict with nodes, private\n distance : dict with nodes (dista... | false |
8,723 | 96a4659f03879e051af95b5aa9c1e1364015fb86 | #coding=utf-8
import requests,sys
result_url=[]
def main():
counts=open(sys.argv[1]).readlines()
for line in open(sys.argv[1]):
line=line.strip("\n")
url=line
try:
#url="http://s6000.sgcc.com.cn/WebContent/s6000/main/index.jsp#no-back"
r=requests.get(u... | [
"#coding=utf-8\r\nimport requests,sys\r\nresult_url=[]\r\n\r\ndef main():\r\n counts=open(sys.argv[1]).readlines()\r\n for line in open(sys.argv[1]):\r\n line=line.strip(\"\\n\")\r\n url=line\r\n try:\r\n #url=\"http://s6000.sgcc.com.cn/WebContent/s6000/main/index.jsp#no-back\"... | false |
8,724 | 3989b4c2a15fa8cd54fef86f9d7150fbd0fb74cf | import os
import sys
import shutil
import re
dl_dir = '/home/acarnec/Downloads/'
college_dir = '/home/acarnec/Documents/3rdYear'
latex_dir = '/home/acarnec/Documents/Latex/'
modules = ['mta', 'ana', 'met', 'log', 'mat',
'lin', 'min', 'pol', 'mic', 'mte']
michaelmas = ['mta', 'ana', 'met', 'log', 'mat']... | [
"import os \nimport sys\n\nimport shutil \nimport re\n\ndl_dir = '/home/acarnec/Downloads/'\ncollege_dir = '/home/acarnec/Documents/3rdYear'\nlatex_dir = '/home/acarnec/Documents/Latex/'\n\nmodules = ['mta', 'ana', 'met', 'log', 'mat',\n 'lin', 'min', 'pol', 'mic', 'mte']\n\nmichaelmas = ['mta', 'ana', 'm... | false |
8,725 | 1508697f93114d7f20182a3e9c1df5617904529a | # import libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import warnings
import pickle
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error
impor... | [
"# import libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nimport pickle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squar... | false |
8,726 | de77fa677b3b200a41083e609d4da697f9e77f21 | def printall(s):
for i in s:
print i
n=str(raw_input("Enter Word:- "))
printall(n)
| [
"def printall(s):\r\n for i in s:\r\n print i\r\n\r\nn=str(raw_input(\"Enter Word:- \"))\r\nprintall(n)\r\n"
] | true |
8,727 | 7ff029e2f0054146e438f4e4f13269e83e28c469 | import pytest
import kdlc
from shutil import rmtree
import os
# from .context import kdlc
test_generated_dir = os.path.dirname(__file__) + "/generated/"
@pytest.fixture(scope="session")
def my_setup(request):
print("\nDoing setup")
def fin():
print("\nDoing teardown")
if os.path.exists(tes... | [
"import pytest\nimport kdlc\nfrom shutil import rmtree\nimport os\n\n# from .context import kdlc\n\ntest_generated_dir = os.path.dirname(__file__) + \"/generated/\"\n\n\n@pytest.fixture(scope=\"session\")\ndef my_setup(request):\n print(\"\\nDoing setup\")\n\n def fin():\n print(\"\\nDoing teardown\")\... | false |
8,728 | 2e5d66033c2a049ba2423d01792a629bf4b8176d | # -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from typing import Dict
from Tea.core import TeaCore
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as UtilCl... | [
"# -*- coding: utf-8 -*-\n# This file is auto-generated, don't edit it. Thanks.\nfrom typing import Dict\nfrom Tea.core import TeaCore\n\nfrom alibabacloud_tea_openapi.client import Client as OpenApiClient\nfrom alibabacloud_tea_openapi import models as open_api_models\nfrom alibabacloud_tea_util.client import Clie... | false |
8,729 | 2c8b8e9767ac8400fb6390e0851d9df10df7cd8c | import os
import torch
from collections import OrderedDict
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import image as mplimg
from torch.nn.functional import upsample
import networks.deeplab_resnet as resnet
from mypath import Path
from dataloaders import helpers as h... | [
"import os\nimport torch\nfrom collections import OrderedDict\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import image as mplimg\n\nfrom torch.nn.functional import upsample\n\nimport networks.deeplab_resnet as resnet\nfrom mypath import Path\nfrom dataloaders im... | false |
8,730 | 5848273a76995825f01df53d6beed534e6f9f9fe | #############################################################################
## Crytek Source File
## Copyright (C) 2013, Crytek Studios
##
## Creator: Christopher Bolte
## Date: Oct 31, 2013
## Description: WAF based build system
#############################################################################
from wafl... | [
"#############################################################################\n## Crytek Source File\n## Copyright (C) 2013, Crytek Studios\n##\n## Creator: Christopher Bolte\n## Date: Oct 31, 2013\n## Description: WAF based build system\n###########################################################################... | false |
8,731 | 7571e86be1077ae0f7ae542824cfcaaa2949dc83 | import numpy as np
from scipy.stats import loguniform
import sys
def generate_parameters(seed):
np.random.seed(seed)
out={}
out['nfeatures'] = np.random.randint(3, 25)
out['lr'] = float(loguniform.rvs(0.001, 0.01, size=1))
out['gamma'] = np.random.uniform(0.75, 0.05)
out['penalty'] = float(logu... | [
"import numpy as np\nfrom scipy.stats import loguniform\nimport sys\n\ndef generate_parameters(seed):\n np.random.seed(seed)\n out={}\n out['nfeatures'] = np.random.randint(3, 25)\n out['lr'] = float(loguniform.rvs(0.001, 0.01, size=1))\n out['gamma'] = np.random.uniform(0.75, 0.05)\n out['penalty... | false |
8,732 | fe1a9804862942491b11b9baceecd37bf628fbb8 | # addtwo_run-py
"""
Train and test a TCN on the add two dataset.
Trying to reproduce https://arxiv.org/abs/1803.01271.
"""
print('Importing modules')
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.uti... | [
"# addtwo_run-py\r\n\"\"\"\r\nTrain and test a TCN on the add two dataset.\r\nTrying to reproduce https://arxiv.org/abs/1803.01271.\r\n\"\"\"\r\nprint('Importing modules')\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nfrom torch.utils.tensorboard impor... | false |
8,733 | 6f216420f641c042bb2772b79c10f904ffa21938 | import pygame
from random import randint, choice
BLACK = (0,0,0)
#----------------------------------------------------------
class Ball(pygame.sprite.Sprite):
#------------------------------------------------------
def __init__(self, color, width, height):
# Initialize as a Sprite
super(... | [
"import pygame\nfrom random import randint, choice\n\nBLACK = (0,0,0)\n\n#----------------------------------------------------------\n\nclass Ball(pygame.sprite.Sprite):\n \n #------------------------------------------------------\n def __init__(self, color, width, height):\n # Initialize as a Sprit... | false |
8,734 | a0310b1bab339064c36ff0fe92d275db7a6c5ba9 | from _math import Vector2, Vector3, Quaternion, Transform, Vector3Immutable, QuaternionImmutable, minimum_distance
from _math import mod_2pi
from math import pi as PI, sqrt, fmod, floor, atan2, acos, asin, ceil, pi, e
import operator
from sims4.repr_utils import standard_repr
import enum
import native.animation
import ... | [
"from _math import Vector2, Vector3, Quaternion, Transform, Vector3Immutable, QuaternionImmutable, minimum_distance\nfrom _math import mod_2pi\nfrom math import pi as PI, sqrt, fmod, floor, atan2, acos, asin, ceil, pi, e\nimport operator\nfrom sims4.repr_utils import standard_repr\nimport enum\nimport native.animat... | false |
8,735 | 923a2979df3c37583eec712880ad821541bd898b | import numpy as np
import matplotlib.pyplot as plt
conf_arr = [[ 2987, 58, 955, 832, 1991, 181, 986],
[ 142, 218, 195, 44, 235, 11, 27],
[ 524, 8, 3482, 478, 2406, 708, 588],
[ 140, 0, 386, 12491, 793, 182, 438],
[ 368, 15, 883, 635, 6331, 71, ... | [
"import numpy as np\nimport matplotlib.pyplot as plt\n\nconf_arr = [[ 2987, 58, 955, 832, 1991, 181, 986],\n\t\t[ 142, 218, 195, 44, 235, 11, 27],\n\t\t[ 524, 8, 3482, 478, 2406, 708, 588],\n\t\t[ 140, 0, 386, 12491, 793, 182, 438],\n\t\t[ 368, 15, 883, ... | false |
8,736 | c664257d64b269002964ce95c05f132e563a65d4 | from __future__ import division
rates = { "GBP-EUR":1.10, "EUR-USD":1.11, "GBP-USD":1.22, "GBP-YEN": 129.36 }
def find(rates, fx):
try:
return rates[fx]
except:
return -1
def getInputs():
amount = raw_input("Enter amount: ")
firstCurrency = raw_input("Enter Currency To Convert From: ")
secCurrency = raw_in... | [
"from __future__ import division\n\nrates = { \"GBP-EUR\":1.10, \"EUR-USD\":1.11, \"GBP-USD\":1.22, \"GBP-YEN\": 129.36 }\n\ndef find(rates, fx):\n\ttry:\n\t\treturn rates[fx]\n\texcept:\n\t\treturn -1\n\n\ndef getInputs():\n\tamount = raw_input(\"Enter amount: \")\n\tfirstCurrency = raw_input(\"Enter Currency To C... | true |
8,737 | 1dd5c25cd3b7bc933ba0b63d9a42fdddc92b8531 | import os
import lasagne
import theano
import theano.tensor as T
import numpy as np
from lasagne.layers import Conv2DLayer,\
MaxPool2DLayer,\
InputLayer
from lasagne.nonlinearities import elu, sigmoid, rectify
from lasagne.regularization import l2, regularize_layer_... | [
"import os\nimport lasagne\nimport theano\nimport theano.tensor as T\nimport numpy as np\nfrom lasagne.layers import Conv2DLayer,\\\n MaxPool2DLayer,\\\n InputLayer\nfrom lasagne.nonlinearities import elu, sigmoid, rectify\nfrom lasagne.regularization import l2, r... | false |
8,738 | 70f2fc6873a78305c74e3c3ad04cb24d72019d56 | i = 0
real_value = 8
while i <= 3:
guess = int(input('Guess: '))
if guess == real_value:
print('You Win!')
break
else:
print('You lose')
| [
"i = 0\nreal_value = 8\nwhile i <= 3:\n guess = int(input('Guess: '))\n if guess == real_value:\n print('You Win!')\n break\n else:\n print('You lose')\n \n"
] | true |
8,739 | 876e9f03c908338a247b6bf1f23011e609bbc2a5 | #!/usr/bin/python
__author__ = "morganlnance"
'''
Analysis functions using PyRosetta4
'''
def get_sequence(pose, res_nums=None):
# type: (Pose, list) -> str
"""
Return the sequence of the <pose>, or, return the sequence listed in <res_nums>
:param pose: Pose
:param res_nums: list() of Pose residu... | [
"#!/usr/bin/python\n__author__ = \"morganlnance\"\n\n'''\nAnalysis functions using PyRosetta4\n'''\n\n\ndef get_sequence(pose, res_nums=None):\n # type: (Pose, list) -> str\n \"\"\"\n Return the sequence of the <pose>, or, return the sequence listed in <res_nums>\n :param pose: Pose\n :param res_nums... | false |
8,740 | a9e5d4d48f96974da772f47a4c20ebc96bc31d85 | #! /usr/bin/env python
import os
import glob
import math
from array import array
import sys
import time
import subprocess
import ROOT
mass=[600,700,800,900,1000]
cprime=[01,02,03,05,07,10]
BRnew=[00,01,02,03,04,05]
for i in range(len(mass)):
for j in range(len(cprime)):
for k in range(len(BRnew)):
... | [
"#! /usr/bin/env python\nimport os\nimport glob\nimport math\nfrom array import array\nimport sys\nimport time\nimport subprocess\nimport ROOT\n\nmass=[600,700,800,900,1000]\ncprime=[01,02,03,05,07,10]\nBRnew=[00,01,02,03,04,05]\n\nfor i in range(len(mass)):\n for j in range(len(cprime)):\n for k in range... | true |
8,741 | 8b7894e274647e48e3a1fe12473937bd6c62e943 | from torch.utils.data import DataLoader
from config import Config
from torchnet import meter
import numpy as np
import torch
from torch import nn
from tensorboardX import SummaryWriter
from Funcs import MAvgMeter
from vae.base_vae import VAE
from vae.data_util import Zinc_dataset
import time
import torch.optim
class ... | [
"from torch.utils.data import DataLoader\nfrom config import Config\nfrom torchnet import meter\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom tensorboardX import SummaryWriter\nfrom Funcs import MAvgMeter\nfrom vae.base_vae import VAE\nfrom vae.data_util import Zinc_dataset\nimport time\nimport torc... | false |
8,742 | 4e86dd74374297c3b0ce8fea93910003dac7d5d7 | import random
from PyQt4.QtGui import (
QWidget, QHBoxLayout, QPushButton, QMainWindow, QIcon, QAction, QShortcut,
QKeySequence, QFileDialog, QMessageBox)
from PyQt4 import QtCore
class Controls(QWidget):
def __init__(self, parent):
super(Controls, self).__init__(parent)
... | [
"import random\r\n\r\nfrom PyQt4.QtGui import (\r\n QWidget, QHBoxLayout, QPushButton, QMainWindow, QIcon, QAction, QShortcut,\r\n QKeySequence, QFileDialog, QMessageBox)\r\nfrom PyQt4 import QtCore\r\n\r\nclass Controls(QWidget):\r\n def __init__(self, parent): \r\n super(Controls, self).__i... | false |
8,743 | c7768e44464703552f579a1ec68b58fd9746a381 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 24 18:50:16 2018
@author: User
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 19:05:42 2018
@author: User
"""
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import lxml
import html5lib
import csv
path = 'E:/Data Scienc... | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 24 18:50:16 2018\r\n\r\n@author: User\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 23 19:05:42 2018\r\n\r\n@author: User\r\n\"\"\"\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport numpy as np\r\nimport lxml\r\n... | false |
8,744 | aa24442624aebeb2777f16a826cf59859d7870ba | import torch.nn as nn
from torch.autograd import Variable
import torch
import string
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)
#Find letter index from all_letters, e.g. "a" = 0
def letterToIndex(letter):
return all_letters.find(letter)
#Only for demonstation
def letterToTensor(let... | [
"import torch.nn as nn\nfrom torch.autograd import Variable\nimport torch\nimport string\n\nall_letters = string.ascii_letters + \" .,;'\"\nn_letters = len(all_letters)\n\n#Find letter index from all_letters, e.g. \"a\" = 0\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n#Only for demonstation\n... | false |
8,745 | 7057b882ca1ce2c08e9ba7add5f115636b9b319e | import easyocr
import cv2
import json
import numpy as np
import os
import os.path
import glob
def convert(o):
if isinstance(o, np.generic): return o.item()
raise TypeError
readers = [
easyocr.Reader(['la', 'en', 'de', 'fr', 'es', 'cs', 'is'], gpu = False),
#easyocr.Reader(['ch_tra'], g... | [
"import easyocr\r\nimport cv2\r\nimport json\r\nimport numpy as np\r\nimport os\r\nimport os.path\r\nimport glob\r\n\r\ndef convert(o):\r\n if isinstance(o, np.generic): return o.item() \r\n raise TypeError\r\n\r\nreaders = [\r\n easyocr.Reader(['la', 'en', 'de', 'fr', 'es', 'cs', 'is'], gpu = False),\r\n... | false |
8,746 | c645461effe288a1959b783473d62ff99ca29547 | def test_logsources_model(self):
"""
Comprobacion de que el modelo de la fuente de seguridad coincide con su asociado
Returns:
"""
log_source = LogSources.objects.get(Model="iptables v1.4.21")
self.assertEqual(log_source.get_model(), "iptables v1.4.21")
| [
"def test_logsources_model(self):\n \"\"\"\n Comprobacion de que el modelo de la fuente de seguridad coincide con su asociado\n Returns:\n\n \"\"\"\n log_source = LogSources.objects.get(Model=\"iptables v1.4.21\")\n self.assertEqual(log_source.get_model(), \"iptables v1.4.21\")\n",
"def test_log... | false |
8,747 | 061a78650e2abf6a9d1e4796dd349174a8df5cb8 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Copyright © YXC
# CreateTime: 2016-03-09 10:06:02
"""
Example of functions with arbitrary number arguments
"""
def optional_argument_func(arg1='', arg2=''):
"""
Function with two optional arguments
"""
print("arg1:{0}".format(arg1))
... | [
"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n# Copyright © YXC\n# CreateTime: 2016-03-09 10:06:02\n\n\"\"\"\nExample of functions with arbitrary number arguments\n\"\"\"\n\n\ndef optional_argument_func(arg1='', arg2=''):\n \"\"\"\n Function with two optional arguments\n \"\"\"\n ... | false |
8,748 | 1f4d9f5406b91fd687c0ace8ed29e3c4dfb4d3d2 | n=int(input("val : "))
def fact(n):
c=1;
for i in range(1,n+1):
c*=i;
return c;
print(fact(n)); | [
"n=int(input(\"val : \"))\r\n\r\n\r\ndef fact(n):\r\n c=1;\r\n for i in range(1,n+1):\r\n c*=i;\r\n return c;\r\n\r\nprint(fact(n));",
"n = int(input('val : '))\n\n\ndef fact(n):\n c = 1\n for i in range(1, n + 1):\n c *= i\n return c\n\n\nprint(fact(n))\n",
"<assignment token>\n... | false |
8,749 | 21d2de5719fafd94605f31bc07231644f4be18c5 | from datetime import datetime
from unittest import TestCase
from vpnmupd import versions
class TestClass01(TestCase):
"""Software dependency versions compared"""
def setUp(self) -> None:
super().setUp()
self.any_string = "Some string containing v1.1.1"
def test_case01(self):
"""... | [
"from datetime import datetime\nfrom unittest import TestCase\n\nfrom vpnmupd import versions\n\n\nclass TestClass01(TestCase):\n \"\"\"Software dependency versions compared\"\"\"\n\n def setUp(self) -> None:\n super().setUp()\n self.any_string = \"Some string containing v1.1.1\"\n\n def test... | false |
8,750 | 603d904404ace88205a524d8bfbe3e621b65f425 | #!/usr/bin/python
import os
from subprocess import Popen, PIPE, STDOUT
import time
import re
import telnetlib
from get_sys_info import get_node_list, get_spec_node_list, get_active_tcu, get_ru_list, is_active_ru
g_rg_list = [
'/SGWNetMgr',
'/SS7SGU',
'/MGW_CMRG',
'/MGW_OMURG',
'/Directory',
]
status_dic... | [
"#!/usr/bin/python\nimport os\nfrom subprocess import Popen, PIPE, STDOUT\nimport time\nimport re\nimport telnetlib\nfrom get_sys_info import get_node_list, get_spec_node_list, get_active_tcu, get_ru_list, is_active_ru\ng_rg_list = [\n\t\t\t'/SGWNetMgr',\n\t\t\t'/SS7SGU',\n\t\t\t'/MGW_CMRG',\n\t\t\t'/MGW_OMURG',\n\... | true |
8,751 | 57972e6368aa5749edeab94e45d84f7897ca14ab | """
@file
@brief Various function to clean files.
"""
from __future__ import print_function
import os
import re
def clean_exts(folder=".", fLOG=print, exts=None, fclean=None):
"""
Cleans files in a folder and subfolders with a given extensions.
@param folder folder to clean
@param fLOG... | [
"\"\"\"\n@file\n@brief Various function to clean files.\n\"\"\"\nfrom __future__ import print_function\nimport os\nimport re\n\n\ndef clean_exts(folder=\".\", fLOG=print, exts=None, fclean=None):\n \"\"\"\n Cleans files in a folder and subfolders with a given extensions.\n\n @param folder folder ... | false |
8,752 | ce5f91aa04065aac4d4bc7bdbaab3b74c5a85a93 | import unittest2 as unittest
from zope.component import getUtility
from plone.registry.interfaces import IRegistry
from plone.testing.z2 import Browser
from plone.app.testing import SITE_OWNER_NAME, SITE_OWNER_PASSWORD
from openmultimedia.imagewatchdog.configlet import IImageWatchDogSettings
from openmultimedia.image... | [
"import unittest2 as unittest\n\nfrom zope.component import getUtility\nfrom plone.registry.interfaces import IRegistry\nfrom plone.testing.z2 import Browser\nfrom plone.app.testing import SITE_OWNER_NAME, SITE_OWNER_PASSWORD\n\nfrom openmultimedia.imagewatchdog.configlet import IImageWatchDogSettings\nfrom openmul... | false |
8,753 | 67380fb8b1557b0ed6779009e5f9ae93fd81aedd | #!/usr/bin/python3
"""
module that has
fucntions that
shows attributes
"""
def lookup(obj):
"""
function that returns attributes and methods of an object
"""
return(dir(obj))
| [
"#!/usr/bin/python3\n\"\"\"\nmodule that has\nfucntions that\nshows attributes\n\"\"\"\n\n\ndef lookup(obj):\n \"\"\"\n function that returns attributes and methods of an object\n \"\"\"\n return(dir(obj))\n",
"<docstring token>\n\n\ndef lookup(obj):\n \"\"\"\n function that returns attributes a... | false |
8,754 | 28a920072bad1b411d71f7f70cd991cb7dfbeb8c | # -*- coding:utf-8 -*-
import time
class Base:
def getTime(self):
'''
获取时间戳
:return:
'''
return str(time.time()).split('.')[0] | [
"# -*- coding:utf-8 -*-\nimport time\nclass Base:\n def getTime(self):\n '''\n 获取时间戳\n :return: \n '''\n return str(time.time()).split('.')[0]",
"import time\n\n\nclass Base:\n\n def getTime(self):\n \"\"\"\n 获取时间戳\n :return: \n \"\"\"\n ... | false |
8,755 | df317e914073f5b236f73b616b87f86ae378ef38 | #This is just a test
print("this is something new")
for a in range(10):
print(sum(a))
print("the loop worked")
| [
"#This is just a test\nprint(\"this is something new\")\nfor a in range(10):\n print(sum(a))\nprint(\"the loop worked\")\n",
"print('this is something new')\nfor a in range(10):\n print(sum(a))\nprint('the loop worked')\n",
"<code token>\n"
] | false |
8,756 | b1ae3abb6decf4d70bc2372e70cf4f5b868e805d | # coding: utf-8
# 2019/11/27 @ tongshiwei
import pytest
def test_api(env):
assert set(env.parameters.keys()) == {"knowledge_structure", "action_space", "learning_item_base"}
@pytest.mark.parametrize("n_step", [True, False])
def test_env(env, tmp_path, n_step):
from EduSim.Envs.KSS import kss_train_eval, KS... | [
"# coding: utf-8\n# 2019/11/27 @ tongshiwei\n\nimport pytest\n\n\ndef test_api(env):\n assert set(env.parameters.keys()) == {\"knowledge_structure\", \"action_space\", \"learning_item_base\"}\n\n\n@pytest.mark.parametrize(\"n_step\", [True, False])\ndef test_env(env, tmp_path, n_step):\n from EduSim.Envs.KSS ... | false |
8,757 | 93953f025fed2bcabf29433591689c0a7adf9569 | #!/usr/bin/python
#encoding=utf-8
import os, sys
rules = {
'E': ['A'],
'A': ['A+M', 'M'],
'M': ['M*P', 'P'],
'P': ['(E)', 'N'],
'N': [str(i) for i in range(10)],
}
#st为要扫描的字符串
#target为终止状态,即最后的可接受状态
def back(st, target):
reduced_sets = set()
#cur为当前规约后的字符串,hist为记录的规约规则
def _back(cur, ... | [
"#!/usr/bin/python\n#encoding=utf-8\n\nimport os, sys\n\nrules = {\n 'E': ['A'],\n 'A': ['A+M', 'M'],\n 'M': ['M*P', 'P'],\n 'P': ['(E)', 'N'],\n 'N': [str(i) for i in range(10)],\n}\n\n#st为要扫描的字符串\n#target为终止状态,即最后的可接受状态\ndef back(st, target):\n reduced_sets = set()\n #cur为当前规约后的字符串,hist为记录的规约... | true |
8,758 | 6726c8f1b3ef9a0df74c25c1921203af3aaacb12 | #------------------------------------------------------------------------
#
# @Author : EV2 CHEVALLIER
#
# @Date : 16.09.20
# @Location : École Navale / Chaire de Cyberdéfense des systèmes navals
# @Project : Projet de Fin d'Études
# @Subject : # Real time detection of cyber anomalies upon a NMEA network by using mach... | [
"#------------------------------------------------------------------------\n#\n# @Author : EV2 CHEVALLIER \n#\n# @Date : 16.09.20\n# @Location : École Navale / Chaire de Cyberdéfense des systèmes navals\n# @Project : Projet de Fin d'Études\n# @Subject : # Real time detection of cyber anomalies upon a NMEA network b... | false |
8,759 | bb3c4039ff224c0ca0305778b938ef969c196033 | from app import app
from flask import render_template, request
from app.models import model, formopener
@app.route('/', methods=['GET', 'POST'])
@app.route('/index')
def index():
return render_template("index.html")
@app.route('/personality', methods=['GET', 'POST'])
def personfont():
user_input=dict(request.... | [
"from app import app\nfrom flask import render_template, request\nfrom app.models import model, formopener\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/personality', methods=['GET', 'POST'])\ndef personfont():\n user_i... | false |
8,760 | 48369e1ed826a9a50c0fd9f63b7cc10b8225ce2b | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Implements the webservice calls of the command
like rest apis or other network related methods
""" | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nImplements the webservice calls of the command\nlike rest apis or other network related methods\n\"\"\"",
"<docstring token>\n"
] | false |
8,761 | 6b32f829648b92da4b638ffd79692ffb86be80fe | import cv2
import os
import numpy as np
import sys
from os.path import expanduser
np.random.seed(0)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Generate artificial videos with one subject in Casia-B')
parser.add_argument('--dataset', type=str, required=False... | [
"import cv2\nimport os\nimport numpy as np\nimport sys\nfrom os.path import expanduser\n\nnp.random.seed(0)\n\n\n\nif __name__ == \"__main__\":\n import argparse\n\n parser = argparse.ArgumentParser(description='Generate artificial videos with one subject in Casia-B')\n parser.add_argument('--dataset', typ... | false |
8,762 | e375501e6b815530e61af9181d4cade83d4588ca | #a list of functions/Classes to be inported when a user imports * from swarmpose
__all__ = ['Swarmpose'] | [
"#a list of functions/Classes to be inported when a user imports * from swarmpose\n__all__ = ['Swarmpose']",
"__all__ = ['Swarmpose']\n",
"<assignment token>\n"
] | false |
8,763 | c327f8f7aece1a9c25079613809df52e9a8e7a52 | from rdflib import Graph
from rdflib.plugins.sparql import prepareQuery
def is_file_ontology(file_path):
"""
Method that, given a file, returns its URI.
This method is in a separate file in case we want to extract additional metadata if required
Parameters
----------
@param file_path: path of ... | [
"from rdflib import Graph\nfrom rdflib.plugins.sparql import prepareQuery\n\n\ndef is_file_ontology(file_path):\n \"\"\"\n Method that, given a file, returns its URI.\n This method is in a separate file in case we want to extract additional metadata if required\n Parameters\n ----------\n @param f... | false |
8,764 | f98f2ef0d94839711b473ad1ca32b85645d4014e | """A lightweight Python wrapper of SoX's effects."""
import shlex
from io import BufferedReader, BufferedWriter
from subprocess import PIPE, Popen
import numpy as np
from .sndfiles import (
FileBufferInput,
FileBufferOutput,
FilePathInput,
FilePathOutput,
NumpyArrayInput,
NumpyArrayOutput,
... | [
"\"\"\"A lightweight Python wrapper of SoX's effects.\"\"\"\nimport shlex\nfrom io import BufferedReader, BufferedWriter\nfrom subprocess import PIPE, Popen\n\nimport numpy as np\n\nfrom .sndfiles import (\n FileBufferInput,\n FileBufferOutput,\n FilePathInput,\n FilePathOutput,\n NumpyArrayInput,\n ... | false |
8,765 | b08cface601ee07125090f3ae03a3120974688f2 | from PyQt5.QtWidgets import *
import sys
import math
Data = ''
class Button:
def __init__(self, text, results):
self.b = QPushButton(str(text))
self.text = text
self.results = results
self.b.clicked.connect(lambda: self.handleInput(
self.text)) # Important because we ... | [
"from PyQt5.QtWidgets import *\nimport sys\nimport math\n\nData = ''\n\n\nclass Button:\n def __init__(self, text, results):\n self.b = QPushButton(str(text))\n self.text = text\n self.results = results\n self.b.clicked.connect(lambda: self.handleInput(\n self.text)) # Imp... | false |
8,766 | d111f93144a1d2790470365d0ca31bcea17713d7 | import json
# No llego a solucionarlo entero.
#Aparcamientos que estan cubiertos en el centro de deportes .
from pprint import pprint
with open('Aparcamientos.json') as data_file:
data = json.load(data_file)
for x in data['docs']:
if x['TIPOLOGIA'] == 'Cubierto':
print(x['NOMBRE'])
elif x['TIPOLOGIA'] == '... | [
"import json\n# No llego a solucionarlo entero.\n#Aparcamientos que estan cubiertos en el centro de deportes .\nfrom pprint import pprint\n\nwith open('Aparcamientos.json') as data_file: \n data = json.load(data_file)\nfor x in data['docs']:\n\tif x['TIPOLOGIA'] == 'Cubierto':\n\t\tprint(x['NOMBRE'])\n\telif ... | false |
8,767 | 1f6176e9285d810934ae745cf8759b5cd6f408c8 | import typing
from pydantic import AnyUrl
from .base import FBObject
class MediaPayload(FBObject):
url: AnyUrl
class Coors(FBObject):
lat: float
long: float
class LocationPayload(FBObject):
coordinates: Coors
class AttachmentFallback(FBObject):
title: str
url: AnyUrl
payload: typin... | [
"import typing\n\nfrom pydantic import AnyUrl\n\nfrom .base import FBObject\n\n\nclass MediaPayload(FBObject):\n url: AnyUrl\n\n\nclass Coors(FBObject):\n lat: float\n long: float\n\n\nclass LocationPayload(FBObject):\n coordinates: Coors\n\n\nclass AttachmentFallback(FBObject):\n title: str\n url... | false |
8,768 | 69e8601a387d0987fbb6d1da5ac0f9412fffc63d | import sys
num = int(input())
odd_sum = 0
even_sum = 0
odd_smallest = sys.maxsize
even_smallest = sys.maxsize
odd_biggest = -sys.maxsize
even_biggest = -sys.maxsize
for i in range(0, num):
element = float(input())
if i % 2 != 0:
even_sum += element
if element <= even_smallest:
even_s... | [
"import sys\nnum = int(input())\nodd_sum = 0\neven_sum = 0\nodd_smallest = sys.maxsize\neven_smallest = sys.maxsize\nodd_biggest = -sys.maxsize\neven_biggest = -sys.maxsize\nfor i in range(0, num):\n element = float(input())\n if i % 2 != 0:\n even_sum += element\n if element <= even_smallest:\n... | false |
8,769 | 192c44540018b9e1ab857bdbfba6fdb39bb74431 | # -*- coding: utf-8 -*-
import json
import os
import io
import shutil
import pytest
from chi_annotator.algo_factory.common import TrainingData
from chi_annotator.task_center.config import AnnotatorConfig
from chi_annotator.task_center.data_loader import load_local_data
from chi_annotator.task_center.model import Inte... | [
"# -*- coding: utf-8 -*-\nimport json\nimport os\nimport io\nimport shutil\n\nimport pytest\n\nfrom chi_annotator.algo_factory.common import TrainingData\nfrom chi_annotator.task_center.config import AnnotatorConfig\nfrom chi_annotator.task_center.data_loader import load_local_data\nfrom chi_annotator.task_center.m... | false |
8,770 | a9efa258c223460b2b79861acdde89161706ad9a | '''
Given an infinite sorted array (or an array with unknown size), find if a given number ‘key’ is present in the array. Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1.
Since it is not possible to define an array with infinite (unknown) size, you will be provided ... | [
"'''\nGiven an infinite sorted array (or an array with unknown size), find if a given number ‘key’ is present in the array. Write a function to return the index of the ‘key’ if it is present in the array, otherwise return -1.\n\nSince it is not possible to define an array with infinite (unknown) size, you will be p... | false |
8,771 | 821e89730fde2e12b24b52b04701c1f3501e0d57 | from flask import abort
from flask_restx import Resource, Namespace, Model, fields, reqparse
from infraestructura.lineas_repo import LineasRepo
from infraestructura.equipos_repo import EquiposRepo
from infraestructura.clientes_lep_repo import ClientesLepRepo
from infraestructura.lineaequipoplan_repo import LineaEquipoP... | [
"from flask import abort\nfrom flask_restx import Resource, Namespace, Model, fields, reqparse\nfrom infraestructura.lineas_repo import LineasRepo\nfrom infraestructura.equipos_repo import EquiposRepo\nfrom infraestructura.clientes_lep_repo import ClientesLepRepo\nfrom infraestructura.lineaequipoplan_repo import Li... | false |
8,772 | e4bc2e97b70e2dc91dc86457866ec6b3531ef803 | from pyspark.sql import SQLContext, Row
from pyspark import SparkContext, SparkConf
from pyspark.sql.functions import col
import collections
# Create a Spark Session (the config bit is only for windows)
#conf = SparkConf().setAppName("SQL App").setMaster("local")
sc = SparkContext()
sqlCtx = SQLContext(sc)
def mapp... | [
"from pyspark.sql import SQLContext, Row\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql.functions import col\n\nimport collections\n\n# Create a Spark Session (the config bit is only for windows)\n#conf = SparkConf().setAppName(\"SQL App\").setMaster(\"local\")\nsc = SparkContext()\n\nsqlCtx = SQLCo... | false |
8,773 | 933f74e4fda0b30bdf70ff3f3dbde2383b10c694 | # -*- coding:utf-8 -*-
'''
Created on 2018/2/23
@author : xxfore
'''
import time
import sys
import re
sys.dont_write_bytecode = True
class TimeUtils(object):
@staticmethod
def convert_timestamp_to_date(timestamp):
time_local = time.localtime(timestamp)
dt = time.strftime("%Y-%m-%d %H:%M:%S",t... | [
"# -*- coding:utf-8 -*-\n'''\n\nCreated on 2018/2/23\n\n@author : xxfore\n\n'''\nimport time\nimport sys\nimport re\nsys.dont_write_bytecode = True\nclass TimeUtils(object):\n @staticmethod\n def convert_timestamp_to_date(timestamp):\n time_local = time.localtime(timestamp)\n dt = time.strftime(... | false |
8,774 | ca0616694b30f69263db48282bf8b8c130de0fbb | /home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/tfprof/__init__.py | [
"/home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/tfprof/__init__.py"
] | true |
8,775 | 9f34f94422f4847859e9111f34ade2e1274cb543 | """Visit module to add odoo checks
"""
import os
import re
import astroid
import isort
from pylint.checkers import utils
from six import string_types
from .. import misc, settings
ODOO_MSGS = {
# C->convention R->refactor W->warning E->error F->fatal
# Visit odoo module with settings.BASE_OMODULE_ID
'C... | [
"\"\"\"Visit module to add odoo checks\n\"\"\"\n\nimport os\nimport re\n\nimport astroid\nimport isort\nfrom pylint.checkers import utils\nfrom six import string_types\n\nfrom .. import misc, settings\n\nODOO_MSGS = {\n # C->convention R->refactor W->warning E->error F->fatal\n\n # Visit odoo module with sett... | false |
8,776 | 05e57ed95427f0de74ea5b0589c5cd56e4a96f73 | # https://github.com/openai/gym/blob/master/gym/envs/__init__.py#L449
import gym
import numpy as np
from rl_main.conf.names import EnvironmentName, DeepLearningModelName
from rl_main.environments.environment import Environment
from rl_main.main_constants import DEEP_LEARNING_MODEL
class BreakoutDeterministic_v4(Envi... | [
"# https://github.com/openai/gym/blob/master/gym/envs/__init__.py#L449\nimport gym\nimport numpy as np\n\nfrom rl_main.conf.names import EnvironmentName, DeepLearningModelName\nfrom rl_main.environments.environment import Environment\nfrom rl_main.main_constants import DEEP_LEARNING_MODEL\n\n\nclass BreakoutDetermi... | false |
8,777 | b54f47de85fe95d47a1b1be921997ad86d7b450d | # nomer7
import no2_modul2 # Atau apapun file-nya yang kamu buat tadi
class MhsTIF(no2_modul2.Mahasiswa): # perhatikan class induknya : Mahasiswa
"""Class MhsTIF yang dibangun dari class Mahasiswa"""
def kataKanPy(self):
print('Python is cool.')
"Apakah metode / state itu berasal ... | [
"# nomer7\r\n\r\nimport no2_modul2 # Atau apapun file-nya yang kamu buat tadi\r\n\r\nclass MhsTIF(no2_modul2.Mahasiswa): # perhatikan class induknya : Mahasiswa\r\n \"\"\"Class MhsTIF yang dibangun dari class Mahasiswa\"\"\"\r\n def kataKanPy(self):\r\n print('Python is cool.')\r\n\r\n\"Apak... | true |
8,778 | e08820ff4fb35a3770fcb110ef7181aad1abbae5 | from django.conf.urls import url
from django.contrib import admin
from comments.api.views import CommentListAPIView, CommentDetailAPIView
urlpatterns = [
url(r'^$', CommentListAPIView.as_view(), name='list'),
url(r'^(?P<pk>\d+)/$', CommentDetailAPIView, name='detail'),
]
| [
"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom comments.api.views import CommentListAPIView, CommentDetailAPIView\n\nurlpatterns = [\n url(r'^$', CommentListAPIView.as_view(), name='list'),\n url(r'^(?P<pk>\\d+)/$', CommentDetailAPIView, name='detail'),\n]\n",
"from django.conf.... | false |
8,779 | 00312f57e8a78444937f46cecb62a2b684b4fc91 | a = int(input("Enter no. of over: "))
print("total ball:",a*6 )
import random
comp_runs = random.randint(0,36)
print("computer's run:" ,comp_runs)
comp_runs = comp_runs+1
print("runs need to win:",comp_runs)
chances_1 = a*6
no_of_chances_1 = 0
your_runs = 0
print("-----------------------------------------... | [
"a = int(input(\"Enter no. of over: \"))\r\nprint(\"total ball:\",a*6 )\r\nimport random\r\n\r\ncomp_runs = random.randint(0,36)\r\nprint(\"computer's run:\" ,comp_runs)\r\ncomp_runs = comp_runs+1\r\nprint(\"runs need to win:\",comp_runs)\r\nchances_1 = a*6\r\nno_of_chances_1 = 0\r\nyour_runs = 0\r\n\r\nprint(\"---... | false |
8,780 | 2d4187ab5d178efa4920110ccef61c608fdb14c0 | """
# System of national accounts (SNA)
This is an end-to-end example of national accounts sequence,
from output to net lending. It is based on Russian Federation data
for 2014-2018.
Below is a python session transcript with comments.
You can fork [a github repo](https://github.com/epogrebnyak/sna-ru)
to replica... | [
"\"\"\"\n# System of national accounts (SNA)\n\nThis is an end-to-end example of national accounts sequence, \nfrom output to net lending. It is based on Russian Federation data \nfor 2014-2018. \n\nBelow is a python session transcript with comments. \nYou can fork [a github repo](https://github.com/epogrebnyak/sna... | false |
8,781 | d1ce6c081dce2e4bdb6087cd61d7f857dbb1348d | a=float.input('Valor da conta')
print('Valor da conta com 10%: R$',(a))
| [
"a=float.input('Valor da conta')\nprint('Valor da conta com 10%: R$',(a))\n",
"a = float.input('Valor da conta')\nprint('Valor da conta com 10%: R$', a)\n",
"<assignment token>\nprint('Valor da conta com 10%: R$', a)\n",
"<assignment token>\n<code token>\n"
] | false |
8,782 | a92384a6abee9e231092ee0e4dbdb60bafcc9979 | import glob
import csv
import math
import pandas
# this is used to train the model, try different model, generate the csv file of the result
import pandas
import pandas as pd
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn import datasets
from sklearn.prepro... | [
"import glob\nimport csv\nimport math\n\nimport pandas\n\n# this is used to train the model, try different model, generate the csv file of the result\n\nimport pandas\nimport pandas as pd\nimport pickle\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom sklearn import datasets\n... | false |
8,783 | 2cbdb828ab6e0ad44154f0c5b2a1d807fd0d2520 | from redis_db import RedisClient
from setting import TEST_URL
import requests
class Test_Proxy():
def __init__(self):
self.db=RedisClient()
def proxy_test(self, proxy):
url = TEST_URL
proxies={
"http":proxy,
"https":proxy
}
# print("{}(测试中)".form... | [
"from redis_db import RedisClient\nfrom setting import TEST_URL\nimport requests\n\nclass Test_Proxy():\n def __init__(self):\n self.db=RedisClient()\n\n def proxy_test(self, proxy):\n url = TEST_URL\n proxies={\n \"http\":proxy,\n \"https\":proxy\n }\n ... | false |
8,784 | 2b746d89d34435eb5f3a5b04da61c5cc88178852 | __author__ = 'simsun'
| [
"__author__ = 'simsun'\n",
"<assignment token>\n"
] | false |
8,785 | afb09f9d5860994f38e8553b19e7ebc339cc2df6 | """
These are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py)
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import time
import urllib
try:
# For Python 3.0 and later
import urllib.request
except ImportError:
... | [
"\"\"\"\nThese are data input download and prep scripts. They download and massage the data for the UBM calculations (calc.py)\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport time\nimport urllib\ntry:\n # For Python 3.0 and later\n import urllib.request\ne... | false |
8,786 | 4927a440093e822250af25dfd6a2ce62d7cc099e | input = open('input').read()
stacks_input, instructions = input.split('\n\n')
stacks_input_lines = stacks_input.split('\n')
stack_numbers = map(int, stacks_input_lines[-1].split())
stacks = []
for _ in stack_numbers:
stacks.append([])
for line in stacks_input_lines[:-1]:
for stack_index, i in enumerate(range(1... | [
"input = open('input').read()\n\nstacks_input, instructions = input.split('\\n\\n')\nstacks_input_lines = stacks_input.split('\\n')\nstack_numbers = map(int, stacks_input_lines[-1].split())\nstacks = []\nfor _ in stack_numbers:\n stacks.append([])\nfor line in stacks_input_lines[:-1]:\n for stack_index, i in ... | false |
8,787 | c7ecf8ada74b3e401c2144457d4fa1050f598727 | from collections import deque
for case in xrange(input()):
cards = input()
indexes = map(int, raw_input().split())
deck = [0 for i in xrange(cards)]
index = -1
for i in xrange(1, cards + 1):
while True:
index = (index + 1)%cards
if deck[index] == 0:
break
for j in xrange(i - 1):
... | [
"from collections import deque\n\nfor case in xrange(input()):\n cards = input()\n indexes = map(int, raw_input().split())\n\n deck = [0 for i in xrange(cards)]\n index = -1\n for i in xrange(1, cards + 1):\n while True:\n index = (index + 1)%cards\n if deck[index] == 0:\n break\n for j ... | true |
8,788 | e1c902ef340a0a5538b41a03cc93686e0dd31672 | from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from prettytable import PrettyTable
from time import sleep
from customization import *
import urllib.request,json
chrome_options=webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--inco... | [
"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom prettytable import PrettyTable\nfrom time import sleep\nfrom customization import *\n\nimport urllib.request,json\nchrome_options=webdriver.ChromeOptions()\nchrome_options.add_argument(\"--headless\")\nchrome_options.add_... | false |
8,789 | 315fed1806999fed7cf1366ef0772318a0baa84d | # settings
import config
# various modules
import sys
import time
import multiprocessing
import threading
from queue import Queue
import time
import os
import signal
import db
import time
from random import randint
# telepot's msg loop & Bot
from telepot.loop import MessageLoop
from telepot import Bot
import asyncio... | [
"# settings\nimport config\n\n# various modules\nimport sys\nimport time\nimport multiprocessing\nimport threading\nfrom queue import Queue\nimport time\nimport os\nimport signal\nimport db\nimport time\nfrom random import randint\n\n# telepot's msg loop & Bot\nfrom telepot.loop import MessageLoop\nfrom telepot imp... | true |
8,790 | 68904be892968d4a1d82a59a31b95a8133a30832 | '''
* @Author: Mohammad Fatha.
* @Date: 2021-09-17 19:50
* @Last Modified by: Mohammad Fatha
* @Last Modified time: 2021-09-17 19:55
* @Title: Gambler Game
'''
import random
def gamblerProblem():
"""
Description:
This function Simulates a gambler who start with stake and place fair 1 bets until
... | [
"'''\n* @Author: Mohammad Fatha.\n* @Date: 2021-09-17 19:50 \n* @Last Modified by: Mohammad Fatha\n* @Last Modified time: 2021-09-17 19:55\n* @Title: Gambler Game\n'''\nimport random\n \ndef gamblerProblem():\n \"\"\"\n Description:\n This function Simulates a gambler who start with stake and place... | false |
8,791 | 0f55b598058b65c9dbf9cd4761d1ff6fc7091b19 | __author__ = 'NikolaiEgorov'
def Lad(a1, a2, b1, b2):
if (a1 == b1) | (a2 == b2):
return 'YES'
else:
return 'NO'
a1 = int(input())
a2 = int(input())
b1 = int(input())
b2 = int(input())
print(Lad(a1,a2,b1,b2))
| [
"__author__ = 'NikolaiEgorov'\ndef Lad(a1, a2, b1, b2):\n if (a1 == b1) | (a2 == b2):\n return 'YES'\n else:\n return 'NO'\na1 = int(input())\na2 = int(input())\nb1 = int(input())\nb2 = int(input())\nprint(Lad(a1,a2,b1,b2))\n",
"__author__ = 'NikolaiEgorov'\n\n\ndef Lad(a1, a2, b1, b2):\n i... | false |
8,792 | 5493887e32dbe7ae27eca79d28da8488183b37a3 | import string
fhand = open("romeo-full.txt")
counts = dict()
for line in fhand:
line.tranc | [
"import string\nfhand = open(\"romeo-full.txt\")\ncounts = dict()\nfor line in fhand:\n \n line.tranc",
"import string\nfhand = open('romeo-full.txt')\ncounts = dict()\nfor line in fhand:\n line.tranc\n",
"<import token>\nfhand = open('romeo-full.txt')\ncounts = dict()\nfor line in fhand:\n line.tra... | false |
8,793 | 707c83bc83f606b570af973094574e6675cfc83f | # Copyright (c) 2011-2014 by California Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice,... | [
"# Copyright (c) 2011-2014 by California Institute of Technology\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# 1. Redistributions of source code must retain the above copyright\... | false |
8,794 | 43b5936ca9368dcae8d41b44fd9dc927fe18c9bc | from django.db import transaction
from django.contrib.auth.models import Group
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status, mixins
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets imp... | [
"from django.db import transaction\nfrom django.contrib.auth.models import Group\nfrom drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\n\nfrom rest_framework import status, mixins\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework... | false |
8,795 | d70f77713abf4b35db9de72c1edbf4bf4580b2a4 | from random import shuffle, choice
from typing import Dict, List, Tuple
note_to_midi: Dict[int, int] = {
1: 0,
2: 2,
3: 4,
4: 5,
5: 7,
6: 9,
7: 11,
}
midi_to_note: Dict[int, int] = {
0: 1,
2: 2,
4: 3,
5: 4,
7: 5,
9: 6,
11: 7,
}
class Note:
num: int
@c... | [
"from random import shuffle, choice\nfrom typing import Dict, List, Tuple\n\nnote_to_midi: Dict[int, int] = {\n 1: 0,\n 2: 2,\n 3: 4,\n 4: 5,\n 5: 7,\n 6: 9,\n 7: 11,\n}\n\nmidi_to_note: Dict[int, int] = {\n 0: 1,\n 2: 2,\n 4: 3,\n 5: 4,\n 7: 5,\n 9: 6,\n 11: 7,\n}\n\n\ncla... | false |
8,796 | a70dae504a4dfa3997a11e4c605accfab0024318 | from ttkwidgets import CheckboxTreeview
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import json
import os
from DbDataloader import *
class DataLoader():
def __init__(self,master):
self.anne={}
self.master=Toplevel(master)
master.wait_visibility(self.master)... | [
"from ttkwidgets import CheckboxTreeview\nfrom tkinter import *\nfrom tkinter.ttk import *\nfrom tkinter import messagebox\nimport json\nimport os\nfrom DbDataloader import *\nclass DataLoader():\n def __init__(self,master):\n self.anne={}\n self.master=Toplevel(master)\n master.wait_visibil... | false |
8,797 | b2d5b16c287dc76a088f6e20eca4a16dd0aad00f | from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('poll_id', nargs='+', type=int)
# Named (optional arguments)
... | [
"from django.core.management.base import BaseCommand, CommandError\n\nclass Command(BaseCommand):\n help = 'Closes the specified poll for voting'\n\n def add_arguments(self, parser):\n # Positional arguments\n parser.add_argument('poll_id', nargs='+', type=int)\n\n # Named (optional argum... | false |
8,798 | a995305cb5589fa0cbb246ae3ca6337f4f2c3ca1 | from django.apps import AppConfig
class ClassromConfig(AppConfig):
name = 'classrom'
| [
"from django.apps import AppConfig\n\n\nclass ClassromConfig(AppConfig):\n name = 'classrom'\n",
"<import token>\n\n\nclass ClassromConfig(AppConfig):\n name = 'classrom'\n",
"<import token>\n\n\nclass ClassromConfig(AppConfig):\n <assignment token>\n",
"<import token>\n<class token>\n"
] | false |
8,799 | 8e74bd0c051b672bf22c2c8dfb03760805b105c5 | """Tests for Node objects."""
import numpy as np
import unittest
import optimus.core as core
import optimus.nodes as nodes
import optimus.util as util
def __relu__(x):
"Numpy Rectified Linear Unit."
return 0.5 * (np.abs(x) + x)
class NodeTests(unittest.TestCase):
def setUp(self):
pass
de... | [
"\"\"\"Tests for Node objects.\"\"\"\n\nimport numpy as np\nimport unittest\n\nimport optimus.core as core\nimport optimus.nodes as nodes\nimport optimus.util as util\n\n\ndef __relu__(x):\n \"Numpy Rectified Linear Unit.\"\n return 0.5 * (np.abs(x) + x)\n\n\nclass NodeTests(unittest.TestCase):\n\n def set... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.