index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
4,400
b227f222569761493f50f9dfee32f21e0e0a5cd6
#Copyright 2008, Meka Robotics #All rights reserved. #http://mekabot.com #Redistribution and use in source and binary forms, with or without #modification, are permitted. #THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS #"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #LIMITED...
[ "#Copyright 2008, Meka Robotics\n#All rights reserved.\n#http://mekabot.com\n\n#Redistribution and use in source and binary forms, with or without\n#modification, are permitted. \n\n\n#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS\n#\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ...
true
4,401
d0e957abfe5646fb84aed69902f2382d554dc825
from calc1 import LispTranslator, RPNTranslator, Parser, Lexer import unittest class TestTranslators(unittest.TestCase): def init_rpn(self, program): return RPNTranslator(Parser(Lexer(program))) def init_lisp(self, program): return LispTranslator(Parser(Lexer(program))) def test_simple...
[ "\nfrom calc1 import LispTranslator, RPNTranslator, Parser, Lexer\nimport unittest\n\n\nclass TestTranslators(unittest.TestCase):\n\n def init_rpn(self, program):\n return RPNTranslator(Parser(Lexer(program)))\n\n def init_lisp(self, program):\n return LispTranslator(Parser(Lexer(program)))\n\n ...
false
4,402
8c2920db7fc49d56aa8da6289cd22272ed3e3283
from django.apps import AppConfig class ShortenConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'shorten'
[ "from django.apps import AppConfig\n\n\nclass ShortenConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'shorten'\n", "<import token>\n\n\nclass ShortenConfig(AppConfig):\n default_auto_field = 'django.db.models.BigAutoField'\n name = 'shorten'\n", "<import token>\n\n...
false
4,403
29ec576d1fe04108eeb03a5d1b167671d3004570
# Copyright 2017-2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev> # License MIT (https://opensource.org/licenses/MIT). from datetime import datetime, timedelta from odoo import fields from odoo.tests.common import TransactionCase class TestCase(TransactionCase): def setUp(self): super(Test...
[ "# Copyright 2017-2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>\n# License MIT (https://opensource.org/licenses/MIT).\nfrom datetime import datetime, timedelta\n\nfrom odoo import fields\nfrom odoo.tests.common import TransactionCase\n\n\nclass TestCase(TransactionCase):\n def setUp(self):\n ...
false
4,404
f50c9aec85418553f4724146045ab7c3c60cbb80
import numpy as np from sklearn.preprocessing import OneHotEncoder def formator(value): return "%.2f" % value def features_preprocessor(datasetLocation): data = np.genfromtxt(datasetLocation,delimiter=",",usecols=range(41)) ##!!! usecols = range(41) encoder = OneHotEncoder(categorical_features=[1,2,3]) encoder.fi...
[ "import numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\n\ndef formator(value):\n\treturn \"%.2f\" % value\n\ndef features_preprocessor(datasetLocation):\n\tdata = np.genfromtxt(datasetLocation,delimiter=\",\",usecols=range(41)) ##!!! usecols = range(41)\n\tencoder = OneHotEncoder(categorical_features=...
true
4,405
459bd36037158c9a6a38da6eadf45a3dc6f19e04
import os import sys import requests import urllib.parse import urllib.request import json from shutil import copyfile def sdssDownload(band, location, size, path): """ . sdssArchie populates a directory with links to raw images from the SDSS mission. These images are all in FITS format and su...
[ "import os\nimport sys\nimport requests\nimport urllib.parse\nimport urllib.request\nimport json\n\nfrom shutil import copyfile\n\ndef sdssDownload(band, location, size, path):\n\n \"\"\"\n .\n sdssArchie populates a directory with links to raw images \n from the SDSS mission. These images are all in F...
false
4,406
468c070aebff3124927c5595d68bb94321dd75e5
import datetime if __name__ == "__main__" : keys = {'a','e','i', 'o', 'u', 'y'} values = [1] dictionnaire = {cle : list(values) for cle in keys} print("dictionnaire : ", dictionnaire) values.append(2) #for cle in keys : dictionnaire.update({cle:values}) #dictionnaire.update({cle2 ...
[ "import datetime\n\nif __name__ == \"__main__\" :\n\n keys = {'a','e','i', 'o', 'u', 'y'}\n values = [1]\n\n dictionnaire = {cle : list(values) for cle in keys}\n print(\"dictionnaire : \", dictionnaire)\n\n values.append(2)\n\n #for cle in keys : dictionnaire.update({cle:values})\n \n #dic...
false
4,407
cc87682d4ebb283e2d0ef7c09ad28ba708c904bd
# stopwatch.py - A simple stopwatch program. import time # Display the porgram's instructions print( """ \n\nInstructions\n press Enter to begin.\n Afterwards press Enter to "click" the stopwatch.\n Press Ctrl-C to quit""" ) input() # press Enter to begin print("Started") startTime = time.time() lastTime = star...
[ "# stopwatch.py - A simple stopwatch program.\n\nimport time\n\n# Display the porgram's instructions\n\nprint(\n \"\"\" \\n\\nInstructions\\n\npress Enter to begin.\\n\nAfterwards press Enter to \"click\" the stopwatch.\\n\nPress Ctrl-C to quit\"\"\"\n)\ninput() # press Enter to begin\nprint(\"Started\")\nstart...
false
4,408
d436362468b847e427bc14ca221cf0fe4b2623e3
from flask_restful import Resource, reqparse from db import query import pymysql from flask_jwt_extended import jwt_required """ This module is used to retrieve the data for all the request_no's which have a false or a 0 select_status. This is done by selecting distinct request_no's from requests table for ...
[ "from flask_restful import Resource, reqparse\r\nfrom db import query\r\nimport pymysql\r\nfrom flask_jwt_extended import jwt_required\r\n\r\n\"\"\"\r\nThis module is used to retrieve the data \r\nfor all the request_no's which have a false or a 0 select_status.\r\nThis is done by selecting distinct request_no's fr...
false
4,409
9004314951f77b14bab1aba9ae93eb49c8197a8d
# B. A New Technique # TLE (Time limit exceeded) from sys import stdin, stdout t = int(input()) for _ in range(t): n, m = map(int, input().split()) rows = [0] * n a_column = list() for r in range(n): tmp = list(input().split()) rows[r] = tmp a_column.append(tmp[0]) sorte...
[ "# B. A New Technique\n# TLE (Time limit exceeded)\n\nfrom sys import stdin, stdout\n\nt = int(input())\nfor _ in range(t):\n n, m = map(int, input().split())\n\n rows = [0] * n\n\n a_column = list()\n\n for r in range(n):\n tmp = list(input().split())\n rows[r] = tmp\n a_column.app...
false
4,410
b976dab3c621bb929eb488fa7f4394666efec2ed
import os import json from threading import Thread import time from time import sleep from flask import Flask, json, render_template, request import redis from collections import OrderedDict import requests from Queue import Queue REGISTRAR_URL = 'http://cuteparty-registrar1.cfapps.io/update' app = Flask(__name__) p...
[ "import os\nimport json\nfrom threading import Thread\nimport time\nfrom time import sleep\nfrom flask import Flask, json, render_template, request\nimport redis\nfrom collections import OrderedDict\nimport requests\n\nfrom Queue import Queue\n\nREGISTRAR_URL = 'http://cuteparty-registrar1.cfapps.io/update'\n\napp ...
true
4,411
ff09993a4f8fed65fa00c065eb5cfa41e7f9dcc1
from django.contrib.auth.models import User from django.db import models class QueuedSpace(models.Model): """ Stores space json for possible further editing before being sent to the server. q_etag should update on every save so conflicts can be checked for in queued items. """ space_id = models.In...
[ "from django.contrib.auth.models import User\nfrom django.db import models\n\n\nclass QueuedSpace(models.Model):\n \"\"\" Stores space json for possible further editing before being sent to the server.\n q_etag should update on every save so conflicts can be checked for in queued items.\n \"\"\"\n s...
false
4,412
d0f9dd0a06023dd844b0bf70dff360f6bb46c152
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2008 Rok Garbas <rok@garbas.si> # # ...
[ "#-*- coding: utf-8 -*- \n\n#############################################################################\n# #\n# Copyright (c) 2008 Rok Garbas <rok@garbas.si> #\n# ...
false
4,413
6e739c30b3e7c15bd90b74cfd5a1d6827e863a44
''' Created on 4 Oct 2016 @author: MetalInvest ''' def isHammerHangman(high, low, open, close): body = abs(open - close) leg = min(open, close) - low return leg / body >= 2.0 and high/max(open, close) <= 1.08 def isEngulfing(df, bottom = True): open_0 = df['open'][-1] close_0 = d...
[ "'''\r\nCreated on 4 Oct 2016\r\n\r\n@author: MetalInvest\r\n'''\r\n\r\ndef isHammerHangman(high, low, open, close):\r\n body = abs(open - close)\r\n leg = min(open, close) - low\r\n return leg / body >= 2.0 and high/max(open, close) <= 1.08\r\n \r\ndef isEngulfing(df, bottom = True):\r\n open_0 = df...
false
4,414
7dff15a16ecc3ce3952f4b47290393ea3183807f
x=input("Do you really want to run this program? (y/n) : ") x=x.upper() if x=="Y" or x=="N" or x=="Q": while x=="Y" or x=="N" or x=="Q": if x=="Q": print("Exiting the Program") import sys sys.exit() elif x=="N": print("You decided to leave. See you ag...
[ "x=input(\"Do you really want to run this program? (y/n) : \")\nx=x.upper()\n\nif x==\"Y\" or x==\"N\" or x==\"Q\":\n while x==\"Y\" or x==\"N\" or x==\"Q\":\n if x==\"Q\":\n print(\"Exiting the Program\")\n import sys\n sys.exit()\n elif x==\"N\":\n prin...
false
4,415
44649e44da4eb80e7f869ff906798d5db493b913
# -*- coding: utf-8; -*- import gherkin from gherkin import Lexer, Parser, Ast def test_lex_test_eof(): "lex_text() Should be able to find EOF" # Given a lexer that takes '' as the input string lexer = gherkin.Lexer('') # When we try to lex any text from '' new_state = lexer.lex_text() # T...
[ "# -*- coding: utf-8; -*-\n\nimport gherkin\nfrom gherkin import Lexer, Parser, Ast\n\n\ndef test_lex_test_eof():\n \"lex_text() Should be able to find EOF\"\n\n # Given a lexer that takes '' as the input string\n lexer = gherkin.Lexer('')\n\n # When we try to lex any text from ''\n new_state = lexer...
false
4,416
391ecb2f23cc0ce59bd9fac6f97bd4c1788444b9
n = eval(input("Entrez valeur: ")) res = 0 while n > 0: res += n%10 n //= 10 print(res, n) print(res)
[ "n = eval(input(\"Entrez valeur: \"))\nres = 0\n\nwhile n > 0:\n res += n%10\n n //= 10\n print(res, n)\n\nprint(res)\n", "n = eval(input('Entrez valeur: '))\nres = 0\nwhile n > 0:\n res += n % 10\n n //= 10\n print(res, n)\nprint(res)\n", "<assignment token>\nwhile n > 0:\n res += n % 10\n...
false
4,417
5626e5a4a448630fbbbc92a67ae08f3ed24e1b9e
#Main program: #reads IMU data from arduino uart #receives PS3 Controller input #Mantains Controller input frequency with CST #!/usr/bin/env python from map import mapControllerToDeg from map import constrain from map import wrap_180 from map import motorOutputLimitHandler from uart1 import IMUDevice import socket fro...
[ "#Main program:\n#reads IMU data from arduino uart\n#receives PS3 Controller input\n#Mantains Controller input frequency with CST\n\n#!/usr/bin/env python\nfrom map import mapControllerToDeg\nfrom map import constrain\nfrom map import wrap_180\nfrom map import motorOutputLimitHandler\nfrom uart1 import IMUDevice\ni...
true
4,418
c036621c5f03d94987b4da004d063d11a7cc8424
# -*- coding:utf-8 -*- ''' Created on 2013. 4. 30. @author: Hwang-JinHwan parsing the txt file which are generated by coping the pdf nova praxis rpg rule book to create bootstrap document ''' import re import codecs template = """ <head> <style type="text/css"> body {{ padding-...
[ "# -*- coding:utf-8 -*-\r\n'''\r\nCreated on 2013. 4. 30.\r\n\r\n@author: Hwang-JinHwan\r\n\r\nparsing the txt file which are generated by coping the pdf nova praxis rpg rule book \r\nto create bootstrap document\r\n'''\r\nimport re\r\nimport codecs\r\n\r\ntemplate = \"\"\"\r\n<head>\r\n <style type=\"text/css\"...
true
4,419
80891a4c9703f91509d2c1b22304f33426dfb962
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/cypher/.eric6/eric6plugins/vcsGit/ConfigurationPage/GitPage.ui' # # Created by: PyQt5 UI code generator 5.8 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_GitPage(object):...
[ "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '/home/cypher/.eric6/eric6plugins/vcsGit/ConfigurationPage/GitPage.ui'\n#\n# Created by: PyQt5 UI code generator 5.8\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_G...
false
4,420
4bc61ae2fe6453819a5bbf9cf05976f7800fa7c1
import cv2 import numpy as np from matplotlib import pyplot as plt import glob def des_match(des_l,des_q): bf=cv2.BFMatcher(cv2.NORM_L2,crossCheck=True) matches=bf.match(des_l,des_q) matches = sorted(matches,key=lambda x:x.distance) return matches def check_match(matches,threshold,txt): count=0 if (matches...
[ "import cv2\nimport numpy as np \nfrom matplotlib import pyplot as plt\nimport glob\n\n\n\n\ndef des_match(des_l,des_q):\n\tbf=cv2.BFMatcher(cv2.NORM_L2,crossCheck=True)\n\tmatches=bf.match(des_l,des_q)\n\tmatches = sorted(matches,key=lambda x:x.distance)\n\treturn matches\n\ndef check_match(matches,threshold,txt):...
true
4,421
d6574cacea693517f3eaa92b4b929c2ee73da2e4
from .tc_gcc import * class AndroidGccToolChain(GccToolChain): def __init__(self, name, ndkDir, gccVersionStr, platformVer, archStr, prefix = "", suffix = ""): # TODO: non-windows host platform hostPlatform = 'windows' installDir = os.path.join(ndkDir, 'toolchains', prefix + gccVersionStr,...
[ "from .tc_gcc import *\n\nclass AndroidGccToolChain(GccToolChain):\n def __init__(self, name, ndkDir, gccVersionStr, platformVer, archStr, prefix = \"\", suffix = \"\"):\n # TODO: non-windows host platform\n hostPlatform = 'windows'\n\n installDir = os.path.join(ndkDir, 'toolchains', prefix ...
false
4,422
064f535b7ea0f1e4a09bdf830021f17d175beda7
#coding=utf-8 from __future__ import division import os def judgeReported(evi, content): for item in evi['reported']: flag = content.find(item) if flag > 0: return 'Y' for item in evi['properly']['neg']: flag = content.find(item) if flag > 0: return...
[ "#coding=utf-8\n\nfrom __future__ import division\nimport os\n \ndef judgeReported(evi, content):\n for item in evi['reported']:\n flag = content.find(item)\n if flag > 0:\n return 'Y'\n for item in evi['properly']['neg']:\n flag = content.find(item)\n if flag > 0:\n...
true
4,423
53c5f298dbfb21d7688fef8f0312858e2fd73d79
# Python 3 program - Currency Sum Validator # def bill_count def bill_count(amount_user, list_of_money_bills): n = len(list_of_money_bills) # Initialize Result ans = [] # Traverse through all the list i = n - 1 while (i >= 0): # Find list while (amount_user >= list_of_mo...
[ "# Python 3 program - Currency Sum Validator\n\n\n# def bill_count\ndef bill_count(amount_user, list_of_money_bills):\n\n\n\n n = len(list_of_money_bills)\n\n # Initialize Result\n ans = []\n\n # Traverse through all the list\n i = n - 1\n\n while (i >= 0):\n\n # Find list\n while (a...
false
4,424
02bec34b138d53235dc944adeae8ccb8d6b3d340
from django.shortcuts import render, HttpResponse, redirect from .models import Book, Author # This is the models.py Database # Create your views here. def main(request): context = { "the_books" : Book.objects.all(), #Book Class model.py } return render(request, "index.html", context) def book(re...
[ "from django.shortcuts import render, HttpResponse, redirect\nfrom .models import Book, Author # This is the models.py Database\n\n# Create your views here.\n\ndef main(request):\n context = {\n \"the_books\" : Book.objects.all(), #Book Class model.py\n }\n return render(request, \"index.html\", con...
false
4,425
01849a6bf5ce5eb75c549af28312f61711ad2494
import smtplib import subprocess import time class NotifyError(Exception): def __init__(self, message): self.message = message class Notification(object): def __init__(self, config, dry_run): self.dry_run = dry_run self.notifications = {} def submit(self, recipient, message): ...
[ "import smtplib\nimport subprocess\nimport time\n\nclass NotifyError(Exception):\n def __init__(self, message):\n self.message = message\n\nclass Notification(object):\n def __init__(self, config, dry_run):\n self.dry_run = dry_run\n self.notifications = {}\n\n def submit(self, recipie...
false
4,426
72f3ae476581ff5acd6c7101764f4764285a47bd
input_object = open("input.txt", "r") input_data = input_object.readlines() input_object.close() cleaned_data = [] for line in input_data: cleaned_data.append(int(line.strip())) input_size = len(cleaned_data) for i in range(0, input_size): for j in range(i, input_size): for k in range(j, input_size):...
[ "input_object = open(\"input.txt\", \"r\")\ninput_data = input_object.readlines()\ninput_object.close()\ncleaned_data = []\n\nfor line in input_data:\n cleaned_data.append(int(line.strip()))\ninput_size = len(cleaned_data)\n\n\nfor i in range(0, input_size):\n for j in range(i, input_size):\n for k in ...
false
4,427
571636be9d213d19bddfd1d04688bc0955c9eae5
print('SYL_2整型数组_12 合并排序数组')
[ "print('SYL_2整型数组_12 合并排序数组')", "print('SYL_2整型数组_12 合并排序数组')\n", "<code token>\n" ]
false
4,428
7d6e8e6142184a1540daa29dac802fe75bd93d8e
#Copyright ReportLab Europe Ltd. 2000-2017 #see license.txt for license details __version__='3.3.0' __doc__=""" The Canvas object is the primary interface for creating PDF files. See doc/reportlab-userguide.pdf for copious examples. """ __all__ = ['Canvas'] ENABLE_TRACKING = 1 # turn this off to do profile testing w/...
[ "\n#Copyright ReportLab Europe Ltd. 2000-2017\n#see license.txt for license details\n__version__='3.3.0'\n__doc__=\"\"\"\nThe Canvas object is the primary interface for creating PDF files. See\ndoc/reportlab-userguide.pdf for copious examples.\n\"\"\"\n\n__all__ = ['Canvas']\nENABLE_TRACKING = 1 # turn this off to ...
false
4,429
1522ebb52504f7f27a526b597fe1e262bbcbfbb0
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): if len(tuple_a) < 1: a_x = 0 else: a_x = tuple_a[0] if len(tuple_a) < 2: a_y = 0 else: a_y = tuple_a[1] if len(tuple_b) < 1: b_x = 0 else: b_x = tuple_b[0] if len(tuple_b) < 2: b...
[ "#!/usr/bin/python3\ndef add_tuple(tuple_a=(), tuple_b=()):\n if len(tuple_a) < 1:\n a_x = 0\n else:\n a_x = tuple_a[0]\n if len(tuple_a) < 2:\n a_y = 0\n else:\n a_y = tuple_a[1]\n if len(tuple_b) < 1:\n b_x = 0\n else:\n b_x = tuple_b[0]\n if len(tupl...
false
4,430
9f02313b6f91f83e3a8b4af8d9447b1d8f3558f6
import socket from threading import Thread from ast import literal_eval clients = {} addresses = {} host = '127.0.0.1' port = 5678 active = [] addr = (host, port) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(addr) groups = [] def broadcast(msg, prefix=""): # prefix is for name identificatio...
[ "import socket\nfrom threading import Thread\nfrom ast import literal_eval\n\nclients = {}\naddresses = {}\nhost = '127.0.0.1'\nport = 5678\nactive = []\naddr = (host, port)\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind(addr)\ngroups = []\n\ndef broadcast(msg, prefix=\"\"): # prefix is f...
false
4,431
341fb4442ba1d1bb13dbbe123e1051e1ceeb91e7
import pymongo import pandas as pd import re from pymongo import MongoClient from nltk.corpus import stopwords from nltk import word_tokenize from gensim import corpora import pickle client = MongoClient() db = client.redditCrawler collection = db.data_test1 def remove_posts(data, index_list): data = data.drop(i...
[ "import pymongo\nimport pandas as pd\nimport re\nfrom pymongo import MongoClient\nfrom nltk.corpus import stopwords\nfrom nltk import word_tokenize\nfrom gensim import corpora\n\nimport pickle\n\nclient = MongoClient()\ndb = client.redditCrawler\ncollection = db.data_test1\n\ndef remove_posts(data, index_list):\n ...
false
4,432
5287bd1847848aa527df8ce57e896bc30c70b43c
from django.test import TestCase from stack_it.models import Image class TextPageContentModelTest(TestCase): def test_instance(self): file = Image.create_empty_image_file(name='hello.jpg') image = Image.objects.create(image=file, alt="World") self.assertEqual(Image.objects.count(), 1) ...
[ "from django.test import TestCase\nfrom stack_it.models import Image\n\n\nclass TextPageContentModelTest(TestCase):\n def test_instance(self):\n file = Image.create_empty_image_file(name='hello.jpg')\n image = Image.objects.create(image=file, alt=\"World\")\n self.assertEqual(Image.objects.c...
false
4,433
ef5d235f09eea827b240290218c397f880f1046d
import re text = 'Macademia nuts, Honey tuile, Cocoa powder, Pistachio nuts' search_pattern = re.compile('nuts') search_match_object = search_pattern.search(text) if search_match_object: print(search_match_object.span()) print(search_match_object.start()) print(search_match_object.end()) print(search_...
[ "import re\n\ntext = 'Macademia nuts, Honey tuile, Cocoa powder, Pistachio nuts'\nsearch_pattern = re.compile('nuts')\nsearch_match_object = search_pattern.search(text)\n\nif search_match_object:\n print(search_match_object.span())\n print(search_match_object.start())\n print(search_match_object.end())\n ...
false
4,434
6cc23e370d1ec1e3e043c3fa6819f9166b6e3b40
#!/usr/bin/python class Symbol(object): pass class Fundef(Symbol): def __init__(self, name, type, args): self.name = name self.type = type self.args = args class VariableSymbol(Symbol): def __init__(self, name, type): self.name = name self.type = type class ...
[ "#!/usr/bin/python\n\n\nclass Symbol(object):\n pass\n\n\nclass Fundef(Symbol):\n\n def __init__(self, name, type, args):\n self.name = name\n self.type = type\n self.args = args\n\n\nclass VariableSymbol(Symbol):\n\n def __init__(self, name, type):\n self.name = name\n s...
false
4,435
2168d10a1b4796576cc7ebb6893e0dc8b58085ca
""" view.py: Contains the View class. """ import random import config from graphics import * class View: """ The view class which handles the visual component of the application. """ def __init__(self, pygame, master): """ Set up and initialise the view. Does not start the display. "...
[ "\n\"\"\" view.py: Contains the View class. \"\"\"\n\n\nimport random\n\nimport config\nfrom graphics import *\n\n\nclass View:\n \n \"\"\" The view class which handles the visual component of the application.\n \"\"\"\n \n def __init__(self, pygame, master):\n \"\"\" Set up and initialise the...
false
4,436
d75187ed435c3d3aeeb31be4a0a4ed1754f8d160
from temp_conversion_script import convert_c_to_f from temp_conversion_script import fever_detection def test_convert_c_to_f(): answer = convert_c_to_f(20.0) expected = 68.0 assert answer == expected def test2(): answer = convert_c_to_f(-40.0) expected = -40.0 assert answer == expected def test_fever_detection...
[ "from temp_conversion_script import convert_c_to_f\nfrom temp_conversion_script import fever_detection\n\ndef test_convert_c_to_f():\n\tanswer = convert_c_to_f(20.0)\n\texpected = 68.0\n\tassert answer == expected\n\ndef test2():\n\tanswer = convert_c_to_f(-40.0)\n\texpected = -40.0\n\tassert answer == expected\n\n...
false
4,437
dd902f99ee8dc23f56641b8e75544a2d4576c19a
""" Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B. Example 1: Input: A = "ab", B = "ba" Output: true """ class Solution: def buddyStrings(self, A: str, B: str) -> bool: if len(A) != len(B): return False...
[ "\"\"\"\nGiven two strings A and B of lowercase letters, return true \nif and only if we can swap two letters in A so that the result \nequals B.\n\n Example 1:\n\n Input: A = \"ab\", B = \"ba\"\n Output: true\n\"\"\"\n\nclass Solution:\n def buddyStrings(self, A: str, B: str) -> bool:\n if len(A) != len(...
false
4,438
5c61ec549a3e78da4ea8a18bb4f8382f2b5c2cfa
#!/usr/bin/env python # encoding: utf-8 # -*- coding: utf-8 -*- # @contact: ybsdeyx@foxmail.com # @software: PyCharm # @time: 2019/3/6 9:59 # @author: Paulson●Wier # @file: 5_词向量.py # @desc: # (1)Word2Vec from gensim.models import Word2Vec import jieba # 定义停用词、标点符号 punctuation = ['、',')','(',',',",", "。", ":", ";",...
[ "#!/usr/bin/env python\n# encoding: utf-8\n\n# -*- coding: utf-8 -*-\n# @contact: ybsdeyx@foxmail.com\n# @software: PyCharm\n# @time: 2019/3/6 9:59\n# @author: Paulson●Wier\n# @file: 5_词向量.py\n# @desc:\n\n# (1)Word2Vec\n\nfrom gensim.models import Word2Vec\nimport jieba\n\n# 定义停用词、标点符号\npunctuation = ['、',')','(','...
false
4,439
c0adc0032a2647a19d3540c057fa9762906e5f62
from __future__ import division import random as rnd import math from collections import Counter from matplotlib import pyplot as plt import ds_library import ds_algebra import ds_probability import ds_gradient_descent def normal_pdfs_visualization(): xs = [x/10.0 for x in range(-50, 50)] plt.plot(xs...
[ "from __future__ import division\r\nimport random as rnd\r\nimport math\r\nfrom collections import Counter\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\nimport ds_library\r\nimport ds_algebra\r\nimport ds_probability\r\nimport ds_gradient_descent\r\n\r\ndef normal_pdfs_visualization():\r\n\txs = [x/10.0 for x ...
false
4,440
db1b6c545555116a334061440614e83e62994838
from flask import Flask, render_template serious12 = Flask(__name__) @serious12.route("/") def home(): return "HOME" @serious12.route("/user/<username>") def user(username): user = { "trung": { "name": "Trung", "age": 19, "birthplace": "Hanoi" }, "n...
[ "from flask import Flask, render_template\n\nserious12 = Flask(__name__)\n\n@serious12.route(\"/\")\ndef home():\n return \"HOME\"\n\n@serious12.route(\"/user/<username>\")\ndef user(username):\n user = {\n \"trung\": {\n \"name\": \"Trung\",\n \"age\": 19,\n \"birthpla...
false
4,441
7378f76b4c1f67d8a549aa2a88db8caa9b05338e
# -*- coding:utf-8 -*- import time import random import numpy as np from collections import defaultdict class Simulator(object): ALLOCATION_INTERVAL_MEAN = 150 ALLOCATION_INTERVAL_STDEV = 30 AFTER_ALLOCATION_INTERVAL_MEAN = 150 AFTER_ALLOCATION_INTERVAL_STDEV = 30 CLICK_INTERVAL_MEAN = 30 CLICK_INTERVAL_STDEV = ...
[ "# -*- coding:utf-8 -*-\nimport time\nimport random\nimport numpy as np\nfrom collections import defaultdict\n\nclass Simulator(object):\n\tALLOCATION_INTERVAL_MEAN = 150\n\tALLOCATION_INTERVAL_STDEV = 30\n\tAFTER_ALLOCATION_INTERVAL_MEAN = 150\n\tAFTER_ALLOCATION_INTERVAL_STDEV = 30\n\tCLICK_INTERVAL_MEAN = 30\n\t...
true
4,442
dfae1007adc557a15d03b78f2bf790fb5b06141a
from distributions.zero_inflated_poisson import ZeroInflatedPoisson from distributions.negative_binomial import NegativeBinomial from distributions.zero_inflated_negative_binomial import ZeroInflatedNegativeBinomial from distributions.zero_inflated import ZeroInflated from distributions.categorized import Categorized f...
[ "from distributions.zero_inflated_poisson import ZeroInflatedPoisson\nfrom distributions.negative_binomial import NegativeBinomial\nfrom distributions.zero_inflated_negative_binomial import ZeroInflatedNegativeBinomial\nfrom distributions.zero_inflated import ZeroInflated\nfrom distributions.categorized import Cate...
false
4,443
6a3fd3323ed8792853afdf5af76161f3e20d4896
''' The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause. ''' #Modifying the values using while loop in a list l1: list = [1,2,3,4,5,6,7,8,9,10...
[ "'''\nThe while statement allows you to repeatedly execute a block of statements as long as a condition is true.\nA while statement is an example of what is called a looping statement. A while statement can have an optional else clause.\n'''\n\n#Modifying the values using while loop in a list\nl1: list = [1,2,3,4,5...
false
4,444
d2fce15636e43ca618c39c5c963bbf0c3a6a3886
# this is just to test with ilp_polytope import polytope polytope.ilp_polytope.test2()
[ "# this is just to test with ilp_polytope\nimport polytope\n\npolytope.ilp_polytope.test2()\n\n", "import polytope\npolytope.ilp_polytope.test2()\n", "<import token>\npolytope.ilp_polytope.test2()\n", "<import token>\n<code token>\n" ]
false
4,445
533154fe58511ac9c9c693bf07f076146b0c6136
import os from PIL import Image import urllib import json import math def download_images(a,b): image_count = 0 k = a no_of_images = b baseURL='https://graph.facebook.com/v2.2/' imgURL='/picture?type=large' sil_check='/picture?redirect=false' while image_count<no_of_images: obj=urllib.urlopen(baseURL+str(k)+s...
[ "import os\nfrom PIL import Image\nimport urllib\nimport json\nimport math\n\ndef download_images(a,b):\n\timage_count = 0\n\tk = a\n\tno_of_images = b\n\tbaseURL='https://graph.facebook.com/v2.2/'\n\timgURL='/picture?type=large'\n\tsil_check='/picture?redirect=false'\n\twhile image_count<no_of_images:\n\t\tobj=url...
true
4,446
166a8cd0e09fbec739f43019659eeaf98b1d4fa4
import argparse def wrong_subtraction(n, k): output = n for i in range(k): string_n = str(output) if string_n[len(string_n) - 1] == '0': output = int(string_n[:-1]) else: output -= 1 return output # d = "Do the wrong subtraction as per https://codeforces.com...
[ "import argparse\n\ndef wrong_subtraction(n, k):\n output = n\n for i in range(k):\n string_n = str(output)\n if string_n[len(string_n) - 1] == '0':\n output = int(string_n[:-1])\n else:\n output -= 1\n return output\n\n# d = \"Do the wrong subtraction as per http...
false
4,447
7a6d5309580b673413f57047e631a08e61e837cf
from django.core.exceptions import ValidationError from django.utils import timezone def year_validator(value): if value < 1 or value > timezone.now().year: raise ValidationError( ('%s is not a correct year!' % value) ) def raiting_validator(value): if value < 1 or value > 10: ...
[ "from django.core.exceptions import ValidationError\nfrom django.utils import timezone\n\n\ndef year_validator(value):\n if value < 1 or value > timezone.now().year:\n raise ValidationError(\n ('%s is not a correct year!' % value)\n )\n\n\ndef raiting_validator(value):\n if value < 1 ...
false
4,448
43a23958b8c8779e3292f0f523a37b6d712fdbac
import time class Block: def __init__(self, index, transactions, previous_hash, nonce=0): self.index = index self.transaction = transactions self.timestamp = time.time() self.previous_hash = previous_hash self.nonce = nonce self.hash = None
[ "import time\n\n\nclass Block:\n\n def __init__(self, index, transactions, previous_hash, nonce=0):\n self.index = index\n self.transaction = transactions\n self.timestamp = time.time()\n self.previous_hash = previous_hash\n self.nonce = nonce\n self.hash = None\n", "<...
false
4,449
913ff9b811d3abbe43bda0554e40a6a2c87053be
from abc import ABC, abstractmethod from raspberry_home.view.geometry import * from raspberry_home.view.renderable import Renderable class View(Renderable, ABC): @abstractmethod def content_size(self, container_size: Size) -> Size: pass
[ "from abc import ABC, abstractmethod\n\nfrom raspberry_home.view.geometry import *\nfrom raspberry_home.view.renderable import Renderable\n\n\nclass View(Renderable, ABC):\n\n @abstractmethod\n def content_size(self, container_size: Size) -> Size:\n pass\n", "from abc import ABC, abstractmethod\nfrom...
false
4,450
3179c13968f7bcdccbd00ea35b9f098dc49b42d8
from functools import reduce with open("input.txt") as f: numbers = f.read().split("\n") n = sorted(list(map(lambda x: int(x), numbers))) n.insert(0, 0) n.append(n[-1] + 3) target = n[-1] memoize = {} def part2(number): if number == target: return 1 if number in memoize.keys(): return ...
[ "from functools import reduce\n\nwith open(\"input.txt\") as f:\n numbers = f.read().split(\"\\n\")\n\nn = sorted(list(map(lambda x: int(x), numbers)))\nn.insert(0, 0)\nn.append(n[-1] + 3)\n\ntarget = n[-1]\n\nmemoize = {}\n\n\ndef part2(number):\n if number == target:\n return 1\n if number in memo...
false
4,451
d2c9ee64472c74767812d842d2c49eec962e28c6
from utils import * from wordEmbedding import * print("bat dau") def predict(text, phobert, tokenizer): model = load_model('model.h5') X_test = word2vec(text, phobert, tokenizer) x_test_tensor = tf.convert_to_tensor(X_test) X_tests = [] X_tests.append(x_test_tensor) X_tests = tf.convert_to_t...
[ "from utils import *\nfrom wordEmbedding import *\nprint(\"bat dau\")\n\ndef predict(text, phobert, tokenizer):\n model = load_model('model.h5')\n X_test = word2vec(text, phobert, tokenizer)\n x_test_tensor = tf.convert_to_tensor(X_test)\n\n X_tests = []\n X_tests.append(x_test_tensor)\n\n X_tests...
false
4,452
1dcea61908753777604d99235407981e89c3b9d4
import sys sys.path.append('/usr/local/anaconda3/lib/python3.6/site-packages') from numpy import sin, linspace x = linspace(0, 4, 101) y = sin(x) from numpy import sin, linspace plt.grid() plt.xlabel('x') plt.ylabel('f(x)') plt.title('Funkcija $sin(x)$ un tās izvitzījums rindā') plt.plot(x, y2) plt.plot(x, y2, color ...
[ "import sys\nsys.path.append('/usr/local/anaconda3/lib/python3.6/site-packages')\n\nfrom numpy import sin, linspace\nx = linspace(0, 4, 101)\ny = sin(x)\n\nfrom numpy import sin, linspace\nplt.grid()\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.title('Funkcija $sin(x)$ un tās izvitzījums rindā')\nplt.plot(x, y2)\nplt....
false
4,453
6b647dc2775f54706a6c18ee91145ba60d70be21
import konlpy import nltk # POS tag a sentence sentence = u'만 6세 이하의 초등학교 취학 전 자녀를 양육하기 위해서는' words = konlpy.tag.Twitter().pos(sentence) # Define a chunk grammar, or chunking rules, then chunk grammar = """ NP: {<N.*>*<Suffix>?} # Noun phrase VP: {<V.*>*} # Verb phrase AP: {<A.*>*} # Adjective...
[ "import konlpy\nimport nltk\n\n# POS tag a sentence\nsentence = u'만 6세 이하의 초등학교 취학 전 자녀를 양육하기 위해서는'\nwords = konlpy.tag.Twitter().pos(sentence)\n\n# Define a chunk grammar, or chunking rules, then chunk\ngrammar = \"\"\"\nNP: {<N.*>*<Suffix>?} # Noun phrase\nVP: {<V.*>*} # Verb phrase\nAP: {<A.*>*} ...
false
4,454
ff8ffeb418bf4f9bc7d5dadd126ebc7c34c5c2cd
speed, lic_plate = input().split() salary = int(0) while lic_plate != "A999AA": if int(speed) > 60: if lic_plate[1] == lic_plate[2] and lic_plate [2] == lic_plate[3]: salary += 1000 elif lic_plate[1] == lic_plate[2] or lic_plate [1] == lic_plate[3]: salary += 500 elif...
[ "speed, lic_plate = input().split()\nsalary = int(0)\nwhile lic_plate != \"A999AA\":\n if int(speed) > 60:\n if lic_plate[1] == lic_plate[2] and lic_plate [2] == lic_plate[3]:\n salary += 1000\n elif lic_plate[1] == lic_plate[2] or lic_plate [1] == lic_plate[3]:\n salary += 50...
false
4,455
382cb55a6b849f0240276d8f45746e995b16d714
import pandas as pd import folium ctx = '../data/' json = ctx + 'us-states.json' csv = ctx + 'US_Unemployment_Oct2012.csv' data = pd.read_csv(csv) m = folium.Map(location=[37, -102], zoom_start=5) m.choropleth( geo_data=json, name='choropleth', data=data, columns=['State', 'Unemployment'], Key_on=...
[ "import pandas as pd\nimport folium\n\nctx = '../data/'\njson = ctx + 'us-states.json'\ncsv = ctx + 'US_Unemployment_Oct2012.csv'\ndata = pd.read_csv(csv)\n\nm = folium.Map(location=[37, -102], zoom_start=5)\nm.choropleth(\n geo_data=json,\n name='choropleth',\n data=data,\n columns=['State', 'Unemploym...
false
4,456
5eab41a2ef536365bab6f6b5ad97efb8d26d7687
import numpy as np import initialization as init import evaluation as eval import selection as sel import recombination as rec import mutation as mut initialize = init.permutation evaluate = eval.custom select = sel.rank_based mutate = mut.swap reproduce = rec.pairwise crossover = rec.order replace = sel.rank_based ...
[ "import numpy as np\nimport initialization as init\nimport evaluation as eval\nimport selection as sel\nimport recombination as rec\nimport mutation as mut\n\n\ninitialize = init.permutation\nevaluate = eval.custom\nselect = sel.rank_based\nmutate = mut.swap\nreproduce = rec.pairwise\ncrossover = rec.order\nreplace...
false
4,457
d178818faf5fb18f5da48c1e2cf7991600731d06
# -*- coding: utf-8 -*- class Bot(dict): def __init__(self): self["getRayon"] = 0 self["getPosition"] = (-1000, -1000) self.traj = [] def getTrajectoires(self): return self.traj def getRayon(self): return self["getRayon"] def getPosition(self): return self["getPosition"] if __name__ == "__main__": i...
[ "# -*- coding: utf-8 -*-\n\n\nclass Bot(dict):\n\tdef __init__(self):\n\t\tself[\"getRayon\"] = 0\n\t\tself[\"getPosition\"] = (-1000, -1000)\n\t\tself.traj = []\n\tdef getTrajectoires(self):\n\t\treturn self.traj\n\tdef getRayon(self):\n\t\treturn self[\"getRayon\"]\n\tdef getPosition(self):\n\t\treturn self[\"get...
false
4,458
963499e071873083dc942486b9a5b094393cd99e
from db_upgrader.Repositories.store import Store, StoreException from db_upgrader.Models.product import * class ProductStore(Store): table = 'product' def add_product(self, product): try: c = self.conn.cursor() c.execute( 'INSERT INTO product (`name`,customerId,i...
[ "from db_upgrader.Repositories.store import Store, StoreException\nfrom db_upgrader.Models.product import *\n\nclass ProductStore(Store):\n table = 'product'\n def add_product(self, product):\n try:\n c = self.conn.cursor()\n c.execute(\n 'INSERT INTO product (`name...
false
4,459
efe5df4005dbdb04cf4e7da1f350dab483c94c92
from django.db import models # Create your models here. class person(models.Model): name=models.CharField(max_length=20,unique=True) age=models.IntegerField() email=models.CharField(max_length=20,unique=True) phone=models.CharField(max_length=10, unique=True) gender=models.CharField(max_length=10) ...
[ "from django.db import models\n\n# Create your models here.\nclass person(models.Model):\n name=models.CharField(max_length=20,unique=True)\n age=models.IntegerField()\n email=models.CharField(max_length=20,unique=True)\n phone=models.CharField(max_length=10, unique=True)\n gender=models.CharField(ma...
false
4,460
85d1069d85e285bc5c36811f569dabd793b5064b
config = {'numIndividuals': 50, 'maxNumGen':20, 'eliteProp':0.1, 'mutantProp':0.2, 'inheritanceProb':0.7}
[ "config = {'numIndividuals': 50, 'maxNumGen':20, 'eliteProp':0.1, 'mutantProp':0.2, 'inheritanceProb':0.7}\n", "config = {'numIndividuals': 50, 'maxNumGen': 20, 'eliteProp': 0.1,\n 'mutantProp': 0.2, 'inheritanceProb': 0.7}\n", "<assignment token>\n" ]
false
4,461
229d7378695f7e00176eb7c3962519af3db1b7e1
# encoding: utf-8 from GlyphsApp.plugins import * from outlineTestPenGlyphs import OutlineTestPenGlyphs from string import strip plugin_id = "de.kutilek.RedArrow" class RedArrow(ReporterPlugin): def settings(self): self.menuName = "Red Arrows" self.keyboardShortcut = 'a' self.keyboardShortcutModifier = N...
[ "# encoding: utf-8\n\n\nfrom GlyphsApp.plugins import *\n\nfrom outlineTestPenGlyphs import OutlineTestPenGlyphs\nfrom string import strip\n\nplugin_id = \"de.kutilek.RedArrow\"\n\n\nclass RedArrow(ReporterPlugin):\n\t\n\tdef settings(self):\n\t\tself.menuName = \"Red Arrows\"\n\t\tself.keyboardShortcut = 'a'\n\t\t...
false
4,462
6d4950ca61cd1e2ee7ef8b409577e9df2d65addd
from disaggregation import DisaggregationManager import numpy as np from more_itertools import windowed x = np.random.random_sample(10 * 32 * 1024) w = windowed(x, n=1024, step=128) z = DisaggregationManager._overlap_average(np.array(list(w)), stride=128) print(z.shape) print(x.shape) assert z.shape == x.shape
[ "from disaggregation import DisaggregationManager\nimport numpy as np\nfrom more_itertools import windowed\n\nx = np.random.random_sample(10 * 32 * 1024)\nw = windowed(x, n=1024, step=128)\n\nz = DisaggregationManager._overlap_average(np.array(list(w)), stride=128)\nprint(z.shape)\nprint(x.shape)\nassert z.shape ==...
false
4,463
a5ef2adbf85b5ab80c59697340f94bc57d60952e
""" Code for Alexa skill to check PB tracking """ from __future__ import print_function import traceback import requests import os import json # --------------- Helpers that build all of the responses ---------------------- def build_speechlet_response(title, output, reprompt_text, should_end_session): return {...
[ "\"\"\"\nCode for Alexa skill to check PB tracking\n\"\"\"\n\nfrom __future__ import print_function\nimport traceback\nimport requests\nimport os\nimport json\n\n\n# --------------- Helpers that build all of the responses ----------------------\n\ndef build_speechlet_response(title, output, reprompt_text, should_en...
false
4,464
48cef0377087d9245aad1fb759adf8ff07d2b66f
# 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 agree...
[ "# 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 applicab...
false
4,465
da41f26489c477e0df9735606457bd4ee4e5a396
import kubernetes.client from kubernetes.client.rest import ApiException from pprint import pprint from kubeops_api.models.cluster import Cluster class ClusterMonitor(): def __init__(self,cluster): self.cluster = cluster self.token = self.cluster.get_cluster_token() self.cluster.change_to(...
[ "import kubernetes.client\nfrom kubernetes.client.rest import ApiException\nfrom pprint import pprint\nfrom kubeops_api.models.cluster import Cluster\n\nclass ClusterMonitor():\n\n def __init__(self,cluster):\n self.cluster = cluster\n self.token = self.cluster.get_cluster_token()\n self.clu...
false
4,466
6abfd6c0a644356ae0bc75d62472b5c495118a8e
import time from bitfinex_trade_client import BitfinexClient,BitfinexTradeClient KEY = "nBi8YyJZZ9ZhSOf2jEpMAoBpzKt2Shh6IoLdTjFRYvb" SECRET = "XO6FUYbhFYqBflXYSaKMiu1hGHLhGf63xsOK0Pf7osA" class EMA: def __init__(self, duration): self.value = 0 self.duration = duration self.count = 0 ...
[ "import time\n\nfrom bitfinex_trade_client import BitfinexClient,BitfinexTradeClient\n\nKEY = \"nBi8YyJZZ9ZhSOf2jEpMAoBpzKt2Shh6IoLdTjFRYvb\"\nSECRET = \"XO6FUYbhFYqBflXYSaKMiu1hGHLhGf63xsOK0Pf7osA\"\n\nclass EMA:\n def __init__(self, duration):\n self.value = 0\n\n self.duration = duration\n ...
false
4,467
d122267e1da2d9cf68d245148bb496dfba3e7d19
#!/usr/bin/env python """ Load API client for a Tool Registry Service (TRS) endpoint based either on the GA4GH specification or an existing client library. """ import logging from bravado.requests_client import RequestsClient from ga4ghtest.core.config import trs_config from .client import TRSClient logger = logging...
[ "#!/usr/bin/env python\n\"\"\"\nLoad API client for a Tool Registry Service (TRS) endpoint based\neither on the GA4GH specification or an existing client library.\n\"\"\"\nimport logging\n\nfrom bravado.requests_client import RequestsClient\n\nfrom ga4ghtest.core.config import trs_config\nfrom .client import TRSCli...
false
4,468
45750152313fd3670867c61d0173e4cb11a806ba
T = int(input()) for cnt in range(1, T + 1): S = input() S_list = [] card = {'S': 13, 'D': 13, 'H': 13, 'C': 13} print('#' + str(cnt), end=' ') for i in range(0, len(S), 3): S_list.append(S[i:i + 3]) if len(set(S_list)) != len(S_list): print('ERROR') else: for i in S_...
[ "T = int(input())\nfor cnt in range(1, T + 1):\n S = input()\n S_list = []\n card = {'S': 13, 'D': 13, 'H': 13, 'C': 13}\n print('#' + str(cnt), end=' ')\n for i in range(0, len(S), 3):\n S_list.append(S[i:i + 3])\n if len(set(S_list)) != len(S_list):\n print('ERROR')\n else:\n ...
false
4,469
e2e5ca388d67f2a13eaef6067fc19e2dfe284a55
import json import sys import os # Change to Singularity working directory. os.chdir('/mnt/cwd') # Take subset index as argument subset_index = sys.argv[1] # Open up subset matching this. with open('/mnt/scripts/outputs/instcat_list_subset'+str(subset_index)+'.json', 'r') as f: instcat_list_subset = json.load(f)...
[ "import json\nimport sys\nimport os\n\n# Change to Singularity working directory.\nos.chdir('/mnt/cwd')\n\n# Take subset index as argument\nsubset_index = sys.argv[1]\n\n# Open up subset matching this.\nwith open('/mnt/scripts/outputs/instcat_list_subset'+str(subset_index)+'.json', 'r') as f:\n instcat_list_subs...
false
4,470
6c27f70e820202f6cc4348de3c9198e7b20ec7d9
from zExceptions import Unauthorized if REQUEST is not None: raise Unauthorized portal = context.getPortalObject() compute_node = context reference = "TIOCONS-%s-%s" % (compute_node.getReference(), source_reference) version = "%s" % context.getPortalObject().portal_ids.generateNewId( id_group=('slap_tioxml_consum...
[ "from zExceptions import Unauthorized\nif REQUEST is not None:\n raise Unauthorized\n\nportal = context.getPortalObject()\ncompute_node = context\n\nreference = \"TIOCONS-%s-%s\" % (compute_node.getReference(), source_reference)\nversion = \"%s\" % context.getPortalObject().portal_ids.generateNewId(\n id_group=('...
false
4,471
00c6899b9d49cbbd0f1980eada77ad91562211a0
import requests import json class Parser: init_url = r'https://www.joom.com/tokens/init' products_url = r'https://api.joom.com/1.1/search/products?language=ru-RU&currency=RUB' def __init__(self, links_list): self.links = links_list self.product_info_dict = {} access_token = json.l...
[ "import requests\nimport json\n\n\nclass Parser:\n init_url = r'https://www.joom.com/tokens/init'\n products_url = r'https://api.joom.com/1.1/search/products?language=ru-RU&currency=RUB'\n\n def __init__(self, links_list):\n self.links = links_list\n self.product_info_dict = {}\n acces...
false
4,472
7dce240a891e807b1f5251a09a69368f4e513973
# Advent of Code: Day 4 """A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces. To ensure security, a valid passphrase must contain no duplicate words. """ def valid...
[ "# Advent of Code: Day 4\n\n\"\"\"A new system policy has been put in place that requires all accounts to \nuse a passphrase instead of simply a password. A passphrase consists of a \nseries of words (lowercase letters) separated by spaces.\n\nTo ensure security, a valid passphrase must contain no duplicate words.\...
false
4,473
a52e0dde47d7df1b7b30887a690b201733ac7592
from trytond.pool import Pool from .reporte import MyInvoiceReport def register(): Pool.register( MyInvoiceReport, module='cooperar-reporte-factura', type_='report')
[ "from trytond.pool import Pool\nfrom .reporte import MyInvoiceReport\n\ndef register():\n Pool.register(\n MyInvoiceReport,\n module='cooperar-reporte-factura', type_='report')\n\n", "from trytond.pool import Pool\nfrom .reporte import MyInvoiceReport\n\n\ndef register():\n Pool.register(MyInv...
false
4,474
0d28ab54f08301d9788ca9a5e46d522e043e9507
from django.test import TestCase, Client from pdf_crawler.models import Document from rest_framework.reverse import reverse class TestCase(TestCase): client = Client() def setUp(self): Document.objects.create(name='First').save() def test_endpoints(self): """ test for endpoints ...
[ "from django.test import TestCase, Client\nfrom pdf_crawler.models import Document\nfrom rest_framework.reverse import reverse\n\n\nclass TestCase(TestCase):\n\n client = Client()\n\n def setUp(self):\n Document.objects.create(name='First').save()\n\n def test_endpoints(self):\n \"\"\"\n ...
false
4,475
5456fb2938ae4d0f69414c153390f86437088114
# Copyright 2017 Battelle Energy Alliance, LLC # # 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 t...
[ "# Copyright 2017 Battelle Energy Alliance, LLC\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 ...
false
4,476
b7d3af29e024b0b2cf5d2c054290f799eae7fed1
import pymysql pymysql.install_as_MySQLdb() # from keras.models import load_model # from keras.models import Model # from ai import settings # # print('load model ...') # model = load_model(settings.MODEL_PATH) # model = Model(inputs=model.input, outputs=model.get_layer('dnsthree').output) # print('load done.')
[ "import pymysql\n\npymysql.install_as_MySQLdb()\n\n# from keras.models import load_model\n# from keras.models import Model\n# from ai import settings\n#\n# print('load model ...')\n# model = load_model(settings.MODEL_PATH)\n# model = Model(inputs=model.input, outputs=model.get_layer('dnsthree').output)\n# print('lo...
false
4,477
08f0b261b5a9b0f5133c468b3f92dc00285eda6a
import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.grid_search import GridSearchCV import matplotlib.pyplot as plt def loadTrainSet(filepath): raw = np.loadtxt(filepath, delimiter=',', dtype=np.str, skiprows=1) X, y = raw[:,1:], raw[:,0] trainSet = np.hstack((X, y.reshape(-...
[ "import numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.grid_search import GridSearchCV\nimport matplotlib.pyplot as plt\n\ndef loadTrainSet(filepath):\n raw = np.loadtxt(filepath, delimiter=',', dtype=np.str, skiprows=1)\n X, y = raw[:,1:], raw[:,0]\n trainSet = np.hstack((X...
false
4,478
8ae6630ccd2f2b5a10401cadb4574772f6ecbc4a
import numpy as np from math import inf """ Strategy made by duckboycool for carykh's Prisoner's Dilemma Tournament. (https://youtu.be/r2Fw_rms-mA) It is a nice Tit for Tat based strategy that attempts to detect when the opponent is not changing their actions based off of ours so we can maximize with defects, and att...
[ "import numpy as np\nfrom math import inf\n\n\"\"\"\nStrategy made by duckboycool for carykh's Prisoner's Dilemma Tournament. (https://youtu.be/r2Fw_rms-mA)\n\nIt is a nice Tit for Tat based strategy that attempts to detect when the opponent is not changing their actions based\noff of ours so we can maximize with d...
false
4,479
149ac778a552fac4499d7146db8600c91c68c60e
from time import sleep import RPi.GPIO as gpio buzzer_pin = 18 gpio.setmode(gpio.BCM) gpio.setup(buzzer_pin, gpio.OUT) def buzz(pitch, duration): peroid = 1.0/pitch delay = peroid / 2.0 cycles = int(duration*pitch) for i in range(cycles): gpio.output(buzzer_pin, True) sleep(delay) ...
[ "from time import sleep\nimport RPi.GPIO as gpio\n\n\nbuzzer_pin = 18\ngpio.setmode(gpio.BCM)\ngpio.setup(buzzer_pin, gpio.OUT)\n\ndef buzz(pitch, duration):\n peroid = 1.0/pitch\n delay = peroid / 2.0\n cycles = int(duration*pitch)\n for i in range(cycles):\n gpio.output(buzzer_pin, True)\n ...
false
4,480
5ed34ada35dfb2f783af4485bf9d31aa42712b9a
""" Django settings for hauki project. """ import logging import os import subprocess import environ import sentry_sdk from django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES from django.core.exceptions import ImproperlyConfigured from sentry_sdk.integrations.django import DjangoIntegration CONFIG_FILE...
[ "\"\"\"\nDjango settings for hauki project.\n\"\"\"\n\nimport logging\nimport os\nimport subprocess\n\nimport environ\nimport sentry_sdk\nfrom django.conf.global_settings import LANGUAGES as GLOBAL_LANGUAGES\nfrom django.core.exceptions import ImproperlyConfigured\nfrom sentry_sdk.integrations.django import DjangoI...
false
4,481
04938e14f22c44437188469b53dfb05d2ecd4a5c
''' tag名だけで変えてもいいよね?? ただし,置換するときは,「代表参照表現(参照表現)」のように,元の参照表現が分かるように配慮せよ.→何を言いたい!? もしかして: <mention> -> <mention representative="false"> 欲しい??「元の参照表現が分かる」とは <mention representative="true"> と区割りできればいいよね? ''' from bs4 import BeautifulSoup, element soup = BeautifulSoup(open("nlp.txt.xml"),"lxml") mentions = soup.find_all('me...
[ "'''\ntag名だけで変えてもいいよね??\nただし,置換するときは,「代表参照表現(参照表現)」のように,元の参照表現が分かるように配慮せよ.→何を言いたい!?\nもしかして:\n<mention> -> <mention representative=\"false\"> 欲しい??「元の参照表現が分かる」とは <mention representative=\"true\"> と区割りできればいいよね?\n'''\nfrom bs4 import BeautifulSoup, element\nsoup = BeautifulSoup(open(\"nlp.txt.xml\"),\"lxml\")\nmention...
false
4,482
c173c4673fd716a8b88faf751639d52e9ea4ffab
''' Copyright 2014-2015 Reubenur Rahman All Rights Reserved @author: reuben.13@gmail.com ''' import XenAPI inputs = {'xenserver_master_ip': '15.22.18.17', 'xenserver_password': 'reuben', 'xenserver_user': 'root', 'vm_name': 'SLES11SP2x64', 'target_host': 'xenserver-2' ...
[ "'''\nCopyright 2014-2015 Reubenur Rahman\nAll Rights Reserved\n@author: reuben.13@gmail.com\n'''\n\nimport XenAPI\n\ninputs = {'xenserver_master_ip': '15.22.18.17',\n 'xenserver_password': 'reuben',\n 'xenserver_user': 'root',\n 'vm_name': 'SLES11SP2x64',\n 'target_host': 'xense...
true
4,483
1ac3630e6433a2d11c716b558640cab7c559f6ba
# coding: utf8 from __future__ import unicode_literals from nltk.tag import stanford from .SequenceTagger import SequenceTagger class POSTagger(SequenceTagger): """ >>> tagger = POSTagger(model='resources/postagger.model') >>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.']) [('من', 'PRO'), ('به', 'P'), ('مدر...
[ "# coding: utf8\n\nfrom __future__ import unicode_literals\nfrom nltk.tag import stanford\nfrom .SequenceTagger import SequenceTagger\n\n\nclass POSTagger(SequenceTagger):\n\t\"\"\"\n\t>>> tagger = POSTagger(model='resources/postagger.model')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PR...
false
4,484
3da82bcff0a4f91c1245892bc01e9f743ea354a8
import sys n=int(input().strip()) a=list(input().strip().split(' ')) H=list(input().strip().split(' ')) a = [int(i) for i in a] m=int(H[0]) hmin=int(H[1]) hmax=int(H[2]) pos=0 found = 0 d=a[-1]-a[0] if(d==m): print(a[0]) elif(0<d<m): for i in range(hmin, hmax+1): fin1 = a[0]-i+m if(hmin<=fin1-...
[ "import sys\n\nn=int(input().strip())\na=list(input().strip().split(' '))\nH=list(input().strip().split(' '))\na = [int(i) for i in a]\nm=int(H[0])\nhmin=int(H[1])\nhmax=int(H[2])\npos=0\nfound = 0\nd=a[-1]-a[0]\nif(d==m):\n print(a[0])\nelif(0<d<m):\n for i in range(hmin, hmax+1):\n fin1 = a[0]-i+m\n...
false
4,485
3956d4cdb0a8654b6f107975ac003ce59ddd3de1
import random def generatePassword (): numLowerCase = numUpperCase = numSpecialCase = numNumber = 0 password = "" randomChars = "-|@.,?/!~#%^&*(){}[]\=*" length = random.randint(10, 25) while(numSpecialCase < 1 or numNumber < 1 or numLowerCase < 1 or numUpperCase < 1): password = "" ...
[ "import random\n\ndef generatePassword ():\n numLowerCase = numUpperCase = numSpecialCase = numNumber = 0\n password = \"\"\n randomChars = \"-|@.,?/!~#%^&*(){}[]\\=*\"\n length = random.randint(10, 25)\n\n while(numSpecialCase < 1 or numNumber < 1 or numLowerCase < 1 or numUpperCase < 1):\n ...
false
4,486
fe3584dd858c06d66215b4a182adf87d35324975
from pyecharts import options as opts from pyecharts.charts import * import pandas as pd import namemap from pyecharts.globals import ThemeType # import time import json import requests from datetime import datetime import pandas as pd import numpy as np def read_country_code(): """ 获取...
[ "from pyecharts import options as opts\r\nfrom pyecharts.charts import *\r\nimport pandas as pd\r\nimport namemap\r\nfrom pyecharts.globals import ThemeType\r\n\r\n\r\n#\r\nimport time \r\nimport json\r\nimport requests\r\nfrom datetime import datetime\r\nimport pandas as pd \r\nimport numpy as np\r\n \r\ndef re...
false
4,487
90a220775efcc8ff9e83f1a1f011f424ddc3476d
import tensorflow as tf from model import CabbageModel import numpy as np from krx import KrxCrawler from naver_stock import StockModel as sm from scattertest import scattertest as st class CabbageController: def __init__(self): #def __init__(self, avg_temp, min_temp, max_temp, rain_fall): #self._a...
[ "import tensorflow as tf\nfrom model import CabbageModel\nimport numpy as np\nfrom krx import KrxCrawler\nfrom naver_stock import StockModel as sm\nfrom scattertest import scattertest as st\n\nclass CabbageController:\n def __init__(self):\n #def __init__(self, avg_temp, min_temp, max_temp, rain_fall):\n ...
false
4,488
5e6bbb10ec82e566c749dd4d794eabd2e8f7a648
#!/usr/bin/env python3 import numpy as np from DMP.PIDMP import RLDMPs import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D np.random.seed(50) dmp_y0 = np.array([-1.52017496, 0.04908739, 1.41433029]) dmp_goal = np.array([-1.50848603, 0.0591503 , 1.44347592]) load_file_name = "w_0_2_right_3...
[ "#!/usr/bin/env python3\nimport numpy as np\nfrom DMP.PIDMP import RLDMPs\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nnp.random.seed(50)\ndmp_y0 = np.array([-1.52017496, 0.04908739, 1.41433029])\ndmp_goal = np.array([-1.50848603, 0.0591503 , 1.44347592])\n \n\nload_file_name ...
false
4,489
af80cb4d4ce5c071efc39e85f89bb412cff6bf6e
IMAGE_SIZE=(640, 480)
[ "IMAGE_SIZE=(640, 480)\n", "IMAGE_SIZE = 640, 480\n", "<assignment token>\n" ]
false
4,490
eee60a6f46549ededfbc7b0b294ab723e2e73f7e
from .base import * RAVEN_CONFIG = {} ALLOWED_HOSTS = ['*']
[ "from .base import *\n\nRAVEN_CONFIG = {}\n\nALLOWED_HOSTS = ['*']\n", "from .base import *\nRAVEN_CONFIG = {}\nALLOWED_HOSTS = ['*']\n", "<import token>\nRAVEN_CONFIG = {}\nALLOWED_HOSTS = ['*']\n", "<import token>\n<assignment token>\n" ]
false
4,491
f996dffcb9650663278ec1e31d9f88d50142f4ea
class TrieNode: def __init__(self): self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode) self.word: Optional[str] = None class Solution: def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: m = len(board) n = len(board[0]) ans = [] root = TrieNode()...
[ "class TrieNode:\n def __init__(self):\n self.children: Dict[str, TrieNode] = collections.defaultdict(TrieNode)\n self.word: Optional[str] = None\n\n\nclass Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n m = len(board)\n n = len(board[0])\n ans = []\n r...
false
4,492
8fedaeb13fde117cf6b7ace23b59c26e4aab2bc2
a = input() b = [] ind = [] for i in a: if i.isalpha(): b.append(i) else: ind.append(a.index(i)) c = list(reversed(b)) for i in ind: c.insert(i,a[i]) print(''.join(c))
[ "a = input()\nb = []\nind = []\nfor i in a:\n if i.isalpha():\n b.append(i)\n else:\n ind.append(a.index(i))\n \nc = list(reversed(b))\n\nfor i in ind:\n c.insert(i,a[i])\n \nprint(''.join(c))\n \n", "a = input()\nb = []\nind = []\nfor i in a:\n if i.isalpha():\n b.a...
false
4,493
b216c0f92bcf91fd538eabf0239cf149342ef2eb
from django.shortcuts import render from django.views.generic import ListView from auth_person.models import Post_news, User # Create your views here. def blog(request, foo): inf = {'login': foo} return render(request, 'blog/blog.html', context=inf) class feed(ListView): template_name = 'blog/feed.html'...
[ "from django.shortcuts import render\nfrom django.views.generic import ListView\nfrom auth_person.models import Post_news, User\n\n# Create your views here.\n\n\ndef blog(request, foo):\n inf = {'login': foo}\n return render(request, 'blog/blog.html', context=inf)\n\nclass feed(ListView):\n template_name =...
true
4,494
9b715fb95e89804a57ea77a98face673b57220c6
import socket import struct def parsing_ethernet_header(data): ethernet_header=struct.unpack("!6c6c2s",data) ether_dest = convert_ethernet_address(ethernet_header[0:6]) ether_src = convert_ethernet_address(ethernet_header[6:12]) ip_header="0x"+ethernet_header[12].hex() print("=========ethernet hea...
[ "import socket\nimport struct\n\ndef parsing_ethernet_header(data):\n ethernet_header=struct.unpack(\"!6c6c2s\",data)\n ether_dest = convert_ethernet_address(ethernet_header[0:6])\n ether_src = convert_ethernet_address(ethernet_header[6:12])\n ip_header=\"0x\"+ethernet_header[12].hex()\n\n print(\"==...
false
4,495
7a243f5e24d81d3395cc790dface5e795b9c04e6
"""Distribution script for unitreport.""" import setuptools with open("README.md", "r") as f: long_description = f.read() setuptools.setup( name="unitreport", version="0.1.1", author="annahadji", author_email="annahadji@users.noreply.github.com", description="A small unittest-based tool for ge...
[ "\"\"\"Distribution script for unitreport.\"\"\"\nimport setuptools\n\nwith open(\"README.md\", \"r\") as f:\n long_description = f.read()\n\nsetuptools.setup(\n name=\"unitreport\",\n version=\"0.1.1\",\n author=\"annahadji\",\n author_email=\"annahadji@users.noreply.github.com\",\n description=\...
false
4,496
b63ed9e09b9e8c539aff765d719f3610283663fe
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function from abc import ABCMeta, abstractmethod from six import with_metaclass from .utils import parse_query_parameters class CollectionMixin(with_metaclass(ABCMeta, object)): @abstractmethod def list(self, size=100, offset=None, **fil...
[ "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function\nfrom abc import ABCMeta, abstractmethod\n\nfrom six import with_metaclass\n\nfrom .utils import parse_query_parameters\n\n\nclass CollectionMixin(with_metaclass(ABCMeta, object)):\n @abstractmethod\n def list(self, size=100, of...
false
4,497
ba13bcf9e89ae96e9a66a42fc4e6ae4ad33c84b4
import mclient from mclient import instruments import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl #from pulseseq import sequencer, pulselib mpl.rcParams['figure.figsize']=[6,4] qubit_info = mclient.get_qubit_info('qubit_info') qubit_ef_info = mclient.get_qubit_info('qubit_ef_info') ...
[ "import mclient\r\nfrom mclient import instruments\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\n#from pulseseq import sequencer, pulselib\r\n\r\nmpl.rcParams['figure.figsize']=[6,4]\r\n\r\nqubit_info = mclient.get_qubit_info('qubit_info')\r\nqubit_ef_info = mclient.get_qub...
true
4,498
2bc20f3410d068e0592c8a45e3c13c0559059f24
#Use bisection search to determine square root def square_calculator(user_input): """ accepts input from a user to determine the square root returns the square root of the user input """ precision = .000000000001 counter = 0 low = 0 high = user_input guess = (low + high) / 2.0 w...
[ "#Use bisection search to determine square root\ndef square_calculator(user_input):\n \"\"\"\n accepts input from a user to determine the square root\n returns the square root of the user input\n \"\"\"\n precision = .000000000001\n counter = 0\n low = 0\n high = user_input\n guess = (low...
false
4,499
4f0a0089ad128edca3052da58a4c71f935592e25
import sys from arguments_parser import parse_args from open_ldap import OpenLdap from csv_parser import parse_csv, random_password from smtp_mail import SmtpServer def create_user(open_ldap, smtp, entries): """ If the 'ldap_insert' returns True, then the email will be send with the account info. """ ...
[ "import sys\nfrom arguments_parser import parse_args\nfrom open_ldap import OpenLdap\nfrom csv_parser import parse_csv, random_password\nfrom smtp_mail import SmtpServer\n\n\ndef create_user(open_ldap, smtp, entries):\n \"\"\"\n If the 'ldap_insert' returns True, then\n the email will be send with the acco...
false