id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
31603 | from os import environ
from pathlib import Path
from appdirs import user_cache_dir
from ._version import version as __version__ # noqa: F401
from .bridge import Transform # noqa: F401
from .core import combine # noqa: F401
from .geodesic import BBox, line, panel, wedge # noqa: F401
from .geometry import get_coast... |
31611 | class ControlStyles(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies the style and behavior of a control.
enum (flags) ControlStyles,values: AllPaintingInWmPaint (8192),CacheText (16384),ContainerControl (1),DoubleBuffer (65536),EnableNotifyMessage (32768),FixedHeight (64),FixedWidth (32),Opaque ... |
31617 | from Crypto.Hash import HMAC, SHA256
import base64
def hmac256Calculation(keyHmac, data):
h = HMAC.new(keyHmac.encode("ascii"), digestmod=SHA256)
h.update(data.encode("ascii"))
return h.digest()
def base64Encoding(input):
dataBase64 = base64.b64encode(input)
dataBase64P = dataBase64.decode("UTF-8"... |
31645 | from django.shortcuts import render,redirect,HttpResponse
from repository import models
def trouble_list(request):
# user_info = request.session.get('user_info') # {id:'',}
current_user_id = 1
result = models.Trouble.objects.filter(user_id=current_user_id).order_by('status').\
only('title','status',... |
31648 | from datetime import datetime
from typing import Optional
from src.utils.config import config
from tortoise import fields
from tortoise.models import Model
defaule_nickname: str = config.get('default').get('nickname')
class BotInfo(Model):
'''QQ机器人表'''
bot_id = fields.IntField(pk=True)
'''机器人QQ号'''
... |
31671 | import datetime
import json
import logging
import operator
import os
from collections import defaultdict
from datetime import date
import vk_api
import vk_api.exceptions
from vk_api import execute
#from .TimeActivityAnalysis import VKOnlineGraph
from .VKFilesUtils import check_and_create_path, DIR_PREFIX
class VKAc... |
31707 | import numpy as np
from nlpaug.model.audio import Audio
class Normalization(Audio):
def manipulate(self, data, method, start_pos, end_pos):
aug_data = data.copy()
if method == 'minmax':
new_data = self._min_max(aug_data[start_pos:end_pos])
elif method == 'max':
new_data = self._max(aug_data[start_pos:en... |
31708 | from __future__ import print_function, division
import numpy as np
weights = np.transpose(np.load('w0.npy'))
print(weights.shape)
feature_names = ["" for i in range(125)]
prev = 0
prev_name = ''
for line in open('feature_names.txt'):
if line.startswith('#'):
continue
words = line.split()
index = ... |
31762 | try:
import ujson as json
except ModuleNotFoundError:
# https://github.com/python/mypy/issues/1153 (mypy bug with try/except conditional imports)
import json # type: ignore
try:
import msgpack
except ModuleNotFoundError:
pass
class Serializer:
pass
class StringSerializer(Serializer):
d... |
31766 | import numpy as np
from numpy.testing import assert_allclose
from robogym.envs.rearrange.common.utils import (
get_mesh_bounding_box,
make_block,
make_blocks_and_targets,
)
from robogym.envs.rearrange.simulation.composer import RandomMeshComposer
from robogym.mujoco.mujoco_xml import MujocoXML
def _get_d... |
31784 | import logging
import pytest
from selenium.webdriver.remote.remote_connection import LOGGER
from stere.areas import Area, Areas
LOGGER.setLevel(logging.WARNING)
def test_areas_append_wrong_type():
"""Ensure a TypeError is raised when non-Area objects are appended
to an Areas.
"""
a = Areas()
... |
31810 | class ATMOS(object):
'''
class ATMOS
- attributes:
- self defined
- methods:
- None
'''
def __init__(self,info):
self.info = info
for key in info.keys():
setattr(self, key, info[key])
def __repr__(self):
return 'Instance of class AT... |
31904 | import re
from .utils import validator
regex = (
r'^[A-Z]{2}[0-9]{2}[A-Z0-9]{13,30}$'
)
pattern = re.compile(regex)
def char_value(char):
"""A=10, B=11, ..., Z=35
"""
if char.isdigit():
return int(char)
else:
return 10 + ord(char) - ord('A')
def modcheck(value):
"""Check if... |
31969 | import math
def get_dist_bins(num_bins, interval=0.5):
bins = [(interval * i, interval * (i + 1)) for i in range(num_bins - 1)]
bins.append((bins[-1][1], float('Inf')))
return bins
def get_dihedral_bins(num_bins, rad=False):
first_bin = -180
bin_width = 2 * 180 / num_bins
bins = [(first_bin ... |
31999 | import logging
from fastapi import APIRouter
from starlette import status
from api.endpoints.dependencies.tenant_security import get_from_context
from api.endpoints.models.v1.tenant import TenantGetResponse
from api.services.v1 import tenant_service
router = APIRouter()
logger = logging.getLogger(__name__)
@rou... |
32062 | import SpiceInterface
import TestUtilities
# create the test utility object
test_utilities_obj = TestUtilities.TestUtilities()
test_utilities_obj.netlist_generation('bandgap_opamp_test_op.sch', 'rundir')
# create the spice interface
spice_interface_obj = SpiceInterface.SpiceInterface(netlist_path="rundir/bandgap_opa... |
32101 | class GraphLearner:
"""Base class for causal discovery methods.
Subclasses implement different discovery methods. All discovery methods are in the package "dowhy.causal_discoverers"
"""
def __init__(self, data, library_class, *args, **kwargs):
self._data = data
self._labels = list(self._data.columns)
self... |
32135 | import pdfkit
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
pdfkit.from_url('http://google.com', '/tmp/out.pdf')
with open('/tmp/out.pdf', 'rb') as f:
response = s3.put_object(
Bucket='temp-awseabsgddev',
Key='juni/google.pdf',
Body=f.re... |
32142 | class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
# Since all the three parts are equal, if we sum all element of arrary it should be a multiplication of 3
# so the sum of each part must be equal to sum of all element divided by 3
quotient, remainder = divmod(sum(A), 3)
... |
32144 | import os
import sys
sys.path.append('.')
import argparse
import numpy as np
import os.path as osp
from multiprocessing import Process, Pool
from glob import glob
from tqdm import tqdm
import tensorflow as tf
from PIL import Image
from lib.core.config import INSTA_DIR, INSTA_IMG_DIR
def process_single_record(fname,... |
32150 | STATE_CITY = "fluids_state_city"
OBS_QLIDAR = "fluids_obs_qlidar"
OBS_GRID = "fluids_obs_grid"
OBS_BIRDSEYE = "fluids_obs_birdseye"
OBS_NONE = "fluids_obs_none"
BACKGROUND_CSP = "fluids_background_csp"
BACKGROUND_NULL = "fluids_background_null"
REWARD_PATH = "fluids_reward_path"
REWARD_NONE = "fluids_rew... |
32173 | import numpy as np
from JacobiPolynomials import *
import math
# 1D - LINE
#------------------------------------------------------------------------------------------------------------------#
#------------------------------------------------------------------------------------------------------------------#
#---------... |
32192 | from conans import ConanFile, tools
class HapplyConan(ConanFile):
name = "happly"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/nmwsharp/happly"
topics = ("conan", "happly", "ply", "3D")
license = "MIT"
description = "A C++ header-only parser for the PLY... |
32206 | import pytest
import stweet as st
from tests.test_util import get_temp_test_file_name, get_tweets_to_tweet_output_test, \
two_lists_assert_equal
def test_csv_serialization():
csv_filename = get_temp_test_file_name('csv')
tweets_collector = st.CollectorTweetOutput()
get_tweets_to_tweet_output_test([
... |
32311 | import os
os.system("pip install tqsdk -i https://pypi.tuna.tsinghua.edu.cn/simple")
os.system("pip install numba -i https://pypi.tuna.tsinghua.edu.cn/simple")
os.system("pip install janus -i https://pypi.tuna.tsinghua.edu.cn/simple")
os.system("pip install redis -i https://pypi.tuna.tsinghua.edu.cn/simple")
os... |
32322 | from opyoid.bindings.binding import Binding
from opyoid.bindings.binding_to_provider_adapter import BindingToProviderAdapter
from opyoid.bindings.registered_binding import RegisteredBinding
from opyoid.injection_context import InjectionContext
from opyoid.provider import Provider
from opyoid.utils import InjectedT
from... |
32359 | from abc import ABCMeta, abstractmethod
from functools import partial
from typing import Tuple, Union
import numexpr
import numpy as np
from scipy import sparse, special
from tabmat import MatrixBase, StandardizedMatrix
from ._functions import (
binomial_logit_eta_mu_deviance,
binomial_logit_rowwise_gradient_... |
32370 | from app.factory import create_app, celery_app
app = create_app(config_name="DEVELOPMENT")
app.app_context().push()
if __name__ == "__main__":
app.run()
|
32392 | import json
def get_qtypes(dataset_name, part):
"""Return list of question-types for a particular TriviaQA-CP dataset"""
if dataset_name not in {"location", "person"}:
raise ValueError("Unknown dataset %s" % dataset_name)
if part not in {"train", "dev", "test"}:
raise ValueError("Unknown part %s" % par... |
32395 | from cssdbpy import Connection
from time import time
import md5
if __name__ == '__main__':
conn = Connection('127.0.0.1', 8888)
for i in xrange(0, 10000):
md5word = md5.new('word{}'.format(i)).hexdigest()
create = conn.execute('hset','words', md5word, int(time()))
value = conn.execute('hget','words', md5word)... |
32397 | import datetime
import pytz
from tws_async import *
stocks = [
Stock('TSLA'),
Stock('AAPL'),
Stock('GOOG'),
Stock('INTC', primaryExchange='NASDAQ')
]
forexs = [
Forex('EURUSD'),
Forex('GBPUSD'),
Forex('USDJPY')
]
endDate = datetime.date.today()
startDate = endDate - datetime.timedelta(day... |
32403 | import numpy as np
def mean_or_nan(xs):
"""Return its mean a non-empty sequence, numpy.nan for a empty one."""
return np.mean(xs) if xs else np.nan |
32414 | import pytest
from playwright.sync_api import Page
from pages.main_page.main_page import MainPage
from test.test_base import *
import logging
import re
logger = logging.getLogger("test")
@pytest.mark.only_browser("chromium")
def test_find_element_list(page: Page):
main_page = MainPage(base_url, page)
main_pa... |
32444 | import sys
import os
import timeit
# use local python package rather than the system install
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../python"))
from bitboost import BitBoostRegressor
import numpy as np
import sklearn.metrics
nfeatures = 5
nexamples = 10000
data = np.random.choice(np.array([0.0,... |
32446 | import unittest
import os
import logging
import time
import re
import splunklib.client as client
import splunklib.results as results
from splunklib.binding import HTTPError
from . import dltk_api
from . import splunk_api
from . import dltk_environment
level_prog = re.compile(r'level=\"([^\"]*)\"')
msg_prog = re.comp... |
32490 | from factory import Faker
from .network_node import NetworkNodeFactory
from ..constants.network import ACCOUNT_FILE_HASH_LENGTH, BLOCK_IDENTIFIER_LENGTH, MAX_POINT_VALUE, MIN_POINT_VALUE
from ..models.network_validator import NetworkValidator
class NetworkValidatorFactory(NetworkNodeFactory):
daily_confirmation_... |
32491 | from menu.models import Menu
from products.models import Product, Category
def get_dashboard_data_summary():
cardapios = Menu.objects.all()
produtos = Product.objects.all()
categorias = Category.objects.all()
return {'total_cardapios': len(cardapios),
'total_produtos': len(produtos),
... |
32548 | import torch
from torch.nn import Module, Parameter
from torch.autograd import Function
class Forward_Warp_Python:
@staticmethod
def forward(im0, flow, interpolation_mode):
im1 = torch.zeros_like(im0)
B = im0.shape[0]
H = im0.shape[2]
W = im0.shape[3]
if interpolation_m... |
32549 | import itertools
import Partitioning
class Algorithm( object ):
def __init__( self, linv, variant, init, repart, contwith, before, after, updates ):
self.linv = linv
self.variant = variant
if init:
#assert( len(init) == 1 )
self.init = init[0]
else:
... |
32603 | from .defines import MsgLv, UnknownFieldValue, ValidateResult, get_msg_level
from .validators import SpecValidator
def _wrap_error_with_field_info(failure):
if get_msg_level() == MsgLv.VAGUE:
return RuntimeError(f'field: {failure.field} not well-formatted')
if isinstance(failure.value, UnknownFieldVal... |
32604 | import sys
__all__ = ['IntegerTypes', 'StringTypes']
if sys.version_info < (3,):
IntegerTypes = (int, long)
StringTypes = (str, unicode)
long = long
import __builtin__ as builtins
else:
IntegerTypes = (int,)
StringTypes = (str,)
long = int
import builtins
|
32615 | try:
import tensorflow
except ModuleNotFoundError:
pkg_name = 'tensorflow'
import os
import sys
import subprocess
from cellacdc import myutils
cancel = myutils.install_package_msg(pkg_name)
if cancel:
raise ModuleNotFoundError(
f'User aborted {pkg_name} installation'
... |
32616 | import aioredis
import trafaret as t
import yaml
from aiohttp import web
CONFIG_TRAFARET = t.Dict(
{
t.Key('redis'): t.Dict(
{
'port': t.Int(),
'host': t.String(),
'db': t.Int(),
'minsize': t.Int(),
'maxsize': t.In... |
32633 | import sys
from antlr4 import *
from ChatParser import ChatParser
from ChatListener import ChatListener
from antlr4.error.ErrorListener import *
import io
class ChatErrorListener(ErrorListener):
def __init__(self, output):
self.output = output
self._symbol = ''
def syntaxError(sel... |
32634 | from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
path("faq/", views.faq, name="faq"),
path("plagiarism_policy/", views.plagiarism_policy,
name="plagiarism_policy"),
path("privacy_policy/", views.privacy_policy, name="privacy_policy"),
path... |
32648 | from utils import *
import torch
import sys
import numpy as np
import time
import torchvision
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as datasets
def validate_pgd(val_loader, model, criterion, K, step, configs, logger, save_image=False, HE=False):
... |
32661 | from tool.runners.python import SubmissionPy
class DavidSubmission(SubmissionPy):
def bucket_key(self, w, i):
return w[:i] + w[i+1:]
def run(self, s):
words = s.split("\n")
n = len(words[0])
buckets = [set() for i in range(n)]
for w in words:
for i in range(... |
32666 | import pytest
@pytest.mark.parametrize("cli_options", [
('-k', 'notestdeselect',),
])
def test_autoexecute_yml_keywords_skipped(testdir, cli_options):
yml_file = testdir.makefile(".yml", """
---
markers:
- marker1
- marker2
---
- provider: python
type: assert
expression: "1"
""")
assert yml_fi... |
32670 | import solana_rpc as rpc
def get_apr_from_rewards(rewards_data):
result = []
if rewards_data is not None:
if 'epochRewards' in rewards_data:
epoch_rewards = rewards_data['epochRewards']
for reward in epoch_rewards:
result.append({
'percent_c... |
32675 | import re
class Solution:
def helper(self, expression: str) -> List[str]:
s = re.search("\{([^}{]+)\}", expression)
if not s: return {expression}
g = s.group(1)
result = set()
for c in g.split(','):
result |= self.helper(expression.replace('{' + g + '}', c, ... |
32680 | from unittest.mock import patch
from dependent import parameter_dependent
@patch('math.sqrt')
def test_negative(mock_sqrt):
assert parameter_dependent(-1) == 0
mock_sqrt.assert_not_called()
@patch('math.sqrt')
def test_zero(mock_sqrt):
mock_sqrt.return_value = 0
assert parameter_dependent(0) == 0
... |
32683 | import os
_lab_components = """from api2db.ingest import *
CACHE=True # Caches API data so that only a single API call is made if True
def import_target():
return None
def pre_process():
return None
def data_features():
return None
def post_process():
return None
if __name__ == "__main__":
... |
32711 | from .client import Client
class Stats(Client):
def __init__(self, api_key='YourApiKeyToken'):
Client.__init__(self, address='', api_key=api_key)
self.url_dict[self.MODULE] = 'stats'
def get_total_ether_supply(self):
self.url_dict[self.ACTION] = 'ethsupply'
self.build_url()
... |
32719 | import MiniNero
import ed25519
import binascii
import PaperWallet
import cherrypy
import os
import time
import bitmonerod
import SimpleXMR2
import SimpleServer
message = "send0d000114545737471em2WCg9QKxRxbo6S3xKF2K4UDvdu6hMc"
message = "send0d0114545747771em2WCg9QKxRxbo6S3xKF2K4UDvdu6hMc"
sec = raw_input("sec?")
print... |
32730 | import datetime
import remi
import core.globals
connected_clients = {} # Dict with key=session id of App Instance and value=ws_client.client_address of App Instance
connected_clients['number'] = 0 # Special Dict Field for amount of active connections
client_route_url_to... |
32756 | from diofant.utilities.decorator import no_attrs_in_subclass
__all__ = ()
def test_no_attrs_in_subclass():
class A:
x = 'test'
A.x = no_attrs_in_subclass(A, A.x)
class B(A):
pass
assert hasattr(A, 'x') is True
assert hasattr(B, 'x') is False
|
32763 | from ckan_cloud_operator import kubectl
def get(what, *args, required=True, namespace=None, get_cmd=None, **kwargs):
return kubectl.get(what, *args, required=required, namespace=namespace, get_cmd=get_cmd, **kwargs)
|
32773 | import os
import tarfile
import time
import pickle
import numpy as np
from Bio.Seq import Seq
from scipy.special import expit
from scipy.special import logit
import torch
import torch.nn.functional as F
""" Get directories for model and seengenes """
module_dir = os.path.dirname(os.path.realpath(__file__))
model_dir ... |
32787 | import inspect
from unittest.mock import Mock
from _pytest.monkeypatch import MonkeyPatch
from rasa.core.policies.ted_policy import TEDPolicy
from rasa.engine.training import fingerprinting
from rasa.nlu.classifiers.diet_classifier import DIETClassifier
from rasa.nlu.selectors.response_selector import ResponseSelector... |
32818 | import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from .build import MODEL_REGISTRY
@MODEL_REGISTRY.register()
class CNNRNN(nn.Module):
def __init__(self, cfg):
super().__init__()
input_dim = 512
... |
32820 | from os import environ as env
import json
import utils
import utils.aws as aws
import utils.handlers as handlers
def put_record_to_logstream(event: utils.LambdaEvent) -> str:
"""Put a record of source Lambda execution in LogWatch Logs."""
log_group_name = env["REPORT_LOG_GROUP_NAME"]
utils.Log.info("Fet... |
32823 | import os
from bc import Imitator
import numpy as np
from dataset import Example, Dataset
import utils
#from ale_wrapper import ALEInterfaceWrapper
from evaluator import Evaluator
from pdb import set_trace
import matplotlib.pyplot as plt
#try bmh
plt.style.use('bmh')
def smooth(losses, run=10):
new_losses = []
... |
32824 | from IPython import get_ipython
from IPython.display import display
def is_ipynb():
return type(get_ipython()).__module__.startswith('ipykernel.')
|
32857 | import pytest
@pytest.mark.order(4)
def test_four():
pass
@pytest.mark.order(3)
def test_three():
pass
|
32868 | import math
import random
from typing import Tuple
import cv2
import numpy as np
def np_free_form_mask(
max_vertex: int, max_length: int, max_brush_width: int, max_angle: int, height: int, width: int
) -> np.ndarray:
mask = np.zeros((height, width), np.float32)
num_vertex = random.randint(0, max_vertex)... |
32892 | import json
from pathlib import Path
from typing import Any, Dict
from git import Repo
from cruft.exceptions import CruftAlreadyPresent, NoCruftFound
CruftState = Dict[str, Any]
#######################
# Cruft related utils #
#######################
def get_cruft_file(project_dir_path: Path, exists: bool = True)... |
32898 | import enum
from django.db import models
from care.facility.models import FacilityBaseModel
from care.users.models import User
from django.contrib.postgres.fields import JSONField
class Notification(FacilityBaseModel):
class EventType(enum.Enum):
SYSTEM_GENERATED = 50
CUSTOM_MESSAGE = 100
E... |
32954 | import pickle
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
import pytest
from oddt.scoring.models import classifiers, regressors
@pytest.mark.filterwarnings('ignore:Stochastic Optimizer')
@pytest.mark.parametrize('cls',
[classifiers.svm(probabil... |
32991 | from bitmovin_api_sdk.account.organizations.groups.groups_api import GroupsApi
from bitmovin_api_sdk.account.organizations.groups.tenants.tenants_api import TenantsApi
from bitmovin_api_sdk.account.organizations.groups.invitations.invitations_api import InvitationsApi
from bitmovin_api_sdk.account.organizations.groups.... |
32993 | import numpy as np
import random
N = 10
def null(a, rtol=1e-5):
u, s, v = np.linalg.svd(a)
rank = (s > rtol*s[0]).sum()
return rank, v[rank:].T.copy()
def gen_data(N, noisy=False):
lower = -1
upper = 1
dim = 2
X = np.random.rand(dim, N)*(upper-lower)+lower
while True:
Xsa... |
33004 | import logging
def create_app(config=None, testing=False):
from airflow.www_rbac import app as airflow_app
app, appbuilder = airflow_app.create_app(config=config, testing=testing)
# only now we can load view..
# this import might causes circular dependency if placed above
from dbnd_airflow.airfl... |
33015 | import argparse
import json
from easydict import EasyDict
def get_args():
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument(
'-c', '--config',
metavar='C',
default=None,
help='The Configuration file')
argparser.add_argument(
'-i', '--id... |
33017 | from typing import List
from typing import Optional
from pydantic import BaseModel
class WebFingerRequest(BaseModel):
rel: Optional[str] = 'http://openid.net/specs/connect/1.0/issuer'
resource: str
class AuthorizationRequest(BaseModel):
acr_values: Optional[List[str]]
claims: Optional[dict]
cla... |
33029 | from . import configure, core, draw, io, interp, retrieve, qc
__all__ = ["configure", "core", "draw", "io", "interp", "qc", "retrieve"]
|
33074 | from avatar2 import *
import sys
import os
import logging
import serial
import time
import argparse
import pyudev
import struct
import ctypes
from random import randint
# For profiling
import pstats
logging.basicConfig(filename='/tmp/inception-tests.log', level=logging.INFO)
# ************************************... |
33103 | import torch
def magic_box(x):
"""DiCE operation that saves computation graph inside tensor
See ``Implementation of DiCE'' section in the DiCE Paper for details
Args:
x (tensor): Input tensor
Returns:
1 (tensor): Tensor that has computation graph saved
References:
https://g... |
33140 | from openem.models import ImageModel
from openem.models import Preprocessor
import cv2
import numpy as np
import tensorflow as tf
from collections import namedtuple
import csv
Detection=namedtuple('Detection', ['location',
'confidence',
'species',... |
33144 | import pytest
grblas = pytest.importorskip("grblas")
from metagraph.tests.util import default_plugin_resolver
from . import RoundTripper
from metagraph.plugins.numpy.types import NumpyMatrixType
from metagraph.plugins.graphblas.types import GrblasMatrixType
import numpy as np
def test_matrix_roundtrip_dense_square(... |
33166 | import os
import sys
import torch
from torch import nn
from torch.nn import functional as F, init
from src.utils import bernoulli_log_pdf
from src.objectives.elbo import \
log_bernoulli_marginal_estimate_sets
class Statistician(nn.Module):
def __init__(self, c_dim, z_dim, hidden_dim_statistic=3, hidden_dim=40... |
33192 | import numpy as np
import pandas as pd
from pandas.util import testing as pdt
import pytest
from spandex import TableFrame
from spandex.io import db_to_df, df_to_db
def test_tableframe(loader):
table = loader.tables.sample.hf_bg
for cache in [False, True]:
tf = TableFrame(table, index_col='gid', cach... |
33200 | print("linear search")
si=int(input("\nEnter the size:"))
data=list()
for i in range(0,si):
n=int(input())
data.append(n)
cot=0
print("\nEnter the number you want to search:")
val=int(input())
for i in range(0,len(data)):
if(data[i]==val):
break;
else:
cot=co... |
33206 | from dataclasses import dataclass
from app import crud
from app.schemas import UserCreate, SlackEventHook
from app.settings import REACTION_LIST, DAY_MAX_REACTION
# about reaction
REMOVED_REACTION = 'reaction_removed'
ADDED_REACTION = 'reaction_added'
APP_MENTION_REACTION = 'app_mention'
# about command
CREATE_USER... |
33249 | import os
import re
import yaml
for root, dirs, files in os.walk("."):
for file in files:
njk = os.path.join(root, file)
if njk.endswith(".njk"):
with open(njk, "r") as file:
lines = file.read().split("\n")
if not(lines[0].startswith("---")):
... |
33285 | import sys
try:
import uos as os
except ImportError:
import os
if not hasattr(os, "unlink"):
print("SKIP")
sys.exit()
# cleanup in case testfile exists
try:
os.unlink("testfile")
except OSError:
pass
try:
f = open("testfile", "r+b")
print("Unexpectedly opened non-existing file")
excep... |
33364 | def f(x):
if x:
x = 1
else:
x = 'zero'
y = x
return y
f(1)
|
33379 | import autograd.numpy as anp
import numpy as np
from autograd import value_and_grad
from pymoo.factory import normalize
from pymoo.util.ref_dirs.energy import squared_dist
from pymoo.util.ref_dirs.optimizer import Adam
from pymoo.util.reference_direction import ReferenceDirectionFactory, scale_reference_directions
c... |
33406 | import torch
from torch import Tensor
from torch.utils.data import Dataset
from torchvision import io
from pathlib import Path
from typing import Tuple
from torchvision import transforms as T
class CelebAMaskHQ(Dataset):
CLASSES = [
'background', 'skin', 'nose', 'eye_g', 'l_eye', 'r_eye', 'l_brow', 'r_br... |
33459 | import _config
import _utils
CONFIG_PATH = "config.toml"
def main():
config = _config.read(CONFIG_PATH)
for path_name in [x.in_ for x in config.directorios]:
_utils.list_jpg_files_in_dir(path_name)
if __name__ == "__main__":
main()
|
33501 | from pyfasta import Fasta
def writebed(probelist, outbedfile):
'''probe list format:
chr\tstart\tend
'''
outio = open(outbedfile, 'w')
for pbnow in probelist:
print(pbnow, file=outio)
outio.close()
def writefa(genomefile, bedfile, outfile):
fastafile = Fasta(genomefile... |
33503 | import rclpy
from rclpy.action import ActionClient
from rclpy.node import Node
from action_tutorials_interfaces.action import Fibonacci
class FibonacciActionClient(Node):
def __init__(self):
super().__init__('fibonacci_action_client')
self._action_client = ActionClient(self, Fibonacci, 'fibonacc... |
33545 | from winrt.windows.media.control import GlobalSystemMediaTransportControlsSessionManager
from winrt.windows.storage.streams import DataReader, Buffer, InputStreamOptions
async def get_current_session():
"""
current_session.try_play_async()
current_session.try_pause_async()
current_session.try_toggle_p... |
33564 | from collections import namedtuple
import json, logging, socket, re, struct, time
from typing import Tuple, Iterator
from urllib.parse import urlparse, parse_qs
from backend import Backend, Change
from protocol import PacketType, recvall, PKT_CHANGE_TYPES, change_from_packet, packet_from_change, send_packet, recv_pack... |
33569 | from ..factory import Method
class setBotUpdatesStatus(Method):
pending_update_count = None # type: "int32"
error_message = None # type: "string"
|
33589 | from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from argparse import ArgumentParser, Namespace
class CtlCommand(metaclass=ABCMeta):
"""Implements a subcommand of grouper-ctl."""
@staticmethod
@abstractmethod
def add_arguments(parser):
# type: (A... |
33602 | import time
from time import sleep
def print_elapsed_time(exit_event):
start_time = time.time()
while True:
if exit_event.is_set():
break
print(f'Running for {round(time.time() - start_time)} s', end='\r')
sleep(1)
|
33609 | import os
import tensorflow as tf
from BertLibrary.bert_predictor import BertPredictor
from BertLibrary.bert_trainer import BertTrainer
from BertLibrary.bert_evaluator import BertEvaluator
from tensorflow.estimator import Estimator
from tensorflow.estimator import RunConfig
from BertLibrary.bert.run_classifier import... |
33631 | import itertools
import logging
import netCDF4
import numpy
from .. import core
from ..constants import masked as cfdm_masked
from ..decorators import (
_inplace_enabled,
_inplace_enabled_define_and_cleanup,
_manage_log_level_via_verbosity,
)
from ..functions import abspath
from ..mixin.container import C... |
33658 | import pytest
import yaml
from nequip.utils import instantiate
simple_default = {"b": 1, "d": 31}
class SimpleExample:
def __init__(self, a, b=simple_default["b"], d=simple_default["d"]):
self.a = a
self.b = b
self.d = d
nested_default = {"d": 37}
class NestedExample:
def __init... |
33692 | from pathlib import Path
from tkinter import Frame, Canvas, Entry, Text, Button, PhotoImage, messagebox
import controller as db_controller
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
def add_reserva... |
33727 | from com.huawei.iotplatform.client.dto.DeviceCommandCancelTaskRespV4 import DeviceCommandCancelTaskRespV4
from com.huawei.iotplatform.client.dto.Pagination import Pagination
class QueryDeviceCmdCancelTaskOutDTO(object):
pagination = Pagination()
data = DeviceCommandCancelTaskRespV4()
def __init__(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.