index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
6,100
ac033e45ea61770c302be677f4dfc95945e2cca5
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Calcu.py # import os, sys def menuCalc(): os.system('clear') print("Esto parece un menu:") print("\t1 - Suma") print("\t2 - Resta") print("\t3 - Multiplicacion") print("\t4 - Division") print("\tq - Para salir") def calculadora(cal...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Calcu.py\n# \n\nimport os, sys\n\ndef menuCalc():\n\n os.system('clear')\n print(\"Esto parece un menu:\")\n print(\"\\t1 - Suma\")\n print(\"\\t2 - Resta\")\n print(\"\\t3 - Multiplicacion\")\n print(\"\\t4 - Division\")\n print(\"\\tq - ...
false
6,101
21050d66120787c1260efd42bb6456d7131fcc6b
N=input() l=map(int,raw_input().split()) l.sort() flag=0 if l[0]<0: print 'False' else: for i in l: if str(i)==str(i)[::-1]: flag=flag+1 if flag>=1: print 'True' else: print 'False'
[ "N=input()\nl=map(int,raw_input().split())\nl.sort()\nflag=0\n\nif l[0]<0:\n print 'False'\nelse:\n for i in l:\n if str(i)==str(i)[::-1]:\n flag=flag+1\n if flag>=1:\n print 'True'\n else:\n print 'False'\n" ]
true
6,102
6b6fac3bfb1b1478dd491fc4dd9c45a19aeb7bd8
#!/usr/bin/env python #-*- coding: utf-8 -*- import pygtk pygtk.require("2.0") import gtk from testarMsg import * class tgApp(object): def __init__(self): builder = gtk.Builder() builder.add_from_file("../tg.glade") self.window = builder.get_object("window1") self.text_area = buil...
[ "#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport pygtk\npygtk.require(\"2.0\")\nimport gtk\nfrom testarMsg import *\n\n\nclass tgApp(object):\n def __init__(self):\n builder = gtk.Builder()\n builder.add_from_file(\"../tg.glade\")\n self.window = builder.get_object(\"window1\")\n ...
false
6,103
3be7183b5c1d86ee0ebfdea89c6459efe89510f8
from data import constants from data.action import Action from data.point import Point class MoveActorsAction(Action): """A code template for moving actors. The responsibility of this class of objects is move any actor that has a velocity more than zero. Stereotype: Controller Attributes:...
[ "from data import constants\nfrom data.action import Action\nfrom data.point import Point\n\nclass MoveActorsAction(Action):\n \"\"\"A code template for moving actors. The responsibility of this class of\n objects is move any actor that has a velocity more than zero.\n \n Stereotype:\n Controller...
false
6,104
c38aff77a7beebc13e7486150d549b876c830db8
class Pwm(): def __init__(self, number, path, features): self.id = number self.path = path + 'pwm' + number self.features = features self.duty = self.get_feature('') self.enable = self.get_feature('_enable') def get_feature(self, feature): return self.features['pwm' + self.id + feature] def set_featu...
[ "\nclass Pwm():\n\n\tdef __init__(self, number, path, features):\n\t\tself.id = number\n\t\tself.path = path + 'pwm' + number\n\t\tself.features = features\n\t\tself.duty = self.get_feature('')\n\t\tself.enable = self.get_feature('_enable')\n\n\tdef get_feature(self, feature):\n\t\treturn self.features['pwm' + self...
false
6,105
6fdfcbcfdf2b680a1fbdb74f77fd5d1a9f7eac0b
# -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # Copyright (c) 2017, Battelle Memorial Institute # 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. Redistri...
[ "# -*- coding: utf-8 -*- {{{\n# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:\n\n# Copyright (c) 2017, Battelle Memorial Institute\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#...
false
6,106
9b6d30a40bafa0e9e4760843d6a2f750f0f88a57
from datetime import date def diff_in_date(first, second): value = str(second - first) if value.__contains__(','): generated_sum = value.split(',') return generated_sum[0] else: return value first_date = date(2014, 7, 2) second_date = date(2014, 7, 11) current_date = date.today()...
[ "from datetime import date\n\n\ndef diff_in_date(first, second):\n value = str(second - first)\n if value.__contains__(','):\n generated_sum = value.split(',')\n return generated_sum[0]\n else:\n return value\n\n\nfirst_date = date(2014, 7, 2)\nsecond_date = date(2014, 7, 11)\ncurrent_...
false
6,107
e0541c377eb6631e4ef5eb79b1204612ce8af48c
import sys import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from uraeus.nmbd.python import simulation from uraeus.nmbd.python.engine.numerics.math_funcs import A, B database_directory = os.path.abspath('../../') sys.path.append(database_directory) from uraeus_fsae.simenv.assemblies i...
[ "import sys\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom uraeus.nmbd.python import simulation\nfrom uraeus.nmbd.python.engine.numerics.math_funcs import A, B\n\ndatabase_directory = os.path.abspath('../../')\nsys.path.append(database_directory)\n\nfrom uraeus_fsae.s...
false
6,108
96bf6220bfc884e3a19f70a63d9ecba449e2e7e2
#!/usr/bin/env python # -*- coding: utf-8 -*- # staticbox.py import wx class StaticBox(wx.Dialog): def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size = (250, 230)) wx.StaticBox(self, -1, 'Personal Info', (5, 5), size = (240, 170)) wx.CheckBox(self, ...
[ "#!/usr/bin/env python \n# -*- coding: utf-8 -*- \n\n# staticbox.py\n\nimport wx\n\nclass StaticBox(wx.Dialog):\n def __init__(self, parent, id, title):\n wx.Dialog.__init__(self, parent, id, title, size = (250, 230))\n\n wx.StaticBox(self, -1, 'Personal Info', (5, 5), size = (240, 170))\n w...
false
6,109
6682c864a3da6f2c894a3a40359726b4eb97d040
#!/usr/bin/python # -*- coding: UTF-8 -*- # author: MSJ # date: 2021/3/11 # desc:冒泡排序 def bubble_sort(arr): for i in range(1, len(arr)): for j in range(0, len(arr) - i): if arr[j] > arr[j + 1]: tmp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = tmp ...
[ "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# author: MSJ\n# date: 2021/3/11\n# desc:冒泡排序\n\n\ndef bubble_sort(arr):\n for i in range(1, len(arr)):\n for j in range(0, len(arr) - i):\n if arr[j] > arr[j + 1]:\n tmp = arr[j]\n arr[j] = arr[j + 1]\n a...
false
6,110
61e38ae6ae2a1ed061f9893742f45b3e44f19a68
from tkinter import * from tkinter import messagebox root = Tk() def hello(): messagebox.showinfo("Say Hello", "Hello World") B1 = Button(root, text = "Say Hello", command = hello, font='arial 20') B1.pack() mainloop()
[ "from tkinter import *\r\nfrom tkinter import messagebox\r\n\r\nroot = Tk()\r\ndef hello():\r\n messagebox.showinfo(\"Say Hello\", \"Hello World\")\r\n\r\nB1 = Button(root, text = \"Say Hello\", command = hello, font='arial 20')\r\nB1.pack()\r\n\r\nmainloop()\r\n\r\n", "from tkinter import *\nfrom tkinter impor...
false
6,111
f925b3b2f55c3f8daf57438d8d20b60446ae39af
from torchsummary import summary import torch import torch.nn as nn import torch.nn.functional as F from eva4modeltrainer import ModelTrainer class Net(nn.Module): """ Base network that defines helper functions, summary and mapping to device """ def conv2d(self, in_channels, out_channels, ker...
[ "from torchsummary import summary\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom eva4modeltrainer import ModelTrainer\r\n\r\nclass Net(nn.Module):\r\n \"\"\"\r\n Base network that defines helper functions, summary and mapping to device\r\n \"\"\"\r\n def conv2d(self,...
false
6,112
7e58fe636e6d835d7857a49900bbc127b52f63d9
class HashTableEntry: """ Hash Table entry, as a linked list node. """ def __init__(self, key, value): self.key = key self.value = value self.next = None class HashTable: """ A hash table that with `capacity` buckets that accepts string keys Implement this. ...
[ "class HashTableEntry:\n \"\"\"\n Hash Table entry, as a linked list node.\n \"\"\"\n\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\n\nclass HashTable:\n \"\"\"\n A hash table that with `capacity` buckets\n that accepts string ...
false
6,113
dc2b074d7d0e87105b2479bb60b46c73dce6c069
# -*-coding:utf-8 -*- # # Created on 2016-04-01 # __ __ # - /__) _ /__) __/ # / / ( (/ / ( / # / from core.views import BaseView class TestView(BaseView): """ 测试页面 """ # template_name = 'test/blog-1.html' template_name = 'test/music-1.html'
[ "# -*-coding:utf-8 -*-\n#\n# Created on 2016-04-01\n# __ __\n# - /__) _ /__) __/\n# / / ( (/ / ( /\n# /\n\nfrom core.views import BaseView\n\n\nclass TestView(BaseView):\n \"\"\"\n 测试页面\n \"\"\"\n\n # template_name = 'test/blog-1.html'\n template_name = 'test/music-...
false
6,114
bfa5739949c26758e3762fcff8347d23ad70f704
# 데이터 출처: kaggle # 데이터 개요: 511, 유리를 위한 다양한 속성(화학원소)들로부터 type 구별 # 데이터 예측 모델: 이진클래스 # 적용 머신러닝 모델: 깊은 다층 퍼셉트론 신경망 # 훈련 데이터셋: 160건 # 검증 데이터셋: 건 # 시험 데이터셋: 수집데이터로서 시험셋을 확보할 수 없으므로 고려하지 않음 # 입력 데이터: 10개 항목의 데이터 # 은닉층: 2개 # 사용한 활성화 함수 # - 제1 은닉층: Relu # - 제2 은닉층: Relu # - Output Layer: Softmax # 사용한 손실함수: categorical_cros...
[ "# 데이터 출처: kaggle\n# 데이터 개요: 511, 유리를 위한 다양한 속성(화학원소)들로부터 type 구별\n# 데이터 예측 모델: 이진클래스\n# 적용 머신러닝 모델: 깊은 다층 퍼셉트론 신경망\n# 훈련 데이터셋: 160건\n# 검증 데이터셋: 건\n# 시험 데이터셋: 수집데이터로서 시험셋을 확보할 수 없으므로 고려하지 않음\n# 입력 데이터: 10개 항목의 데이터\n# 은닉층: 2개\n# 사용한 활성화 함수\n# - 제1 은닉층: Relu\n# - 제2 은닉층: Relu\n# - Output Layer: Softmax\n# 사용한 손실함수...
false
6,115
3f2c1a83ae0dfdba202038a209b90162ccddee36
#!/usr/bin/python3 """City Module""" from models.base_model import BaseModel class City(BaseModel): """City Class Public class attributes: state_d: type string name: type string """ state_id = "" name = ""
[ "#!/usr/bin/python3\n\"\"\"City Module\"\"\"\nfrom models.base_model import BaseModel\n\n\nclass City(BaseModel):\n \"\"\"City Class\n Public class attributes:\n state_d: type string\n name: type string\n \"\"\"\n state_id = \"\"\n name = \"\"\n", "<docstring token>\nfrom models.base_...
false
6,116
cb903f3f7fd3c4f3ba5f8ff2ce12aac9c680aa15
from pyramid.request import Request from pyramid.response import Response from pyramid.view import view_config from svc1_first_auto_service.data.repository import Repository @view_config(route_name='autos_api', request_method='GET', renderer='json') def all_autos(_): cars = Repository.a...
[ "from pyramid.request import Request\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\n\nfrom svc1_first_auto_service.data.repository import Repository\n\n\n@view_config(route_name='autos_api',\n request_method='GET',\n renderer='json')\ndef all_autos(_):\n car...
false
6,117
9a2002b5ff0fe41f2b5b568f4c278d4376bf4fb1
import pandas as pd from bokeh.models import ColumnDataSource, LinearColorMapper, HoverTool from bokeh.plotting import figure from bokeh.transform import transform from sklearn.metrics import confusion_matrix from reporter.settings import COLORS from reporter.metrics import Metric class ConfusionMatrix(Metric): d...
[ "import pandas as pd\nfrom bokeh.models import ColumnDataSource, LinearColorMapper, HoverTool\nfrom bokeh.plotting import figure\nfrom bokeh.transform import transform\nfrom sklearn.metrics import confusion_matrix\nfrom reporter.settings import COLORS\nfrom reporter.metrics import Metric\n\n\nclass ConfusionMatrix(...
false
6,118
9fd33089a9dc919ef2fb2698059e60a24a0e05e6
import mechanicalsoup from bs4 import BeautifulSoup import re import json def extract_title(page): return page.find("header").find("h1").contents[0] def extract_colours(page): color_list = page.find("ul") return list(dict.fromkeys(re.findall("#\w+", str(color_list.contents)))) def get_colours_from_pa...
[ "import mechanicalsoup\nfrom bs4 import BeautifulSoup\nimport re\nimport json\n\n\ndef extract_title(page):\n return page.find(\"header\").find(\"h1\").contents[0]\n\n\n\ndef extract_colours(page):\n color_list = page.find(\"ul\")\n return list(dict.fromkeys(re.findall(\"#\\w+\", str(color_list.contents)))...
false
6,119
7502e28197cb40044303a0a2163546f42375aeb6
#!/usr/bin/env python import os, time, sys fifoname = '/dev/pi-blaster' # must open same name def child( ): pipeout = os.open(fifoname, os.O_WRONLY) # open fifo pipe file as fd zzz = 0 while 1: time.sleep(zzz) os.write(pipeout, 'Spam %03d\n' % zzz) zzz = (z...
[ "#!/usr/bin/env python\nimport os, time, sys\nfifoname = '/dev/pi-blaster' # must open same name\n\ndef child( ):\n pipeout = os.open(fifoname, os.O_WRONLY) # open fifo pipe file as fd\n zzz = 0\n while 1:\n time.sleep(zzz)\n os.write(pipeout, 'Spam %03d\\n' % zzz)\n...
true
6,120
2a3c3112122dee5574a1569155287ea3e5f8c7b2
def say_hi(argument): return f"Hello {argument}" def call_func(some_func, argument): return some_func(argument) def main(argument): """docstring""" return call_func(say_hi, argument) if __name__ == "__main__": print(main(1))
[ "def say_hi(argument):\n return f\"Hello {argument}\"\n\ndef call_func(some_func, argument):\n return some_func(argument)\n\ndef main(argument):\n \"\"\"docstring\"\"\"\n return call_func(say_hi, argument)\n\nif __name__ == \"__main__\":\n print(main(1))", "def say_hi(argument):\n return f'Hello...
false
6,121
141e0f20ce912ecf21940f78e9f40cb86b91dc2b
#! /usr/bin/env python """ Normalizes a vidoe by dividing against it's background. See: BackgroundExtractor.py to get the background of a video. USING: As a command line utility: $ Normalizer.py input_video input_image output_video As a module: from Normalizer import Normalizer ...
[ "#! /usr/bin/env python\n\"\"\"\nNormalizes a vidoe by dividing against it's background.\nSee: BackgroundExtractor.py to get the background of a video.\n\nUSING:\n\n As a command line utility:\n \n $ Normalizer.py input_video input_image output_video\n \n As a module:\n \n from Normaliz...
false
6,122
01eef391f6d37d1e74cb032c5b27e1d8fc4395da
def countdown(n): def next(): nonlocal n r = n n-=1 return r return next a = countdown(12) while True: v = a() if not v:break
[ "def countdown(n):\n def next():\n nonlocal n\n r = n\n n-=1\n return r\n return next\n\na = countdown(12)\nwhile True:\n v = a()\n if not v:break\n", "def countdown(n):\n\n def next():\n nonlocal n\n r = n\n n -= 1\n return r\n return next...
false
6,123
a40c87fe4b805495e5bd30155faa861cbe16c368
from eboss_qso.fits.joint import run_joint_mcmc_fit from eboss_qso.measurements.utils import make_hash import os.path as osp import os from glob import glob ARGS = [(False, 1.0), (False, 1.6), (True, 1.6), (True, 1.0) ] ITERATIONS = 500 WALKERS = 100 def main(argnum, kmin): z_we...
[ "from eboss_qso.fits.joint import run_joint_mcmc_fit\nfrom eboss_qso.measurements.utils import make_hash\nimport os.path as osp\nimport os\nfrom glob import glob\n\n\nARGS = [(False, 1.0),\n (False, 1.6),\n (True, 1.6),\n (True, 1.0)\n ]\nITERATIONS = 500\nWALKERS = 100\n\n\ndef main(arg...
false
6,124
fb9d639bca59ecb081e7d9f30f97bdcd35627d34
# -*- coding: utf-8 -*- class FizzBuzz: def convert(self, number): # raise NotImplementedError # for number in range(1, 101): if number%3 == 0 and number%5 != 0: return ("Fizz") elif number%3 != 0 and number%5 == 0: return("Buzz") ...
[ "# -*- coding: utf-8 -*-\n\nclass FizzBuzz:\n\n def convert(self, number):\n # raise NotImplementedError\n # for number in range(1, 101):\n if number%3 == 0 and number%5 != 0:\n return (\"Fizz\")\n elif number%3 != 0 and number%5 == 0:\n return(\"...
false
6,125
4c010f9d9e7813a4ae4f592ade60130933b51958
#/usr/share/python3 from sklearn.linear_model import LogisticRegression from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import train_test_split import numpy as np import seaborn as sb import pandas as pd from pmlb import fetch_data, classification_dataset_names import util # f...
[ "#/usr/share/python3\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nfrom sklearn.model_selection import train_test_split\n\nimport numpy as np\nimport seaborn as sb\nimport pandas as pd\n\nfrom pmlb import fetch_data, classification_dataset_names\n...
false
6,126
ccfc78ae430f835244e0618afdeebe960c868415
#!/usr/bin/env python ''' Usage: dep_tree.py [-h] [-v] [-p P] [-m component_map] repos_root top_dir [top_depfile] Parse design dependency tree and generate build scripts and other useful files positional arguments: repos_root repository root top_dir top level design directory top_depfile ...
[ "#!/usr/bin/env python\n\n'''\nUsage:\n\ndep_tree.py [-h] [-v] [-p P] [-m component_map]\n repos_root top_dir [top_depfile]\n\nParse design dependency tree and generate build scripts and other useful files\n\npositional arguments:\n repos_root repository root\n top_dir top level design director...
false
6,127
a18fad746a1da3327d79ac0a61edd156c5fb8892
 class TrieTree(object): def __init__(self): self.size=0 self.childern=[None]*26 def insert(self,word): node=self for w in word: index=ord(w)-97 node.size+=1 if node.childern[index]==None: node.childern[index]=TrieTree() ...
[ "\n\nclass TrieTree(object):\n def __init__(self):\n self.size=0\n self.childern=[None]*26\n def insert(self,word):\n node=self\n for w in word:\n index=ord(w)-97\n node.size+=1\n if node.childern[index]==None:\n node.childern[index]...
true
6,128
ef0c9f740f1ca0906aeb7a5c5e5d35baca189310
# pylint: disable=missing-docstring,function-redefined import uuid from behave import given, then, when import requests from features.steps import utils from testsuite.oauth import authorize from testsuite import fhir ERROR_AUTHORIZATION_FAILED = 'Authorization failed.' ERROR_BAD_CONFORMANCE = 'Could not parse conf...
[ "# pylint: disable=missing-docstring,function-redefined\nimport uuid\n\nfrom behave import given, then, when\nimport requests\n\nfrom features.steps import utils\nfrom testsuite.oauth import authorize\nfrom testsuite import fhir\n\n\nERROR_AUTHORIZATION_FAILED = 'Authorization failed.'\nERROR_BAD_CONFORMANCE = 'Cou...
false
6,129
92c247b827d2ca4dce9b631a2c09f2800aabe216
import main from pytest import approx def test_duration(): ins = main.convert() names = ins.multiconvert() for name in names: induration, outduration = ins.ffprobe(name[0], name[1]) assert induration == approx(outduration) induration, outduration = ins.ffprobe(name[0], name[2]) ...
[ "import main\nfrom pytest import approx\n\ndef test_duration():\n\n ins = main.convert()\n names = ins.multiconvert()\n for name in names:\n induration, outduration = ins.ffprobe(name[0], name[1])\n assert induration == approx(outduration)\n induration, outduration = ins.ffprobe(name[0...
false
6,130
2ffe4b0eb7af9b3a4d5724442b5409d27bfa92a1
import math def max_heapity(arr, start, end): root = start while True: child = 2 * root + 1 # 若子節點指標超出範圍則結束 if child > end: break # 先比較左右兩個子節點大小,選擇最大的那個子節點 if child + 1 <= end and arr[child] < arr[child + 1]: child += 1 # 如果 root 的值小於 c...
[ "import math\n\n\ndef max_heapity(arr, start, end):\n root = start\n while True:\n child = 2 * root + 1\n # 若子節點指標超出範圍則結束\n if child > end:\n break\n\n # 先比較左右兩個子節點大小,選擇最大的那個子節點\n if child + 1 <= end and arr[child] < arr[child + 1]:\n child += 1\n\n ...
false
6,131
1f953b20ff0eb868c2fbff367fafa8b651617e64
#!/usr/bin/env python3 import sys from argparse import ArgumentParser from arg_checks import IsFile, MinInt from visualisation import Visualisation parser = ArgumentParser(description="Visualises DS simulations") # The order of arguments in descending order of file frequency is: config, failures, log. # This should...
[ "#!/usr/bin/env python3\n\nimport sys\nfrom argparse import ArgumentParser\n\nfrom arg_checks import IsFile, MinInt\nfrom visualisation import Visualisation\n\nparser = ArgumentParser(description=\"Visualises DS simulations\")\n\n# The order of arguments in descending order of file frequency is: config, failures, l...
false
6,132
46b8d0ba58d4bf17021b05fc03bd480802f65adf
# -*- coding: utf-8 -*- """Utilities for reading BEL Script.""" import time from typing import Iterable, Mapping, Optional, Set from .constants import ( ANNOTATION_PATTERN_FMT, ANNOTATION_URL_FMT, NAMESPACE_PATTERN_FMT, NAMESPACE_URL_FMT, format_annotation_list, ) __all__ = [ 'make_knowledge_header', ] de...
[ "# -*- coding: utf-8 -*-\n\n\"\"\"Utilities for reading BEL Script.\"\"\"\n\nimport time\nfrom typing import Iterable, Mapping, Optional, Set\n\nfrom .constants import (\n ANNOTATION_PATTERN_FMT, ANNOTATION_URL_FMT, NAMESPACE_PATTERN_FMT, NAMESPACE_URL_FMT, format_annotation_list,\n)\n\n__all__ = [\n 'make_kn...
false
6,133
beda3d13e3dc12f7527f5c5ba8a0eb05c2734fd9
# -*- coding: utf-8 -*- """ Created on Tue Sep 4 15:19:49 2018 @author: haoyu """ import numpy as np def train_test_split(X, y, test_ratio = 0.2, seed = None): '''将数据X和y按照test_ratio分割成X_train,X_test,y_train,y_test''' assert X.shape[0] == y.shape[0], \ 'the size of X must be equal to the size of y' ...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 4 15:19:49 2018\n\n@author: haoyu\n\"\"\"\nimport numpy as np\n\ndef train_test_split(X, y, test_ratio = 0.2, seed = None):\n '''将数据X和y按照test_ratio分割成X_train,X_test,y_train,y_test'''\n assert X.shape[0] == y.shape[0], \\\n 'the size of X must be equ...
false
6,134
5e20a517131f7a372d701548e4f370766a84ba52
""" Definition of SegmentTreeNode: """ class SegmentTreeNode: def __init__(self, start, end): self.start, self.end = start, end self.left, self.right = None, None class Solution: """ @param: start: start value. @param: end: end value. @return: The root of Segment Tree. """ ...
[ "\"\"\"\nDefinition of SegmentTreeNode:\n\"\"\"\nclass SegmentTreeNode:\n def __init__(self, start, end):\n self.start, self.end = start, end\n self.left, self.right = None, None\n\n\nclass Solution:\n \"\"\"\n @param: start: start value.\n @param: end: end value.\n @return: The root of...
false
6,135
2db6f88b733c23063803c374d7a5b651e8443bd5
print("Hello world! im in github")
[ "print(\"Hello world! im in github\")\n", "print('Hello world! im in github')\n", "<code token>\n" ]
false
6,136
16cd89a43a1985276bd14d85ad8ddb990c4d82c3
import discord from discord.ext import commands import datetime from discord.utils import get from discord import User class Sinner(commands.Converter): async def convert(self, ctx, argument): argument = await commands.MemberConverter().convert(ctx, argument) permission = argument.guild_permissions...
[ "import discord\nfrom discord.ext import commands\nimport datetime\nfrom discord.utils import get\nfrom discord import User\n\nclass Sinner(commands.Converter):\n async def convert(self, ctx, argument):\n argument = await commands.MemberConverter().convert(ctx, argument)\n permission = argument.gui...
false
6,137
4a13f05fbbe598242f5663d27d578d2eb977e103
n = 1 ip = [] ma = [] l = [0, 0, 0, 0, 0, 0, 0] # a, b, c, d, e, wpm, pr while n != 0: a = input().strip().split("~") n = len(a) if n == 1: break ip.append(a[0]) ma.append(a[1]) for i in ip: ipn = i.split(".") try: if 1 <= int(ipn[0]) <= 126: p = 0 elif 1...
[ "n = 1\nip = []\nma = []\nl = [0, 0, 0, 0, 0, 0, 0] # a, b, c, d, e, wpm, pr\nwhile n != 0:\n a = input().strip().split(\"~\")\n n = len(a)\n if n == 1:\n break\n ip.append(a[0])\n ma.append(a[1])\n\nfor i in ip:\n ipn = i.split(\".\")\n try:\n if 1 <= int(ipn[0]) <= 126:\n ...
false
6,138
04c1765e6c2302098be2a7f3242dfd536683f742
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-08-24 22:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0026_auto_20160712_1541'), ] operations = [ migrations.CreateModel(...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.5 on 2016-08-24 22:13\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0026_auto_20160712_1541'),\n ]\n\n operations = [\n migr...
false
6,139
ecf09f2c503452fefc427e8dbe151e7bc7ef677e
import tensorflow as tf class PolicyFullyConnected: def __init__(self, observation_space, action_space, batch_size, reuse): height = observation_space[0] width = observation_space[1] self.observations = tf.placeholder(shape=(batch_size, height, width), dtype=tf.float32) with tf.va...
[ "import tensorflow as tf\n\n\nclass PolicyFullyConnected:\n def __init__(self, observation_space, action_space, batch_size, reuse):\n height = observation_space[0]\n width = observation_space[1]\n self.observations = tf.placeholder(shape=(batch_size, height, width), dtype=tf.float32)\n\n ...
false
6,140
d650f578ea30772489625ee26f3e4bf04131964b
from django.shortcuts import render, redirect from .models import Game, Player, CardsInHand, Feedback from django.db.models import Q from .forms import GameForm, JoinForm, FeedbackForm from django.shortcuts import get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.vie...
[ "from django.shortcuts import render, redirect\nfrom .models import Game, Player, CardsInHand, Feedback\nfrom django.db.models import Q\nfrom .forms import GameForm, JoinForm, FeedbackForm\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom...
false
6,141
0f3e19b02dbe508bc4e0ef7879af81a9eabfd8c9
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 16:11:46 2021 @author: Suman """ import numpy as np import cv2 rect = (0,0,0,0) startPoint = False endPoint = False def mark_object(event,x,y,flags,params): global rect,startPoint,endPoint # get mouse click if event == cv2.EVENT_LB...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 16 16:11:46 2021\r\n\r\n@author: Suman\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\nrect = (0,0,0,0)\r\nstartPoint = False\r\nendPoint = False\r\n\r\ndef mark_object(event,x,y,flags,params):\r\n\r\n global rect,startPoint,endPoint\r\n\r\n ...
false
6,142
d3af5ac87474a99f1ade222995884bc8e035ce35
from room import Room class Office(Room): def __init__(self): pass
[ "from room import Room\nclass Office(Room):\n def __init__(self):\n pass", "from room import Room\n\n\nclass Office(Room):\n\n def __init__(self):\n pass\n", "<import token>\n\n\nclass Office(Room):\n\n def __init__(self):\n pass\n", "<import token>\n\n\nclass Office(Room):\n ...
false
6,143
753617c189a88adee8430e994aa597c9db9410fe
from genericentity import GenericEntity as GEntity import random as ran class GenericBreeder(object): """description of class: its a classy class""" def __init__(self,nlifesize,nparentsize,nlowestscore): self.Reset(nlifesize,nparentsize,nlowestscore) def Reset(self,nlifesize,nparentsize,nlowe...
[ "from genericentity import GenericEntity as GEntity\nimport random as ran\n\nclass GenericBreeder(object):\n \"\"\"description of class: its a classy class\"\"\"\n \n\n\n def __init__(self,nlifesize,nparentsize,nlowestscore):\n self.Reset(nlifesize,nparentsize,nlowestscore)\n\n def Reset(self,nlife...
false
6,144
f3b3bee494493263f8b00827e6f3ff3a1dcd8c37
import graphics import ply.lex as lex import ply.yacc as yacc import jstokens import jsgrammar def interpret(trees): # Hello, friend for tree in trees: # Hello, # ("word-element","Hello") nodetype=tree[0] # "word-element" if nodetype == "word-element": graphics.word(tree[1]) ...
[ "import graphics\nimport ply.lex as lex\nimport ply.yacc as yacc\nimport jstokens\nimport jsgrammar\n\ndef interpret(trees): # Hello, friend\n for tree in trees: # Hello,\n # (\"word-element\",\"Hello\")\n nodetype=tree[0] # \"word-element\"\n if nodetype == \"word-element\":\n gr...
false
6,145
e5a71250ca9f17798011d8fbfaee6a3d55446598
from connect.client import ClientError, ConnectClient, R def test_import_client(): from cnct import ConnectClient as MovedConnectClient assert MovedConnectClient == ConnectClient def test_import_error(): from cnct import ClientError as MovedClientError assert MovedClientError == ClientError def te...
[ "from connect.client import ClientError, ConnectClient, R\n\n\ndef test_import_client():\n from cnct import ConnectClient as MovedConnectClient\n assert MovedConnectClient == ConnectClient\n\n\ndef test_import_error():\n from cnct import ClientError as MovedClientError\n assert MovedClientError == Clien...
false
6,146
afa22db946f77e9b33a443657592c20fbea21eb1
from setup import app, manager from Users.controller import user_controller from Test.controller import test_controller app.register_blueprint(test_controller, url_prefix="/test") #registeting test_controller blueprint with the main "app" and asking it to handle all url that begins with "/test". For eg: http://127.0.0...
[ "from setup import app, manager\nfrom Users.controller import user_controller\nfrom Test.controller import test_controller\n\napp.register_blueprint(test_controller, url_prefix=\"/test\") #registeting test_controller blueprint with the main \"app\" and asking it to handle all url that begins with \"/test\". For eg:...
false
6,147
cd9f94d55eb13f5fc9959546e89a0af8ab2ea0db
import urllib2 import urllib import json import gzip from StringIO import StringIO service_url = 'https://babelfy.io/v1/disambiguate' lang = 'EN' key = '' filehandle = open('triples/triples2.tsv') # the triples and the sentences where the triples were extracted filehandle_write = open('triples/disambiguated_triples...
[ "import urllib2\nimport urllib\nimport json\nimport gzip\n\nfrom StringIO import StringIO\n\nservice_url = 'https://babelfy.io/v1/disambiguate'\nlang = 'EN'\nkey = ''\n\nfilehandle = open('triples/triples2.tsv') # the triples and the sentences where the triples were extracted\nfilehandle_write = open('triples/disa...
true
6,148
9e8ed462e429d6c6c0fe232431ee1e98721863e9
import platform import keyboard import threading import atexit from threading import Timer triggerCount = 0 triggerTimer = -1 result = None def cleanup (): print 'cleanup before exit' clearTimer() keyboard triggerCount = 0 def clearTimer (): global triggerTimer global triggerCount try: ...
[ "import platform\nimport keyboard\nimport threading\nimport atexit\nfrom threading import Timer\n\ntriggerCount = 0\ntriggerTimer = -1\n\nresult = None\n\ndef cleanup ():\n print 'cleanup before exit'\n clearTimer()\n keyboard\n triggerCount = 0\n\ndef clearTimer ():\n global triggerTimer\n global...
true
6,149
8dbcd7bba09f8acff860890d8201e016b587796d
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # from sklearn import tree # import joblib music_data = pd.read_csv(r"C:\Users\junha\PythonProjects\predict_music_preferences\music.csv") # print(music_dat...
[ "\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n# from sklearn import tree\n# import joblib\nmusic_data = pd.read_csv(r\"C:\\Users\\junha\\PythonProjects\\predict_music_preferences\\music.csv\"...
false
6,150
5cb7af5ded532058db7f5520d48ff418ba856f04
import numpy as np # # # basedir = '/n/regal/pfister_lab/haehn/CREMITEST/' testA = basedir + 'testA.npz.npy' testA_targets = basedir + 'testA_targets.npz.npy' testB = basedir + 'testB.npz.npy' testB_targets = basedir + 'testB_targets.npz.npy' testC = basedir + 'testC.npz.npy' testC_targets = basedir + 'testC_targets...
[ "import numpy as np\n\n#\n#\n#\n\nbasedir = '/n/regal/pfister_lab/haehn/CREMITEST/'\n\ntestA = basedir + 'testA.npz.npy'\ntestA_targets = basedir + 'testA_targets.npz.npy'\ntestB = basedir + 'testB.npz.npy'\ntestB_targets = basedir + 'testB_targets.npz.npy'\ntestC = basedir + 'testC.npz.npy'\ntestC_targets = basedi...
true
6,151
94d303716eac7fa72370435fe7d4d1cdac0cdc48
smodelsOutput = {'OutputStatus': {'sigmacut': 0.01, 'minmassgap': 5.0, 'maxcond': 0.2, 'ncpus': 1, 'file status': 1, 'decomposition status': 1, 'warnings': 'Input file ok', 'input file': 'inputFiles/scanExample/slha/100968509.slha', 'database version': '1.2.0', 'smodels version': '1.2.0rc'}, 'ExptRes': [{'maxcond': 0.0...
[ "smodelsOutput = {'OutputStatus': {'sigmacut': 0.01, 'minmassgap': 5.0, 'maxcond': 0.2, 'ncpus': 1, 'file status': 1, 'decomposition status': 1, 'warnings': 'Input file ok', 'input file': 'inputFiles/scanExample/slha/100968509.slha', 'database version': '1.2.0', 'smodels version': '1.2.0rc'}, 'ExptRes': [{'maxcond'...
false
6,152
1ea31a126417c2feb079339aa79f97ea9e38fa40
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
[ "# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable l...
false
6,153
81b9fc78d92fdc4392cb71a77fdfd354ff950ae3
n, x0, y0 = list(map(int, input().split())) cards = [y0] + list(map(int, input().split())) # yの手持ちはゲームに関与するため、リストに加えてしまう xs = [[-1] * (n+1) for i in range(n+1)] ys = [[-1] * (n+1) for i in range(n+1)] #xs[i][j] = xの手番で、xがcards[i]を持ちyがcards[j]を持っているとき(i<j)の最善スコア #ys[i][j] = yの手番で、xがcards[j]を持ちyがcards[i]を持っているとき(i<j)の...
[ "n, x0, y0 = list(map(int, input().split()))\n\ncards = [y0] + list(map(int, input().split()))\n# yの手持ちはゲームに関与するため、リストに加えてしまう\n\nxs = [[-1] * (n+1) for i in range(n+1)]\nys = [[-1] * (n+1) for i in range(n+1)] \n#xs[i][j] = xの手番で、xがcards[i]を持ちyがcards[j]を持っているとき(i<j)の最善スコア\n#ys[i][j] = yの手番で、xがcards[j]を持ちyがcards[i]を...
false
6,154
b066ab81eccee538eb3f85b49a3e46c00a947428
# 데이터베이스 연동(SQLite) # 테이블 생성 및 삽입 # pkg 폴더안에 db 파일이 있어서 해당 파일 import 하기 위해 ... 다른 방법 없을까 ... import os, sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) # db 정보 import 후 DbConn 메소드를 dbConn으로 사용명 변경 from pkg._DB_INFO import DbConn as dbConn from pkg._DB_INFO import sysDate as nowDate #...
[ "# 데이터베이스 연동(SQLite)\n# 테이블 생성 및 삽입\n\n# pkg 폴더안에 db 파일이 있어서 해당 파일 import 하기 위해 ... 다른 방법 없을까 ...\nimport os, sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\n\n# db 정보 import 후 DbConn 메소드를 dbConn으로 사용명 변경\nfrom pkg._DB_INFO import DbConn as dbConn\nfrom pkg._DB_INFO import sysDate...
false
6,155
b0aeede44a4b54006cf0b7d541d5b476a7178a93
# Part 1 - Build the CNN from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense ## Initialize the CNN classifier = Sequential() ## Step 1 - Convolution Layer classifier.add(Convolution2D(32, 3, 3,...
[ "# Part 1 - Build the CNN\nfrom keras.models import Sequential\nfrom keras.layers import Convolution2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom keras.layers import Dense\n\n## Initialize the CNN\nclassifier = Sequential()\n\n## Step 1 - Convolution Layer\nclassifier.add(Convolu...
false
6,156
3d2b8730953e9c2801eebc23b6fb56a1b5a55e3c
from sqlalchemy import create_engine, Column, Integer, Float, \ String, Text, DateTime, Boolean, ForeignKey from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.ext.declarative import declarative_base from flask_sqlalchemy import SQLAlchemy engine = create_engine('sqlite:///app/databases/fays-web-...
[ "from sqlalchemy import create_engine, Column, Integer, Float, \\\n String, Text, DateTime, Boolean, ForeignKey\nfrom sqlalchemy.orm import sessionmaker, relationship\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom flask_sqlalchemy import SQLAlchemy\n\nengine = create_engine('sqlite:///app/databas...
false
6,157
f9261c1844cc629c91043d1221d0b76f6e22fef6
import os.path as path from googleapiclient.discovery import build from google.oauth2 import service_account # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1FSMATLJUNCbV8...
[ "import os.path as path\nfrom googleapiclient.discovery import build\nfrom google.oauth2 import service_account\n\n# If modifying these scopes, delete the file token.pickle.\nSCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']\n\n# The ID and range of a sample spreadsheet.\nSAMPLE_SPREADSHEET_ID = '1...
false
6,158
ac664cd7d62f89399e37f74e0234b3ad244fe460
# Generated by Django 3.1.4 on 2021-01-11 16:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tutorials', '0003_auto_20210111_1705'), ] operations = [ migrations.AlterField( model_name='tutorial', name='upload'...
[ "# Generated by Django 3.1.4 on 2021-01-11 16:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tutorials', '0003_auto_20210111_1705'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tutorial',\n ...
false
6,159
b00c9f099fcb31262df947f47d7190912ee66965
#-*- coding: utf-8 -*- from django.db import models from authentication.models import Account class QuestionFaq(models.Model): title = models.CharField(max_length=50, verbose_name=u'Тема вопроса') question = models.TextField(verbose_name=u'Задайте вопрос') date = models.DateField(auto_now_add=True) ch...
[ "#-*- coding: utf-8 -*-\nfrom django.db import models\nfrom authentication.models import Account\n\n\nclass QuestionFaq(models.Model):\n title = models.CharField(max_length=50, verbose_name=u'Тема вопроса')\n question = models.TextField(verbose_name=u'Задайте вопрос')\n date = models.DateField(auto_now_add...
false
6,160
ce11a5c2fbd6e0ea0f8ab293dc53afd07a18c25c
from Modules.Pitch.Factory import MainFactory from Modules.ToJson import Oto from audiolazy.lazy_midi import midi2str import utaupy import string import random import math import os, subprocess, shutil def RandomString(Length): Letters = string.ascii_lowercase return ''.join(random.choice(Letters) for i ...
[ "from Modules.Pitch.Factory import MainFactory\r\nfrom Modules.ToJson import Oto \r\nfrom audiolazy.lazy_midi import midi2str\r\nimport utaupy\r\nimport string\r\nimport random\r\nimport math\r\nimport os, subprocess, shutil\r\n\r\ndef RandomString(Length):\r\n\tLetters = string.ascii_lowercase\r\n\treturn ''.join(...
false
6,161
03854f48751460fdc27d42ee5c766934ee356cfd
import sys sys.stdin = open('줄긋기.txt') T = int(input()) for tc in range(1, T+1): N = int(input()) dot = [list(map(int, input().split())) for _ in range(N)] ran = [] for a in range(N-1): for b in range(a+1, N): if dot[a][1]-dot[b][1] == 0: if 'inf' not in ran: ...
[ "import sys\nsys.stdin = open('줄긋기.txt')\n\n\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n dot = [list(map(int, input().split())) for _ in range(N)]\n ran = []\n for a in range(N-1):\n for b in range(a+1, N):\n if dot[a][1]-dot[b][1] == 0:\n if 'inf' n...
false
6,162
3c22b187f8538e16c0105706e6aac2875ea3a25c
from django.db import models class Subscribe(models.Model): mail_subscribe = models.EmailField('Пошта', max_length=40) def __str__(self): return self.mail_subscribe class Meta: verbose_name = 'підписку' verbose_name_plural = 'Підписки'
[ "from django.db import models\n\n\nclass Subscribe(models.Model):\n mail_subscribe = models.EmailField('Пошта', max_length=40)\n\n def __str__(self):\n return self.mail_subscribe\n\n class Meta:\n verbose_name = 'підписку'\n verbose_name_plural = 'Підписки'\n", "from django.db import...
false
6,163
e1829904cea51909b3a1729b9a18d40872e7c13c
from django.shortcuts import render, redirect from .game import run from .models import Match from team.models import Team, Player from django.urls import reverse # Create your views here. def startgame(request): match = Match(team1_pk = 1, team2_pk = 2) team1 = Team.objects.get(pk = match.team1_pk) team...
[ "from django.shortcuts import render, redirect\nfrom .game import run\nfrom .models import Match\nfrom team.models import Team, Player\nfrom django.urls import reverse\n\n# Create your views here.\n\ndef startgame(request):\n match = Match(team1_pk = 1, team2_pk = 2)\n\n team1 = Team.objects.get(pk = match.te...
false
6,164
4dde161d25ed41154e13b94cc9640c6aac055f87
# coding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License...
[ "# coding: utf-8\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the...
false
6,165
2c181a33c84ce262404c192abdc515924a1916a9
import numpy as np import pandas as pd import geopandas as gp from sklearn.cluster import KMeans import shapely from descartes import PolygonPatch # -- load the data data = pd.read_csv('/scratch/share/gdobler/parqa/output/Tables/' 'ParkQualityScores/QualityArea_ZipCode_FiscalYears.csv') zips = gp....
[ "import numpy as np\nimport pandas as pd\nimport geopandas as gp\nfrom sklearn.cluster import KMeans\nimport shapely\nfrom descartes import PolygonPatch\n\n\n# -- load the data\ndata = pd.read_csv('/scratch/share/gdobler/parqa/output/Tables/'\n 'ParkQualityScores/QualityArea_ZipCode_FiscalYears.cs...
false
6,166
888ec915d89f1fd8fd6465f1035f7c658af78596
{% load code_generator_tags %}from rest_framework.serializers import ModelSerializer {% from_module_import app.name|add:'.models' models %}{% comment %} {% endcomment %}{% for model in models %} class {{ model.name }}Serializer(ModelSerializer): class Meta: model = {{ model.name }} depth = 1 ...
[ "{% load code_generator_tags %}from rest_framework.serializers import ModelSerializer\n{% from_module_import app.name|add:'.models' models %}{% comment %}\n{% endcomment %}{% for model in models %}\n\n\nclass {{ model.name }}Serializer(ModelSerializer):\n class Meta:\n model = {{ model.name }}\n d...
true
6,167
6903584b27c0720cebf42ed39968b18f0f67f796
""" Url router for the federated search application """ from django.conf.urls import include from django.urls import re_path urlpatterns = [ re_path(r"^rest/", include("core_federated_search_app.rest.urls")), ]
[ "\"\"\" Url router for the federated search application\n\"\"\"\nfrom django.conf.urls import include\nfrom django.urls import re_path\n\nurlpatterns = [\n re_path(r\"^rest/\", include(\"core_federated_search_app.rest.urls\")),\n]\n", "<docstring token>\nfrom django.conf.urls import include\nfrom django.urls i...
false
6,168
93a47d6ba1f699d881f0d22c4775433e4a451890
# -*- coding:utf-8 -*- """ 逆波兰表达式,中缀表达式可以对应一棵二叉树,逆波兰表达式即该二叉树后续遍历的结果。 """ def isOperator(c): return c == '+' or c == '-' or c == '*' or c == '/' def reversePolishNotation(p): stack = list() for cur in p: if not isOperator(cur): stack.append(cur) else: b = float(sta...
[ "# -*- coding:utf-8 -*-\n\n\"\"\"\n逆波兰表达式,中缀表达式可以对应一棵二叉树,逆波兰表达式即该二叉树后续遍历的结果。\n\"\"\"\n\ndef isOperator(c):\n return c == '+' or c == '-' or c == '*' or c == '/'\n\n\ndef reversePolishNotation(p):\n stack = list()\n for cur in p:\n if not isOperator(cur):\n stack.append(cur)\n else:...
true
6,169
3f5096ef5677373a1e436f454109c7b7577c0205
from IPython import display display.Image("./image.png")
[ "from IPython import display\ndisplay.Image(\"./image.png\")", "from IPython import display\ndisplay.Image('./image.png')\n", "<import token>\ndisplay.Image('./image.png')\n", "<import token>\n<code token>\n" ]
false
6,170
e5d704541acd0f68a7885d7323118e1552e064c9
''' You're playing casino dice game. You roll a die once. If you reroll, you earn the amount equal to the number on your second roll otherwise, you earn the amount equal to the number on your first roll. Assuming you adopt a profit-maximizing strategy, what would be the expected amount of money you would win? This qu...
[ "'''\nYou're playing casino dice game. You roll a die once. If you reroll, you earn the amount equal to the number on your second roll otherwise, you earn the amount equal to the number on your first roll.\n\nAssuming you adopt a profit-maximizing strategy, what would be the expected amount of money you would win?\...
false
6,171
28e5667db4a620ec627cd94154a024b4c8dbc5f7
from nonebot_plugin_datastore import get_plugin_data from sqlalchemy import UniqueConstraint from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column Model = get_plugin_data().Model class MorningGreeting(MappedAsDataclass, Model): __table_args__ = ( UniqueConstraint( "platform", ...
[ "from nonebot_plugin_datastore import get_plugin_data\nfrom sqlalchemy import UniqueConstraint\nfrom sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column\n\nModel = get_plugin_data().Model\n\n\nclass MorningGreeting(MappedAsDataclass, Model):\n __table_args__ = (\n UniqueConstraint(\n ...
false
6,172
b92497396e711d705760db547b43cc65beba6cfd
# Generated by Django 2.1.1 on 2019-11-20 12:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sandbox_report', '0006_sandboxreportlink_sandboxreportval'), ] operations = [ migrations.DeleteModel( name='SandboxReportLink', ...
[ "# Generated by Django 2.1.1 on 2019-11-20 12:34\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sandbox_report', '0006_sandboxreportlink_sandboxreportval'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='SandboxRep...
false
6,173
bb02ba68eb6629dad364b5f015680e4126e655f3
# *** Обработка исключений (исключительные события, искл. ситуации)*** # генерация исключения a=100 b=0 # "деление на ноль" - пример ошибки (не рабочий) # c=a/b # решение - обработка исключений (отлов исключения) # конструкция "try-except" # try: # c = a / b # print("Все отлично") # except: # # тут долж...
[ "# *** Обработка исключений (исключительные события, искл. ситуации)***\n\n# генерация исключения\na=100\nb=0\n\n# \"деление на ноль\" - пример ошибки (не рабочий)\n# c=a/b\n\n# решение - обработка исключений (отлов исключения)\n# конструкция \"try-except\"\n\n# try:\n# c = a / b\n# print(\"Все отлично\")\n...
false
6,174
e41df44db92e2ef7f9c20a0f3052e1c8c28b76c7
class Sala: def __init__(self, sala): self.Turmas = [] self.numero = sala def add_turma(self, turma): # do things self.Turmas.append(turma) def __str__(self): return str(self.numero)
[ "class Sala:\n def __init__(self, sala):\n self.Turmas = []\n self.numero = sala\n\n def add_turma(self, turma):\n # do things\n self.Turmas.append(turma)\n\n def __str__(self):\n return str(self.numero)\n", "class Sala:\n\n def __init__(self, sala):\n self.Tu...
false
6,175
4905b820f33619a80a9915d0603bc39e0d0368d9
# !/usr/bin/env python3 # -*- coding:utf-8 -*- # @Time : 2021/05/08 20:06 # @Author : Yi # @FileName: show_slices.py import os import pydicom import glob import shutil import random import numpy as np import cv2 import skimage.io as io from data_Parameter import parse_args import matplotlib.pyplot as plt def d...
[ "# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n# @Time : 2021/05/08 20:06\n# @Author : Yi\n# @FileName: show_slices.py\n\nimport os\nimport pydicom\nimport glob\nimport shutil\nimport random\nimport numpy as np\nimport cv2\nimport skimage.io as io\n\nfrom data_Parameter import parse_args\nimport matplotlib...
false
6,176
d869aa32cb9793ce11a5b6a782cc66c2dd0be309
import numpy as np import matplotlib.pyplot as plt x_list = [] y_list = [] file1 = open("pos_data_x.txt", "r") for line in file1: #x_list.append(float(file1.readline(line))) x_list.append(float(line)) file2 = open("pos_data_y.txt", "r") for line in file2: #y_list.append(float(file1.readline(line))) y_list.ap...
[ "import numpy as np\n\nimport matplotlib.pyplot as plt\n\nx_list = []\ny_list = []\n\nfile1 = open(\"pos_data_x.txt\", \"r\")\nfor line in file1:\n\t#x_list.append(float(file1.readline(line)))\n\tx_list.append(float(line))\n\t\nfile2 = open(\"pos_data_y.txt\", \"r\")\nfor line in file2:\n\t#y_list.append(float(fi...
false
6,177
fad2ad89e4d0f04fad61e27048397a5702870ca9
import random import datetime import os import time import json # l_target_path = "E:/code/PYTHON_TRAINING/Training/Apr2020/BillingSystem/bills/" while True: l_store_id = random.randint(1, 4) now = datetime.datetime.now() l_bill_id = now.strftime("%Y%m%d%H%M%S") # Generate Random Date start_da...
[ "import random\nimport datetime\nimport os\nimport time\nimport json\n\n#\nl_target_path = \"E:/code/PYTHON_TRAINING/Training/Apr2020/BillingSystem/bills/\"\n\n\nwhile True:\n\n l_store_id = random.randint(1, 4)\n now = datetime.datetime.now()\n l_bill_id = now.strftime(\"%Y%m%d%H%M%S\")\n\n\n # Generat...
false
6,178
d61024ecbd092852fc3396e6919d6d3c8aa554db
import json import redis redis_client = redis.StrictRedis(host="redis", port=6379, db=1, password="pAssw0rd") def publish_data_on_redis(data, channel): redis_client.publish(channel, json.dumps(data))
[ "import json\nimport redis\n\nredis_client = redis.StrictRedis(host=\"redis\", port=6379, db=1, password=\"pAssw0rd\")\n\n\ndef publish_data_on_redis(data, channel):\n redis_client.publish(channel, json.dumps(data))", "import json\nimport redis\nredis_client = redis.StrictRedis(host='redis', port=6379, db=1, p...
false
6,179
8be70543a7aa177d9ad48fb736228b1ffba5df16
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from interface_app.models import TestTask, TestCase from interface_app.extend.task_run import run_cases import os import json from interface_app.apps import TASK_PATH, RUN_TASK_FILE """ 说明:接口任务文件,返回HTML页面 """ # 获取任务列表 def...
[ "from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom interface_app.models import TestTask, TestCase\nfrom interface_app.extend.task_run import run_cases\nimport os \nimport json\nfrom interface_app.apps import TASK_PATH, RUN_TASK_FILE\n\n\n\"\"\"\n说明:接口任务文件,返回HTML页面...
false
6,180
18e032b7ff7ae9d3f5fecc86f63d12f4da7b8067
# 예시 입력값 board = [[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] moves = [1,5,3,5,1,2,1,4] # 로직 resultList = [] count = 0 for nth in moves: for i in range(len(board)): selected = board[i][nth - 1] if selected == 0: continue else: # 인형을 resultList에 넣고 ...
[ "# 예시 입력값\nboard = [[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]]\nmoves = [1,5,3,5,1,2,1,4]\n\n# 로직\nresultList = []\ncount = 0\n\nfor nth in moves:\n for i in range(len(board)):\n selected = board[i][nth - 1]\n if selected == 0:\n continue\n else:\n # 인...
false
6,181
e22574b5c458c23c48915274656f95a375cdc0e6
i = 0 while i < 10: print("Hello", 2 * i + 5) i = i + 1
[ "\r\ni = 0\r\nwhile i < 10:\r\n print(\"Hello\", 2 * i + 5)\r\ni = i + 1", "i = 0\nwhile i < 10:\n print('Hello', 2 * i + 5)\ni = i + 1\n", "<assignment token>\nwhile i < 10:\n print('Hello', 2 * i + 5)\n<assignment token>\n", "<assignment token>\n<code token>\n<assignment token>\n" ]
false
6,182
8c5815c1dd71b2ae887b1c9b1968176dfceea4f9
from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager import time import csv options = Options() # options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(ChromeDriverManager().install(), ...
[ "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\nimport csv\n\noptions = Options()\n# options.add_argument('--headless')\noptions.add_argument('--disable-gpu')\ndriver = webdriver.Chrome(ChromeDriverManager...
true
6,183
ed5dd954dedb00bf645f9ca14b5ca9cd122b2adc
from .gunicorn import * from .server_app import *
[ "from .gunicorn import *\nfrom .server_app import *\n", "<import token>\n" ]
false
6,184
6e557c2b85031a0038afd6a9987e3417b926218f
import os from setuptools import setup from django_spaghetti import __version__ with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( nam...
[ "import os\nfrom setuptools import setup\nfrom django_spaghetti import __version__\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:\n README = readme.read()\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\...
false
6,185
be58a2e0dcdbcb3a3df0da87be29ce7ebcee7fe9
class Process: def __init__(self, id, at, bt): self.id = id self.at = at self.bt = bt self.wt = 0 self.ct = 0 self.st = 0 self.tat = 0 def fill(self, st): print('Current process:', self.id) self.st = st self.ct = self.st + self.bt ...
[ "class Process:\n def __init__(self, id, at, bt):\n self.id = id\n self.at = at\n self.bt = bt\n self.wt = 0\n self.ct = 0\n self.st = 0\n self.tat = 0\n\n def fill(self, st):\n print('Current process:', self.id)\n self.st = st\n self.ct = ...
false
6,186
e1228f5e17bae6632f8decd114f72723dbbce944
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from libtbx.program_template import ProgramTemplate from mmtbx import pdbtools from libtbx import Auto import os import mmtbx.pdbtools from cctbx import uctbx class Program(ProgramTemplate): description = ''' phenix.pdbtools to...
[ "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\nfrom libtbx.program_template import ProgramTemplate\nfrom mmtbx import pdbtools\nfrom libtbx import Auto\nimport os\nimport mmtbx.pdbtools\nfrom cctbx import uctbx\n\nclass Program(ProgramTemplate):\n\n description = '''\np...
false
6,187
5bfb7fc60ddf4f6ad6d89771eb0a8903b04da3d9
''' Import necessary libraries ''' import re import csv import os from urllib.request import urlopen, Request from bs4 import BeautifulSoup as soup ''' Function to request page html from given URL ''' def page_html(requested_url): try: # define headers to be provided for request authenticatio...
[ "'''\r\nImport necessary libraries\r\n'''\r\nimport re\r\nimport csv\r\nimport os\r\nfrom urllib.request import urlopen, Request\r\nfrom bs4 import BeautifulSoup as soup\r\n\r\n'''\r\nFunction to request page html from given URL\r\n'''\r\ndef page_html(requested_url):\r\n try:\r\n # define headers to be p...
false
6,188
49679782ac696b3dc4f5038565f88304a44098e1
#!/usr/bin/env python3 import json import sys import time import zmq log_file = "./mavlink-log.txt" zmq_context = zmq.Context() connect_to = sys.argv[1] send_socket = zmq_context.socket(zmq.PUSH) send_socket.connect(connect_to) def get_first_timestamp(log_file): with open(log_file) as f: for line in f: line_...
[ "#!/usr/bin/env python3\n\nimport json\nimport sys\nimport time\nimport zmq\n\nlog_file = \"./mavlink-log.txt\"\n\nzmq_context = zmq.Context()\n\nconnect_to = sys.argv[1]\nsend_socket = zmq_context.socket(zmq.PUSH)\nsend_socket.connect(connect_to)\n\ndef get_first_timestamp(log_file):\n\twith open(log_file) as f:\n...
false
6,189
52eec56f7f5da8356f61301994f846ef7769f73b
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import tempfile from functools import partial import numpy as np import torch from ax.benchmark.benchmark_pr...
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nimport tempfile\nfrom functools import partial\n\nimport numpy as np\nimport torch\nfrom ax.bench...
false
6,190
f6f1cd95e4aaa5e434c3cf3cff0d46b45fc7b830
import re import datetime from django import forms from django.utils.translation import ugettext as _ from vcg.util.forms import mobile_number_validation from vcg.company_management.models import ConfigurationContact, ConfigurationLogo, ConfigurationHomepage, ConfigurationLocation class ConfigurationContactForm(for...
[ "import re \nimport datetime\n\nfrom django import forms\nfrom django.utils.translation import ugettext as _\n\nfrom vcg.util.forms import mobile_number_validation\nfrom vcg.company_management.models import ConfigurationContact, ConfigurationLogo, ConfigurationHomepage, ConfigurationLocation\n\nclass ConfigurationC...
false
6,191
de7cd231aceb2700acb3ecafe36d1ba1f5c1643b
#!/usr/bin/python import sys import itertools as it pop_list = [] #with open("/Users/dashazhernakova/Documents/Doby/GenomeRussia/ancientDNA/GR+Lazaridis.ind") as f: with open(sys.argv[1]) as f: [pop_list.append(l.strip().split("\t")[2]) for l in f if l.strip().split("\t")[2] not in pop_list] triplets = it.combinati...
[ "#!/usr/bin/python\nimport sys\nimport itertools as it\n\npop_list = []\n\n#with open(\"/Users/dashazhernakova/Documents/Doby/GenomeRussia/ancientDNA/GR+Lazaridis.ind\") as f:\nwith open(sys.argv[1]) as f:\n\t[pop_list.append(l.strip().split(\"\\t\")[2]) for l in f if l.strip().split(\"\\t\")[2] not in pop_list]\n\...
true
6,192
16850d931eec0356f71317cc24461e006fbcd59c
start = input() user_list = start.split() if user_list[-1] == 'wolf': print('Please go away and stop eating my sheep') else: user_list.reverse() print(f'Oi! Sheep number {user_list.index("wolf,") }! You are about to be eaten by a wolf!')
[ "start = input()\n\nuser_list = start.split()\n\nif user_list[-1] == 'wolf':\n print('Please go away and stop eating my sheep')\nelse:\n user_list.reverse()\n print(f'Oi! Sheep number {user_list.index(\"wolf,\") }! You are about to be eaten by a wolf!')\n", "start = input()\nuser_list = start.split()\nif...
false
6,193
a2d2ffe5ed6a844341f7ad731357bb837cee4787
import math import random from PILL import Image, ImageDraw for i in range(1,1025): pass for j in range(1,1025): pass epipedo[i][j] for i in range(1,21): pass im = Image.new("RGB", (512, 512), "white") x=random.choice(1,1025) y=random.choice(1,1025) r=random.choi...
[ "import math\r\nimport random\r\nfrom PILL import Image, ImageDraw\r\nfor i in range(1,1025):\r\n pass\r\n for j in range(1,1025):\r\n pass\r\n epipedo[i][j]\r\nfor i in range(1,21):\r\n pass\r\n im = Image.new(\"RGB\", (512, 512), \"white\")\r\n x=random.choice(1,1025)\r\n y=random....
true
6,194
f7174bf4e7612921e730ac87141c85654a2f2411
from PyQt5.QtWidgets import QHeaderView, QWidget from presenters.studyings_presenter import StudyingsPresenter from view.q_objects_view import QObjectsView class QStudyingsView(QObjectsView): def __init__(self, parent): QWidget.__init__(self, parent) QObjectsView.__init__(self, parent) se...
[ "from PyQt5.QtWidgets import QHeaderView, QWidget\n\nfrom presenters.studyings_presenter import StudyingsPresenter\nfrom view.q_objects_view import QObjectsView\n\n\nclass QStudyingsView(QObjectsView):\n def __init__(self, parent):\n QWidget.__init__(self, parent)\n QObjectsView.__init__(self, pare...
false
6,195
878937e19d6a48a0d44309efbac1d41c208ce849
''' This module is used for handling the button. ''' import RPi.GPIO as GPIO from aiy.voicehat import * class Button: status = bool() #status indicates whether it is supposed to be on or off. LED_pin = 25 #Pin for the LED in the button in the Google AIY kit. button_pin = 23#...
[ "'''\nThis module is used for handling the button. \n'''\nimport RPi.GPIO as GPIO\nfrom aiy.voicehat import *\n\nclass Button:\n status = bool() #status indicates whether it is supposed to be on or off. \n LED_pin = 25 #Pin for the LED in the button in the Google AIY kit. \n bu...
false
6,196
3ec0c20fb2dfed9930885885288cc5d47f4f5ee5
import xmlrpclib import socket import time import math import re from roundup.exceptions import Reject REVPAT = re.compile(r'(r[0-9]+\b|rev(ision)? [0-9]+\b)') def extract_classinfo(db, klass, nodeid, newvalues): if None == nodeid: node = newvalues content = newvalues['content'] else: ...
[ "\nimport xmlrpclib\nimport socket\nimport time\nimport math\nimport re\n\nfrom roundup.exceptions import Reject\n\nREVPAT = re.compile(r'(r[0-9]+\\b|rev(ision)? [0-9]+\\b)')\n\ndef extract_classinfo(db, klass, nodeid, newvalues):\n if None == nodeid:\n node = newvalues\n content = newvalues['conte...
true
6,197
ecbb64223b0d5aa478cf91e1fcafe45572eac1af
# Copyright 2021 TerminalWarlord under the terms of the MIT # license found at https://github.com/TerminalWarlord/Subtitle-Downloader-Bot/blob/master/LICENSE # Encoding = 'utf-8' # Fork and Deploy, do not modify this repo and claim it yours # For collaboration mail me at dev.jaybee@gmail.com from pyrogram impo...
[ "# Copyright 2021 TerminalWarlord under the terms of the MIT\r\n# license found at https://github.com/TerminalWarlord/Subtitle-Downloader-Bot/blob/master/LICENSE\r\n# Encoding = 'utf-8'\r\n# Fork and Deploy, do not modify this repo and claim it yours\r\n# For collaboration mail me at dev.jaybee@gmail.com\r\n\r\n\r\...
false
6,198
ad813216ba8162a7089340c677e47c3e656f7c95
from flask import Flask, request, render_template, redirect from pymongo import MongoClient from envparse import env from flask_httpauth import HTTPDigestAuth import os.path # Get env vars stored either in an env file or on the machine def get_env(name): if (os.path.exists('./env')): env.read_envfile('./env') ret...
[ "from flask import Flask, request, render_template, redirect\nfrom pymongo import MongoClient\nfrom envparse import env\nfrom flask_httpauth import HTTPDigestAuth\nimport os.path\n\n\n# Get env vars stored either in an env file or on the machine\ndef get_env(name):\n\tif (os.path.exists('./env')):\n\t\tenv.read_env...
false
6,199
c5b50420788ddde7483a46c66aca3922ddb47952
#-*- coding: utf-8 -*- from SPARQLWrapper import SPARQLWrapper, SPARQLWrapper2, JSON import time, random # testes NOW=time.time() sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?label WHERE { <http://dbpedia.org/resource/L...
[ "#-*- coding: utf-8 -*-\nfrom SPARQLWrapper import SPARQLWrapper, SPARQLWrapper2, JSON\nimport time, random\n\n# testes\nNOW=time.time()\nsparql = SPARQLWrapper(\"http://dbpedia.org/sparql\")\nsparql.setQuery(\"\"\"\n PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n SELECT ?label\n WHERE { <http://db...
false