index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
900
502e0f0c6376617dc094fcdd47bea9773d011864
def filter_lines(in_filename, in_filename2,out_filename): """Read records from in_filename and write records to out_filename if the beginning of the line (taken up to the first comma at or after position 11) is found in keys (which must be a set of byte strings). """ proper_convert = 0 missing_...
[ "def filter_lines(in_filename, in_filename2,out_filename):\n \"\"\"Read records from in_filename and write records to out_filename if\n the beginning of the line (taken up to the first comma at or after\n position 11) is found in keys (which must be a set of byte strings).\n\n \"\"\"\n proper_convert...
false
901
a17abd3947a946daf2c453c120f2e79d2ba60778
# 赛场统分 # 【问题】在编程竞赛中,有10个评委为参赛的选手打分,分数为0 ~ 100分。 # 选手最后得分为:去掉一个最高分和一个最低分后其余8个分数的平均值。请编写一个程序实现。 sc_lst = [] i = 1 while len(sc_lst) < 10: try: sc = int(input('请第%d位评委打分:' % i)) if sc > 0 and sc < 101: sc_lst.append(sc) i += 1 else: print('超出范围,输入无效') ex...
[ "# 赛场统分\n# 【问题】在编程竞赛中,有10个评委为参赛的选手打分,分数为0 ~ 100分。\n# 选手最后得分为:去掉一个最高分和一个最低分后其余8个分数的平均值。请编写一个程序实现。\n\nsc_lst = []\ni = 1\nwhile len(sc_lst) < 10:\n try:\n sc = int(input('请第%d位评委打分:' % i))\n if sc > 0 and sc < 101:\n sc_lst.append(sc)\n i += 1\n else:\n print('...
false
902
04670041dab49f8c2d4a0415030356e7ea92925f
from tempfile import mkdtemp from shutil import rmtree from os.path import join import os MAX_UNCOMPRESSED_SIZE = 100e6 # 100MB # Extracts a zipfile into a directory safely class ModelExtractor(object): def __init__(self, modelzip): self.modelzip = modelzip def __enter__(self): if not self._...
[ "from tempfile import mkdtemp\nfrom shutil import rmtree\nfrom os.path import join\nimport os\n\nMAX_UNCOMPRESSED_SIZE = 100e6 # 100MB\n\n# Extracts a zipfile into a directory safely\nclass ModelExtractor(object):\n def __init__(self, modelzip):\n self.modelzip = modelzip \n\n def __enter__(self):\n ...
false
903
cf3b66a635c6549553af738f263b035217e75a7a
count=0 def merge(a, b): global count c = [] h = j = 0 while j < len(a) and h < len(b): if a[j] <= b[h]: c.append(a[j]) j += 1 else: count+=(len(a[j:])) c.append(b[h]) h += 1 if j == len(a): for i in b[h:]: ...
[ "count=0\ndef merge(a, b):\n global count\n c = []\n h = j = 0\n while j < len(a) and h < len(b):\n if a[j] <= b[h]:\n c.append(a[j])\n j += 1\n else:\n count+=(len(a[j:]))\n c.append(b[h])\n h += 1\n\n if j == len(a):\n for ...
false
904
d2298ad1e4737b983ba6d1f2fff59750137510b5
import json import os import uuid from django.core.files.uploadedfile import SimpleUploadedFile from django.conf import settings from django.contrib.contenttypes.models import ContentType from nautobot.dcim.models import Site from nautobot.extras.choices import JobResultStatusChoices from nautobot.extras.jobs import ...
[ "import json\nimport os\nimport uuid\n\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom nautobot.dcim.models import Site\nfrom nautobot.extras.choices import JobResultStatusChoices\nfrom nautobot.extr...
false
905
48f2cc5b6d53c7317ad882947cabbc367cda0fb7
import random import numpy as np import pandas as pd def linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0, parameter_std=1, error_mean=0, error_std=1): """ Generate a column that is a random linear combination of X1, X2 and X3 plus some random error """ length = X.shape[0] ...
[ "import random\nimport numpy as np\nimport pandas as pd\n\ndef linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0, parameter_std=1, error_mean=0, error_std=1):\n \"\"\"\n Generate a column that is a random linear combination of\n X1, X2 and X3 plus some random error\n \"\"\"\n le...
false
906
6ae529a5e5658ba409ec3e7284d8b2911c60dd00
import os from linkedin_scraper import get_jobs chrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver') df = get_jobs('Data Scientist', 40, False, chrome_driver_path) df.to_csv('linkedin_jobs.csv', index= False)
[ "import os\nfrom linkedin_scraper import get_jobs\n\nchrome_driver_path = os.path.join(os.path.abspath(os.getcwd()), 'chromedriver')\n\ndf = get_jobs('Data Scientist', 40, False, chrome_driver_path)\n\ndf.to_csv('linkedin_jobs.csv', index= False)\n\n\n", "import os\nfrom linkedin_scraper import get_jobs\nchrome_d...
false
907
d268f8d563aac28852457f6f130b2fb4ea6269a2
import nltk from nltk import bigrams from lm import * # Oppgave 1: # opretter LM klasse til aa perpleksitere news og adventure m = LM() # Henter news og adventure for videre bruk news=nltk.corpus.brown.sents(categories='news') adventure=nltk.corpus.brown.sents(categories='adventure') # initial parametre perpNews = 0...
[ "import nltk\nfrom nltk import bigrams\nfrom lm import *\n\n# Oppgave 1:\n# opretter LM klasse til aa perpleksitere news og adventure\nm = LM()\n\n# Henter news og adventure for videre bruk\nnews=nltk.corpus.brown.sents(categories='news')\nadventure=nltk.corpus.brown.sents(categories='adventure')\n\n# initial param...
false
908
2f489a87e40bea979000dd429cc4cb0150ff4c3b
from flask import escape import pandas as pd import json import requests with open('result.csv', newline='') as f: df = pd.read_csv(f) def get_level_diff(word, only_common=False): if only_common: word_df = df[(df['word']==word) & (df['common']==1)] else: word_df = df[df['word']==word] ...
[ "from flask import escape\nimport pandas as pd\nimport json\nimport requests\n\nwith open('result.csv', newline='') as f:\n df = pd.read_csv(f)\n\ndef get_level_diff(word, only_common=False):\n if only_common:\n word_df = df[(df['word']==word) & (df['common']==1)]\n else:\n word_df = df[df['w...
false
909
7a65a5522db97a7a113a412883b640feede5bcee
from layout import UIDump import Tkinter from Tkinter import * from ScriptGenerator import ScriptGen class Divide_and_Conquer(): def __init__(self, XY): self.XY = XY self.user_val = 'None' self.flag = 'green' print self.XY def bounds_Compare(self, bounds, filename): """ Compares the bounds with Master...
[ "from layout import UIDump\nimport Tkinter \nfrom Tkinter import *\nfrom ScriptGenerator import ScriptGen\n\nclass Divide_and_Conquer():\n\n\tdef __init__(self, XY):\n\t\tself.XY = XY\n\t\tself.user_val = 'None'\n\t\tself.flag = 'green'\n\n\t\tprint self.XY\n\t\n\tdef bounds_Compare(self, bounds, filename):\n\t\t\"...
true
910
7ce679d5b889493f278de6deca6ec6bdb7acd3f5
#Author: Abeer Rafiq #Modified: 11/23/2019 3:00pm #Importing Packages import socket, sys, time, json, sqlite3 import RPi.GPIO as GPIO from datetime import datetime, date #Creating a global server class class GlobalServer: #The constructor def __init__(self, port, room_ip_addrs, app_ip_addrs):...
[ "#Author: Abeer Rafiq\n#Modified: 11/23/2019 3:00pm\n\n#Importing Packages\nimport socket, sys, time, json, sqlite3\nimport RPi.GPIO as GPIO\nfrom datetime import datetime, date\n\n#Creating a global server class\nclass GlobalServer:\n #The constructor\n def __init__(self, port, room_ip_addrs,\n ...
true
911
08a5a903d3757f8821554aa3649ec2ac2b2995a5
/Users/tanzy/anaconda3/lib/python3.6/_dummy_thread.py
[ "/Users/tanzy/anaconda3/lib/python3.6/_dummy_thread.py" ]
true
912
09d31df9c76975377b44470e1f2ba4a5c4b7bbde
import sys import logging import copy import socket from . import game_map class GameUnix: """ :ivar map: Current map representation :ivar initial_map: The initial version of the map before game starts """ def _send_string(self, s): """ Send data to the game. Call :function:`done_...
[ "import sys\nimport logging\nimport copy\nimport socket\n\nfrom . import game_map\n\nclass GameUnix:\n \"\"\"\n :ivar map: Current map representation\n :ivar initial_map: The initial version of the map before game starts\n \"\"\"\n\n def _send_string(self, s):\n \"\"\"\n Send data to th...
false
913
891588327046e26acb9a691fa8bb9a99420712d6
from django.conf.urls import url, include from django.contrib import admin from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Pastebin API') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^doc_u/', schema_view), url(r'^', include('o.urls', )), url(...
[ "from django.conf.urls import url, include\nfrom django.contrib import admin\n\nfrom rest_framework_swagger.views import get_swagger_view\nschema_view = get_swagger_view(title='Pastebin API')\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^doc_u/', schema_view),\n url(r'^', include('o.urls'...
false
914
a6f3c51d4115a6e0d6f01aa75bf5e6e367840d43
from typing import (Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union, overload) from pccm.stubs import EnumClassValue, EnumValue from cumm.tensorview import Tensor class ConvMainUnitTest: @staticmethod def implicit_gemm(input: Tensor, weight: Tensor, output: Tensor, padding: L...
[ "from typing import (Any, Callable, Dict, List, Optional, Set, Tuple, Type,\n Union, overload)\n\nfrom pccm.stubs import EnumClassValue, EnumValue\n\nfrom cumm.tensorview import Tensor\n\nclass ConvMainUnitTest:\n @staticmethod\n def implicit_gemm(input: Tensor, weight: Tensor, output: Tens...
false
915
0dd361239d85ed485594ac0f5e7e2168f0684544
import pytest import gadget @pytest.mark.parametrize('invalid_line', [ 'beginningGDG::', 'beginning::end', 'nothing', ]) def test_parse_invalid_line(invalid_line): assert gadget.parse_log_line(invalid_line) is None
[ "import pytest\nimport gadget\n\n@pytest.mark.parametrize('invalid_line', [\n 'beginningGDG::',\n 'beginning::end',\n 'nothing',\n])\ndef test_parse_invalid_line(invalid_line):\n assert gadget.parse_log_line(invalid_line) is None\n", "import pytest\nimport gadget\n\n\n@pytest.mark.parametrize('invalid...
false
916
7de19a85a6a05bd2972b11571d5f05219c6beb1a
import os import shutil # root_path = '../from_1691' root_path = 'C:/Users/koyou/Desktop/test' # 실수할 수도 있으므로 dry_run 을 설정해서 로그만 찍을 것인지 # 실제 작동도 진행할 것인지 결정한다. # dry_run = True dry_run = False def move_directory(input_directory_path, output_directory_path): print("moving %s to %s" % (input_directory_path, output_d...
[ "import os\nimport shutil\n\n# root_path = '../from_1691'\nroot_path = 'C:/Users/koyou/Desktop/test'\n\n# 실수할 수도 있으므로 dry_run 을 설정해서 로그만 찍을 것인지\n# 실제 작동도 진행할 것인지 결정한다.\n# dry_run = True\ndry_run = False\n\ndef move_directory(input_directory_path, output_directory_path):\n print(\"moving %s to %s\" % (input_direc...
false
917
c85d7e799a652e82bfaf58e1e8bfa9c4606a8ecb
import ast import datetime from pathlib import Path from typing import Any, Dict import yaml from .lemmatizer import LemmatizerPymorphy2, Preprocessor def get_config(path_to_config: str) -> Dict[str, Any]: """Get config. Args: path_to_config (str): Path to config. Returns: Dict[str, An...
[ "import ast\nimport datetime\nfrom pathlib import Path\nfrom typing import Any, Dict\n\nimport yaml\n\nfrom .lemmatizer import LemmatizerPymorphy2, Preprocessor\n\n\ndef get_config(path_to_config: str) -> Dict[str, Any]:\n \"\"\"Get config.\n\n Args:\n path_to_config (str): Path to config.\n\n Retur...
false
918
73ff1444b5ab1469b616fe449ee6ab93acbbf85a
import time from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtSql import * from PyQt5.QtWidgets import * from qgis.core import QgsFeature, QgsGeometry, QgsProject from shapely import wkb print(__name__) # Function definition def TicTocGenerator(): # Generator that returns time differences ti...
[ "import time\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtSql import *\nfrom PyQt5.QtWidgets import *\nfrom qgis.core import QgsFeature, QgsGeometry, QgsProject\nfrom shapely import wkb\n\nprint(__name__)\n\n\n# Function definition\n\ndef TicTocGenerator():\n # Generator that returns time...
true
919
4d9575c178b672815bb561116689b9b0721cb5ba
# -*- coding: utf-8 -*- """ Created on Thu Jun 25 15:14:15 2020 @author: luisa """ horast = int(input("Horas Trabajadas: "+"\n\t\t")) tarifa = int(input("Tarifa por hora: "+"\n\t\t")) descu = int(input("Descuentos: "+"\n\t\t")) resp0 = horast - descu resp1 = (resp0 * tarifa)/2 resp2 = (horast * tarifa) ...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 25 15:14:15 2020\r\n\r\n@author: luisa\r\n\"\"\"\r\n\r\n\r\nhorast = int(input(\"Horas Trabajadas: \"+\"\\n\\t\\t\"))\r\ntarifa = int(input(\"Tarifa por hora: \"+\"\\n\\t\\t\"))\r\ndescu = int(input(\"Descuentos: \"+\"\\n\\t\\t\"))\r\nresp0 = horast - descu\r...
false
920
8479c70fed36dc6f1e6094c832fb22d8c2e53e3a
import os import time from datetime import datetime, timedelta from git import Repo class CommitAnalyzer(): """ Takes path of the repo """ def __init__(self, repo_path): self.repo_path = repo_path self.repo = Repo(self.repo_path) assert not self.repo.bare def get_conflict_commits(self): conflict_commits...
[ "import os\nimport time\nfrom datetime import datetime, timedelta\nfrom git import Repo\n\nclass CommitAnalyzer():\n\n\t\"\"\"\n\tTakes path of the repo\n\t\"\"\"\n\tdef __init__(self, repo_path):\n\t\tself.repo_path = repo_path\n\t\tself.repo = Repo(self.repo_path)\n\t\tassert not self.repo.bare\n\n\tdef get_confl...
false
921
a41d00c86d0bdab1bced77c275e56c3569af4f4e
from django.apps import AppConfig from django.conf import settings import importlib import importlib.util class RestAdminAppConfig(AppConfig): name = 'libraries.django_rest_admin' verbose_name = 'Rest Admin' loaded = False def ready(self): autodiscover() def autodiscover(): """ Auto...
[ "from django.apps import AppConfig\nfrom django.conf import settings\nimport importlib\nimport importlib.util\n\n\nclass RestAdminAppConfig(AppConfig):\n name = 'libraries.django_rest_admin'\n verbose_name = 'Rest Admin'\n loaded = False\n\n def ready(self):\n autodiscover()\n\n\ndef autodiscover...
false
922
e0435b0b34fc011e7330ab8882865131f7f78882
import pytest import responses from auctioneer import constants, controllers, entities from common.http import UnExpectedResult def test_keywordbid_rule_init(kwb_rule, account): assert kwb_rule.get_max_bid_display() == kwb_rule.max_bid * 1_000_000 assert kwb_rule.get_bid_increase_percentage_display() == kwb_...
[ "import pytest\nimport responses\n\nfrom auctioneer import constants, controllers, entities\nfrom common.http import UnExpectedResult\n\n\ndef test_keywordbid_rule_init(kwb_rule, account):\n assert kwb_rule.get_max_bid_display() == kwb_rule.max_bid * 1_000_000\n assert kwb_rule.get_bid_increase_percentage_dis...
false
923
66904cbe3e57d9cc1ee385cd8a4c1ba3767626bd
#!/usr/bin/env python # -*- coding: utf-8 -*- # sphinx_gallery_thumbnail_number = 3 import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import NullFormatter # useful for `logit` scale import matplotlib.ticker as ticker import matplotlib as mpl mpl.style.use('classic') # Data for plotting ch...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# sphinx_gallery_thumbnail_number = 3\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import NullFormatter # useful for `logit` scale\nimport matplotlib.ticker as ticker\nimport matplotlib as mpl\n\nmpl.style.use('classic')\n\n\n# Data...
false
924
a01ca49c3fa8ea76de2880c1b04bf15ccd341edd
# coding=UTF-8 """ View for managing accounts """ from django.contrib import messages from django.http import Http404, HttpResponse from django.shortcuts import redirect from django import forms from athena.core import render_to_response from athena.users.models import User from athena.users import must_be_admin def...
[ "# coding=UTF-8\n\"\"\"\nView for managing accounts\n\"\"\"\n\nfrom django.contrib import messages\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import redirect\nfrom django import forms\nfrom athena.core import render_to_response\nfrom athena.users.models import User\nfrom athena.users impo...
false
925
9adff5da4e26088def9f0e32aa712a1f2b0336ba
class Step: def __init__(self, action): self.action = action def __str__(self) -> str: return f'Step: {{action: {self.action.__str__()}}}' def __repr__(self) -> str: return f'Step: {{action: {self.action.__str__()}}}'
[ "class Step:\n def __init__(self, action):\n self.action = action\n\n def __str__(self) -> str:\n return f'Step: {{action: {self.action.__str__()}}}'\n\n def __repr__(self) -> str:\n return f'Step: {{action: {self.action.__str__()}}}'\n\n", "class Step:\n\n def __init__(self, acti...
false
926
668a8005f2f66190d588fb9289293d73a608f767
# -*- coding: utf-8-*- import random import re from datetime import datetime, time from phue import Bridge import os import glob WORDS = [] def handle(text, mic, profile): messages1 = ["Naturally Sir ","Of course Sir ","I'll get right at it"] final = random.choice(messages1) mic.say(final) command = "ssh pi@...
[ "# -*- coding: utf-8-*-\nimport random\nimport re\nfrom datetime import datetime, time\nfrom phue import Bridge\nimport os\nimport glob\n\nWORDS = []\n\n\ndef handle(text, mic, profile):\n \n\n\tmessages1 = [\"Naturally Sir \",\"Of course Sir \",\"I'll get right at it\"]\n\tfinal = random.choice(messages1)\n\tmic....
false
927
2257f73a290dfd428a874e963c26e51f1c1f1efa
# -*- coding: utf-8 -*- """The app module, containing the app factory function.""" from flask import Flask, render_template from flask_cors import CORS from flask_misaka import Misaka from flask_mailman import Mail from flask_talisman import Talisman from werkzeug.middleware.proxy_fix import ProxyFix from micawber.pro...
[ "# -*- coding: utf-8 -*-\n\"\"\"The app module, containing the app factory function.\"\"\"\n\nfrom flask import Flask, render_template\nfrom flask_cors import CORS\nfrom flask_misaka import Misaka\nfrom flask_mailman import Mail\nfrom flask_talisman import Talisman\nfrom werkzeug.middleware.proxy_fix import ProxyFi...
false
928
d39e3a552a7c558d3f5b410e0b228fb7409d732a
# -*- coding:utf-8 -*- """ Author:xufei Date:2021/1/21 """
[ "# -*- coding:utf-8 -*-\n\"\"\"\nAuthor:xufei\nDate:2021/1/21\n\"\"\"\n", "<docstring token>\n" ]
false
929
c18c407476375fb1647fefaedb5d7ea0e0aabe3a
import pandas as pd import numpy as np import csv #import nltk #nltk.download('punkt') from nltk.tokenize import sent_tokenize csv_file=open("/home/debajit15/train+dev.csv") pd.set_option('display.max_colwidth', None) df=pd.read_csv(csv_file,sep=','); df = df[pd.notnull(df['Aspects'])] #print(df['Opinion_Words'].iloc[0...
[ "import pandas as pd\nimport numpy as np\nimport csv\n#import nltk\n#nltk.download('punkt')\nfrom nltk.tokenize import sent_tokenize\ncsv_file=open(\"/home/debajit15/train+dev.csv\")\npd.set_option('display.max_colwidth', None)\ndf=pd.read_csv(csv_file,sep=',');\ndf = df[pd.notnull(df['Aspects'])]\n#print(df['Opini...
false
930
74b0ccb5193380ce596313d1ac3f898ff1fdd2f3
from .mail_utils import send_mail from .request_utils import get_host_url
[ "from .mail_utils import send_mail\nfrom .request_utils import get_host_url\n", "<import token>\n" ]
false
931
4e1f7fddb6bd3413dd6a8ca21520d309af75c811
import sys import os sys.path.insert(0, "main") import main workspace = os.path.abspath(sys.argv[1]) main.hammer(workspace)
[ "import sys\nimport os\nsys.path.insert(0, \"main\")\nimport main\nworkspace = os.path.abspath(sys.argv[1])\nmain.hammer(workspace)\n", "import sys\nimport os\nsys.path.insert(0, 'main')\nimport main\nworkspace = os.path.abspath(sys.argv[1])\nmain.hammer(workspace)\n", "<import token>\nsys.path.insert(0, 'main'...
false
932
db1e3a109af2db2c8794a7c9c7dfb0c2ccee5800
#!/usr/bin/python3 """0. How many subs""" def number_of_subscribers(subreddit): """return the number of subscribers from an Reddit API""" import requests resInf = requests.get("https://www.reddit.com/r/{}/about.json" .format(subreddit), headers={"Us...
[ "#!/usr/bin/python3\n\"\"\"0. How many subs\"\"\"\n\ndef number_of_subscribers(subreddit):\n \"\"\"return the number of subscribers from an Reddit API\"\"\"\n\n import requests\n\n resInf = requests.get(\"https://www.reddit.com/r/{}/about.json\"\n .format(subreddit),\n ...
false
933
d20e41dd7054ff133be264bebf13e4e218710ae5
from django.shortcuts import resolve_url as r from django.test import TestCase class coreGetHome(TestCase): def setUp(self): self.resp = self.client.get(r('core:core_home')) def test_template_home(self): self.assertTemplateUsed(self.resp, 'index.html') def test_200_template_home(self): ...
[ "from django.shortcuts import resolve_url as r\nfrom django.test import TestCase\n\n\nclass coreGetHome(TestCase):\n def setUp(self):\n self.resp = self.client.get(r('core:core_home'))\n\n def test_template_home(self):\n self.assertTemplateUsed(self.resp, 'index.html')\n\n def test_200_templa...
false
934
ff7a865822a4f8b343ab4cb490c24d6d530b14e1
#!/usr/bin/env python kube_description= \ """ Compute Server """ kube_instruction= \ """ Not instructions yet """ # # Standard geni-lib/portal libraries # import geni.portal as portal import geni.rspec.pg as PG import geni.rspec.emulab as elab import geni.rspec.igext as IG import geni.urn as URN # # PhantomNet ext...
[ "#!/usr/bin/env python\n\nkube_description= \\\n\"\"\"\nCompute Server\n\"\"\"\nkube_instruction= \\\n\"\"\"\nNot instructions yet\n\"\"\"\n\n#\n# Standard geni-lib/portal libraries\n#\nimport geni.portal as portal\nimport geni.rspec.pg as PG\nimport geni.rspec.emulab as elab\nimport geni.rspec.igext as IG\nimport ...
false
935
a93884757069393b4d96de5ec9c7d815d58a2ea5
# coding: utf-8 import logging import uuid import json import xmltodict import bottle from bottle import HTTPError from bottle.ext import sqlalchemy from database import Base, engine from database import JdWaybillSendResp, JdWaybillApplyResp jd = bottle.Bottle(catchall=False) plugin = sqlalchemy.Plugin( engine, ...
[ "# coding: utf-8\nimport logging\nimport uuid\nimport json\nimport xmltodict\nimport bottle\nfrom bottle import HTTPError\nfrom bottle.ext import sqlalchemy\nfrom database import Base, engine\nfrom database import JdWaybillSendResp, JdWaybillApplyResp\n\njd = bottle.Bottle(catchall=False)\n\nplugin = sqlalchemy.Plu...
false
936
0cc1aaa182fcf002ff2ae6cbcd6cbb84a08a3bc1
# Basic script which send some request via rest api to the test-management-tool. # Be sure you setup host and api_token variable import http.client host = "localhost:8000" api_token = "fuukp8LhdxxwoVdtJu5K8LQtpTods8ddLMq66wSUFXGsqJKpmJAa1YyqkHN3" # Connection conn = http.client.HTTPConnection(host) # Create a heade...
[ "# Basic script which send some request via rest api to the test-management-tool.\n# Be sure you setup host and api_token variable\n\nimport http.client\n\nhost = \"localhost:8000\"\napi_token = \"fuukp8LhdxxwoVdtJu5K8LQtpTods8ddLMq66wSUFXGsqJKpmJAa1YyqkHN3\"\n\n# Connection\nconn = http.client.HTTPConnection(host)...
false
937
5bd8cee2595215fda6ab523a646cf918e3d84a50
from django.urls import path,include from.import views from user.views import DetailsChangeView, HomeView, PasswordChangeView,SignUpView,LoginView,SettingsView,LogoutView,CreatePostView,CommentPostView,PasswordChangeView urlpatterns = [ path('', HomeView.as_view(), name = 'HomeView'), path('LoginView/', LoginV...
[ "from django.urls import path,include\nfrom.import views\nfrom user.views import DetailsChangeView, HomeView, PasswordChangeView,SignUpView,LoginView,SettingsView,LogoutView,CreatePostView,CommentPostView,PasswordChangeView\n\nurlpatterns = [\n path('', HomeView.as_view(), name = 'HomeView'),\n path('LoginVie...
false
938
18dce1ce683b15201dbb5436cbd4288a0df99c28
from const import BORN_KEY, PRESIDENT_KEY, CAPITAL_KEY, PRIME_KEY, MINISTER_KEY, POPULATION_KEY, \ GOVERNMENT_KEY,AREA_KEY, WHO_KEY, IS_KEY, THE_KEY, OF_KEY, WHAT_KEY, WHEN_KEY, WAS_KEY from geq_queries import capital_of_country_query, area_of_country_query, government_of_country_query, \ population_of_country...
[ "from const import BORN_KEY, PRESIDENT_KEY, CAPITAL_KEY, PRIME_KEY, MINISTER_KEY, POPULATION_KEY, \\\n GOVERNMENT_KEY,AREA_KEY, WHO_KEY, IS_KEY, THE_KEY, OF_KEY, WHAT_KEY, WHEN_KEY, WAS_KEY\n\nfrom geq_queries import capital_of_country_query, area_of_country_query, government_of_country_query, \\\n population...
false
939
1968923cd923e68dc5ff2148802f18e40a5e6c33
''' Created on Nov 16, 2013 @author: mo ''' import unittest from Board import TicTacToe_Board from ComputerPlayer import ComputerPlayer from utils import debug_print as d_pr from main import StartNewGame class Test(unittest.TestCase): def setUp(self): self.the_board = TicTacToe_Board() de...
[ "'''\nCreated on Nov 16, 2013\n\n@author: mo\n'''\nimport unittest\nfrom Board import TicTacToe_Board\nfrom ComputerPlayer import ComputerPlayer\nfrom utils import debug_print as d_pr\n\nfrom main import StartNewGame\n\nclass Test(unittest.TestCase):\n\n\n def setUp(self):\n self.the_board = TicTacToe_Boa...
false
940
8e629ee53f11e29aa026763508d13b06f6ced5ba
# -*- coding:utf-8 -*- __author__ = 'yangxin_ryan' """ Solutions: 题目要求非递归的中序遍历, 中序遍历的意思其实就是先遍历左孩子、然后是根结点、最后是右孩子。我们按照这个逻辑,应该先循环到root的最左孩子, 然后依次出栈,然后将结果放入结果集合result,然后是根的val,然后右孩子。 """ class BinaryTreeInorderTraversal(object): def inorderTraversal(self, root: TreeNode) -> List[int]: result = list() ...
[ "# -*- coding:utf-8 -*-\n__author__ = 'yangxin_ryan'\n\"\"\"\nSolutions:\n题目要求非递归的中序遍历,\n中序遍历的意思其实就是先遍历左孩子、然后是根结点、最后是右孩子。我们按照这个逻辑,应该先循环到root的最左孩子,\n然后依次出栈,然后将结果放入结果集合result,然后是根的val,然后右孩子。\n\"\"\"\n\n\nclass BinaryTreeInorderTraversal(object):\n\n def inorderTraversal(self, root: TreeNode) -> List[int]:\n ...
false
941
bc837d95ef22bd376f8b095e7aeb1f7d15c0e22e
"""Write a program that asks the user to enter a word and then capitalizes every other letter of that word. So if the user enters "rhinoceros", the program should print "rHiNoCeRoS""" word=str(input("please enter the word\n")) count=0 for char in word: if count==0: print(char.upper(),end="") count=1 ...
[ "\"\"\"Write a program that asks the user to enter a word and then\ncapitalizes every other letter of that word. So if the user enters \"rhinoceros\",\nthe program should print \"rHiNoCeRoS\"\"\"\n\nword=str(input(\"please enter the word\\n\"))\ncount=0\nfor char in word:\n if count==0:\n print(char.upper(),...
false
942
da34eb25ec08c8311fa839a0cdcd164eff036a5d
import bnn #get #!wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz #!wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz #unzip #!gzip -d t10k-images-idx3-ubyte.gz #!gzip -d t10k-labels-idx1-ubyte.gz #read labels print("Reading labels") labels = [] with open("/home/xilinx/jupyter_notebooks/...
[ "import bnn\n\n#get\n#!wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz\n#!wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz\n#unzip\n#!gzip -d t10k-images-idx3-ubyte.gz\n#!gzip -d t10k-labels-idx1-ubyte.gz\n\n#read labels\nprint(\"Reading labels\")\nlabels = []\nwith open(\"/home/xilin...
false
943
04b5df5cfd052390f057c6f13b2e21d27bac6449
""" This example shows how to communicate with a SH05 (shutter) connected to a KSC101 (KCube Solenoid). """ # this "if" statement is used so that Sphinx does not execute this script when the docs are being built if __name__ == '__main__': import os import time from msl.equipment import EquipmentRecord, Co...
[ "\"\"\"\nThis example shows how to communicate with a SH05 (shutter) connected to a KSC101 (KCube Solenoid).\n\"\"\"\n\n# this \"if\" statement is used so that Sphinx does not execute this script when the docs are being built\nif __name__ == '__main__':\n import os\n import time\n\n from msl.equipment impo...
false
944
11f29508d52e856f4751a5dc8911a1f1c9832374
def test(d_iter): from cqlengine import columns from cqlengine.models import Model from cqlengine.query import ModelQuerySet from cqlengine import connection from cqlengine.management import sync_table from urllib2 import urlopen, Request from pyspark.sql import S...
[ "def test(d_iter):\n from cqlengine import columns\n from cqlengine.models import Model\n from cqlengine.query import ModelQuerySet\n from cqlengine import connection\n from cqlengine.management import sync_table\n from urllib2 import urlopen, Request\n from pyspark....
false
945
71cdddfdd7c1327a8a77808dbdd0ff98d827231f
from flask.ext.restful import Resource, abort from flask_login import current_user, login_required from peewee import DoesNotExist from redash.authentication.org_resolving import current_org from redash.tasks import record_event class BaseResource(Resource): decorators = [login_required] def __init__(self, ...
[ "from flask.ext.restful import Resource, abort\nfrom flask_login import current_user, login_required\nfrom peewee import DoesNotExist\n\nfrom redash.authentication.org_resolving import current_org\nfrom redash.tasks import record_event\n\n\nclass BaseResource(Resource):\n decorators = [login_required]\n\n def...
false
946
0b3f16ee9b287c6c77acde674abec9deb4053c83
import tensorflow as tf import keras import numpy as np def house_model(y_new): xs = np.array([0, 1, 2, 4, 6, 8, 10], dtype=float) # Your Code Here# ys = np.array([0.50, 0.100, 1.50, 2.50, 3.50, 4.50, 5.50], dtype=float) # Your Code Here# model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape...
[ "import tensorflow as tf\nimport keras\nimport numpy as np\n\ndef house_model(y_new):\n xs = np.array([0, 1, 2, 4, 6, 8, 10], dtype=float) # Your Code Here#\n ys = np.array([0.50, 0.100, 1.50, 2.50, 3.50, 4.50, 5.50], dtype=float) # Your Code Here#\n model = tf.keras.Sequential([keras.layers.Dense(units=1,...
false
947
1754bce54a47cb78dce3b545d3dce835a4e0e69f
#!/usr/bin/env python # coding: utf-8 import logging import config def get_common_logger(name='common', logfile=None): ''' args: name (str): logger name logfile (str): log file, use stream handler (stdout) as default. return: logger obj ''' my_logger = logging.getLogger(name) ...
[ "#!/usr/bin/env python\n# coding: utf-8\n\nimport logging\n\nimport config\n\n\ndef get_common_logger(name='common', logfile=None):\n '''\n args: name (str): logger name\n logfile (str): log file, use stream handler (stdout) as default.\n return:\n logger obj\n '''\n my_logger = logging...
false
948
6affc182f5d3353d46f6e9a21344bc85bf894165
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() # pylint: disable=dangerous-default-value,wrong-import-position,unused-import, import-outside-toplevel def create_app(settings_override={}): app = Flask(__name__) app.config.from_object('zezin.settings.Configuration') app.c...
[ "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\n\n# pylint: disable=dangerous-default-value,wrong-import-position,unused-import, import-outside-toplevel\ndef create_app(settings_override={}):\n app = Flask(__name__)\n app.config.from_object('zezin.settings.Configurati...
false
949
9abf2b9b90d18332ede94cf1af778e0dda54330b
# Stubs for docutils.parsers.rst.directives.tables (Python 3.6) # # NOTE: This dynamically typed stub was automatically generated by stubgen. import csv from docutils.statemachine import StringList from docutils.nodes import Node, system_message, table, title from docutils.parsers.rst import Directive from typing impo...
[ "# Stubs for docutils.parsers.rst.directives.tables (Python 3.6)\n#\n# NOTE: This dynamically typed stub was automatically generated by stubgen.\n\nimport csv\nfrom docutils.statemachine import StringList\nfrom docutils.nodes import Node, system_message, table, title\nfrom docutils.parsers.rst import Directive\nfro...
false
950
94e8f0532da76c803b23fe2217b07dc8cf285710
# -*- coding: utf-8 -*- """ Created on Mon May 27 17:38:50 2019 @author: User """ import numpy as np import pandas as pd dataset = pd.read_csv('University_data.csv') print(dataset.info()) features = dataset.iloc[:, :-1].values labels = dataset.iloc[:, -1:].values from sklearn.preprocessing import LabelEncoder la...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 27 17:38:50 2019\n\n@author: User\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\ndataset = pd.read_csv('University_data.csv') \nprint(dataset.info())\nfeatures = dataset.iloc[:, :-1].values \nlabels = dataset.iloc[:, -1:].values \nfrom sklearn.preprocessin...
false
951
f5d353694a719472320f4d6fa28bc9d2cc5a69b0
# -*- coding: utf-8 -*- """ This is the very first A.I. in this series. The vision is to devlop 'protocol droid' to talk to, to help with tasks, and with whom to play games. The droid will be able to translate langages and connect ppl. """ import speech_recognition as sr import pyttsx3 import pywhatkit ...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis is the very first A.I. in this series. \r\nThe vision is to devlop 'protocol droid' to talk to, to help with tasks, and with whom to play games.\r\nThe droid will be able to translate langages and connect ppl.\r\n\r\n\r\n\"\"\"\r\n\r\nimport speech_recognition as sr\r\nim...
false
952
27a12a0f5ea6120036b66ee1cdd903da868a037f
# coding=utf-8 import base64 from sandcrawler.scraper import ScraperBase, SimpleScraperBase class Hdmovie14Ag(SimpleScraperBase): BASE_URL = 'http://www1.solarmovie.net' OTHER_URLS = ['http://solarmovie.net', 'http://hdmovie14.ag'] SCRAPER_TYPES = [ ScraperBase.SCRAPER_TYPE_OSP, ] LANGUAGE = 'eng' ...
[ "# coding=utf-8\nimport base64\nfrom sandcrawler.scraper import ScraperBase, SimpleScraperBase\n\nclass Hdmovie14Ag(SimpleScraperBase):\n BASE_URL = 'http://www1.solarmovie.net'\n OTHER_URLS = ['http://solarmovie.net', 'http://hdmovie14.ag']\n SCRAPER_TYPES = [ ScraperBase.SCRAPER_TYPE_OSP, ]\n LANGUAGE...
false
953
aba2a0a262c14f286c278f21ba42871410c174f0
from django.shortcuts import render from django.shortcuts import redirect # Create your views here. from .forms import AddBookForm ,UpdateBookForm,BookCreateModelForm,SearchForm,RegistrationForm,SignInForm from book.models import Books from django.contrib.auth import authenticate,login,logout def book_add(reques...
[ "from django.shortcuts import render\nfrom django.shortcuts import redirect\n\n\n\n# Create your views here.\nfrom .forms import AddBookForm ,UpdateBookForm,BookCreateModelForm,SearchForm,RegistrationForm,SignInForm\nfrom book.models import Books\nfrom django.contrib.auth import authenticate,login,logout\n\n\n\nde...
false
954
d5903698eb8ed6be531b0cc522d4feff6b79da4e
import argparse import pandas as pd import random import time class Deck: def __init__(self, num_cols, front, back): self.flashcards = [] self.num_cols = num_cols self.front = front self.back = back class Flashcard: def __init__(self, deck, front, back, column, row): self.deck = deck self.front = front ...
[ "import argparse\nimport pandas as pd\nimport random\nimport time\n\nclass Deck:\n\tdef __init__(self, num_cols, front, back):\n\t\tself.flashcards = []\n\t\tself.num_cols = num_cols\n\t\tself.front = front\n\t\tself.back = back\n\nclass Flashcard:\n\tdef __init__(self, deck, front, back, column, row):\n\t\tself.de...
false
955
48291ab3deb1ca1ba672d3e642d55635a7270171
import serial from settings import * class CommunicationController: def __init__(self): global board board = serial.Serial(ROBOT_SERIAL, BAUDRATE, serial.EIGHTBITS, timeout=0) self.count = 0 print("Communication controller") def sendCommand(self, right, back, left): self...
[ "import serial\nfrom settings import *\nclass CommunicationController:\n def __init__(self):\n global board\n board = serial.Serial(ROBOT_SERIAL, BAUDRATE, serial.EIGHTBITS, timeout=0)\n self.count = 0\n print(\"Communication controller\")\n\n def sendCommand(self, right, back, lef...
false
956
d7b0ff6549d854d21ad1d2d0f5a9e7f75f4ac1d5
from django.test import TestCase from recruitmentapp.apps.core.models import Competence class CompetenceTest(TestCase): def setUp(self): self.competence = Competence.objects.create(name='mining') self.competence.set_current_language('sv') self.competence.name = 'gruvarbete' self.c...
[ "from django.test import TestCase\n\nfrom recruitmentapp.apps.core.models import Competence\n\n\nclass CompetenceTest(TestCase):\n def setUp(self):\n self.competence = Competence.objects.create(name='mining')\n self.competence.set_current_language('sv')\n self.competence.name = 'gruvarbete'\...
false
957
8457cdde8f8ad069505c7729b8217e5d272be41e
from apps.mastermind.core.domain.domain import Color, Game from apps.mastermind.infrastructure.mongo_persistence.uow import MongoUnitOfWork from composite_root.container import provide class GameMother: async def a_game( self, num_slots: int, num_colors: int, max_guesses: int, ...
[ "from apps.mastermind.core.domain.domain import Color, Game\nfrom apps.mastermind.infrastructure.mongo_persistence.uow import MongoUnitOfWork\nfrom composite_root.container import provide\n\n\nclass GameMother:\n async def a_game(\n self,\n num_slots: int,\n num_colors: int,\n max_gue...
false
958
690e7cc9047b3a445bf330524df52e2b359f1f13
AuthorPath = 'data/Author.csv' PaperPath = 'buff/Paper.TitleCut.csv' PaperAuthorPath = 'data/PaperAuthor.csv' AffilListPath = 'buff/AffilList2.csv' StopwordPath='InternalData/en.lst'
[ "AuthorPath = 'data/Author.csv'\r\nPaperPath = 'buff/Paper.TitleCut.csv'\r\nPaperAuthorPath = 'data/PaperAuthor.csv'\r\nAffilListPath = 'buff/AffilList2.csv'\r\nStopwordPath='InternalData/en.lst'\r\n\r\n", "AuthorPath = 'data/Author.csv'\nPaperPath = 'buff/Paper.TitleCut.csv'\nPaperAuthorPath = 'data/PaperAuthor....
false
959
7a9515b1f8cc196eb7551137a1418d5a387e7fd3
import pandas as pd import numpy as np import difflib as dl import sys def get_close(x): if len(x) == 0: return "" return x[0] list_file = sys.argv[1] rating_file = sys.argv[2] output_file = sys.argv[3] movie_list = open(list_file).read().splitlines() movie_data = pd.DataFrame({'movie': movie_list}) rating_data ...
[ "import pandas as pd\nimport numpy as np\nimport difflib as dl\nimport sys\n\ndef get_close(x):\n\tif len(x) == 0:\n\t\treturn \"\"\n\treturn x[0]\n\nlist_file = sys.argv[1]\nrating_file = sys.argv[2]\noutput_file = sys.argv[3]\n\nmovie_list = open(list_file).read().splitlines()\nmovie_data = pd.DataFrame({'movie':...
false
960
19aad7d45416e311530aa2ce3e854cf1f65d18f5
import multiprocessing import time def foo(): time.sleep(0.1) p = multiprocessing.Process(target=foo) p.start() print("process running: ", p, p.is_alive()) p.terminate() print("process running: ", p, p.is_alive()) p.join() print("process running: ", p, p.is_alive()) print("process exit code:", p.exitcode)
[ "import multiprocessing\nimport time\n\n\ndef foo():\n time.sleep(0.1)\n\n\np = multiprocessing.Process(target=foo)\np.start()\nprint(\"process running: \", p, p.is_alive())\np.terminate()\nprint(\"process running: \", p, p.is_alive())\np.join()\nprint(\"process running: \", p, p.is_alive())\nprint(\"process exi...
false
961
623bd858923d5f9cc109af586fdda01cd3d5fff3
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Length, EqualTo, ValidationError from passlib.hash import pbkdf2_sha256 from models import User def invalid_credentials(form, field): ''' Username and password checker ''' userna...
[ "from flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, SubmitField\nfrom wtforms.validators import InputRequired, Length, EqualTo, ValidationError\nfrom passlib.hash import pbkdf2_sha256\nfrom models import User\n\ndef invalid_credentials(form, field):\n\t''' Username and password checker...
false
962
9abc5f18e2eb07afe6bc31d6bd27298350707d1d
""" 爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。 因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。) 返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。 如果有多个答案,你可以返回其中任何一个。保证答案存在。 """ def fairCandySwap(A, B): sumA, sumB = sum(A), sum(B) setA, setB = set(A), se...
[ "\"\"\"\n爱丽丝和鲍勃有不同大小的糖果棒:A[i] 是爱丽丝拥有的第 i 根糖果棒的大小,B[j] 是鲍勃拥有的第 j 根糖果棒的大小。\n\n因为他们是朋友,所以他们想交换一根糖果棒,这样交换后,他们都有相同的糖果总量。(一个人拥有的糖果总量是他们拥有的糖果棒大小的总和。)\n\n返回一个整数数组 ans,其中 ans[0] 是爱丽丝必须交换的糖果棒的大小,ans[1] 是 Bob 必须交换的糖果棒的大小。\n\n如果有多个答案,你可以返回其中任何一个。保证答案存在。\n\"\"\"\n\ndef fairCandySwap(A, B):\n sumA, sumB = sum(A), sum(B)\n ...
false
963
6f698196e9391d73bd99cda0a098a5bf7a3832ff
from turtle import * while True: n=input("Right or left? ") if n == 'right': right(60) forward(100) elif n == 'left': left(60) forward(100)
[ "from turtle import *\nwhile True:\n n=input(\"Right or left? \")\n\n if n == 'right':\n right(60)\n forward(100)\n elif n == 'left':\n left(60)\n forward(100)\n", "from turtle import *\nwhile True:\n n = input('Right or left? ')\n if n == 'right':\n right(60)\n forward(100)\n e...
false
964
b4d412e8b45722a855a16dd64b7bce9b303d0ffe
from collections import defaultdict class Graph: def __init__(self): self._graph = defaultdict(list) self._odd_vertices = [] def add_vertex(self, v): if not v in self._graph: self._graph[v] = list() def add_edge(self, v1, v2): self._graph[v1].append(v2) ...
[ "from collections import defaultdict\n\nclass Graph:\n def __init__(self):\n self._graph = defaultdict(list)\n self._odd_vertices = []\n\n def add_vertex(self, v):\n if not v in self._graph:\n self._graph[v] = list()\n\n def add_edge(self, v1, v2):\n self._graph[v1].a...
false
965
bab78e8a88f9a26cc13fe0c301f82880cee2b680
from django.contrib import admin from .models import Predictions @admin.register(Predictions) class PredictionsAdmin(admin.ModelAdmin): pass
[ "from django.contrib import admin\nfrom .models import Predictions\n\n\n@admin.register(Predictions)\nclass PredictionsAdmin(admin.ModelAdmin):\n pass\n", "<import token>\n\n\n@admin.register(Predictions)\nclass PredictionsAdmin(admin.ModelAdmin):\n pass\n", "<import token>\n<class token>\n" ]
false
966
fd450b5454b65ed69b411028788c587f9674760c
#!/usr/bin/env python """ Script that generates the photon efficiency curves and stores them in a root file. For the moment only the pT curves for the different eta bins are created """ import re import json import ROOT as r r.PyConfig.IgnoreCommandLineOptions = True import numpy as np import sympy as sp from utils...
[ "#!/usr/bin/env python\n\"\"\"\nScript that generates the photon efficiency curves and stores them in a root\nfile.\n\nFor the moment only the pT curves for the different eta bins are created\n\"\"\"\n\nimport re\nimport json\nimport ROOT as r\nr.PyConfig.IgnoreCommandLineOptions = True\n\nimport numpy as np\nimpor...
false
967
176ffac7ad47f5c43a24acc664631f8353ec5100
import matplotlib.pyplot as plt import numpy as np steps = 10 num_tests = 100 res = [] with open('txt.txt', 'r') as f: data = f.readlines() line = 0 for i in range(10, 110, 10): agg = 0 for j in range(num_tests): agg += int(data[line]) line += 1 res.append(...
[ "import matplotlib.pyplot as plt\nimport numpy as np\n\nsteps = 10\nnum_tests = 100\n\nres = []\n\nwith open('txt.txt', 'r') as f:\n data = f.readlines()\n line = 0\n for i in range(10, 110, 10):\n agg = 0\n for j in range(num_tests):\n agg += int(data[line])\n line += 1...
false
968
b3d26d01d45c073192d06c8e94c06f7eae267b14
old_file = open("new.csv", "r") new_file = open("new1,csv", "w") for line in old_file.readlines(): cleaned_line =line.replace(',','.') new_file.write(cleaned_line) old_file.close new_file.close
[ "old_file = open(\"new.csv\", \"r\")\nnew_file = open(\"new1,csv\", \"w\")\nfor line in old_file.readlines():\n cleaned_line =line.replace(',','.')\n new_file.write(cleaned_line)\nold_file.close\nnew_file.close", "old_file = open('new.csv', 'r')\nnew_file = open('new1,csv', 'w')\nfor line in old_file.readli...
false
969
aa13278a4686e9bab7948c2f212f87f9bd6eee00
import socket END = bytearray() END.append(255) print(END[0]) def recvall(sock): # Odbiór danych BUFF_SIZE = 4096 # 4 KiB data = b'' while True: # odbieramy dane, pakiety 4KiB part = sock.recv(BUFF_SIZE) data += part if len(part) < BUFF_SIZE: # 0 lub koniec danych ...
[ "import socket\n\nEND = bytearray()\nEND.append(255)\nprint(END[0])\n\n\ndef recvall(sock): # Odbiór danych\n BUFF_SIZE = 4096 # 4 KiB\n data = b''\n while True: # odbieramy dane, pakiety 4KiB\n part = sock.recv(BUFF_SIZE)\n data += part\n if len(part) < BUFF_SIZE:\n # 0 ...
false
970
736fee6f9a46b8568b2dd217b81d54d689306630
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import numpy as np import datetime import time from sys import exit from matplotlib import colors, pyplot as plt from functools import reduce import matplotlib.cm as cm import seaborn as sns from astropy.io import ascii, fits from astropy.wcs import wcs fr...
[ "\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport time\nfrom sys import exit\nfrom matplotlib import colors, pyplot as plt\nfrom functools import reduce\nimport matplotlib.cm as cm\nimport seaborn as sns\nfrom astropy.io import ascii, fits\nfrom astrop...
false
971
dbe3aa107de8e62822803d1740773a4b22f41edf
import sys, os sys.path.append(os.pardir) import numpy as np from dataset.mnist import load_mnist from two_layer_net import TwoLayerNet (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label = True) train_loss_list = [] #hiper param iters_num = 1000 train_size = x_train.shape[0] batch_size =...
[ "import sys, os\nsys.path.append(os.pardir)\nimport numpy as np\nfrom dataset.mnist import load_mnist\nfrom two_layer_net import TwoLayerNet\n\n(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label = True)\n\ntrain_loss_list = []\n\n#hiper param\niters_num = 1000\ntrain_size = x_train.shap...
false
972
3f9be81c86852a758440c6a144b8caba736b3868
# Generated by Django 3.1.7 on 2021-02-20 02:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('usuarios', '0001_initial'), ('plataforma', '0005_auto_20210219_2343'), ] operations = [ migrations....
[ "# Generated by Django 3.1.7 on 2021-02-20 02:52\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('usuarios', '0001_initial'),\n ('plataforma', '0005_auto_20210219_2343'),\n ]\n\n operations = [\n...
false
973
e06b740f27e41b9f120c962fd76a38a29d54af3c
from more_itertools import ilen from my.body import weight, shower, food, water def test_body() -> None: for func in (weight, shower, food, water): assert ilen(func()) >= 1
[ "from more_itertools import ilen\n\nfrom my.body import weight, shower, food, water\n\n\ndef test_body() -> None:\n\n for func in (weight, shower, food, water):\n assert ilen(func()) >= 1\n", "from more_itertools import ilen\nfrom my.body import weight, shower, food, water\n\n\ndef test_body() ->None:\n...
false
974
1fd4d1a44270ef29512e601af737accb916dc441
from estmd import ESTMD input_directory = "test.avi" e = ESTMD() e.open_movie(input_directory) e.run(by_frame=True) r = e.create_list_of_arrays() print "Done testing!"
[ "from estmd import ESTMD\n\ninput_directory = \"test.avi\"\ne = ESTMD()\ne.open_movie(input_directory)\ne.run(by_frame=True)\nr = e.create_list_of_arrays()\n\nprint \"Done testing!\"\n" ]
true
975
c7c412fe4e2d53af1b4f2a55bd3453496767890d
from time import sleep import pytest import allure from app.debug_api import DebugAPI from app.check_api import HandlersAPI from locators.movies_details_locators import MoviesDetailsPageLocators from locators.movies_locators import MoviesPageLocators from locators.shedule_locators import ShedulePageLocators from scree...
[ "from time import sleep\nimport pytest\nimport allure\n\nfrom app.debug_api import DebugAPI\nfrom app.check_api import HandlersAPI\nfrom locators.movies_details_locators import MoviesDetailsPageLocators\nfrom locators.movies_locators import MoviesPageLocators\nfrom locators.shedule_locators import ShedulePageLocato...
false
976
327371d373819273a2f77f63e0cedee6950dbc46
#!/usr/bin/env python """ ############################################################################## Software Package Risk Analysis Development Environment Specific Work Book View ############################################################################## """ # -*- coding: utf-8 -*- # # rtk.softw...
[ "#!/usr/bin/env python\r\n\"\"\"\r\n##############################################################################\r\nSoftware Package Risk Analysis Development Environment Specific Work Book View\r\n##############################################################################\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 ...
false
977
136215a3ba99f74160373181c458db9bec4bb6b7
#PortableKanban 4.3.6578.38136 - Encrypted Password Retrieval #Python3 -m pip install des #or #pip install des import json import base64 from des import * #python3 -m pip install des, pip install des import sys def decode(hash): hash = base64.b64decode(hash.encode('utf-8')) key = DesKey(b"7ly6UznJ") r...
[ "#PortableKanban 4.3.6578.38136 - Encrypted Password Retrieval\r\n#Python3 -m pip install des\r\n#or\r\n#pip install des\r\n\r\nimport json\r\nimport base64\r\nfrom des import * #python3 -m pip install des, pip install des\r\nimport sys\r\n\r\ndef decode(hash):\r\n\thash = base64.b64decode(hash.encode('utf-8'))\r\n...
false
978
cc46485a3b5c68e4f77a2f9a033fd2ee2859b52b
from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split import pandas as pd import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import cross_val_score iris_dataset=load_iris() X=iris_dataset['data'] y=iris_dataset['target'] X_tra...
[ "\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.model_selection import train_test_split\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.datasets import load_iris\r\nfrom sklearn.model_selection import cross_val_score\r\niris_dataset=load_iris()\r\nX=iris_dataset['data']\r\ny=iris_d...
false
979
ce98c13555c474de0a9cb12e99a97b2316312b00
yuki = list(map(int, input().split())) S = input() enemy = [S.count('G'), S.count('C'), S.count('P')] ans = 0 for i in range(3): ans += min(yuki[i], enemy[(i+1)%3]) * 3 yuki[i], enemy[(i+1)%3] = max(0, yuki[i]-enemy[(i+1)%3]), max(0, enemy[(i+1)%3]-yuki[i]) for i in range(3): ans += min(yuki[i], enemy[i]) ...
[ "yuki = list(map(int, input().split()))\nS = input()\nenemy = [S.count('G'), S.count('C'), S.count('P')]\nans = 0\nfor i in range(3):\n ans += min(yuki[i], enemy[(i+1)%3]) * 3\n yuki[i], enemy[(i+1)%3] = max(0, yuki[i]-enemy[(i+1)%3]), max(0, enemy[(i+1)%3]-yuki[i])\n\nfor i in range(3):\n ans += min(yuki[...
false
980
3f3ed0165120dc135a4ce1f282dbdf9dad57adf8
# coding: UTF-8 -*- import os.path PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) EMOTICONS = { "O:)": "angel", "o:)": "angel", "O:-)": "angel", "o:-)": "angel", "o:-3": "angel", "o:3": "angel", "O;^)": "angel", ">:[": "annoyed/disappointed", ":-(": "annoyed/disappointed...
[ "# coding: UTF-8 -*-\nimport os.path\n\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\n\nEMOTICONS = {\n \"O:)\": \"angel\",\n \"o:)\": \"angel\",\n \"O:-)\": \"angel\",\n \"o:-)\": \"angel\",\n \"o:-3\": \"angel\",\n \"o:3\": \"angel\",\n \"O;^)\": \"angel\",\n \">:[\": \"annoye...
false
981
3cc894570189fe545f5db3150d0b69c16dc211dc
class player: def __init__(self, name: str, symbol: str): self._name = name self._symbol = symbol def decide_next_move(self): """ Checks all possible combinations to decide best next move :return: board position """ pass def get_next_move(self): ...
[ "\nclass player:\n\n def __init__(self, name: str, symbol: str):\n self._name = name\n self._symbol = symbol\n\n def decide_next_move(self):\n \"\"\"\n Checks all possible combinations to decide best next move\n :return: board position\n \"\"\"\n pass\n\n de...
false
982
3f8b8b8cfbe712f09734d0fb7302073187d65a73
''' def Sort(a): i=1 while i<len(a): j=i while j>0 and a[j-1] > a[j]: temp = a[j-1] a[j-1] = a[j] a[j] = temp j-=1 i+=1 return a ''' def Sort(a): i=1 n=len(a) while i<len(a): j=i print(i-1,'\t',i) whi...
[ "'''\ndef Sort(a):\n i=1\n while i<len(a):\n j=i\n while j>0 and a[j-1] > a[j]:\n temp = a[j-1]\n a[j-1] = a[j]\n a[j] = temp\n j-=1\n i+=1\n return a\n'''\ndef Sort(a):\n i=1\n n=len(a)\n while i<len(a):\n j=i\n print(...
false
983
e95de58828c63dc8ae24efff314665a308f6ce0c
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-13 02:06 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('stores', '0001_initial'), ...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.7 on 2017-12-13 02:06\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('stores',...
false
984
a406efcab62b2af67484da776f01fc4e6d20b697
#!/usr/bin/env python3 def twoNumberSum(array, targetSum): # Write your code here. # O(n^2) time | O(1) space ''' Double for loop, quadratic run time No variables increase as the input size increases, therefore constant space complexity. ''' for i in range(len(array) - 1): firstNu...
[ "#!/usr/bin/env python3\n\ndef twoNumberSum(array, targetSum):\n # Write your code here.\n\n # O(n^2) time | O(1) space\n ''' Double for loop, quadratic run time\n No variables increase as the input size increases,\n therefore constant space complexity.\n '''\n for i in range(len(array)...
true
985
d265781c6b618752a1afcf65ac137052c26388a6
import xarray as xr import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle import seaborn as sns %load_ext autoreload %autoreload 2 %matplotlib data_dir = Path('/Volumes/Lees_Extend/data/ecmwf_sowc/data/') # READ in model (maybe want to do more predictions on historical data) from src.m...
[ "import xarray as xr\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nimport seaborn as sns\n\n%load_ext autoreload\n%autoreload 2\n%matplotlib\n\ndata_dir = Path('/Volumes/Lees_Extend/data/ecmwf_sowc/data/')\n\n# READ in model (maybe want to do more predictions on historica...
true
986
15edb1c051ccbc6f927c0a859288511f94a3d853
from types import MappingProxyType from typing import Any, Dict, Mapping, Type, TypeVar, Union import yaml from typing_extensions import Protocol from mashumaro.serializer.base import DataClassDictMixin DEFAULT_DICT_PARAMS = { "use_bytes": False, "use_enum": False, "use_datetime": False, } EncodedData = ...
[ "from types import MappingProxyType\nfrom typing import Any, Dict, Mapping, Type, TypeVar, Union\n\nimport yaml\nfrom typing_extensions import Protocol\n\nfrom mashumaro.serializer.base import DataClassDictMixin\n\nDEFAULT_DICT_PARAMS = {\n \"use_bytes\": False,\n \"use_enum\": False,\n \"use_datetime\": F...
false
987
274185896ab5c11256d69699df69fc2c0dde4f2d
''' extract package names from the Meteor guide and write them to packages-guide Uses the content folder of https://github.com/meteor/guide ''' from collections import defaultdict import os import sys import markdown from bs4 import BeautifulSoup def get_links_from_markdown(path, name): try: with op...
[ "''' extract package names from the Meteor guide and write them to packages-guide\n Uses the content folder of https://github.com/meteor/guide '''\n\nfrom collections import defaultdict\nimport os\nimport sys\n\nimport markdown\nfrom bs4 import BeautifulSoup\n\n\ndef get_links_from_markdown(path, name):\n try...
false
988
21e86e4719cda5c40f780aca6e56eb13c8c9b8e5
# encoding: utf-8 '''🤠 PDS Roundup: A step takes you further towards a complete roundup''' from enum import Enum from .util import commit, invoke import logging, github3, tempfile, zipfile, os _logger = logging.getLogger(__name__) class Step(object): '''An abstract step; executing steps comprises a roundup'''...
[ "# encoding: utf-8\n\n'''🤠 PDS Roundup: A step takes you further towards a complete roundup'''\n\nfrom enum import Enum\nfrom .util import commit, invoke\nimport logging, github3, tempfile, zipfile, os\n\n_logger = logging.getLogger(__name__)\n\n\nclass Step(object):\n '''An abstract step; executing steps compr...
false
989
333914f99face050376e4713ca118f2347e50018
""" URL Configuration to test mounting created urls from registries """ from django.contrib import admin from django.urls import include, path from staticpages.loader import StaticpagesLoader staticpages_loader = StaticpagesLoader() urlpatterns = [ path("admin/", admin.site.urls), # Add base pages urls usi...
[ "\"\"\"\nURL Configuration to test mounting created urls from registries\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\n\nfrom staticpages.loader import StaticpagesLoader\n\n\nstaticpages_loader = StaticpagesLoader()\n\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n ...
false
990
5ef7c838d8e9a05a09bd974790a85ff36d56a336
import mock def exc(): print 'here should raise' def recursion(): try: print 'here' return exc() except StandardError: print 'exc' return recursion() def test_recursion(): global exc exc = mock.Mock(side_effect = [StandardError, StandardError, mock.DEFAULT]) r...
[ "import mock\n\ndef exc():\n print 'here should raise'\n\ndef recursion():\n try:\n print 'here'\n return exc()\n except StandardError:\n print 'exc'\n return recursion()\n\n\ndef test_recursion():\n global exc\n exc = mock.Mock(side_effect = [StandardError, StandardError,...
true
991
88b3dd7414a68de65bafb317fbd4da2b1bc933fc
import json def corec_set(parameter, value): params_fn = "corec_parameters.json" with open(params_fn) as f: params = json.load(f) params[parameter] = value with open(params_fn, 'w') as f: json.dump(params, f, indent=4) def corec_get(parameter): params_fn = "corec_parameters.json" with open(params_fn)...
[ "\nimport json\n\ndef corec_set(parameter, value):\n\n\tparams_fn = \"corec_parameters.json\"\n\n\twith open(params_fn) as f:\n\t\tparams = json.load(f)\n\n\tparams[parameter] = value\n\n\twith open(params_fn, 'w') as f:\n\t\tjson.dump(params, f, indent=4)\n\ndef corec_get(parameter):\n\n\tparams_fn = \"corec_param...
false
992
095374aa7613f163fedbd7d253219478108d4f42
# Celery配置文件 # 指定消息队列为Redis broker_url = "redis://120.78.168.67/10" CELERY_RESULT_BACKEND = "redis://120.78.168.67/0" CELERY_TIMEZONE = 'Asia/Shanghai'
[ "# Celery配置文件\n\n# 指定消息队列为Redis\nbroker_url = \"redis://120.78.168.67/10\"\nCELERY_RESULT_BACKEND = \"redis://120.78.168.67/0\"\nCELERY_TIMEZONE = 'Asia/Shanghai'\n", "broker_url = 'redis://120.78.168.67/10'\nCELERY_RESULT_BACKEND = 'redis://120.78.168.67/0'\nCELERY_TIMEZONE = 'Asia/Shanghai'\n", "<assignment t...
false
993
2c1de638ac25a9f27b1af94fa075b7c1b9df6884
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'PhoneUser.last_contacted' db.add_column(u'smslink_phoneuser', 'last_contacted', ...
[ "# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding field 'PhoneUser.last_contacted'\n db.add_column(u'smslink_phoneuser', 'last_contacte...
false
994
18bad56ff6d230e63e83174672b8aa8625c1ebb4
RANGES = { # Intervalles de la gamme majeure 0: [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], # Intervalles de la gamme mineure naturelle 1: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0], # Intervalles de la gamme mineure harmonique 2: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1] } RANGES_NAMES = { 'fr': ['Maje...
[ "\nRANGES = {\n # Intervalles de la gamme majeure\n 0: [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], \n # Intervalles de la gamme mineure naturelle\n 1: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0],\n # Intervalles de la gamme mineure harmonique \n 2: [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1] \n}\n\nRANGES_NAMES = {\n...
true
995
364ac79e0f885c67f2fff57dfe3ddde63f0c269e
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question DB_HOST = os.getenv('DB_HOST', '127.0.0.1:5432') DB_USER = os.getenv('DB_USER', 'postgres') DB_PASSWORD = os.getenv('DB_PASSWORD', 'postgres') DB_NAME = os.getenv('DB_NAME'...
[ "import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flaskr import create_app\nfrom models import setup_db, Question\n\nDB_HOST = os.getenv('DB_HOST', '127.0.0.1:5432')\nDB_USER = os.getenv('DB_USER', 'postgres')\nDB_PASSWORD = os.getenv('DB_PASSWORD', 'postgres')\nDB_NAME = os....
false
996
34c81b9318d978305748d413c869a86ee6709e2c
# import visual_servoing_utils_main as utils from autolab_core import rigid_transformations as rt from yumipy import YuMiState class YumiConstants: T_gripper_gripperV = rt.RigidTransform(rotation=[[-1, 0, 0], [0, 1, 0], [0, 0, -1]], from_frame='gripper', to_frame='obj') ...
[ "# import visual_servoing_utils_main as utils\nfrom autolab_core import rigid_transformations as rt\nfrom yumipy import YuMiState\n\nclass YumiConstants:\n\n T_gripper_gripperV = rt.RigidTransform(rotation=[[-1, 0, 0], [0, 1, 0], [0, 0, -1]],\n from_frame='gripper', to_f...
false
997
04099c46c029af37a08b3861809da13b3cc3153b
""" OBJECTIVE: Given a list, sort it from low to high using the QUICK SORT algorithm Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are: 1. Pick an element, called a pivot, from the array. 2. Par...
[ "\"\"\"\nOBJECTIVE: Given a list, sort it from low to high using the QUICK SORT algorithm\n\nQuicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements.\nQuicksort can then recursively sort the sub-arrays.\n\nThe steps are:\n\n1. Pick an element, called a pivot, from t...
false
998
9a6d6637cd4ecf2f6e9c8eb8e702be06e83beea4
from app import create_app __author__ = '七月' app = create_app() if __name__ == '__main__': app.run(debug=app.config['DEBUG'])
[ "from app import create_app\n\n\n__author__ = '七月'\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(debug=app.config['DEBUG'])", "from app import create_app\n__author__ = '七月'\napp = create_app()\nif __name__ == '__main__':\n app.run(debug=app.config['DEBUG'])\n", "<import token>\n__author__ ...
false
999
f405a3e9ccabbba6719f632eb9c51809b8deb319
import boto3 from botocore.exceptions import ClientError import logging import subprocess import string import random import time import os import sys import time import json from ProgressPercentage import * import logging def upload_file(file_name, object_name=None): RESULT_BUCKET_NAME = "worm4047bucket2" s...
[ "import boto3\nfrom botocore.exceptions import ClientError\nimport logging\nimport subprocess\nimport string\nimport random\nimport time\nimport os\nimport sys\nimport time\nimport json\nfrom ProgressPercentage import *\nimport logging\n\n\n\ndef upload_file(file_name, object_name=None):\n RESULT_BUCKET_NAME = \...
false