id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3273016 | import random
def random_list(length):
l = []
for i in range(length):
l.append(random.randint(0, 9))
return l
def next_example(length):
l1 = random_list(length)
l2 = sorted(l1)
return l1, l2
def generate_examples(N, length, out_file):
with open(out_file, "w") as f:
for... |
3273018 | from django.apps import AppConfig
class SsoConfig(AppConfig):
name = "apps.sso"
verbose_name = "Sso"
def ready(self):
# Is attached just by importations, thus ignored flake-rule
from apps.sso.signals import handle_app_authorized # noqa: F401
|
3273019 | import torch.nn as nn
import os
import time
import torch
import torchvision
import numpy as np
import cv2 as cv
import scipy.io as sio
def _nms(heat, kernel=3):
pad = (kernel - 1) // 2
hmax = nn.functional.max_pool2d(
heat, (kernel, kernel), stride=1, padding=pad)
keep = (hmax == heat).float()
... |
3273049 | from django.apps import AppConfig
from .utilities import behaviour
# from bot_task_graph import *
class BotsConfig(AppConfig):
name = 'bots'
def ready(self):
behaviour.global_behaviour_thread = \
behaviour.ThreadPool(threads=2, config=behaviour.TaskPoolConfig(5.0, 1.0))
|
3273144 | class Dependency:
"""
Dependency descriptor for dependencies specified as class
level annotations
"""
def __init__(self, name):
self.__name = name
def __get__(self, instance, owner):
if instance is None:
return self
dependency_instance = getattr(instance, sel... |
3273175 | from ....utils.code_utils import deprecate_module
deprecate_module("ediFilesUtils", "edi_files_utils", "0.16.0", error=True)
from .edi_files_utils import *
|
3273191 | from hashlib import blake2b
# the 'database' of users
users = []
class User:
def __init__(self, name: str, password: str, email: str):
self.name = name
self.password = <PASSWORD>(password.encode('UTF-8')).hex<PASSWORD>()
self.email = email
self.plan = "basic"
self.reset_cod... |
3273310 | import argparse
def get():
parser = argparse.ArgumentParser()
parser.add_argument("-M",
"--model-file",
type=str,
default=None)
parser.add_argument("-d",
"--train-dataset",
type=str,
... |
3273334 | from __future__ import absolute_import
from builtins import zip
from builtins import map
from builtins import str
from builtins import range
from builtins import object
from nose.tools import (assert_equal, assert_not_equal, raises, assert_true,
assert_false)
from nose.plugins.skip import SkipTe... |
3273353 | import data_algebra
import data_algebra.test_util
from data_algebra.data_ops import *
import data_algebra.util
def test_ghost_col_issue():
d2 = data_algebra.default_data_model.pd.DataFrame(
{
"x": [1, 4, 5, 7, 8, 9],
"v": [10.0, 40.0, 50.0, 70.0, 80.0, 90.0],
"g": [1, 2... |
3273374 | from Point import Point
from Segment import Segment
from Circle import Circle
from Polygon import Polygon
from Linestring import Linestring
from collections import OrderedDict
from operator import itemgetter
def item_in_focus(project_data, mouse, engagement_distance=20):
"""Find item in focus."""
eng_dist_sqr... |
3273397 | import datetime
import pytest
import dateutil.tz
from graphql import GraphQLError
import strawberry
@pytest.mark.parametrize(
"typing,instance,serialized",
[
(datetime.date, datetime.date(2019, 10, 25), "2019-10-25"),
(
datetime.datetime,
datetime.datetime(2019, 10,... |
3273423 | import os
import tempfile
import uuid
from pathlib import Path
from common.boto_utils import BotoUtils
from common.constant import BuildStatus
from common.utils import Utils, extract_zip_file, make_tarfile, download_file_from_url
from contract_api.config import REGION_NAME, ASSETS_COMPONENT_BUCKET_NAME
from contract_a... |
3273467 | class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 0
end = len(nums) - 1
while (start + 1 < end):
mid = start + (end - start) // 2
if (nums[mid] > nums[mid - ... |
3273512 | from . Token import TokenService
from . Application import ApplicationService
from . Airtime import AirtimeService
from . SMS import SMSService
from . Payment import PaymentService
from . Voice import VoiceService
SMS = None
Airtime = None
Payment = None
USSD = None
Voice = None
Application = None
Token = None
def i... |
3273530 | import warnings
from collections import OrderedDict
from textwrap import dedent
from typing import Union, Optional, List
import logging
import pandas as pd
from red_panda.pandas import PANDAS_TOCSV_KWARGS
from red_panda.aws import (
REDSHIFT_RESERVED_WORDS,
REDSHIFT_COPY_KWARGS,
)
from red_panda.utils import ... |
3273544 | from __future__ import absolute_import
import unittest
import numpy as np
from tests.sample_data import SampleData
from pyti import average_true_range
class TestAverageTrueRange(unittest.TestCase):
def setUp(self):
"""Create data to use for testing."""
self.close_data = SampleData().get_sample_cl... |
3273548 | import discord
from discord.ext import commands
from discord.commands import Option #Importing the packages
import datetime
from discord.commands import slash_command
class Info(commands.Cog):
def __init__(self, bot):#to Initialise
self.bot = bot
@slash_command()
async def userinfo(self, ctx, us... |
3273561 | import scrapy
class ItemSpider(scrapy.Spider):
name = "items"
allowed_domains = ["https://github.com/eepMoody/open5e/blob/master/source/equipment/armor.rst"]
start_urls = [
"https://github.com/eepMoody/open5e/blob/master/source/equipment/armor.rst",
]
def parse(self, response):
null = ... |
3273569 | from animec import Anime, NoResultFound
def get_anime(name: str):
try:
anime = Anime(name)
except NoResultFound:
return None
return anime
def body(base: Anime):
display_body = f"""
Name: {base.name}
Alt Titles: {base.alt_titles}
Description: {base.descr... |
3273598 | import io
import sys
from unittest import mock
from _pytest import capture
from m2cgen import __version__, cli
from tests.utils import verify_python_model_is_expected
def _get_mock_args(
indent=4,
function_name=None,
namespace=None,
module_name=None,
package_name=None,
class_name=None,
... |
3273603 | class InvalidBindingIdentifier(Exception):
def __init__(self, message, binding):
super(InvalidBindingIdentifier, self).__init__(message, binding)
self.binding = binding
def parse_binding(binding):
parts = binding.split(':')
if len(parts) != 3:
raise InvalidBindingIdentifier('Invalid binding', binding... |
3273686 | import ast
from typing import Dict
from skippy.core.clustercontext import ClusterContext
from skippy.core.model import Pod, Node
from skippy.core.priorities import Priority, _scale_scores
from sim.oracle.oracle import FetOracle, ResourceOracle
class CapabilityMatchingPriority(Priority):
def map_node_score(self,... |
3273712 | from abc import ABCMeta, abstractmethod
from collections import namedtuple
DeliveryItem = namedtuple('DeliveryItem', ['sku', 'price', 'qty'])
SupplierProduct = namedtuple('SupplierProduct', ['name', 'price', 'units'])
class SupplierAPIException(Exception):
pass
class SupplierBase(metaclass=ABCMeta):
"""De... |
3273714 | import unittest
import collections
from solution import (RANKS, SUITS, Card, CardCollection,
StandardDeck, SixtySixDeck, BeloteDeck)
class RankTest(unittest.TestCase):
def setUp(self):
self.rank_string = 'Three'
self.rank = RANKS[self.rank_string]()
def test_creation(sel... |
3273727 | from bento.errors \
import \
ParseError
from bento.utils.utils \
import \
extract_exception, is_string
from bento.parser.lexer \
import \
BentoLexer
from bento.compat.api.moves import unittest
TestCase = unittest.TestCase
def split(s):
ret = []
for i in s.split(" "):
... |
3273742 | from config import *
import os
app = Flask(__name__)
@app.route('/dashboard')
def dashboard():
return render_template('index.html')
@app.route('/' + TOKEN, methods=['POST'])
def getMessage():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "!", 200... |
3273746 | from sqlalchemy import Column, Integer, String
from tests.database import Base
class User(Base):
__tablename__ = 'user2'
id = Column(Integer, primary_key=True)
name = Column(String)
full_name = Column(String)
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=T... |
3273770 | from zschema.keys import Port
from zschema.compounds import ListOf, Record, SubRecord
from zschema.leaves import Boolean, DateTime, IPv4Address, String, Unsigned32BitInteger
heartbleed = SubRecord({
"heartbeat_support":Boolean(),
"heartbleed_vulnerable":Boolean(),
"timestamp":DateTime()
})
host = Record(... |
3273771 | import time
import logging
import threading
from typing import Callable, Optional, Dict, Any
from dataclasses import dataclass
from multiprocessing import Process, Queue
from queue import Empty
from modlunky2.utils import tb_info
from .logs import register_queue_handler, QueueHandler
logger = logging.getLogger("modl... |
3273798 | import argparse
import os
import time
import logging
from logging import getLogger
import urllib
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.datasets as... |
3273811 | import os,sys,re
import numpy as np
import subprocess
from multiprocessing import Process,Pool
import pickle
from Bio.Blast import NCBIXML
from Bio import pairwise2
from Bio.SubsMat import MatrixInfo as matlist
from Bio.SeqIO.FastaIO import SimpleFastaParser
import math
from math import log, exp
from getNatureA import ... |
3273818 | encoding = {
'd': 0,
'c': 1
}
inv_encoding = {
0: 'd',
1: 'c'
}
def decode(choice, history):
choice = encoding.get(choice.lower())
if choice is None:
return 1 if history.shape[1] == 0 else history[1, -1]
return choice
def code(response):
return ''.join(inv_encoding.get(digit, ... |
3273852 | import os
import pudb
import shutil
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from scipy.io import loadmat, savemat
def patientwise_splitting(train, test, img_list):
patient_ids = [f.split('_')[1] for f in img_list]
patient_ids = list(set(patient_ids))
train_ids, test_ids ... |
3273882 | from django.apps import AppConfig
class ServiceNow(AppConfig):
name = 'service-now'
verbose_name = 'ServiceNow'
def ready(self):
pass
|
3273887 | import pandas as pd
from cowidev.vax.utils.incremental import enrich_data, increment
from cowidev.utils.clean.dates import localdate
from cowidev.utils import paths
def read(source: str) -> pd.Series:
data = pd.read_csv(source, sep=";")
return parse_data(data).pipe(enrich_data, "date", get_date())
def pars... |
3273892 | from django.urls import path
from . import default_settings as settings
from .apps import AZIranianBankGatewaysConfig
from .views import callback_view, go_to_bank_gateway, sample_payment_view, sample_result_view
app_name = AZIranianBankGatewaysConfig.name
_urlpatterns = [
path('callback/', callback_view, name='ca... |
3273907 | import os
import sys
sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path
from quantile_ml import Predictor
import dill
import numpy as np
from nose.tools import assert_equal, assert_not_equal, with_setup
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
im... |
3273988 | import numpy as np
from net.vgg16 import model as vgg_model
from net.inception import model as inception_model
from net.xception import model as xception_model
from net.mobilenet import model as mobilenet_model
class Fingertips:
def __init__(self, model, weights):
if model is 'vgg':
self.model... |
3273992 | from django.views.generic import ListView, DetailView
from .models import Article
class ArticleList(ListView):
model = Article
paginate_by = 10
class ArticleDetail(DetailView):
model = Article
context_object_name = "article"
|
3273993 | class Solution:
def findComplement(self, num: int) -> int:
p = 1
while p < num: p = (p << 1) + 1
return num ^ p
|
3274065 | from arm.logicnode.arm_nodes import *
class SensorCoordsNode(ArmLogicTreeNode):
"""TO DO."""
bl_idname = 'LNSensorCoordsNode'
bl_label = 'Sensor Coords'
arm_section = 'sensor'
arm_version = 1
def arm_init(self, context):
self.add_output('ArmVectorSocket', 'Coords')
|
3274112 | import yaml
class BuildTestError(Exception):
"""Class responsible for error handling in buildtest. This is a sub-class
of Exception class."""
def __init__(self, msg, *args):
"""This class is used for printing error message when exception is raised.
Args:
msg (str): message to... |
3274120 | from ct.crypto import cert
from observation import Observation
class IpAddressObservation(Observation):
def __init__(self, description, *args, **kwargs):
super(IpAddressObservation, self).__init__(
"IPAddres: " + description, *args, **kwargs)
class IPv6(IpAddressObservation):
def __in... |
3274171 | from typing import List, Set, Tuple
import sublime
import sublime_plugin
ASS_COMMENT_PAIRS: Tuple[Tuple[str, str], ...] = (
# (before_command_executed, after_command_executed),
("Comment: ", "Dialogue: "),
("Dialogue: ", "Comment: "),
("; ", ""),
("", "; "), # always matches
)
def find_first_dif... |
3274196 | from soccermetrics.rest.resources import Resource
class ValidationResource(Resource):
"""
Establish access to Validation resources (/<resource> endpoint).
The Validation resources provide access to data that are used
to ensure consistency and integrity in personnel and match
records in the databas... |
3274198 | from django.core.mail import EmailMultiAlternatives
from django.core.mail.backends.smtp import EmailBackend
from .functions import get_option, get_advanced_option
from django.utils.html import strip_tags
def send_when_comment():
conf = get_advanced_option("smtp")
if conf == None:
return False
retur... |
3274205 | class AbTarget(models.Model):
""" Describes where an antibody is thought to bind. """
term = models.CharField("term", primaryKey=True, max_length=255)
# A relatively short label, no more than a few words
deprecated = models.CharField("deprecated", max_length=255, blank=True)
# If non-empty, the reason why thi... |
3274224 | from app.fixtures.api import anon, api
from app.fixtures.factory import factory, mixer
from app.fixtures.send_mail import send_mail
__all__ = [
'anon',
'api',
'factory',
'mixer',
'send_mail',
]
|
3274238 | from rest_framework import serializers
from koalixcrm.accounting.accounting.product_category import ProductCategory
from koalixcrm.accounting.rest.product_categorie_rest import ProductCategoryMinimalJSONSerializer
from koalixcrm.crm.product.product_type import ProductType
from koalixcrm.crm.product.tax import Tax
from... |
3274243 | from bigraph.preprocessing import import_files, make_graph
from bigraph.predict import aa_predict
import unittest
df, df_nodes = import_files()
G = make_graph(df)
class TestAAPredict(unittest.TestCase):
def test_aa_predict(self):
output = aa_predict(G)
print(output)
self.assertEqual(typ... |
3274296 | for _ in range(int(input())):
a,b,c = [int(x) for x in input().split()]
print("Possible" if c in [a+b, a-b, b-a, a*b, a/b, b/a] else "Impossible")
|
3274297 | from __future__ import print_function
from alignment.sequence import Sequence
from alignment.vocabulary import Vocabulary
from alignment.sequencealigner import SimpleScoring, GlobalSequenceAligner
# Create sequences to be aligned.
a = Sequence('what a beautiful day'.split())
b = Sequence('what a disappointingly bad d... |
3274300 | from click.testing import CliRunner
from sqlite_transform import cli
import textwrap
import pytest
@pytest.mark.parametrize(
"code",
[
"return value.replace('October', 'Spooktober')",
# Return is optional:
"value.replace('October', 'Spooktober')",
],
)
def test_lambda_single_line(t... |
3274307 | from textwrap import dedent
from rest_framework.schemas.openapi import AutoSchema
from ._errors import error_responses
from ._message import message_schema
from ._message import message_with_id_schema
boilerplate = dedent("""\
Affiliations specify a permission level of a user to an organization. There are currently
... |
3274309 | import time
from img2unicode import *
from pathlib import Path
print("""
| Optimizer name | Constructor | Chars | Setup time |
| -------------- | ----------- | ----- | ---------- |
""", end='')
images = ['obama.jpg', 'matplotlib.png']
dual_optimizers = {
'space': 'SpaceDualOptimizer()',
'half': 'HalfBlockDua... |
3274313 | class NoContentError(RuntimeError):
pass
class DuplicateUploadError(RuntimeError):
pass
class ApiError(RuntimeError):
pass
class NotFoundError(ApiError):
pass
|
3274314 | import torch
import torch.nn as nn
import torch.nn.functional as F
class SeparableConv2d(nn.Sequential):
"""
for Xception
"""
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, bias=True, padding_mode='zeros'):
super(SeparableConv2d, se... |
3274443 | from setuptools import find_packages, setup
setup(
name='sphinx_click_examples',
packages=find_packages('.'),
install_requires=['click'],
)
|
3274458 | from unittest.mock import patch
import pytest
from common import connect
from tests import MockResp
TIMEOUT = 5
status_repsonses = [None, {}, {"foo": {}}, {"foo": {"status": {}}}]
@pytest.mark.parametrize("data", status_repsonses)
def test_load_state(data):
patcherGet = patch("requests.get")
mock_get = pa... |
3274529 | import numpy as np
import random
import torch
import math
class Dataset:
def __init__(self, ds_name):
self.name = ds_name
self.dir = "datasets/" + ds_name + "/"
self.ent2id = {}
self.rel2id = {}
self.data = {spl: self.read(self.dir + spl + ".txt") for spl in ["train", "valid... |
3274579 | from io import StringIO
import contextlib
import sys
# import subprocess
# import webbrowser
from codelab_adapter import settings
from codelab_adapter.core_extension import Extension
import traceback
def get_traceback():
fp = StringIO()
traceback.print_exc(file=fp)
message = fp.getvalue()
return messag... |
3274655 | import djs_angle_match
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import plotsetup
from matplotlib import gridspec
plotsetup.fullpaperfig()
co=0
xlabel=['g mag','MJD/100','Airmass','Ang. Dist. (Deg)']
fil2=['g','r','i','z']
fields=['053','054','055','057','058','059']
fields=['0','053','054',... |
3274693 | from settings import WATCHED_SOURCES
from parsers import default
PARSERS = {}
for source, parsers in WATCHED_SOURCES.items():
parsers = [parsers] if type(parsers) == str else parsers
parser_modules = []
for module_name in parsers:
if module_name:
try:
exec('from parsers... |
3274722 | from __future__ import print_function
from __future__ import absolute_import
import unittest
import qgate
from qgate.script import *
class TestRepr(unittest.TestCase) :
def setUp(self) :
import io
self.file = io.StringIO()
def tearDown(self) :
# print(self.file.getvalue())
pa... |
3274729 | from django.core.management.base import BaseCommand
from django.db import transaction
from c3nav.mapdata.models.geometry.base import GeometryMixin
from c3nav.mapdata.utils.models import get_submodels
class Command(BaseCommand):
help = 'clean-up/fix all geometries in the database'
def handle(self, *args, **o... |
3274732 | import argparse
import collections
import faiss
import json
import logging
import numpy as np
import os
import time
import torch
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_text
from elasticsearch import Elasticsearch
from transformers import BertConfig, BertTokenizer, BertModel, BertPreTrai... |
3274744 | from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from profiles.models import Token
@login_required
def profile(request):
tokens = Token.objects.filter(user=request.user)
context = {
'tokens': tokens,
'current_tab': 'details'
}
if 'current_t... |
3274764 | import os
from utils.Phases import Phases
def join_and_create(path, folder):
full_path = os.path.join(path, folder)
if not os.path.exists(full_path):
os.mkdir(full_path)
return full_path
def path_to_datasets():
return os.path.join('..', 'datasets')
def path_to_condition(conf):
experim... |
3274767 | import torch
import pytest
from e3nn.nn import FullyConnectedNet
from e3nn.util.test import assert_auto_jitable
@pytest.mark.parametrize('act', [None, torch.tanh])
@pytest.mark.parametrize('var_in, var_out, out_act', [(1, 1, False), (1, 1, True), (0.1, 10.0, False), (0.1, 0.05, True)])
def test_variance(act, var_in,... |
3274775 | import unittest
from transformers import AutoModelForQuestionAnswering, AutoTokenizer
from nn_pruning.modules.quantization import (
prepare_qat,
prepare_static,
quantize,
)
class TestQuantization(unittest.TestCase):
def _test_quantization(self, prepare_fn):
model_name = "bert-base-uncased"
... |
3274810 | import csp
import re
import sys
class KenKen():
def __init__(self, size, lines):
self.variables = list()
self.neighbors = dict()
self.blockVar = list()
self.blockOp = list()
self.blockValue = list()
self.blockVariables = list()
"""Cre... |
3274813 | import os.path
from flask import request, abort
from flask_login import current_user
from werkzeug import Response
from werkzeug.wsgi import wrap_file
from wikked.web import app, get_wiki
from wikked.webimpl import (
get_page_or_raise, url_from_viewarg, mimetype_map)
@app.route('/pagefiles/<path:url>')
def read_p... |
3274847 | from typing import List
from .fib_number import recurring_fibonacci_number
def calculate_numbers(numbers: List[int]) -> List[int]:
"""
Calculates a range of Fibonacci numbers from a list.
:param numbers: (List[int]) the Fibonacci numbers to be calculated
:return: (List[int]) the calculated Fibonacci... |
3274860 | import json
import random
import time
from datetime import datetime, timezone
from broker import connect_mqtt_broker
def publish(client):
while True:
time.sleep(1)
# Test topic
test_topic = "test"
test_result = client.publish(
test_topic,
json.dumps(
... |
3274911 | from flask_babelex import lazy_gettext
from psi.app.models.product_sales import OverallProductSales, \
LastMonthProductSales, YesterdayProductSales, LastWeekProductSales, \
LastYearProductSales, LastQuarterProductSales, TodayProductSales, \
ThisWeekProductSales, ThisMonthProductSales, ThisYearProductSales,... |
3274920 | import torch
from torch.nn.functional import leaky_relu
from rational.torch import Rational
import numpy as np
t = torch.tensor([-2., -1, 0., 1., 2.])
expected_res = np.array(leaky_relu(t))
inp = torch.from_numpy(np.array(t)).reshape(-1)
cuda_inp = torch.tensor(np.array(t), dtype=torch.float, device="cuda").reshape(-... |
3274922 | from django.db import models
from django.contrib.auth.models import User
class Contact(models.Model):
firstname = models.CharField(verbose_name="Firstname", max_length=100)
lastname = models.CharField(verbose_name="Lastname", max_length=100)
email = models.EmailField(verbose_name="Email", max_length=100)
... |
3274959 | from pymel.core.modeling import *
from pymel.core.nodetypes import *
from pymel.core.uitypes import *
from pymel.core.animation import *
from pymel.core.other import *
from pymel.core.effects import *
from pymel.core.language import *
from pymel.core.windows import *
from pymel.core.context import *
from pymel.core.sys... |
3275034 | from fog.key.fingerprint import (
FingerprintingKeyer,
NgramsFingerprintKeyer
)
from fog.key.levenshtein import (
levenshtein_1d_keys,
damerau_levenshtein_1d_keys,
levenshtein_1d_blocks,
damerau_levenshtein_1d_blocks,
levenshtein_2d_blocks,
damerau_levenshtein_2d_blocks
)
from fog.key.mi... |
3275042 | from pathlib import Path
import dadmatools.pipeline.download as dl
import time
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence
import torch.nn.functional as F
from tqdm import tqdm
import os, sys
import pickle
import numpy as np
import transformers
################### helpers ##########... |
3275053 | import torch
import torchvision as tv
from torchvision import transforms
from torch.utils.data import DataLoader
from tqdm import tqdm
from colorama import Fore, Style
from torch.optim import SGD
from torch.optim.lr_scheduler import ReduceLROnPlateau
import torch.nn as nn
import statistics as stats
from keypoints impo... |
3275069 | import torch
import pandas as pd
from transformers import AutoTokenizer
from model import CoSent
from config import Params
def read_test_data(test_file):
test_df = pd.read_csv(test_file)
test_df = test_df.fillna("")
return test_df
def split_similarity(similarity, threshold):
if similarity >= thresho... |
3275078 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib
def read_from_txt(filename):
ans_dict = {}
with open(filename, "r") as f: # 打开文件
data = f.readlines() # 读取文件
for line in data:
line = line.strip('\n')
lines = line.split(" ")
ans_dict[lines[0]] = float(li... |
3275115 | from app.github.client import *
def test_parses_valid_github_url_with_https_scheme():
parsed = parse_github_url('https://github.com/acme/foobar')
assert parsed == ('acme', 'foobar', None)
def test_parses_valid_github_url_with_http_scheme():
parsed = parse_github_url('http://github.com/acme/foobar')
... |
3275126 | from threading import RLock
import struct
class Channel(object):
"""
a channel transfers frames over a stream. a frame is any blob of data,
up to 4GB in size. it is made of a type field (byte), a sequence number
(dword), and a length field (dword), followed by raw data. at the end
of the frame, a ... |
3275149 | from common import *
def db_insertion():
print('DB insertion tests')
test_data = get_test_data('.tmp')
results = {}
for key in sorted(test_data.keys()):
hm_history_db = get_data_path() + 'history_{}.testdb'.format(key)
cmd = ['hm-db', hm_history_db, 'parse', test_data[key], '!!hmse... |
3275173 | from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Int... |
3275185 | import time
import random
from tqdm import tqdm
import numpy as np
def greedy(
measure,
dataset_size,
subset_size,
start_indices,
intermediate_target=None,
clustering_combinations=None,
verbose=True
):
candidates = list(set(range(dataset_size)) - set(start_indices))
random.shuffl... |
3275203 | from fastapi import Depends, FastAPI, Header, HTTPException
from .routers import items, users
app = FastAPI()
async def get_token_header(x_token: str = Header(...)):
if x_token != "<PASSWORD>-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
app.include_router(users.router)... |
3275232 | import unittest
import textwrap
from collections import defaultdict
class TrackCallbacks(object):
kv_pre_events = []
'''Stores values added during the pre event dispatched callbacks.
'''
kv_applied_events = []
'''Stores values added during the applied event dispatched callbacks.
'''
kv_... |
3275241 | import time
from datetime import datetime
import sys
from copy import deepcopy
import multiprocessing as mp
import multiprocessing.pool
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from concurrent.futures import _base
from concurrent.futures.process import _global_shutdown, BrokenProcessPool, ... |
3275242 | f = open("count_log.txt", 'w', encoding="utf8")
for i in range(1, 11):
data = "%d번째 줄입니다.\n" % i
f.write(data)
f.close()
with open("count_log.txt", 'a', encoding="utf8") as f:
for i in range(100, 111):
data = "%d번째 줄입니다.\n" % i
f.write(data)
|
3275258 | from .extractors import (
Extractor,
NoneEvalExtractor,
NoneExtractor,
SimpleExtractor,
EvalExtractor,
SequenceEvalExtractor,
SequenceSimpleExtractor,
)
|
3275279 | from decimal import Decimal
from .abc import WithdrawalStrategy
from metrics import average, pmt
from collections import deque
from metrics import mean
# This ignores the Reserve stuff for now.
class ADD(WithdrawalStrategy):
def __init__(self, portfolio, harvest_strategy,
withdrawal_rate=Decimal('0.05... |
3275298 | from __future__ import absolute_import
from __future__ import print_function
try:
from unittest.mock import patch
except ImportError:
from mock import patch
import os
import tempfile
import shutil
from os.path import join as p
from rdflib.term import URIRef
from owmeta.data_trans.neuron_data import NeuronCSVDa... |
3275338 | import logging
from typing import Any, Callable, Union
from .conditions import render
from .exceptions import (
InvalidModel,
InvalidStream,
InvalidTemplate,
MissingObjects,
)
from .models import BaseModel, Index, subclassof, unpack_from_dynamodb
from .search import Search
from .session import SessionW... |
3275355 | import cv2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
img = cv2.imread('beach.jpg')
rows, cols, ch = img.shape
# CAM0 rotation
R = np.array([[0.949462, 0.046934, 0.310324],
[-0.042337, 0.998867, -0.021532],
[-0.310985, 0.007308, 0.950373]])
... |
3275386 | from apiwrapper.endpoints.cash_register import CashRegister
from apiwrapper.endpoints.endpoint import Endpoint
from apiwrapper.endpoints.monetary_account import MonetaryAccount
class CashRegisterTab(Endpoint):
__endpoint_cash_register_tab = "tab"
__endpoint_cash_register_tab_item = "tab-item"
__endpoint_c... |
3275412 | from pytti import *
from pytti.Image import DifferentiableImage
import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.transforms import functional as TF
from PIL import Image
def break_tensor(tensor):
floors = tensor.floor().long()
ceils = tensor.ce... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.