index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
3,000
0233b46da3b9351f110ffc7f8622ca8f9ee9944d
import asyncio import secrets import pytest from libp2p.host.ping import ID, PING_LENGTH from libp2p.tools.factories import pair_of_connected_hosts @pytest.mark.asyncio async def test_ping_once(): async with pair_of_connected_hosts() as (host_a, host_b): stream = await host_b.new_stream(host_a.get_id(),...
[ "import asyncio\nimport secrets\n\nimport pytest\n\nfrom libp2p.host.ping import ID, PING_LENGTH\nfrom libp2p.tools.factories import pair_of_connected_hosts\n\n\n@pytest.mark.asyncio\nasync def test_ping_once():\n async with pair_of_connected_hosts() as (host_a, host_b):\n stream = await host_b.new_stream...
false
3,001
89059915df8891efcbe742174bd468a1390598e3
from unittest import TestCase from utils.fileutils import is_empty_dir, clear_attributes class FileUtilsTest(TestCase): def test_is_empty_dir(self): self.assertFalse(is_empty_dir(r'c:\Windows')) def test_clear_attributes(self): clear_attributes(__file__)
[ "from unittest import TestCase\n\nfrom utils.fileutils import is_empty_dir, clear_attributes\n\n\nclass FileUtilsTest(TestCase):\n def test_is_empty_dir(self):\n self.assertFalse(is_empty_dir(r'c:\\Windows'))\n\n def test_clear_attributes(self):\n clear_attributes(__file__)\n\n", "from unittes...
false
3,002
4a0d8e6b6205fa57b8614857e1462203a2a7d2c5
from django.conf.urls import url from ..views import (buildings_upload, keytype_upload, key_upload, keystatus_upload, keyissue_upload) from django.contrib.auth.decorators import login_required urlpatterns = [ url(r'^buildings_csv/$', # NOQA buildings_upload, name="buildings_upload"), url(r'^ke...
[ "from django.conf.urls import url\nfrom ..views import (buildings_upload, keytype_upload, key_upload, keystatus_upload, keyissue_upload)\nfrom django.contrib.auth.decorators import login_required\n\nurlpatterns = [\n url(r'^buildings_csv/$', # NOQA\n buildings_upload,\n name=\"buildings_upload\"),...
false
3,003
01b14da7d081a67bab6f9921bb1a6a4c3d5ac216
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.core.urlresolvers import reverse import datetime class Document(models.Model): document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add...
[ "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.core.urlresolvers import reverse\nimport datetime\n\n\nclass Document(models.Model):\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeFiel...
false
3,004
1a7a28a2264ed0204184ab1dd273b0b114657fa7
# -*- coding:utf-8 -*- from spider.driver.base.driver import Driver from spider.driver.base.mysql import Mysql import time from pyquery import PyQuery from spider.driver.base.field import Field,FieldName,Fieldlist,FieldType from spider.driver.base.page import Page from spider.driver.base.listcssselector import ListCssS...
[ "# -*- coding:utf-8 -*-\nfrom spider.driver.base.driver import Driver\nfrom spider.driver.base.mysql import Mysql\nimport time\nfrom pyquery import PyQuery\nfrom spider.driver.base.field import Field,FieldName,Fieldlist,FieldType\nfrom spider.driver.base.page import Page\nfrom spider.driver.base.listcssselector imp...
false
3,005
5d618acc0962447554807cbb9d3546cd4e0b3572
#Calculadora mediante el terminal numero1 = 0 numero2 = 0 #Preguntamos los valores operacion = input("¿Qué operación quiere realizar (Suma / Resta / Division / Multiplicacion)?: ").upper() numero1 = int(input("Introduzca el valor 1: ")) numero2 = int(input("Introduzca el valor 2: ")) #Realizamos las operaciones ...
[ "#Calculadora mediante el terminal\n\nnumero1 = 0\nnumero2 = 0\n\n\n#Preguntamos los valores\n\noperacion = input(\"¿Qué operación quiere realizar (Suma / Resta / Division / Multiplicacion)?: \").upper()\n\nnumero1 = int(input(\"Introduzca el valor 1: \"))\nnumero2 = int(input(\"Introduzca el valor 2: \"))\n\n\n#Re...
false
3,006
9bbf0953d228c970764b8ba94675346820bc5d90
#!../virtual_env/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from models.base import metadata from sqlalchemy import create_engine import os.path engine = create_engine(SQLALCHEMY_DATABASE_URI) metadata.create_all(engine) if not...
[ "#!../virtual_env/bin/python\nfrom migrate.versioning import api\nfrom config import SQLALCHEMY_DATABASE_URI\nfrom config import SQLALCHEMY_MIGRATE_REPO\nfrom models.base import metadata\nfrom sqlalchemy import create_engine\n\nimport os.path\n\nengine = create_engine(SQLALCHEMY_DATABASE_URI)\n\nmetadata.create_all...
false
3,007
5d05351cd6cd6c0d216e8bc09308532605bfd26e
from sys import exit def hard(): print("Nice! Let's try something harder") print("Could you calculate this for me?") print("4 * 35 + 18 / 2 = ") aws = input(">") while True: if aws == "176": print("Nice, you correctly answer all the questions") exit(0) els...
[ "from sys import exit\n\n\ndef hard():\n print(\"Nice! Let's try something harder\")\n print(\"Could you calculate this for me?\")\n print(\"4 * 35 + 18 / 2 = \")\n\n aws = input(\">\")\n\n while True:\n if aws == \"176\":\n print(\"Nice, you correctly answer all the questions\")\n ...
false
3,008
4f870e0d86d9f9b8c620115a618ea32abc24c52d
# 只放置可执行文件 # # from ..src import package # data_dict = package.pack() # from ..src.plugins import * #解释一遍全放入内存 # from ..src import plugins #导入这个文件夹(包,模块,类库),默认加载init文件到内存 # # # plugins.pack() from ..src.script import run if __name__ == '__main__': run()
[ "# 只放置可执行文件\n#\n# from ..src import package\n# data_dict = package.pack()\n\n# from ..src.plugins import * #解释一遍全放入内存\n# from ..src import plugins #导入这个文件夹(包,模块,类库),默认加载init文件到内存\n#\n#\n# plugins.pack()\n\n\nfrom ..src.script import run\n\nif __name__ == '__main__':\n run()\n\n\n\n", "from ..src.script import ...
false
3,009
f2c592a0ea38d800510323a1001c646cdbecefff
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author:tom_tao626 @license: Apache Licence @file: 17.列表中的元素统计.py @time: 2020/12/09 @contact: tp320670258@gmail.com @site: xxxx.suizhu.net @software: PyCharm """ # collections.Counter() from collections import Counter list1 = ['a', 'b', 'b', 'c', 'd', 'e', 'a', ...
[ "#!/usr/bin/env python \n# -*- coding:utf-8 _*-\n\"\"\" \n@author:tom_tao626 \n@license: Apache Licence \n@file: 17.列表中的元素统计.py \n@time: 2020/12/09\n@contact: tp320670258@gmail.com\n@site: xxxx.suizhu.net\n@software: PyCharm \n\"\"\"\n\n# collections.Counter()\n\nfrom collections import Counter\nlist1 = ['a', 'b',...
false
3,010
1a72da7f436e6c5e73e396b771f8ce1a3affba1a
DEFAULT_LL_URL = "https://ll.thespacedevs.com" DEFAULT_VERSION = "2.0.0" DEFAULT_API_URL = "/".join([DEFAULT_LL_URL, DEFAULT_VERSION])
[ "DEFAULT_LL_URL = \"https://ll.thespacedevs.com\"\nDEFAULT_VERSION = \"2.0.0\"\nDEFAULT_API_URL = \"/\".join([DEFAULT_LL_URL, DEFAULT_VERSION])\n", "DEFAULT_LL_URL = 'https://ll.thespacedevs.com'\nDEFAULT_VERSION = '2.0.0'\nDEFAULT_API_URL = '/'.join([DEFAULT_LL_URL, DEFAULT_VERSION])\n", "<assignment token>\n"...
false
3,011
422a4945ebf453d3e09e9e7e76dd32b30488680e
import pandas as pd df = pd.DataFrame({'col1':[1,2,3,4],'col2':[444,555,666,444],'col3':['abc','def','ghi','xyz']}) print(df.head()) #print(df['col2'].unique()) #print(df['col1'] > 2) newdf = df[(df['col1']>0) & (df['col2'] == 444)] print("========================") print(newdf) def times2(x): return x*2 print("=...
[ "import pandas as pd\ndf = pd.DataFrame({'col1':[1,2,3,4],'col2':[444,555,666,444],'col3':['abc','def','ghi','xyz']})\nprint(df.head())\n#print(df['col2'].unique())\n#print(df['col1'] > 2)\nnewdf = df[(df['col1']>0) & (df['col2'] == 444)]\nprint(\"========================\")\nprint(newdf)\n\ndef times2(x):\n ret...
false
3,012
41f70cdfc9cbe5ec4560c1f3271a4636cca06d16
#!/usr/bin/env python ''' export_claims -- export claims in CSV format https://sfreeclaims.anvicare.com/docs/forms/Reference-CSV%20Specifications.txt ''' import csv from itertools import groupby from operator import itemgetter import wsgiref.handlers import MySQLdb import ocap from hhtcb import Xataface, WSGI def...
[ "#!/usr/bin/env python\n''' export_claims -- export claims in CSV format\n\nhttps://sfreeclaims.anvicare.com/docs/forms/Reference-CSV%20Specifications.txt\n'''\n\nimport csv\nfrom itertools import groupby\nfrom operator import itemgetter\nimport wsgiref.handlers\n\nimport MySQLdb\n\nimport ocap\nfrom hhtcb import X...
true
3,013
06a721c12e3140d4d1cf544a598f512595c4ab66
#!/usr/bin/env python3 """(Optional) Test for GameDealer class.""" import unittest import os, sys from functools import reduce sys.path.insert(0, os.path.join(os.path.split(__file__)[0], "..")) import Lab19_Extending_Builtins.lab19_3 as game_dealer WHOLE_DECK = sorted(game_dealer.Deck()) class ReportingDealer(...
[ "#!/usr/bin/env python3\n\"\"\"(Optional) Test for GameDealer class.\"\"\"\n\nimport unittest\n\nimport os, sys\nfrom functools import reduce\nsys.path.insert(0, os.path.join(os.path.split(__file__)[0], \"..\"))\n \nimport Lab19_Extending_Builtins.lab19_3 as game_dealer\n\nWHOLE_DECK = sorted(game_dealer.Deck())...
false
3,014
3efa5eb97af116929a7426ed3bfb5e4a170cfacd
import sys, math nums = sys.stdin.readline().split(" ") my_set = set() my_list = [] for i in xrange(int(nums[1])): inpt = int(sys.stdin.readline()) my_set.add(inpt) my_list.append(inpt) x = 0 for i in xrange(1, int(nums[0]) + 1): if (i in my_set): continue while (x < len(my_list) and my_l...
[ "import sys, math\n\nnums = sys.stdin.readline().split(\" \")\nmy_set = set()\nmy_list = []\nfor i in xrange(int(nums[1])):\n inpt = int(sys.stdin.readline())\n my_set.add(inpt)\n my_list.append(inpt)\n\nx = 0\nfor i in xrange(1, int(nums[0]) + 1):\n if (i in my_set): \n continue\n while (x < ...
true
3,015
d44f8a2dee35d76c152695d49d73f74e9c25bfa9
#read file my_file=open("file.txt","r") #print(my_file.read()) #print(my_file.readline()) #print(my_file.read(3))#read 3 caracteres """ for line in my_file: print(line) my_file.close() """ print(my_file.readlines())#list #close file my_file.close() #create new file and writing new_file=open("newfile.txt",mode="w",...
[ "#read file\nmy_file=open(\"file.txt\",\"r\")\n#print(my_file.read())\n#print(my_file.readline())\n#print(my_file.read(3))#read 3 caracteres\n\"\"\"\nfor line in my_file:\n print(line)\nmy_file.close()\n\"\"\"\nprint(my_file.readlines())#list\n#close file\nmy_file.close()\n\n#create new file and writing\nnew_fil...
false
3,016
1b4a012f5b491c39c0abd139dd54f2095ea9d221
import re from captcha.fields import CaptchaField from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.core.exceptions import ValidationError from news.models import News, Comment, Profile class UserRegisterForm(Use...
[ "import re\nfrom captcha.fields import CaptchaField\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom news.models import News, Comment, Profile\n\n\nclass UserRe...
false
3,017
0f2d215a34758f85a29ef7ed8264fccd5e85b66f
#Peptide Encoding Problem: Find substrings of a genome encoding a given amino acid sequence. # Input: A DNA string Text, an amino acid string Peptide, and the array GeneticCode. # Output: All substrings of Text encoding Peptide (if any such substrings exist). def reverse_string(seq): return seq[::-1] def compl...
[ "#Peptide Encoding Problem: Find substrings of a genome encoding a given amino acid sequence.\n# Input: A DNA string Text, an amino acid string Peptide, and the array GeneticCode.\n# Output: All substrings of Text encoding Peptide (if any such substrings exist).\ndef reverse_string(seq):\n return seq[::-1]\n...
false
3,018
6f35c29f6f2dcc6c1dae3e9c1ddf595225748041
#import cvxopt from cvxopt import matrix, spmatrix, solvers #import scipy from scipy.special import expit import numpy as np import sys import pandas as pd import time class KernelNC(): """ distance based classifier for spectrum kernels """ def __init__(self, classes): self.classes = class...
[ "#import cvxopt\nfrom cvxopt import matrix, spmatrix, solvers\n#import scipy\nfrom scipy.special import expit\nimport numpy as np\nimport sys\nimport pandas as pd\nimport time\n\nclass KernelNC():\n \"\"\"\n distance based classifier for spectrum kernels\n \"\"\"\n \n def __init__(self, classes):\n ...
false
3,019
ac2edcd6ea71ebdc5b1df5fd4211632b5d8e2704
# -*- coding: utf-8 -*- """ Created on Tue Aug 18 18:53:02 2020 @author: vinhe I followed below tutorial to push newly created csv to google sheets: https://medium.com/craftsmenltd/from-csv-to-google-sheet-using-python-ef097cb014f9 """ import gspread from oauth2client.service_account import ServiceAcc...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 18 18:53:02 2020\r\n\r\n@author: vinhe\r\n\r\nI followed below tutorial to push newly created csv to google sheets:\r\nhttps://medium.com/craftsmenltd/from-csv-to-google-sheet-using-python-ef097cb014f9\r\n\r\n\"\"\"\r\n\r\n\r\nimport gspread\r\nfrom oauth2cli...
false
3,020
14f7f31fa64799cdc08b1363b945da50841d16b5
class Component: pass class Entity: def __init__(self, id): self.id = id self.components = {} def add_component(self, component): if type(component) in self.components: raise Exception("This entity already has a component of that type") # Since there is only ...
[ "\nclass Component:\n pass\n\nclass Entity:\n\n def __init__(self, id):\n self.id = id\n self.components = {}\n\n def add_component(self, component):\n if type(component) in self.components:\n raise Exception(\"This entity already has a component of that type\")\n\n #...
false
3,021
cb0be932813a144cfb51b3aa2f6e0792e49c4945
# encoding=UTF-8 # This file serves the project in production # See http://wsgi.readthedocs.org/en/latest/ from __future__ import unicode_literals from moya.wsgi import Application application = Application( "./", ["local.ini", "production.ini"], server="main", logging="prodlogging.ini" )
[ "# encoding=UTF-8\n\n# This file serves the project in production\n# See http://wsgi.readthedocs.org/en/latest/\n\nfrom __future__ import unicode_literals\nfrom moya.wsgi import Application\n\napplication = Application(\n \"./\", [\"local.ini\", \"production.ini\"], server=\"main\", logging=\"prodlogging.ini\"\n...
false
3,022
73d1129418711c35046a99c1972a413357079836
../../2.0.2/mpl_examples/axes_grid/simple_axesgrid2.py
[ "../../2.0.2/mpl_examples/axes_grid/simple_axesgrid2.py" ]
true
3,023
b7d75c2523dba0baaf06ba270045a4a344b8156c
"""A simple script to create a motion plan.""" import os import json import logging from logging.config import dictConfig import argparse import numpy as np from opentrons_hardware.hardware_control.motion_planning import move_manager from opentrons_hardware.hardware_control.motion_planning.types import ( AxisConst...
[ "\"\"\"A simple script to create a motion plan.\"\"\"\nimport os\nimport json\nimport logging\nfrom logging.config import dictConfig\nimport argparse\nimport numpy as np\n\nfrom opentrons_hardware.hardware_control.motion_planning import move_manager\nfrom opentrons_hardware.hardware_control.motion_planning.types im...
false
3,024
0c8eb90c1d8a58f54186a30ce98a67310955a367
import pygame import utils from random import randint class TileSurface(): tileGroup = pygame.sprite.Group() tileGrid = [] def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height self.surface = pygame.Surface((width, height)) def updatePos(self, x, y): ...
[ "import pygame\nimport utils\nfrom random import randint\n\nclass TileSurface():\n\n\ttileGroup = pygame.sprite.Group()\n\n\ttileGrid = []\n\n\tdef __init__(self, x, y, width, height):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.surface = pygame.Surface((width, height...
false
3,025
b147a22d6bd12a954c0d85c11e578a67f0a51332
number = int(input("Enter a number, and I'll tell you if it's even or odd: ")) if number % 2 == 0: print(f"{number} is an even number.") else: print(f"{number} is an odd number.")
[ "number = int(input(\"Enter a number, and I'll tell you if it's even or odd: \"))\n\nif number % 2 == 0:\n print(f\"{number} is an even number.\")\nelse:\n print(f\"{number} is an odd number.\")", "number = int(input(\"Enter a number, and I'll tell you if it's even or odd: \"))\nif number % 2 == 0:\n pri...
false
3,026
a9531fb020428e573d189c377652692e301ea4d3
#!/usr/bin/env python # -*- coding:utf-8 -*- school = "Old boy" def chang_name(name): global school #声明全局变量 school = "Mage Linux" print("Before change:", name, school) name = 'Stack Cong' age = 33 print("After change:", name) print("School:", school) name = "Stack" chang_name(name) print(na...
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nschool = \"Old boy\"\n\ndef chang_name(name):\n global school #声明全局变量\n school = \"Mage Linux\"\n print(\"Before change:\", name, school)\n name = 'Stack Cong'\n age = 33\n print(\"After change:\", name)\n\nprint(\"School:\", school)\nname = \"St...
false
3,027
4e5e1be289b32655736d8c6c02d354a85d4268b7
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """BatchNorm (BN) utility functions and custom batch-size BN implementations""" from functools import partial import torch import torch.nn as nn from pytorchvideo.layers.batch_norm import ( NaiveSyncBatchNorm1d, Na...
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\n\"\"\"BatchNorm (BN) utility functions and custom batch-size BN implementations\"\"\"\n\nfrom functools import partial\nimport torch\nimport torch.nn as nn\n\nfrom pytorchvideo.layers.batch_norm import (\n NaiveSy...
false
3,028
f26dc3139413c4ed4b04484c095a433e53039cdb
import requests as r import re class web_scrap: seed="" result="" tag_attr=[] def __init__(self,seed): self.seed=seed self.set_tag() self.set_attr() self.fetch_web(self.seed) self.crawl() def fetch_web(self,link): ...
[ "import requests as r\r\nimport re\r\nclass web_scrap:\r\n seed=\"\"\r\n result=\"\"\r\n tag_attr=[]\r\n \r\n def __init__(self,seed):\r\n self.seed=seed\r\n self.set_tag()\r\n self.set_attr()\r\n self.fetch_web(self.seed)\r\n self.crawl() \r\n\...
false
3,029
9d0d4707cc9a654752dd0b98fe0fec6a0c1419a1
# -*- coding: utf-8 -*- from handlers.base import Base class Home(Base): def start(self): from movuca import DataBase, User from datamodel.article import Article, ContentType, Category from datamodel.ads import Ads self.db = DataBase([User, ContentType, Category, Article, Ads]) ...
[ "# -*- coding: utf-8 -*-\n\nfrom handlers.base import Base\n\n\nclass Home(Base):\n def start(self):\n from movuca import DataBase, User\n from datamodel.article import Article, ContentType, Category\n from datamodel.ads import Ads\n self.db = DataBase([User, ContentType, Category, Ar...
false
3,030
886101e5d86daf6c2ac0fe92b361ccca6132b1aa
#!/usr/bin/env python #_*_ coding:utf-8 _*_ ''' @author: tanglei @contact: tanglei_0315@163.com @file: index.py @time: 2017/11/1 16:26 ''' #需求: #1.每个客户端需要监控的服务不同 #2.每个服务的监控间隔不同 #3.允许模板的形式批量修改监控指标 #4.不同设备的监控阀值不同 #5.可自定义最近n分钟内hit\max\avg\last\... 指标超过阀值 #6.报警策略,报警等级,报警自动升级 #7.历史数据的存储和优化 时间越久数据越失真 #8.跨机房,跨区域代理服务器 #第三方的soc...
[ "#!/usr/bin/env python\n#_*_ coding:utf-8 _*_\n'''\n@author: tanglei\n@contact: tanglei_0315@163.com\n@file: index.py\n@time: 2017/11/1 16:26\n'''\n#需求:\n#1.每个客户端需要监控的服务不同\n#2.每个服务的监控间隔不同\n#3.允许模板的形式批量修改监控指标\n#4.不同设备的监控阀值不同\n#5.可自定义最近n分钟内hit\\max\\avg\\last\\... 指标超过阀值\n#6.报警策略,报警等级,报警自动升级\n#7.历史数据的存储和优化 时间越久数据越失真\...
false
3,031
5e17299e6a409e433e384935a815bab6ce178ff5
import tkinter as tk # Import tkinker for GUI creation from PIL import Image, ImageTk # Allow images to be used as backgrounds import socket # Importing sockets for low level implementation of networks import select # Importing select to poll between the user input and received message import sys # Getting inp...
[ "import tkinter as tk # Import tkinker for GUI creation\nfrom PIL import Image, ImageTk # Allow images to be used as backgrounds\nimport socket # Importing sockets for low level implementation of networks\nimport select # Importing select to poll between the user input and received message\nimport sys # Ge...
false
3,032
e7494104ab98df2b640f710fa69584802b3e1259
class Solution: def maximumTime(self, time: str) -> str: ans = '' for i in range(5): if time[i] != '?': ans += time[i] continue if i == 0: if time[1] in ['0', '1', '2', '3', '?']: ans += '2' e...
[ "class Solution:\n def maximumTime(self, time: str) -> str:\n ans = ''\n for i in range(5):\n if time[i] != '?':\n ans += time[i]\n continue\n if i == 0:\n if time[1] in ['0', '1', '2', '3', '?']:\n ans += '2'\n ...
false
3,033
a01783e3687278d1ec529c5123b9151721ba3364
# coding=utf8 def InsertSort(array_a, n): for i in range(1, n): temp = array_a[i] j = i - 1 while temp < array_a[j] and j >= 0: array_a[j + 1] = array_a[j] # 如果小于其前驱,则从后往前寻找插入位置并后移。 j -= 1 array_a[j + 1] = temp return array_a def ShellSort(array_a, n):...
[ "# coding=utf8\n\ndef InsertSort(array_a, n):\n for i in range(1, n):\n temp = array_a[i]\n j = i - 1\n while temp < array_a[j] and j >= 0:\n array_a[j + 1] = array_a[j] # 如果小于其前驱,则从后往前寻找插入位置并后移。\n j -= 1\n array_a[j + 1] = temp\n return array_a\n\n\ndef Shel...
true
3,034
024bc95f7255bb8be5c3c4ade9d212c9555a4f01
string="Rutuja MaluSare" print(string.casefold()) print(len(string)) """string1=input("enter string 1") print("string1") print(len(string1)) string2=input("enter string 2") print("string2") print(len(string2)) string3=string1+string2 print(len(string3))""" #lower case print(string.lower()) #upper case print(string...
[ "string=\"Rutuja MaluSare\"\nprint(string.casefold())\nprint(len(string))\n\n\"\"\"string1=input(\"enter string 1\")\nprint(\"string1\")\nprint(len(string1))\n\nstring2=input(\"enter string 2\")\nprint(\"string2\")\nprint(len(string2))\n\n\nstring3=string1+string2\nprint(len(string3))\"\"\"\n\n#lower case\nprint(st...
false
3,035
019e8d7159fe07adc245e6476ac1fed5e9c457b5
import os, sys, string import linecache, math import numpy as np import datetime , time from pople import NFC from pople import uniqatoms from pople import orca_printbas ####### orca_run - S def orca_run(method, basis,optfreq,custombasis, correlated, values, charge, multip, sym, R_coord): """ Runs orca ...
[ "import os, sys, string\nimport linecache, math\nimport numpy as np\nimport datetime , time\n\n\nfrom pople import NFC\nfrom pople import uniqatoms\nfrom pople import orca_printbas\n\n\n####### orca_run - S\ndef orca_run(method, basis,optfreq,custombasis, correlated, values, charge, multip, sym, R_coord):\n \"\"...
false
3,036
cd1ada2d7979fffc17f707ed113efde7aa134954
# Copyright (c) 2023 Intel Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writ...
[ "# Copyright (c) 2023 Intel Corporation\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# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agree...
false
3,037
807f0094a9736abdfa3f5b629615a80f1e0d13ef
class Rect(): def __init__(self, w, h): self.w = w self.h = h def half(self): return self.w / 2; bricks = [Rect(40, 25), Rect(30, 25), Rect(28, 25), Rect(13, 25)] def setup(): size(500, 500) noLoop() def draw(): posx = 0 posy = 0 i = 0 for...
[ "class Rect():\n def __init__(self, w, h):\n self.w = w\n self.h = h\n \n def half(self):\n return self.w / 2;\n \nbricks = [Rect(40, 25), Rect(30, 25), Rect(28, 25), Rect(13, 25)]\n\ndef setup():\n size(500, 500)\n noLoop()\n \ndef draw():\n \n posx = 0\n posy...
false
3,038
6c8f690e1b43d459535238e24cccc8aa118e2d57
# pylint: disable=W0621,C0114,C0116,W0212,W0613 import io import textwrap from typing import cast, Any, Dict import toml import pytest from dae.testing import convert_to_tab_separated from dae.configuration.gpf_config_parser import GPFConfigParser from dae.configuration.schemas.person_sets import person_set_collectio...
[ "# pylint: disable=W0621,C0114,C0116,W0212,W0613\nimport io\nimport textwrap\nfrom typing import cast, Any, Dict\n\nimport toml\nimport pytest\n\nfrom dae.testing import convert_to_tab_separated\nfrom dae.configuration.gpf_config_parser import GPFConfigParser\nfrom dae.configuration.schemas.person_sets import perso...
false
3,039
0d1fda864edc73cc6a9853727228c6fa3dfb19a1
""" Author : Gülşah Büyük Date : 17.04.2021 """ import numpy as np A = np.array([[22, -41, 2], [61, 17, -18], [-9, 74, -13]]) # For a square matrix A the QR Decomposition converts into the product of an orthogonal matrix Q # (Q.T)Q= I and an upper triangular matrix R. def householder_reflection(A): # A H...
[ "\"\"\"\r\nAuthor : Gülşah Büyük\r\nDate : 17.04.2021\r\n\"\"\"\r\nimport numpy as np\r\nA = np.array([[22, -41, 2], [61, 17, -18], [-9, 74, -13]])\r\n# For a square matrix A the QR Decomposition converts into the product of an orthogonal matrix Q\r\n# (Q.T)Q= I and an upper triangular matrix R.\r\ndef householde...
false
3,040
d56c80b4822b1bd0f2d4d816ed29a4da9d19a625
import collections def solution(genres, plays): answer = [] cache = collections.defaultdict(list) # 장르 : [고유번호, 재생횟수] genre_order = collections.defaultdict(int) # 장르 : 전체재생횟수 order = collections.defaultdict() # 전체재생횟수 : 장르 # 첫번째 딕셔너리와 두번째 딕셔너리 생성 for i in range(len(genres)): cache[ge...
[ "import collections\ndef solution(genres, plays):\n answer = []\n cache = collections.defaultdict(list) # 장르 : [고유번호, 재생횟수]\n genre_order = collections.defaultdict(int) # 장르 : 전체재생횟수\n order = collections.defaultdict() # 전체재생횟수 : 장르\n # 첫번째 딕셔너리와 두번째 딕셔너리 생성\n for i in range(len(genres)):\n ...
false
3,041
84a4a0a16aea08ee874b09de163fd777be925f18
import numpy as np import math import matplotlib.pyplot as plt def signif_conf(ts, p): ''' Given a timeseries (ts), and desired probability (p), compute the standard deviation of ts (s) and use the number of points in the ts (N), and the degrees of freedom (DOF) to calculate chi. ''' s = np.std(ts...
[ "import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n\ndef signif_conf(ts, p):\n ''' Given a timeseries (ts), and desired probability (p),\n compute the standard deviation of ts (s) and use the\n number of points in the ts (N), and the degrees of freedom (DOF)\n to calculate chi. '''\n ...
true
3,042
882d265f14c04b2f2f626504d18e2cd07dcc8637
""" This module is used to extract features from the lines extracted from documents using BERT encodings. This package leverages the bert-as-a-server package to create the embeddings. Example: feature_extractor = FeatureExtractor(document) # document is of class Document encoded_doc = feature_extracto...
[ "\"\"\"\n\nThis module is used to extract features from the lines extracted from documents\nusing BERT encodings. This package leverages the bert-as-a-server package to create the\nembeddings.\n\nExample:\n feature_extractor = FeatureExtractor(document) # document is of class Document\n encoded_doc = ...
false
3,043
2e23225ec4cd693f5e9460a13d64206f184a86a0
# -*- coding: utf-8 -*- """Code handling the concurrency of data analysis."""
[ "# -*- coding: utf-8 -*-\n\"\"\"Code handling the concurrency of data analysis.\"\"\"\n", "<docstring token>\n" ]
false
3,044
836d712c811079f190eae9c2780131a844c9dddf
def twoSensorAvg(input_data, duration=1): times = {} for i in input_data: data = i.split(',') time = int(int(data[1]) / (duration * 1000)) if time not in times: times[time] = [0, 0] times[time][0] += int(data[2]) times[time][1] += 1 ans = [] for i, v i...
[ "def twoSensorAvg(input_data, duration=1):\n times = {}\n for i in input_data:\n data = i.split(',')\n time = int(int(data[1]) / (duration * 1000))\n if time not in times:\n times[time] = [0, 0]\n times[time][0] += int(data[2])\n times[time][1] += 1\n ans = []\...
false
3,045
fbb081fd52b14336ab4537bb795105bcd6a03070
from os import environ from flask import Flask from flask_restful import Api from flask_migrate import Migrate from applications.db import db from applications.gamma_api import add_module_gamma app = Flask(__name__) app.config["DEBUG"] = True app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DATABASE') app.config...
[ "from os import environ\n\nfrom flask import Flask\nfrom flask_restful import Api\nfrom flask_migrate import Migrate\n\nfrom applications.db import db\nfrom applications.gamma_api import add_module_gamma\n\napp = Flask(__name__)\napp.config[\"DEBUG\"] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DAT...
false
3,046
2de12085ddc73fed85dda8ce3d6908b42fdc4bcc
## Import modules import matplotlib, sys, datetime, time matplotlib.use('TkAgg') from math import * from numpy import * from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib import dates import matplotlib.pyplot as plt from Tkinter ...
[ "## Import modules\nimport matplotlib, sys, datetime, time\nmatplotlib.use('TkAgg')\nfrom math import *\nfrom numpy import *\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nfrom matplotlib import dates\nimport matplotlib.pyplot as plt\...
false
3,047
4d68b663933070cb287689b70d6ded07958cef22
# Should print 516 def final_frequency(): frequency = 0 with open('input') as f: for line in f: frequency += int(line) return frequency print(final_frequency())
[ "# Should print 516\ndef final_frequency():\n frequency = 0\n\n with open('input') as f:\n for line in f:\n frequency += int(line)\n\n return frequency\n\n\nprint(final_frequency())\n", "def final_frequency():\n frequency = 0\n with open('input') as f:\n for line in f:\n ...
false
3,048
32499688db51f701173ec0ea212c483bf902c109
from django.db import models # Create your models here. class Tutorial(models.Model): web_title = models.CharField(max_length=200) web_content = models.TextField() web_published = models.DateTimeField("date published") def __str__(self): return self.web_title
[ "from django.db import models\n\n# Create your models here.\nclass Tutorial(models.Model):\n\tweb_title = models.CharField(max_length=200)\n\tweb_content = models.TextField()\n\tweb_published = models.DateTimeField(\"date published\")\n\n\tdef __str__(self):\n\t\treturn self.web_title\n", "from django.db import m...
false
3,049
22e6616fb98ecfb256587c3767c7c289decc6bf6
#Copyright (c) 2020 Ocado. All Rights Reserved. import vptree, itertools import numpy as np class _ExtendedVPTree(vptree.VPTree): """ VPTree class extended to include the list of points within the tree """ def __init__(self, points, dist_fn): """ :param points: List of points to add t...
[ "#Copyright (c) 2020 Ocado. All Rights Reserved.\n\nimport vptree, itertools\nimport numpy as np\n\n\nclass _ExtendedVPTree(vptree.VPTree):\n \"\"\"\n VPTree class extended to include the list of points within the tree\n \"\"\"\n def __init__(self, points, dist_fn):\n \"\"\"\n :param point...
false
3,050
c69dcffc06146af610a7976e522b6e35cabde1aa
# class User: # def __init__(self, name_parameter, email_parameter): # self.nameofPerson = name_parameter # self.emailofPerson = email_parameter # self.account_balance = 0 # def depositMoney(self, amount); # self.account_balance += amount # return self # def transfe...
[ "# class User:\n# def __init__(self, name_parameter, email_parameter):\n# self.nameofPerson = name_parameter\n# self.emailofPerson = email_parameter\n# self.account_balance = 0\n\n# def depositMoney(self, amount);\n# self.account_balance += amount\n# return self\n\n# ...
false
3,051
a91d2f32afdc20516e56036c352cc267c728e886
import numpy as np import matplotlib.pyplot as plt import csv def save_cp_csvdata(reward, err, filename): with open(filename, mode='w') as data_file: data_writer = csv.writer(data_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) data_writer.writerow(['epoch', 'reward', 'error']) ...
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\n\ndef save_cp_csvdata(reward, err, filename):\n with open(filename, mode='w') as data_file:\n data_writer = csv.writer(data_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n data_writer.writerow(['epoch', 'reward'...
false
3,052
eb403fbb307332c18ffdcdf52589c714f0719960
import xarray as xr def precip_stats_to_climatology(fili, start_year=1981, end_year=2015): """ Calculates average climatology for annual data - either Jan to Dec or accummulation period """ nyear = end_year - start_year + 1 ds = xr.open_dataset(fili) year = ds['time'].dt.year #dsMsk ...
[ "import xarray as xr\n\ndef precip_stats_to_climatology(fili, start_year=1981, end_year=2015):\n \"\"\"\n Calculates average climatology for annual data - either Jan to Dec or accummulation period\n \"\"\"\n\n nyear = end_year - start_year + 1\n \n ds = xr.open_dataset(fili)\n\n year = ds['time...
false
3,053
e05dac901228e6972c1cb48ce2def3d248b4c167
# # -*- coding: utf-8 -*- # # """ # Py40 PyQt5 tutorial # # This example shows three labels on a window # using absolute positioning. # # author: Jan Bodnar # website: py40.com # last edited: January 2015 # """ # # import sys # from PyQt5.QtWidgets import QWidget, QLabel, QApplication # # # class Example(QWidget): # # ...
[ "# # -*- coding: utf-8 -*-\n#\n# \"\"\"\n# Py40 PyQt5 tutorial\n#\n# This example shows three labels on a window\n# using absolute positioning.\n#\n# author: Jan Bodnar\n# website: py40.com\n# last edited: January 2015\n# \"\"\"\n#\n# import sys\n# from PyQt5.QtWidgets import QWidget, QLabel, QApplication\n#\n#\n# ...
false
3,054
f2c53efa4b7c2df592582e3093ff269b703be1e0
# Generated by Django 3.2.5 on 2021-08-05 07:19 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('organization', '0010_aut...
[ "# Generated by Django 3.2.5 on 2021-08-05 07:19\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('organiza...
false
3,055
130f49028833bf57d7e4f9fbb0764801c3508c3b
print("n:",end="") n=int(input()) print("a:",end="") a=list(map(int,input().split())) ans=0 for i in range(n): for j in range(i+1,n): for k in range(j+1,n): ai,aj,ak=sorted([a[i],a[j],a[k]]) if(ai+aj>ak and ai+aj+ak>ans): ans=ai+aj+ak print(ans)
[ "print(\"n:\",end=\"\")\nn=int(input())\nprint(\"a:\",end=\"\")\na=list(map(int,input().split()))\n\nans=0\nfor i in range(n):\n for j in range(i+1,n):\n for k in range(j+1,n):\n ai,aj,ak=sorted([a[i],a[j],a[k]])\n if(ai+aj>ak and ai+aj+ak>ans):\n ans=ai+aj+ak\nprint(a...
false
3,056
5a181b0c22faa47c6c887daac675dd7374037f30
from typing import List, Optional from backend.domain.well import FacilityState, Well from backend.repository.persistence.well import WellPersistenceSchema class WellRepository: schema = WellPersistenceSchema() def __init__(self, db): self._db = db def list(self) -> List[Well]: return [...
[ "from typing import List, Optional\n\nfrom backend.domain.well import FacilityState, Well\nfrom backend.repository.persistence.well import WellPersistenceSchema\n\n\nclass WellRepository:\n schema = WellPersistenceSchema()\n\n def __init__(self, db):\n self._db = db\n\n def list(self) -> List[Well]:...
false
3,057
22b6ea64cdb109e1c6b2536b50935d09d37a7e1a
from nmigen import * class Top(Elaboratable): def __init__(self): self.counter = Signal(3) self.led = Signal() def elaborate(self, platform): m = Module() m.d.comb += self.led.eq(self.counter[2]) m.d.sync += self.counter.eq(self.counter + 1) return m
[ "from nmigen import *\n\n\nclass Top(Elaboratable):\n def __init__(self):\n self.counter = Signal(3)\n self.led = Signal()\n def elaborate(self, platform):\n m = Module()\n m.d.comb += self.led.eq(self.counter[2])\n m.d.sync += self.counter.eq(self.counter + 1)\n retu...
false
3,058
4246773a8da61ff21d5faa8ab8ad2d7e75fafb60
import sqlite3 def to_string(pessoa): for linha in pessoa: print('id: {}\nNome: {}'.format(linha[0], linha[1])) if __name__ == '__main__': con = sqlite3.connect('lab05-ex01.sqlite') cursor = con.cursor() cursor.execute("SELECT * FROM Pessoa") print(cursor.fetchall()) nome = input(...
[ "import sqlite3\n\n\ndef to_string(pessoa):\n for linha in pessoa:\n print('id: {}\\nNome: {}'.format(linha[0], linha[1]))\n\nif __name__ == '__main__':\n\n con = sqlite3.connect('lab05-ex01.sqlite')\n\n cursor = con.cursor()\n\n cursor.execute(\"SELECT * FROM Pessoa\")\n print(cursor.fetchall...
false
3,059
e652196f9c74be6f05c6148de152996e449670ea
import numpy as np from input_parameters.program_constants import ITERATIONS_NUM, TIMESTEPS_NUMB def init_zero_arrays(): radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB)) dot_radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB)) dotdot_radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB)) d...
[ "import numpy as np\n\nfrom input_parameters.program_constants import ITERATIONS_NUM, TIMESTEPS_NUMB\n\n\ndef init_zero_arrays():\n radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB))\n dot_radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS_NUMB))\n dotdot_radius_arr = np.zeros((ITERATIONS_NUM, TIMESTEPS...
false
3,060
1e4d21998b9f8915167166e5965b0c8c87fcf61d
def search_way(adjacency_list, points): use = [False for i in range(points.__len__())] way = [0 for i in range(points.__len__())] cost = [100000 for i in range(points.__len__())] cost[0] = 0 checkVar = 0 test = True while test: min = 100000 for i in range(points.__len__()): ...
[ "def search_way(adjacency_list, points):\n use = [False for i in range(points.__len__())]\n way = [0 for i in range(points.__len__())]\n cost = [100000 for i in range(points.__len__())]\n cost[0] = 0\n checkVar = 0\n test = True\n while test:\n min = 100000\n for i in range(points...
false
3,061
052574be3f4a46bceefc0a54b1fe268a7cef18a9
from django.db import models from django.utils import timezone from django.contrib.auth.models import User """ Using the django shell: $ python manage.py shell from django.contrib.auth.models import User from accounts.models import Profile from papers.models import Paper, Comment, Rating, UserSavedPaper users = User...
[ "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n\n\"\"\"\nUsing the django shell:\n$ python manage.py shell\n\nfrom django.contrib.auth.models import User\nfrom accounts.models import Profile\nfrom papers.models import Paper, Comment, Rating, UserSavedP...
false
3,062
602a7676129721dbfd318407dd972f80d681146c
class CardHolder: acctlen = 8 retireage = 59.5 def __init__(self, acct, name, age, addr): self.acct = acct self.name = name self.age = age self.addr = addr def __getattribute__(self, item): # __getattribute__ intercepts calls for all ...
[ "class CardHolder:\n acctlen = 8\n retireage = 59.5\n\n def __init__(self, acct, name, age, addr):\n self.acct = acct\n self.name = name\n self.age = age\n self.addr = addr\n\n def __getattribute__(self, item): # __getattribute__ intercepts c...
false
3,063
9bb8e0f732eac474dbc01c374f9c74178f65dc36
import sys from bs4 import BeautifulSoup def get_classes(html): """ returns a list of classes and titles, parsing through 'html' """ # elements = html.find_all("span", "code") # titles = html.find_all("span", "title") # classes = [] # for i in range(len(elements)): # item = element...
[ "import sys\nfrom bs4 import BeautifulSoup\n\n\ndef get_classes(html):\n \"\"\"\n returns a list of classes and titles, parsing through 'html'\n \"\"\"\n # elements = html.find_all(\"span\", \"code\")\n # titles = html.find_all(\"span\", \"title\")\n # classes = []\n # for i in range(len(elemen...
false
3,064
fa271d3888dc60582fa0883eaf9f9ebbdffeed9d
# ELABORE UM PROGRAMA QUE CALCULE O A SER PAGO POR UM PRODUTO CONSIDERANDO O PRECO NORMAL E A FORMA DE PAGAMENTO # a vista dinehiro ou cheque: 10% # a vista no cartao: 5% # 2x: preco normal # 3x ou mais: 20% de juros
[ "# ELABORE UM PROGRAMA QUE CALCULE O A SER PAGO POR UM PRODUTO CONSIDERANDO O PRECO NORMAL E A FORMA DE PAGAMENTO\n# a vista dinehiro ou cheque: 10%\n# a vista no cartao: 5%\n# 2x: preco normal\n# 3x ou mais: 20% de juros", "" ]
false
3,065
7d3a33968a375141c1c451ecd531ce8d97906c7f
import FitImport as imp import numpy as np from math import * from sklearn.kernel_ridge import KernelRidge from sklearn.grid_search import GridSearchCV from sklearn import cross_validation from sklearn.cross_validation import train_test_split from sklearn.metrics import mean_squared_error GSFOLDS = 3 FOLDS = 5 NPTS = ...
[ "import FitImport as imp\nimport numpy as np\nfrom math import *\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn import cross_validation\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\nGSFOLDS = 3\nFO...
false
3,066
16d86c48c45ab0441046e968ea364d27f6dcfd12
# -*- coding: utf-8 -*- # 导入包 import matplotlib.pyplot as plt import numpy as np # 显示中文和显示负号 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # X轴和Y轴数据,票房单位亿 a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","...
[ "# -*- coding: utf-8 -*-\n\n# 导入包\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# 显示中文和显示负号\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\n# X轴和Y轴数据,票房单位亿\na = [\"战狼2\",\"速度与激情8\",\"功夫瑜伽\",\"西游伏妖篇\",\"变形金刚5:最后的骑士\",\"摔跤吧!爸爸\",\"加勒比海盗5:死无对证\",\"金刚:骷髅岛\",\"极限特工:...
false
3,067
6ca2a9040897e49c6407b9b0760240fec93b4df0
from redstork import PageObject class AnnotController: def get_annotations(self, project, page_index): page = project.doc[page_index] yield from page.flat_iter()
[ "from redstork import PageObject\n\n\nclass AnnotController:\n def get_annotations(self, project, page_index):\n page = project.doc[page_index]\n\n yield from page.flat_iter()\n\n\n", "from redstork import PageObject\n\n\nclass AnnotController:\n\n def get_annotations(self, project, page_index...
false
3,068
9f0e286268732e8cabb028b7c84f5ba72a6e8528
""" Python asyncio Protocol extension for TCP use. """ import asyncio import logging import socket class TcpTestProtocol(asyncio.Protocol): """ Extension of asyncio protocol for TCP data """ def __init__(self, test_stream=None, no_delay=False, window=None, server=None): """ Initialize ...
[ "\"\"\"\nPython asyncio Protocol extension for TCP use.\n\"\"\"\nimport asyncio\nimport logging\nimport socket\n\nclass TcpTestProtocol(asyncio.Protocol):\n \"\"\"\n Extension of asyncio protocol for TCP data\n \"\"\"\n\n def __init__(self, test_stream=None, no_delay=False, window=None, server=None):\n ...
false
3,069
1438a268780217e647999ba031aa4a50a6912d2f
""" AuthService class module. """ from urllib.parse import urlencode from http.client import HTTPConnection, HTTPResponse, HTTPException from dms2021sensor.data.rest.exc import NotFoundError class AuthService(): """ REST client to connect to the authentication service. """ def __init__(self, host: str, ...
[ "\"\"\" AuthService class module.\n\"\"\"\n\nfrom urllib.parse import urlencode\nfrom http.client import HTTPConnection, HTTPResponse, HTTPException\nfrom dms2021sensor.data.rest.exc import NotFoundError\n\n\nclass AuthService():\n \"\"\" REST client to connect to the authentication service.\n \"\"\"\n\n d...
false
3,070
1e7789b154271eb8407a027c6ddf6c941cc69a41
import json import time from keySender import PressKey,ReleaseKey,dk config = { "Up": "W", "Down": "S", "Left": "A", "Right": "D", "Grab": "LBRACKET", "Drop": "RBRACKET" } ### Commands # Move def Move(direction,delay=.2): PressKey(dk[config[direction]]) time.sleep(delay) # Replace with a better condition Rele...
[ "import json\nimport time\nfrom keySender import PressKey,ReleaseKey,dk\nconfig = {\n\t\"Up\": \"W\",\n\t\"Down\": \"S\",\n\t\"Left\": \"A\",\n\t\"Right\": \"D\",\n\t\"Grab\": \"LBRACKET\",\n\t\"Drop\": \"RBRACKET\"\n}\n\n### Commands\n# Move\ndef Move(direction,delay=.2):\n\tPressKey(dk[config[direction]])\n\ttime...
false
3,071
2101299d6f6bfcd4726591fc256317968373ca1f
REGION_LIST = [ 'Центральный', 'Северо-Западный', 'Южный', 'Северо-Кавказский', 'Приволжский', 'Уральский', 'Сибирский', 'Дальневосточный', ] CITY_LIST = { 'Абакан': 7, 'Альметьевск': 5, 'Ангарск': 7, 'Архангельск': 2, 'Астрахань': 3, 'Барнаул': 7, 'Батайск':...
[ "REGION_LIST = [\n 'Центральный',\n 'Северо-Западный',\n 'Южный',\n 'Северо-Кавказский',\n 'Приволжский',\n 'Уральский',\n 'Сибирский',\n 'Дальневосточный',\n]\n\nCITY_LIST = {\n 'Абакан': 7,\n 'Альметьевск': 5,\n 'Ангарск': 7,\n 'Архангельск': 2,\n 'Астрахань': 3,\n 'Барна...
false
3,072
b236abaa5e206a8244083ee7f9dcdb16741cb99d
from typing import List, Tuple import pytest def fit_transform(*args: str) -> List[Tuple[str, List[int]]]: if len(args) == 0: raise TypeError('expected at least 1 arguments, got 0') categories = args if isinstance(args[0], str) else list(args[0]) uniq_categories = set(categories) bi...
[ "from typing import List, Tuple\r\nimport pytest\r\n\r\n\r\ndef fit_transform(*args: str) -> List[Tuple[str, List[int]]]:\r\n if len(args) == 0:\r\n raise TypeError('expected at least 1 arguments, got 0')\r\n\r\n categories = args if isinstance(args[0], str) else list(args[0])\r\n uniq_categories = ...
false
3,073
cc6f70e328b774972e272e9600274dfd9fca93ee
import cv2 import matplotlib.pyplot as plt import numpy as np ball = plt.imread('ball.png') albedo = plt.imread('ball_albedo.png') shading = cv2.cvtColor(plt.imread('ball_shading.png'), cv2.COLOR_GRAY2RGB) x,y,z = np.where(albedo != 0) print('Albedo:', albedo[x[0],y[0]]) print("Albedo in RGB space:", albedo[x[0],y[0]...
[ "import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nball = plt.imread('ball.png')\nalbedo = plt.imread('ball_albedo.png')\nshading = cv2.cvtColor(plt.imread('ball_shading.png'), cv2.COLOR_GRAY2RGB)\n\nx,y,z = np.where(albedo != 0)\nprint('Albedo:', albedo[x[0],y[0]])\nprint(\"Albedo in RGB space:\",...
false
3,074
c6cbd4d18363f00b73fac873ba45d6063bee7e64
# -*- encoding: utf-8 -*- """ views: vistas sistema recomendador @author Camilo Ramírez @contact camilolinchis@gmail.com camilortte@hotmail.com @camilortte on Twitter @copyright Copyright 2014-2015, RecomendadorUD @license GPL @date 2014-10...
[ "# -*- encoding: utf-8 -*-\n\"\"\"\n \n views: vistas sistema recomendador\n\n @author Camilo Ramírez\n @contact camilolinchis@gmail.com \n camilortte@hotmail.com\n @camilortte on Twitter\n @copyright Copyright 2014-2015, RecomendadorUD\n @license GPL\n ...
true
3,075
bf83556b8e8855a0e410fcfb3b42161fbc681830
b=int(input('enter anum ')) for a in range(1,11,1): print(b,'x',a,'=',a*b)
[ "\nb=int(input('enter anum '))\nfor a in range(1,11,1):\n\tprint(b,'x',a,'=',a*b)", "b = int(input('enter anum '))\nfor a in range(1, 11, 1):\n print(b, 'x', a, '=', a * b)\n", "<assignment token>\nfor a in range(1, 11, 1):\n print(b, 'x', a, '=', a * b)\n", "<assignment token>\n<code token>\n" ]
false
3,076
4aefabf064cdef963f9c62bd5c93892207c301d3
# Generated by Django 2.1.4 on 2019-04-17 03:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('historiasClinicas', '0001_initial'), ] operations = [ migrations.AlterField( model_name='actualizacion', name='valor...
[ "# Generated by Django 2.1.4 on 2019-04-17 03:56\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('historiasClinicas', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='actualizacion',\n ...
false
3,077
41013469e65e45f6c909d66c2a54eaf11dfd474c
"""A number can be broken into different contiguous sub-subsequence parts. Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. And this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different """ def colorful(A): sA = str(A) len_sA = len(s...
[ "\"\"\"A number can be broken into different contiguous sub-subsequence parts. \nSuppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. \nAnd this number is a COLORFUL number, since product of every digit of a contiguous subsequence is different\n\"\"\"\n\ndef colorful(A):\n sA = str(A)\n...
false
3,078
00afab442f56d364c785324f816b52b4a6be609d
''' Take list of iam users in a csv file like S_NO, IAM_User_Name,Programatic_Access,Console_Access,PolicyARN 1,XYZ, Yes,No,arn:aws:iam::aws:policy/AdministratorAccess 2.pqr,Yes,Yes,arn:aws:iam::aws:policy/AdministratorAccess 3.abc,No,Yes,arn:aws:iam::aws:policy/AmazonAPIGatewayInvokeFullAccess ''' import boto3,s...
[ "'''\nTake list of iam users in a csv file like\n\nS_NO, IAM_User_Name,Programatic_Access,Console_Access,PolicyARN\n\n1,XYZ, Yes,No,arn:aws:iam::aws:policy/AdministratorAccess\n\n2.pqr,Yes,Yes,arn:aws:iam::aws:policy/AdministratorAccess\n\n3.abc,No,Yes,arn:aws:iam::aws:policy/AmazonAPIGatewayInvokeFullAccess\n\n'''...
false
3,079
088c77e090d444e7057a91cac606995fb523c8ef
print("Enter string:") s=input() a = s.lower() vowels = "aeiou" consonants = "bcdfghjklmnpqrstvwxyz" digits = "1234567890" whitespace = " " c = 0 v = 0 d = 0 ws= 0 for i in a: if i in vowels: v+=1 elif i in consonants: c+=1 elif i in digits: d+=1 elif i in whitespace: ...
[ "print(\"Enter string:\")\ns=input()\na = s.lower()\n\n\nvowels = \"aeiou\"\nconsonants = \"bcdfghjklmnpqrstvwxyz\"\ndigits = \"1234567890\"\nwhitespace = \" \"\n\nc = 0\nv = 0\nd = 0\nws= 0\n\nfor i in a:\n if i in vowels:\n v+=1\n elif i in consonants:\n c+=1\n elif i in digits:\n d+...
false
3,080
226fc85dc8b6d549fddef0ca43ad629875ac0717
from django.db import models class Course(models.Model): cid = models.CharField(max_length=100) title = models.CharField(max_length=500) link = models.CharField(max_length=300)
[ "from django.db import models\n\nclass Course(models.Model):\n\t\n\tcid = models.CharField(max_length=100)\n\ttitle = models.CharField(max_length=500)\n\tlink = models.CharField(max_length=300)\n\t\n\n", "from django.db import models\n\n\nclass Course(models.Model):\n cid = models.CharField(max_length=100)\n ...
false
3,081
4fa9c00a07c8263a6a3afd460b84f21637a771ec
''' This file creates the model of Post, which maps to the post table in the mysql database. The model Provider contains four attributes: author, title, content, and created time. ''' from django.db import models class Post(models.Model): ''' The education post by provider database model ''' author ...
[ "\n'''\nThis file creates the model of Post, which maps to the post table in the mysql database. \nThe model Provider contains four attributes: author, title, content, and created time. \n'''\nfrom django.db import models\n\nclass Post(models.Model):\n '''\n The education post by provider database model\n ...
false
3,082
8ff9961c1415c04899bbc15ba64811a1b3ade262
from keras.preprocessing.image import img_to_array from keras.models import load_model import tensorflow as tf import numpy as np import argparse import imutils import pickle import cv2 # USAGE # python classify.py --model output/fashion.model --categorybin output/category_lb.pickle # --colorbin output/color_lb.pickle...
[ "from keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport imutils\nimport pickle\nimport cv2\n\n# USAGE\n# python classify.py --model output/fashion.model --categorybin output/category_lb.pickle\n# --colorbin output...
false
3,083
4f8bc19bb113c9eac7c2ac774ac7b16f569d9704
# operatorTest02.py x = 5 x += 3 #복함 대입 연산자 print("x : ", x) print("-"*30) total = 0 total += 1 total
[ "# operatorTest02.py\n\nx = 5\nx += 3 #복함 대입 연산자\nprint(\"x : \", x)\nprint(\"-\"*30)\n\ntotal = 0\ntotal += 1\ntotal ", "x = 5\nx += 3\nprint('x : ', x)\nprint('-' * 30)\ntotal = 0\ntotal += 1\ntotal\n", "<assignment token>\nx += 3\nprint('x : ', x)\nprint('-' * 30)\n<assignment token>\ntotal += 1\ntotal\n", ...
false
3,084
339506777f5471ec99b39c67c28df8ec3d06ce19
from django.shortcuts import render,redirect from . import download_function from django.http import HttpResponse # Create your views here. def download(request): if request.method == "GET": session = request.GET['session'] title = request.GET['download_title'] download_quality = request.GET...
[ "from django.shortcuts import render,redirect\nfrom . import download_function\nfrom django.http import HttpResponse\n# Create your views here.\ndef download(request):\n if request.method == \"GET\":\n session = request.GET['session']\n title = request.GET['download_title']\n download_qualit...
false
3,085
3b803850418638bf65528088044918e93ecabff6
class BucketSort: def __init__(self,a): self.a = a def result(self,bucketCount = 10): buckets = [[] for i in range(bucketCount+1)] maxElement = max(self.a) minElement = min(self.a) bucketRange = (maxElement-minElement+1)/bucketCount for i in range(len(self.a)): ...
[ "class BucketSort:\n def __init__(self,a):\n self.a = a\n\n def result(self,bucketCount = 10):\n buckets = [[] for i in range(bucketCount+1)]\n maxElement = max(self.a)\n minElement = min(self.a)\n bucketRange = (maxElement-minElement+1)/bucketCount\n for i in range(l...
false
3,086
82abed3a60829eeabf6b9e8b791085d130ec3dd4
#Purpose: find the bonds, angles in Zr/GPTMS .xyz outpuf file from simulation from Tkinter import Tk from tkFileDialog import askopenfilename Tk().withdraw() from pylab import * from scipy import * from numpy import * import numpy as np import math ##################################################################...
[ "#Purpose: find the bonds, angles in Zr/GPTMS .xyz outpuf file from simulation \n\nfrom Tkinter import Tk\nfrom tkFileDialog import askopenfilename\nTk().withdraw()\n\nfrom pylab import *\nfrom scipy import *\nfrom numpy import *\nimport numpy as np\nimport math\n\n\n################################################...
true
3,087
779445aa22145d5076940ea5b214c25ad233dd0e
"""This module provides constants for locale-dependent providers.""" import typing as t from mimesis.enums import Locale from mimesis.exceptions import LocaleError __all__ = ["Locale", "validate_locale"] def validate_locale(locale: t.Union[Locale, str]) -> Locale: if isinstance(locale, str): try: ...
[ "\"\"\"This module provides constants for locale-dependent providers.\"\"\"\n\nimport typing as t\n\nfrom mimesis.enums import Locale\nfrom mimesis.exceptions import LocaleError\n\n__all__ = [\"Locale\", \"validate_locale\"]\n\n\ndef validate_locale(locale: t.Union[Locale, str]) -> Locale:\n if isinstance(locale...
false
3,088
74843dea00a88513c3a9237eb024e1e14e8b1ff8
""" 实战练习: 1.打开网页 https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable 2.操作窗口右侧页面,将元素1拖拽到元素2 3.这时候会有一个alert弹框,点击弹框中的‘确定’ 3.然后再按’点击运行’ 4.关闭网页 """ import pytest from selenium import webdriver from time import sleep from selenium.webdriver import ActionChains class TestFrame: def setup(self): self...
[ "\"\"\"\n实战练习:\n1.打开网页\nhttps://www.runoob.com/try/try.php?filename=jqueryui-api-droppable\n2.操作窗口右侧页面,将元素1拖拽到元素2\n3.这时候会有一个alert弹框,点击弹框中的‘确定’\n3.然后再按’点击运行’\n4.关闭网页\n\"\"\"\nimport pytest\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver import ActionChains\nclass TestFrame:\n def ...
false
3,089
0f37baf3b08ecf7bd8db43ecc2f29c3ca6e00af0
version https://git-lfs.github.com/spec/v1 oid sha256:26be7fc8be181fad8e821179cce6be14e37a5f303e532e6fb00f848d5f33fe41 size 752
[ "version https://git-lfs.github.com/spec/v1\noid sha256:26be7fc8be181fad8e821179cce6be14e37a5f303e532e6fb00f848d5f33fe41\nsize 752\n" ]
true
3,090
a95e64877a1fc9f8109f1293b4ae9176f4f64647
import requests import json import pandas as pd from sqlalchemy import create_engine from sqlalchemy.types import VARCHAR,INT,FLOAT,BIGINT import time from tqdm import tqdm #数据库联接设置 connect_info = 'mysql+pymysql://root:rootroot@localhost:3306/db1?charset=UTF8MB4' engine = create_engine(connect_info) sql = ''' s...
[ "import requests \nimport json\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.types import VARCHAR,INT,FLOAT,BIGINT\nimport time\nfrom tqdm import tqdm\n#数据库联接设置\nconnect_info = 'mysql+pymysql://root:rootroot@localhost:3306/db1?charset=UTF8MB4'\nengine = create_engine(connect_info) \nsq...
false
3,091
b9608208f71f25ae05ed9bd7bdf94b8882a26e06
# Generated by Django 2.1.4 on 2019-04-23 23:37 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('mach...
[ "# Generated by Django 2.1.4 on 2019-04-23 23:37\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL...
false
3,092
3f23a50f44ba17c9b0241a4e3b0e939afeb1f5f0
from django import forms class ListingForm(forms.Form): text = forms.CharField( max_length=50, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Things to Buy"} ), )
[ "from django import forms\n\n\nclass ListingForm(forms.Form):\n text = forms.CharField(\n max_length=50,\n widget=forms.TextInput(\n attrs={\"class\": \"form-control\", \"placeholder\": \"Things to Buy\"}\n ),\n )\n", "from django import forms\n\n\nclass ListingForm(forms.For...
false
3,093
3e1ca6ed4668e75a62baa65ef44346dd86a16491
import sqlite3 conn = sqlite3.connect("19-BD/prove.db") cursor = conn.cursor() dipendenti = [ ("Sofia","commessa"), ("Diego","tecnico"), ("Lucia","cassiera"), ("Luca","Magazziniere"), ("Pablo","Capo reparto") ] cursor.executemany("INSERT INTO persone VALUES (null,?,?)", dipendenti) conn.commit() ...
[ "import sqlite3\n\nconn = sqlite3.connect(\"19-BD/prove.db\")\ncursor = conn.cursor()\n\ndipendenti = [\n (\"Sofia\",\"commessa\"),\n (\"Diego\",\"tecnico\"),\n (\"Lucia\",\"cassiera\"),\n (\"Luca\",\"Magazziniere\"),\n (\"Pablo\",\"Capo reparto\")\n]\n\ncursor.executemany(\"INSERT INTO persone VALUE...
false
3,094
9a672c17ee22a05e77491bc1449c1c1678414a8c
import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib.animation as animation import pylab from mpl_toolkits import mplot3d from mpl_toolkits.mplot3d import Axes3D class Hexapod: def __init__(self, axis): """ Инициализация начальных параметров системы :par...
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib.animation as animation\nimport pylab\nfrom mpl_toolkits import mplot3d\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\nclass Hexapod:\n def __init__(self, axis):\n \"\"\"\n Инициализация начальных параметров ...
false
3,095
d4e62950f10efeb27d19c3d9c672969342ef8c7c
"""------------------------------------------------------------------------ MODULE FContactRegulatoryInfoBase - DESCRIPTION: This file provides the custom instance of RegulatoryInfo on the Contact which has all the RegulatoryInfo related methods VERSION: 1.0.25(0.25.7) RESTRICTIONS/ LIMITATIONS: 1. Any modi...
[ "\"\"\"------------------------------------------------------------------------\nMODULE\n FContactRegulatoryInfoBase -\nDESCRIPTION:\n This file provides the custom instance of RegulatoryInfo on the Contact which has all the RegulatoryInfo related methods\nVERSION: 1.0.25(0.25.7)\nRESTRICTIONS/ LIMITATIONS:\n...
false
3,096
4fb1ece28cd7c6e2ac3a479dcbf81ee09ba14223
from farmfs.fs import Path, ensure_link, ensure_readonly, ensure_symlink, ensure_copy, ftype_selector, FILE, is_readonly from func_prototypes import typed, returned from farmfs.util import safetype, pipeline, fmap, first, compose, invert, partial, repeater from os.path import sep from s3lib import Connection as s3conn,...
[ "from farmfs.fs import Path, ensure_link, ensure_readonly, ensure_symlink, ensure_copy, ftype_selector, FILE, is_readonly\nfrom func_prototypes import typed, returned\nfrom farmfs.util import safetype, pipeline, fmap, first, compose, invert, partial, repeater\nfrom os.path import sep\nfrom s3lib import Connection a...
false
3,097
8a04447f12a9cb6ba31a21d43629d887a0d1f411
""" Example 1: Input: J = "aA", S = "aAAbbbb" Output: 3 Example 2: Input: J = "z", S = "ZZ" Output: 0 Note: S and J will consist of letters and have length at most 50. The characters in J are distinct. 查找J中的每个字符在 S 出现的次数的总和。 改进: J有可能有重复的数。 测试数据: https://leetcode.com/problems/jewels-and-stones/description/ """ c...
[ "\"\"\"\nExample 1:\n\nInput: J = \"aA\", S = \"aAAbbbb\"\nOutput: 3\nExample 2:\n\nInput: J = \"z\", S = \"ZZ\"\nOutput: 0\nNote:\n\nS and J will consist of letters and have length at most 50.\nThe characters in J are distinct.\n\n查找J中的每个字符在 S 出现的次数的总和。\n\n改进:\nJ有可能有重复的数。\n\n测试数据:\nhttps://leetcode.com/problems/je...
true
3,098
20518302b6a67f8f1ac01f1adf4fe06ab2eaf280
""" Package for haasplugin. """
[ "\"\"\"\nPackage for haasplugin.\n\"\"\"\n", "<docstring token>\n" ]
false
3,099
09bf7460b2c928bf6e1346d9d1e2e1276540c080
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import versatileimagefield.fields class Migration(migrations.Migration): dependencies = [ ('venue', '0001_initial'), ] operations = [ migrations.CreateModel( name='Images...
[ "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport versatileimagefield.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('venue', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n ...
false