id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
86307 | from ..core.base import ErsiliaBase
from ..app.app import AppBase, StreamlitApp
import subprocess
import os
import shutil
import streamlit
class DeployBase(ErsiliaBase):
def __init__(self, config_json=None, credentials_json=None):
ErsiliaBase.__init__(
self, config_json=config_json, credential... |
86314 | import argparse
import os
import sourcetraildb as srctrl
def main():
parser = argparse.ArgumentParser(description="SourcetrailDB Python API Example")
parser.add_argument("--database-file-path", help="path to the generated Sourcetrail database file",
type=str, required=True)
parser.add_argument("--source-file-path... |
86315 | import tadtool.tad as tad
import tadtool.plot as tp
# load regions data set
regions = tad.HicRegionFileReader().regions("chr12_20-35Mb_regions.bed")
# load matrix
matrix = tad.HicMatrixFileReader().matrix("chr12_20-35Mb.matrix.txt")
# prepare plot
tad_plot = tp.TADtoolPlot(matrix, regions, norm='lin', max_dist=10000... |
86321 | from flask import Blueprint
# 每一个模块蓝图可以拥有自己的静态文件夹,默认的app会设置好系统级别的static
# 但是蓝图需要自己手动设置注册静态文件的路径
# 为了区分加载的是主应用下的static还是模块下的static,给模块初始化的时候添加url前缀
# 添加前缀后,那么该蓝图.route的时候就自动添加了该前缀, 加载img的时候使用/cart/static/xxx.img
# 如果模块模板和主营业模板下都拥有相同的html名字,则优先加载主营业下的模板
cart_blue = Blueprint('cart', __name__,
stat... |
86350 | from .settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'HOST': 'dbe2e',
'PORT': 5432,
}
} |
86373 | from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_conv_layer
from mmcv.runner import load_checkpoint
from mmedit.models.common import (PixelShufflePack, ResidualBlockNoBN,
make_layer)
from mmedit.models.registr... |
86384 | from django.conf import settings
def _ellipse_bbox(x, y, height):
x *= settings.RENDER_SCALE
y *= settings.RENDER_SCALE
y = height-y
return ((x - 2, y - 2), (x + 2, y + 2))
def _line_coords(from_point, to_point, height):
return (from_point.x * settings.RENDER_SCALE, height - (from_point.y * sett... |
86466 | from contextvars import ContextVar
from typing import Optional
from telethon.tl.custom import Message
class Context:
__print_output: ContextVar[str]
__msg: ContextVar[Optional[Message]]
def __init__(self):
self.__msg = ContextVar('msg')
self.__print_output = ContextVar('print_output', de... |
86474 | from types import SimpleNamespace
import pytest
from mock import patch, MagicMock
from backend.lambdas.tasks.check_queue_size import handler
pytestmark = [pytest.mark.unit, pytest.mark.task]
@patch("backend.lambdas.tasks.check_queue_size.sqs")
def test_it_returns_correct_queue_size(mock_resource):
mock_queue =... |
86487 | import os
import cv2
import numpy as np
import random
from tqdm import tqdm
TEMP_CACHE_NAME = './~temp.png'
gaussian_blur_params = [1, 3, 3, 3, 3, 3, 5]
def build_dataset(data_dir, new_dir='datasets', dataset_name='rvl-cdip', mode='train'):
origin_dir = os.path.join(data_dir, dataset_name)
label_path = os.pa... |
86489 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
import numpy.testing as npt
from reinforceflow.core import SumTree, MinTree
def test_sumtree_sum():
capacity = 100000
dataset = list(range(capacity))
dataset_actual = list(range... |
86492 | import threading
import logging
import time
class ThreadHelperException(Exception):
pass
class ThreadHelper(threading.Thread):
"""
The class provides a frame for the threads used in the framework.
"""
# ------------------------------------------------------------------------------... |
86519 | from __future__ import division
from past.utils import old_div
#===============================================================================
# SCG Scaled conjugate gradient optimization.
#
# Copyright (c) <NAME> (1996-2001)
# updates by <NAME> 2013
#
# Permission is granted for anyone to copy, use, or modif... |
86540 | import logging
import os
import time
import pytest
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import TSV
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler())
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
@pytest.fixture(scope="modu... |
86571 | from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class SupportTicket(models.Model):
"""A support ticket submitted by an unsatisfied customer :("""
name = models.CharField(max_length=100)
phone_number = PhoneNumberField(
help_text='Must include international ... |
86619 | pytest_plugins = ("pytester",)
def test_help_message(testdir):
result = testdir.runpytest("--help")
# fnmatch_lines does an assertion internally
result.stdout.fnmatch_lines(
[
"stress:",
"*--delay=DELAY*The amount of time to wait between each test loop.",
"*--ho... |
86640 | import numpy as np
import pandas as pd
import re
import datetime
from datetime import datetime, timedelta
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
# dplyr-style for python
from dppd import dppd
dp, X = dppd()
import itertools
_DEFAULT_TIME_SCALE = 12 * 3 * 31 # 36 months
... |
86643 | import pandas as pd
import matplotlib.pyplot as plt
# Import our data file
stock_prices = pd.read_csv('/data/intel_amd_stock_prices.csv')
# Print DataFrame
# print(stock_prices)
# Create y-columns
y_columns = ['intel', 'amd']
# Name / assign axis
stock_prices.plot(x='month', y=y_columns)
# Create plot title
plt.ti... |
86692 | from typing import Dict, Union, Tuple
from phonenumbers import timezone, parse, geocoder
from waio.rules import ABCRule
from waio.types import Message
G_T = Dict[str, Union[int, str, Tuple[str]]]
class RussianNumberRule(ABCRule):
async def check(self, message: Message) -> Union[bool, Dict[str, G_T]]:
ph... |
86704 | import unittest
import plotly.graph_objs as go
class TestPlotly(unittest.TestCase):
def test_figure(self):
trace = {'x': [1, 2], 'y': [1, 3]}
data = [ trace ]
go.Figure(data=data)
|
86780 | from django.conf.urls import patterns, url
from stucampus.master.views.manage.account import ListAccount, ShowAccount
from stucampus.master.views.manage.infor import ListInfor, PostInfor,Information
from stucampus.master.views.manage.organization import ListOrganization,OrganzationManager,ShowOrganization
from stucamp... |
86794 | import argparse
import time
import numpy as np
import networkx as nx
import json
from sklearn.utils import check_random_state
import zmq
from . import agglo, agglo2, features, classify, evaluate as ev
# constants
# labels for machine learning libs
MERGE_LABEL = 0
SEPAR_LABEL = 1
class Solver:
"""ZMQ-based inter... |
86818 | import pefile
from os import listdir
from os.path import isfile, join
from unicorn import UC_PROT_EXEC, UC_PROT_READ, UC_PROT_NONE, UC_PROT_WRITE
from utility import *
class Target_PEFile:
"""
Class to represent a PE file that is the target of the ROP exploit.
Attributes:
path (str): the PE fil... |
86829 | import pytest
from hive.server.database_api.methods import list_comments
from hive.steem.client import SteemClient
from hive.conf import Conf
@pytest.fixture
def client():
return SteemClient(url='https://api.hive.blog')
@pytest.mark.asyncio
async def test_list_comments_by_cashout_time(client):
with Conf() as ... |
86840 | import argparse
import cv2
import json
import numpy as np
import os
import pickle
import torch
from argparse import Namespace
from scipy.special import softmax
from sklearn.externals import joblib
from pyquaternion import Quaternion
from tqdm import tqdm
from network import CameraBranch
class Camera_Branch_Inferenc... |
86847 | import numpy as np
from torch import nn
from torch.nn import functional as F
import torch
from torchvision import models
import torchvision
__all__ = ['ResNet_IR']
class ResNet_IR(nn.Module):
def __init__(self, args):
super().__init__()
if args.backbone == 'resnet18':
self.backbone ... |
86849 | import json
import os
from geojson import Polygon
from kuwala.modules.common import polyfill_polygon
# Get the aggregated number of a specific POI category per H3 index at a given resolution
def get_pois_by_category_in_h3(sp, category, resolution, polygon_coords):
polygon_cells = None
if polygon_coords:
... |
86863 | import cv2
import threading
import time
import logging
logger = logging.getLogger(__name__)
thread = None
class Camera:
def __init__(self,fps=20,video_source=0):
logger.info(f"Initializing camera class with {fps} fps and video_source={video_source}")
self.fps = fps
self.video_source = video_source
self.came... |
86875 | from __future__ import annotations
import typing
from django.urls import path, include
from restdoctor.utils.api_prefix import get_api_path_prefixes
from tests.stubs.views import EmptyView
if typing.TYPE_CHECKING:
from restdoctor.django.custom_types import URLPatternList
api_prefixes = get_api_path_prefixes()
... |
86939 | from typing import Optional, Dict
import requests
class TelegramBotApi:
def __init__(self, bot_token: str, bot_chat_id: Optional[str]) -> None:
self._bot_token = bot_token
self._bot_chat_id = bot_chat_id
self._base_url = 'https://api.telegram.org/bot' + bot_token
def send_message(se... |
86950 | import sys
from itertools import islice
from .base_magics import DataMagic
from .. import seq
from ..functions import fn, to_callable
from ..typing import Seq
class L(DataMagic, type=list):
"""
Class for the L magic object.
"""
def __getitem__(self, item):
if isinstance(item, slice):
... |
86952 | import argparse
import math
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
from torch.autograd import Variable
from torch.utils.data import Dataset
import math
from model import HierachyVAE
from read_data import *
from util... |
87053 | import os
from permissions.roles import *
from permissions.tables._vars import add_post_visible_limit
from slim.base.permission import Ability, A, DataRecord
from slim.base.sqlquery import SQLQueryInfo, SQL_OP
from slim.utils import get_bytes_from_blob
TABLE_NAME = os.path.basename(__file__).split('.', 1)[0]
# 如果查询... |
87068 | import numpy as np
import math
import random
def f(x):
return (x[0]-3)**2 + (x[1]+1)**2
class ES:
def __init__(self, MaxIter, a, sigma0, f):
self.MaxIter = MaxIter
self.f = f
self.a = a
self.sigma = 0.4
self.sigma0 = sigma0
self.P_S = 0
se... |
87091 | import weakref
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
from rpython.rlib.rarithmetic import LONG_BIT
class GroupType(lltype.ContainerType):
"""A 'group' that stores static structs together in memory.
On 32-bit platforms, the point is that they can be referenced by a
GroupMemberOffs... |
87109 | from typing import Dict, List
import torch
import numpy as np
import copy
from ..modules import Module
from ..datasets import shuffle, collate_dict_wrapper
class ObverterDatasamplingModule(Module):
def __init__(self,
id:str,
config:Dict[str,object]):
"""
:par... |
87124 | from __future__ import annotations
from typing import TYPE_CHECKING
import click
from .output import echo, ok
from .common import convert_api_errors, existing_config_option, inject_proxy
from .core import DropboxPath, CliException
if TYPE_CHECKING:
from ..main import Maestral
@click.command(
help="""
Auto... |
87129 | import matplotlib.pyplot as plt
from corpus import load_corpus
from collections import defaultdict
from yellowbrick.text.freqdist import FreqDistVisualizer
from sklearn.feature_extraction.text import CountVectorizer
def freqdist(docs, outpath, corpus_kwargs={}, **kwargs):
# Create a new figure and axes
fig =... |
87145 | from typing import List, Tuple
from torch import Tensor
from torch.nn import Module
from torchvision.models import wide_resnet50_2
class WideResNet50(Module):
def __init__(self) -> None:
super().__init__()
self.wide_resnet50 = wide_resnet50_2(pretrained=True)
self.wide_resnet50.layer1[-1... |
87155 | import collections
import logging
import os
import tempfile
from pickle import loads
import leveldb
logger = logging.getLogger('mapreduce')
def group_by_key(iterator):
'''Group identical keys together.
Given a sorted iterator of (key, value) pairs, returns an iterator of
(key1, values), (key2, values).
'''
... |
87169 | import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues()
self.description = "A database connectivity and creation framework"
def setDependencies(self):
self.buildDependencies["kde/frameworks/extra-cmake-modules"] = None
self.buildDep... |
87177 | import sys
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
def progressive_max(x):
T = x.size(1)
x = F.pad(x, (T-1, 0), 'constant', -1)
x = F.max_pool1d(x.unsqueeze(1).float(), # shape into B, C, T
T, # kernel... |
87195 | import numpy as np
import warnings
from scipy.ndimage.interpolation import zoom
import torch
import math
import copy
import cv2
from skimage import measure
import pandas as pd
def resample(imgs, spacing, new_spacing, order=2):
if len(imgs.shape) == 3:
new_shape = np.round(imgs.shape * spacing / new_spacing... |
87227 | import ogr
from mapswipe_workers import auth
from mapswipe_workers.definitions import DATA_PATH
from mapswipe_workers.utils import geojson_functions
def add_project_geometries_to_api():
"""Load project geometries from postgres and save as geojson."""
# load from postgres
pg_db = auth.postgresDB()
sq... |
87259 | import torch, psutil, os
from torch.cuda import _get_device_index as get_device_index
from ..meta.process_utils import get_subprocess_ids, format_memory_str
from mani_skill_learn.utils.data import is_dict, is_seq_of
try:
import pynvml
from pynvml import NVMLError_DriverNotLoaded
except ModuleNotFoundError:
... |
87277 | from .batch_preprocessing import basic_preprocessing
from .batch_preprocessing import basic_preprocessing_with_pad
from .registration_parameters import get_registration_preset
from .registration_parameters import get_registration_presets |
87281 | src = Split('''
uart_test.c
''')
component = aos_component('uart_test', src)
component.add_cflags('-Wall')
component.add_cflags('-Werror')
|
87343 | from montepython.likelihood_class import Likelihood_clik
class Planck_lowl_TT(Likelihood_clik):
pass
|
87362 | import logging
import urllib2
import time
import lighter.util as util
class Datadog(object):
def __init__(self, token, tags=[]):
self._token = token
self._url = 'https://app.datadoghq.com'
self._tags = tags + ['source:lighter', 'type:change']
def notify(self, title, message, aggregatio... |
87364 | import torch
from torch.autograd import Variable
def to_cuda_variable(tensor):
"""
Converts tensor to cuda variable
:param tensor: torch tensor, of any size
:return: torch Variable, of same size as tensor
"""
if torch.cuda.is_available():
return Variable(tensor).cuda()
else:
... |
87386 | import logging
from solder_joint import SolderJoint
class BoardView:
def __init__(self, view_identifier):
self.view_identifier = view_identifier
self.solder_joint_dict = {}
self.slice_dict = {}
self.is_incorrect_view = False
logging.info('BoardView obj created for view id... |
87428 | import hashlib
import requests
from haversine import haversine
from requests.exceptions import SSLError, ConnectTimeout, ConnectionError
from django.conf import settings
from django.core.cache import cache
from django.core.files.base import ContentFile
class TencentLBS(object):
key = settings.TENCENT_LBS_KEY
... |
87590 | import unittest
import numpy as np
from numpy import array
from bruges.models import reconcile, interpolate, panel
from bruges.models import wedge
class ModelTest(unittest.TestCase):
"""
Tests models.
"""
def test_reconcile(self):
a = np.array([2, 6, 7, 7, 3])
b = np.array([3, 7, 3])
... |
87612 | import os
import numpy as np
import tensorflow as tf
from depth.self_supervised_sfm.utils import readlines
AUTOTUNE = tf.data.experimental.AUTOTUNE
########################
# Constants
#########################
KITTI_K = np.array([[0.58, 0, 0.5, 0], # fx/width
[0, 1.92, 0.5, 0],
... |
87614 | from re import A
import boto3
import botocore
import click
import configparser
from csv import DictWriter
import io
import itertools
import json
import mimetypes
import os
import re
import sys
import textwrap
from . import policies
def bucket_exists(s3, bucket):
try:
s3.head_bucket(Bucket=bucket)
... |
87615 | import unittest
import unittest.mock
from programy.extensions.base import Extension
class MockExtension(Extension):
def execute(self,context, data):
raise NotImplementedError()
class ExtensionTests(unittest.TestCase):
def test_ensure_not_implemented(self):
bot = unittest.mock.Mock()
... |
87632 | import importlib
import numpy as np
import pandas as pd
import nose
import pytest
import statsmodels.datasets
from statsmodels.datasets.utils import Dataset
exclude = ['check_internet', 'clear_data_home', 'get_data_home',
'get_rdataset', 'tests', 'utils', 'webuse']
datasets = []
for dataset_name in dir(st... |
87648 | from sklearn.svm import OneClassSVM
from uq360.utils.transformers.feature_transformer import FeatureTransformer
class OneClassSVMTransformer(FeatureTransformer):
"""One-class SVM outlier-classifier based derived feature.
This transformer fits an SVM decision boundary enclosing the
full training set. This ... |
87665 | from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
def index(request):
return HttpResponse(status=200)
def get_user(request, id):
return HttpResponse(id)
@csrf_exempt
def create_user(request):
return HttpResponse(status=200)
|
87711 | from dropout import dropout
import math
import theano
import theano.tensor as T
import util
class ConcatWithSoftmax(object):
def __init__(self, inp, n_labels, n_hidden_previous, update_fn,
training=None, keep_prob=None):
if type(inp) == list:
self.input = T.concatenate(inp)
... |
87738 | import numpy as np
n = int(input().strip())
array = np.array([[float(x) for x in input().strip().split()] for _ in range(n)], dtype = float)
print(np.linalg.det(array)) |
87758 | import asyncio
import ipaddress
import logging
import os
from pathlib import Path
from aiohttp import web
from notedrive.magnet import settings
from notedrive.magnet.core import Magnet2Torrent
from notedrive.magnet.dht.network import Server as DHTServer
from notedrive.magnet.server import routes
from notedrive.magnet... |
87764 | import six
from collections import deque, defaultdict
import numpy as np
from pybot.utils.itertools_recipes import chunks
def concat_chunked_dicts(dlist):
"""
Concatenate individual arrays in dictionary
TODO: defaultdict is the right way to do it, except for
conversion to dict in the final retur... |
87768 | from abc import ABC, abstractmethod, ABCMeta
from domain.models.container_settings import ContainerSettings
from domain.models.container_info import ContainerInfo
class AbstractJobManagementService(ABC):
__metaclass__ = ABCMeta
@abstractmethod
def start_container(self, container_settings: ContainerSetting... |
87776 | from django.views.generic.edit import CreateView
from eahub.feedback.models import Feedback
class FeedbackCreate(CreateView):
model = Feedback
fields = ["message", "email", "page_url"]
success_url = "/"
|
87800 | from matrix.server import MatrixServer
from matrix._weechat import MockConfig
import matrix.globals as G
G.CONFIG = MockConfig()
class TestClass(object):
def test_address_parsing(self):
homeserver = MatrixServer._parse_url("example.org", 8080)
assert homeserver.hostname == "example.org"
as... |
87803 | from importlib import import_module
from os import environ
import typing as t
from . import global_settings
from ..errors.server import SettingsFileNotFoundError, ImproperlyConfigured
from ..errors.misc import DataTypeMismatchError
__all__ = ("get_settings_module", "settings")
ENVIRONMENT_VARIABLE = "NAVYCUT_SETTINGS... |
87844 | import itertools
import operator
import re
import bs4
from pudzu.utils import *
# Various utilities for BeautifulSoup
# helper functions since: (a) bs4 tags need to be compared with is, not eq; (b) they're iterable
def remove_duplicate_tags(l):
"""Remove duplicate tags from a list (using object identity rather... |
87852 | from .rman_translator import RmanTranslator
from ..rman_sg_nodes.rman_sg_alembic import RmanSgAlembic
from ..rfb_utils import transform_utils
from ..rfb_utils import string_utils
from ..rfb_logger import rfb_log
class RmanAlembicTranslator(RmanTranslator):
def __init__(self, rman_scene):
super().__init__(... |
87875 | from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class DistributedAvatarUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedAvatarUD')
|
87887 | from resotolib.args import get_arg_parser, ArgumentParser
from resoto_plugin_k8s import KubernetesCollectorPlugin
def test_args():
arg_parser = get_arg_parser()
KubernetesCollectorPlugin.add_args(arg_parser)
arg_parser.parse_args()
assert len(ArgumentParser.args.k8s_context) == 0
assert ArgumentPa... |
87892 | import math
import functools
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import block as B
def pa_upconv_block(
nf, unf, kernel_size=3, stride=1, padding=1, mode='nearest',
upscale_factor=2, act_type='lrelu'):
upsample = B.Upsample(scale_factor=upscale_factor, mode=... |
87896 | from collections import Iterable
from typing import Union, List, Tuple
import numpy as np
from functools import partial
from scipy import ndimage as ndi
import cv2
import random
from .utils import clipBBoxes
from .base import AugBase
# -------------- channel aug_cuda --------------- #
class RGB2Gray(AugBase):
d... |
87916 | from .lop_setup import *
def test_diag():
n = 4
x = jnp.arange(n)+1.
T = lop.diagonal(x)
X = lop.to_matrix(T)
assert_allclose(X, jnp.diag(x))
y = T.times(x)
assert_allclose(y, x**2)
assert lop.dot_test_real(keys[0], T)
def test_zero():
m, n = 4, 5
Z = lop.zero(n, m)
x = ... |
87925 | from enigma import eConsoleAppContainer
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.InputBox import InputBox
from Tools.Log import Log
from Plugins.Plugin import PluginDescriptor
import string
from random import Random
class Chan... |
87964 | from collections import deque
from .types import is_seqcont
__all__ = ['tree_leaves', 'ltree_leaves', 'tree_nodes', 'ltree_nodes']
def tree_leaves(root, follow=is_seqcont, children=iter):
"""Iterates over tree leaves."""
q = deque([[root]])
while q:
node_iter = iter(q.pop())
for sub in n... |
87988 | import unittest
from checkov.common.models.enums import CheckResult
from checkov.terraform.checks.resource.aws.MSKClusterEncryption import check
class TestMSKClusterEncryption(unittest.TestCase):
def test_failure(self):
resource_conf = {
"name": "test-project",
}
scan_result ... |
88011 | import unittest
from typing import List
from nayvy.importing.import_statement import (
ImportAsPart,
SingleImport,
ImportStatement
)
class TestImportAsPart(unittest.TestCase):
def test_of(self) -> None:
# named import
res = ImportAsPart.of('tensorflow as tf')
assert res is no... |
88020 | from boxnotes2html.table import Table
class TestTable:
def test_render_markdown(self):
table = Table()
table.add_data(1, 1, "Name")
table.add_data(1, 2, "Country")
table.add_data(1, 3, "Birthdate")
table.add_data(2, 1, "Jill")
table.add_data(2, 2, "Aus... |
88032 | from django.db import models
class DNSBuildRun(models.Model):
"""
Everytime the DNS build scripts are ran, one of these objects is
created to track which zones we have built and which zones we haven't built
(since nothing has changed in them). :class:`BuildManifest` objects
relate back to a :class... |
88045 | A = [1, 2, 3, 4, 5, 6]
B = [1, 2, 3, 4, 5, 6]
C = [1, 2, 3, 4, 5, 6]
for a in A:
for b in B:
for c in C:
if a > b > c:
print ">", (a, b, c)
if a < b < c:
print ">", (a, b, c)
if a >= b >= c:
print ">=", (a, b, c)
... |
88053 | from fastapi import APIRouter
from streams_explorer.api.routes import (
graph,
kubernetes_health,
metrics,
node,
pipelines,
update,
)
router = APIRouter()
router.include_router(update.router, prefix="/update")
router.include_router(graph.router, prefix="/graph")
router.include_router(pipeline... |
88059 | class EvaluationTask:
"""EvaluationTask class, containing EvaluationTask information."""
def __init__(self, json, client):
self._json = json
self.id = json["id"]
self.initial_response = getattr(json, "initial_response", None)
self.expected_response = json["expected_response"]
... |
88069 | from builtins import zip
from builtins import object
import re
import json
def parse_json(json_path):
replacements = []
with open(json_path) as f:
data = json.load(f)
for replacement_dict in data['replacements']:
try:
replacements.append(Replacement(**{
... |
88091 | class Solution:
def climbStairs(self, n: int) -> int:
if n == 1 or n == 0:
return 1
prev, curr = 1, 1
for i in range(2, n + 1):
temp = curr
curr += prev
prev = temp
return curr
|
88123 | from matchbook.endpoints.baseendpoint import BaseEndpoint
from matchbook.exceptions import AuthError
class Logout(BaseEndpoint):
def __call__(self, session=None):
response = self.request("DELETE", self.client.urn_main, 'security/session', data=self.data, session=session)
self.client.set_session_t... |
88151 | import os
from pymongo import MongoClient
DEFAULT_MONGODB_HOST = "mongodb://mongo:password@127.0.0.1:27017"
def create_client() -> MongoClient:
host = os.getenv("MONGODB_HOST", DEFAULT_MONGODB_HOST)
return MongoClient(host)
|
88163 | def count_and_print(f, l):
c=0
for e in l:
f.write(e)
f.write("\n")
c+=1
f.close()
return c
|
88212 | import numpy as np
import deerlab as dl
#---------------------------------------------------------------------------------------
def assert_bgmodel(model,Bref):
"Check the correct behaviour of the core functionality of a background model"
t = np.linspace(-5,5,500)
# Extract model information
... |
88244 | from dataclasses import astuple, fields
from pywps import LiteralInput
from ravenpy.models import HBVEC
from raven import config
from raven.processes import RavenProcess
from . import wpsio as wio
# Defaults for this process
params_defaults = HBVEC.Params(
par_x01=0.05984519,
par_x02=4.072232,
par_x03=2... |
88309 | from RePoE.parser.util import call_with_default_args, write_json
from RePoE.parser import Parser_Module
class cluster_jewels(Parser_Module):
@staticmethod
def write(file_system, data_path, relational_reader, translation_file_cache, ot_file_cache):
skills = {}
for row in relational_reader["Pass... |
88322 | import random
l1 = []
l2 = []
for i in range(20):
l1.append(random.uniform(-1E10, 1E10))
l2.append(random.uniform(-1E10, 1E10))
print(l1)
print(l2)
l = []
l.extend(l1)
l.extend(l2)
print(sorted(l))
'''
[6015943293.071386, -3878285748.0708866, 8674121166.062424, -1528465047.6118088,
7584260716.4948... |
88357 | import argparse
import time
import torch
from kruskals import kruskals_pytorch, kruskals_pytorch_batched
from kruskals import kruskals_cpp_pytorch, kruskals_cpp_pytorch2
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, default=30, help="Number of nodes.")
parser.add_argument("--batch_size", typ... |
88407 | import os
import logging
from assemblyline.common import forge
from assemblyline.common.str_utils import safe_str
from assemblyline.common.uid import get_id_from_data
from assemblyline.odm.models.signature import Signature
class SuricataImporter(object):
def __init__(self, logger=None):
if not logger:
... |
88414 | from django.utils.text import format_lazy
# Mappings of usable segment => field name
AVAILABLE_PODCAST_SEGMENTS = {
"podcast_slug": "slug",
"podcast_type": "itunes_type",
"podcast_title": "title",
"podcast_subtitle": "subtitle",
"podcast_author": "author",
"podcast_language": "language",
"p... |
88445 | from utils.prepare_data import get_training_data
from utils.prepare_plots import plot_results
from simpleencoderdecoder.build_simple_encoderdecoder_model import simple_encoderdecoder
import random
import numpy as np
if __name__ == "__main__":
profile_gray_objs, midcurve_gray_objs = get_training_data()
test_gra... |
88452 | import tensorflow as tf
import numpy as np
import random
import time
import os
from tensorflow.keras import layers
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
generator_optimizer = tf.keras.optimizers.Adam(1e-4)
discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)
#The Generator Model
de... |
88455 | from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from rest_framework import routers
import cspreports.urls
from .views import AnnouncementViewSet, AssessmentViewSet, Attribut... |
88480 | import awkward as ak
import numpy as np
import pytest
from pytest_lazyfixture import lazy_fixture
from fast_carpenter.testing import FakeBEEvent
import fast_carpenter.tree_adapter as tree_adapter
from fast_carpenter.tree_adapter import ArrayMethods
####################################################################... |
88556 | from tkinter import *
PROGRAM_NAME = "Footprint Editor"
root = Tk()
root.geometry('350x350')
root.title(PROGRAM_NAME)
menu_bar = Menu(root) # menu begins
file_menu = Menu(menu_bar, tearoff=0)
# all file menu-items will be added here next
menu_bar.add_cascade(label='File', menu=file_menu)
edit_menu = Menu(menu_ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.