id
stringlengths
3
8
content
stringlengths
100
981k
3358919
from bitmovin_api_sdk.account.organizations.groups.invitations.invitations_api import InvitationsApi
3358920
from asyncio import CancelledError from typing import Any, Coroutine, Union class BaseHooks: """ Interface for implementation of hooks. """ def on_apply_for(self, coro: Coroutine[Any, Any, Any], ident: str) -> None: """ Calls when ``async_reduce`` apply to coroutine. """ ...
3358944
from noodles import schedule, run_single from noodles.draw_workflow import draw_workflow @schedule def sqr(x): return x*x @schedule def divide(x, y): return x/y @schedule def mul(x, y): return x*y @schedule class A: def __init__(self, value): self.x = value def multiply(self, factor...
3358958
from datetime import datetime from vkwave.bots import SimpleBotEvent from bot.platforms.vk import vk_bot from bot.platforms.vk import guards from bot.platforms.vk.utilities.keyboards import to_menu from bot.platforms.vk.utilities.types import CommandOfVK from bot.utilities.helpers import note_metrics from bot.utili...
3358959
pkgname = "neofetch" pkgver = "7.1.0" pkgrel = 0 build_style = "makefile" depends = ["bash"] pkgdesc = "Simple system information script" maintainer = "q66 <<EMAIL>>" license = "MIT" url = "https://github.com/dylanaraps/neofetch" source = f"{url}/archive/{pkgver}/{pkgname}-{pkgver}.tar.gz" sha256 = "58a95e6b714e41efc80...
3358960
from commands.command import Command from utils.time import format_seconds class ListRecordCommand(Command): def get_banned_word_text(self, ban, current_time): established_record = ban.record_seconds potential_record = (current_time - ban.infracted_at).total_seconds() times_infracted = "Th...
3358995
from src.base import BaseSummary from aion.logger import lprint class VehicleSummary(BaseSummary): def __init__(self): self.reset() def reset(self): super().reset() self.is_first_vehicle = False return def _get_vehicle(self, dicts): res = { 'status': F...
3359001
from sklearn.datasets import fetch_20newsgroups dataset = fetch_20newsgroups(shuffle=True, random_state=1, remove=('headers', 'footers', 'quotes')) documents = dataset.data
3359015
from functools import partial import graphene from graphene_django import DjangoListField from .utils import get_graphene_type __all__ = ( 'ObjectField', 'ObjectListField', ) class ObjectField(graphene.Field): """ Retrieve a single object, identified by its numeric ID. """ def __init__(self...
3359050
import numpy as np # converts the dataset list into a numpy array, discarding the subject data in the process def convert_dataset_list_to_numpy_array(data, labels): no_subjects = len(data) no_examples = 0 for ind_subject in range(no_subjects): no_examples += len(data[ind_subject]) no_features = data[0][0].shap...
3359057
class Train: drop = 'DROP TABLE IF EXISTS train' create = '''CREATE TABLE train( train_id INTEGER NOT NULL AUTO_INCREMENT, train_name VARCHAR(100) UNIQUE, PRIMARY KEY(train_id) ) CHARACTER SET utf8''' class Schedule: drop = 'DROP TABLE IF EXISTS schedule' create = '''CREATE ...
3359095
import os import gettext from kivy.lang import Observable class Translation(Observable): '''Write by tito - https://github.com/tito/kivy-gettext-example.''' observers = [] lang = None def __init__(self, defaultlang, domian, resource_dir): super(Translation, self).__init__() self.ug...
3359127
import struct from boofuzz.primitives.bit_field import BitField class Word(BitField): def __init__(self, value, *args, **kwargs): # Inject our width argument width = 16 max_num = None super(Word, self).__init__(value, width, max_num, *args, **kwargs) if type(self._value...
3359132
import numpy import chaospy def gegenbauer( order, alpha, lower=-1, upper=1, physicist=False, normed=False, retall=False, ): """ Gegenbauer polynomials. Args: order (int): The polynomial order. alpha (float): ...
3359143
from numbers import Number from probtorch.util import log_mean_exp def elbo(q, p, sample_dim=None, batch_dim=None, alpha=0.1, size_average=True, reduce=True): r"""Calculates an importance weighted Monte Carlo estimate of the semi-supervised evidence lower bound (ELBO) .. math:: \frac{1}{B} \sum_...
3359184
import sys sys.path.append('../gen-py') from media_service import TextService from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol import random import string def main(): # Make socket socket = TSocket.TSocket("ath...
3359200
import numpy as np import json def unjson(file): with open(file, 'r') as fo: dict = json.load(fo) return dict # r is noise rate r = 0.2 count = 0 p_a = '' p_g = '' a = unjson(p_a) for i in range(len(a['annotations'])): if np.random.random() < r: id = np.array([24, 25, 26, 27, 28, 31, 3...
3359264
from collections import namedtuple Bread = namedtuple("Bread", "color") class ToastException(Exception): pass def toast(bread): try: put_in_toaster(bread) except: print("Got exception while trying to toast") raise def put_in_toaster(bread): brad.color = "light_brown" # No...
3359288
from typing import Dict, List from vyper import ast as vy_ast from vyper.abi_types import ABI_GIntM from vyper.exceptions import ( EnumDeclarationException, StructureException, UnimplementedException, UnknownAttribute, ) from vyper.semantics.namespace import validate_identifier from vyper.semantics.typ...
3359298
import unittest import os import requests_mock import xml.etree.ElementTree as ET import tableauserverclient as TSC from tableauserverclient.datetime_helpers import format_datetime from tableauserverclient.server.endpoint.exceptions import InternalServerError from tableauserverclient.server.request_factory import Reque...
3359356
from ray import train from ray.train import Trainer from ray.train.callbacks import MLflowLoggerCallback, TBXLoggerCallback def train_func(): for i in range(3): train.report(epoch=i) trainer = Trainer(backend="torch", num_workers=2) trainer.start() # Run the training function, logging all the intermedi...
3359362
from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from integrations.slack.models import SlackConfiguration, SlackEnvironment from .exceptions import SlackChannelJoinError from .slack import SlackWrapper class SlackEnvironmentSerializer(serializers.ModelSerializer): cla...
3359374
from pandas import read_csv as pd_read_csv from ..core import DataFrame def read_csv(filepath, sep=',', header='infer', names=None, usecols=None, dtype=None, converters=None, skiprows=None, nrows=None): """Read CSV into DataFrame. Eager implementation using pandas, i.e. entire file is read at t...
3359379
import os.path from . import TransformerTestCase from ocd_backend.exceptions import NoDeserializerAvailable from ocd_backend.transformers import BaseTransformer class BaseTransformerTestCase(TransformerTestCase): def setUp(self): super(BaseTransformerTestCase, self).setUp() self.PWD = os.path.di...
3359390
from imgaug import augmenters as iaa import config import custom_transforms as t augmentations = { 'pad': ( t.Pad.Both(size=(0, 0, 1, 1)), t.ExpandDims.Mask(axis=2), ), 'crop': ( t.RandomCrop.Both(original_size=(1918, 1280), crop_size=(1024, 1024)), ), 'crop_fliplr_affine_...
3359394
import argparse import json import torch import multiprocessing import time from baseline.robustfill.model import RobustFill from baseline.robustfill.train import load_data from env.env import ProgramEnv from dsl.example import Example from dsl.program import Program def init_worker(*args): global counter, fail_...
3359401
import logging from django.contrib.auth import get_user_model from rest_framework import serializers User = get_user_model() LOG = logging.getLogger(__name__) class UserSerializer(serializers.ModelSerializer): id = serializers.CharField(source="username") class Meta: model = User fields = (...
3359407
import os from PyQt5.QtCore import QProcess """ Usage extcmd.job(self, cmd="something", args="", dest=self.QPlainTextEdit, clean="file to delete when done") To pipe the output of cmd1 to cmd2 use the following Usage extcmd.pipe_job(self, cmd1="something", arg1="", cmd2="pipe to", arg2, "", dest=self.QPlainTextEdit) "...
3359471
import os import re import random import json import copy import tgt import librosa import numpy as np import pyworld as pw from scipy.stats import betabinom from sklearn.preprocessing import StandardScaler from tqdm import tqdm from pathlib import Path from g2p_en import G2p import audio as Audio from model import P...
3359526
import unittest import numpy as np from welib.BEM.unsteadyBEM import * from numpy import cos, sin, arctan2, pi, arccos, exp, abs, min, sqrt import os from welib.BEM.unsteadyBEM import _fInductionCoefficients MyDir=os.path.dirname(__file__) class Test(unittest.TestCase): def test_relaxation_issue(self): ...
3359559
from ._version import get_versions from .chain import MarkovChain from .graph import Graph from .partition import GeographicPartition, Partition from .updaters.election import Election __version__ = get_versions()['version'] del get_versions
3359597
from matplotlib import pyplot as plt from write import strwrite from read import strread with open("../stegano/zen.txt", 'r') as f: zen = f.read() print(zen) print('==========') # zen = 'a' img1 = strwrite(zen, bits=4, hamming=True) # plt.imshow(img1) # plt.show() str1 = strread(img1, bits=4, hamming=True) # pr...
3359611
INPUT_IMAGE_SIZE = (101, 101) BAD_TRAIN_IMAGES = ['aa97ecda8e.png', 'a9e940dccd.png', 'f26e6cffd6.png', '1f0b16aa13.png', '287b0f197f.png', '5edb37f5a8.png', '573f9f58c4.png', 'cc15d94784.png', ...
3359635
import torch class Optimizer(object): def __init__(self, model, solver): self.model = model self.solver = solver # lr self.base_lr = self.solver.BASE_LR self.bias_lr_factor = self.solver.BIAS_LR_FACTOR # weight decay self.weight_decay = self.solver.WEIGHT_DE...
3359671
from typing import Callable, Generator, List, Optional, Union import pytest from ..pipeline import Pipeline from ._meta import _Meta from ._no_return import _NoReturn from ._return import _Return def test_returns(): r = _Return([int, str], _Meta(x=bool)) assert str(r) == "((<class 'int'>, <class 'str'>), {'...
3359685
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X:...
3359704
import pytest pytestmark = [pytest.mark.django_db] @pytest.mark.parametrize(('gender', 'expected'), [ ('male', 'male'), ('female', 'female'), ('', 'male'), ]) def test(mixer, gender, expected): user = mixer.blend('users.User', gender=gender) assert user.get_printable_gender() == expected
3359792
from threading import Event from guizero import App, ButtonGroup from common_test import ( schedule_after_test, schedule_repeat_test, destroy_test, enable_test, display_test, text_test, color_test, size_text_test, size_fill_test, events_test, cascaded_properties_test, inh...
3359798
import json from base64 import b64encode from collections import OrderedDict from io import BytesIO from flask import Response from pyexcel_xlsx import save_data from cloud_inquisitor.config import dbconfig from cloud_inquisitor.constants import ROLE_USER, HTTP, NS_AUDITOR_REQUIRED_TAGS from cloud_inquisitor.json_uti...
3359829
def counting_sort(A, max_val): """ This sorting algorithm will only work with array length n consist of elements from 0 to k for integer k < n. """ k = max_val + 1 count = [0]*k result = [None]*len(A) print("Array A = ", A) # counting the number of i (1 < i < k) in A and store in c...
3359863
import tensorflow as tf import numpy as np ############################################################################################################ # Convolution layer Methods def __conv2d_p(name, x, w=None, num_filters=16, kernel_size=(3, 3), padding='SAME', stride=(1, 1), initializer=tf.contrib.l...
3359865
from datetime import timedelta, datetime import hashlib import os import sendwithus import urllib def unix_time_millis(dt): epoch = datetime.utcfromtimestamp(0) return int((dt - epoch).total_seconds()) def generate_token(data): hash = hashlib.sha256() hash.update(os.environ['EMAIL_TOKEN_SALT']) ha...
3359903
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import * import os import re import sys import glob import codecs import shutil import signal import zipfile import tarfile import itertools import subproce...
3359920
import io import os from fractions import Fraction import pytest import asdf from asdf import types from asdf import extension from asdf import util from asdf import versioning from asdf.exceptions import AsdfWarning, AsdfConversionWarning from . import helpers, CustomTestType, CustomExtension TEST_DATA_PATH = str...
3359981
import requests import lxml.html from collections import namedtuple # named tuples: # used for parsed data and themes Date = namedtuple('Date', ['year' # e.g. '2018' ,'season' # '01'-'03' which means 3rd season ,'season_name' # e.g. 'Bahar' or 'Spring' ...
3360013
import pandas import numpy import keras #Import text data = pandas.read_csv('SS.csv' , sep=';') column = data['Secondary_Structures'] text = '\n'.join(column) chars = sorted(list(set(text))) chars_indices = dict((c , i) for i , c in enumerate(chars)) indices_chars = dict((i , c) for i , c in enumerate(chars)) #Genera...
3360031
from __future__ import with_statement import py try: set except NameError: from sets import Set as set, ImmutableSet as frozenset def compress_char_set(chars): """Take the character list and compress runs of adjacent characters; the result is a list of the first character in a run and the number o...
3360033
import numpy as np import zengl from objloader import Obj from PIL import Image from progress.bar import Bar import assets from window import Window samples = 64 size = 1024 window = Window(1280, 720) ctx = zengl.context() ctx.includes['samples'] = f'const int samples = {samples};' image = ctx.image(window.size, '...
3360070
import functools from eth.vm.computation import BaseComputation def dup_XX(computation: BaseComputation, position: int) -> None: """ Stack item duplication. """ computation.stack_dup(position) dup1 = functools.partial(dup_XX, position=1) dup2 = functools.partial(dup_XX, position=2) dup3 = functools...
3360120
from poium.settings import Setting def insert_assert(describe, result): """ Insert assertion data describe(str): Assertion description information result(bool): Assertion results """ result = [describe, bool(result)] Setting.assert_result.append(result)
3360159
import datetime as dt from re import findall WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") def scrape_line_selector(file_name): html_file = open(file_name, mode='r', encoding="utf-8") raw_content = html_file.readlines() html_file.close() # Match line may ...
3360190
import logging from pathlib import Path from utils.logger import Logger from utils.colors import Color from utils.loader import load_configuration from utils.configuration import pretty from utils.loader import load_list_of_domains from modules.core import Core from os import listdir from os.path import isfile, join, ...
3360195
import json import os import unittest from pathlib import Path import utilities.file_utilities as file_utilities from mhs_common.errors.soap_handler import handle_soap_error class TestOutboundSOAPHandler(unittest.TestCase): message_dir = Path(os.path.dirname(os.path.abspath(__file__))) / 'test_messages' de...
3360219
from collections import namedtuple import jax import pytest import jax.numpy as np import ssm.utils as utils def test_array_tree_equal(): tree1 = ( np.array([[0, 100, 200], [1, 101, 201]]), ( np.array([[1, 5, 10, 15], [2, 6, 11, 16]]), np.array([[2, 12, 14], [3, 13, 15]])...
3360225
import torch, sys, os, pdb import numpy as np from PIL import Image from scipy.spatial import Delaunay sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) from .aligned_reid_utils import load_state_dict from models.yolo_models import Darknet from .featurepointnet_model_util import ...
3360303
from .borehole import multi_fidelity_borehole_function # noqa: F401 from .branin import multi_fidelity_branin_function # noqa: F401 from .currin import multi_fidelity_currin_function # noqa: F401 from .hartmann import multi_fidelity_hartmann_3d # noqa: F401 from .park import multi_fidelity_park_function # noqa: F4...
3360357
from hashlib import sha256 from json import dumps as json_dumps, loads as json_loads from time import sleep from typing import Optional from uuid import uuid4 import pytest from twisted.test.proto_helpers import MemoryReactorClock, StringTransportWithDisconnection from hathor.stratum import ( INVALID_PARAMS, ...
3360444
from typing import List, Dict from .booking import Booking from .clock import Clock class BookingService: """ BookingService manages all booking requests that enter a simulation from a demand model. Each new booking must be in pending state. After a booking changes its state to any other state it will be ...
3360471
import modules.internals def to_color(r: int, g: int, b: int) -> Color: return Color(r, g, b) def invert(color: Color) -> Color: return Color(255 - color.r, 255 - color.g, 255 - color.b) def red_channel(color: Color) -> int: return color.r def green_channel(color: Color) -> int: return color.g def ...
3360488
from flask import Blueprint, jsonify bp = Blueprint('errors', __name__) @bp.app_errorhandler(404) def not_found(error): return 'Not found', 404 @bp.app_errorhandler(500) def internal_error(error): """return more helpful info on 500""" data = { 'type': type(error).__name__, 'message': st...
3360515
from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('django.middleware')
3360521
from datetime import datetime from typing import NamedTuple, List, Optional from autotui.shortcuts import load_prompt_and_writeback import click def edit_in_vim() -> str: return click.edit(text=None, editor="vim").strip() class JournalEntry(NamedTuple): creation_date: datetime tags: Optional[List[str]...
3360590
import csv import json import os from typing import Iterable, Any import yaml from openpyxl import load_workbook class ReadFileData(object): def __init__(self, path, **kwargs): if not os.path.exists(path): return self.path = path self.data = None self.extra_param = kw...
3360657
import torch import torch.nn as nn class UNetSame(nn.Module): def __init__(self): super(UNetSame, self).__init__() self.encoder1 = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=1), nn.Conv2d(in_channels=64, out_channels=64, ker...
3360668
import inspect from typing import Callable from jivago.config.abstract_binder import AbstractBinder from jivago.inject.annotation import Provider from jivago.inject.exception.undefined_return_provider_function import UndefinedReturnProviderFunction from jivago.inject.service_locator import ServiceLocator from jivago.l...
3360671
import re import sublime, sublime_plugin if re.match('3|4', sublime.version()): from . import settings as settings_bv else: import settings as settings_bv def set_settings_listener(instance, settings): def callback(*args): val = instance.kls_get_value(settings) instance.set_value(val) ...
3360678
import oss2 from lin.util import get_random_str from lin.core import lin_config def upload_image_bytes(name: str, data: bytes): access_key_id = lin_config.get_config('oss.access_key_id') access_key_secret = lin_config.get_config('oss.access_key_secret') auth = oss2.Auth(access_key_id, access_key_secret) ...
3360681
from django import forms from tinymce import TinyMCE from .models import Event class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class EventForm(forms.ModelForm): details = forms.CharField( widget=TinyMCEWidget( attrs={'required':False, 'cols':...
3360703
import sublime_plugin from ..libs import * from ..libs.view_helpers import * from ..libs.reference import * from .base_command import TypeScriptBaseTextCommand class TypescriptFindReferencesCommand(TypeScriptBaseTextCommand): """Find references command""" def run(self, text): check_update_view(self.v...
3360704
import cv2 import numpy as np def visualize_rect(img, roi_dict, color=(0, 255, 0)): for index, roi in roi_dict['roi'].items(): tl_x = roi['tl_x'] tl_y = roi['tl_y'] br_x = roi['br_x'] br_y = roi['br_y'] cv2.rectangle(img, (tl_x, tl_y), (br_x, br_y), color, 2) return im...
3360768
import os, stat, platform, shutil, zipfile current_dir = os.path.dirname(os.path.realpath(__file__)) gl_folder = os.path.join(current_dir, '..', 'Malt', 'GL') zip_file = os.path.join(current_dir, 'glslang.zip') glslang_url = { 'Windows' : "https://github.com/KhronosGroup/glslang/releases/download/master-tot/glslang-...
3360809
import upath.core import re class _CloudAccessor(upath.core._FSSpecAccessor): def _format_path(self, path): """ netloc has already been set to project via `CloudPath._from_parts` """ return f"{path._url.netloc}/{path.path.lstrip('/')}" # project is not part of the path, but is pa...
3360843
import pytest import python_jsonschema_objects as pjs import jsonschema import json import copy import pprint pp = pprint.PrettyPrinter(indent=2) lpid_class_schema = { "$id": "https://example.com/schema-repository/lpid", "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "title":...
3360863
from sqlalchemy import Column from sqlalchemy import column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import join from sqlalchemy import lateral from sqlalchemy import String from sqlalchemy import Table from sqlalchemy import table from sqlalchemy import testing from sqlalchemy i...
3360864
import numpy N, M = map(int, input().split()) _ = numpy.array([input().split() for i in range(N)], int) numpy.set_printoptions(legacy='1.13') print(numpy.mean(_, axis=1)) print(numpy.var(_, axis=0)) print(numpy.std(_, axis=None))
3360877
src = Split(''' sdk-impl.c ''') component = aos_component('libsdk-impl', src) if aos_global_config.compiler == 'gcc': component.add_cflags('-Wno-unused-function') component.add_cflags('-Wno-implicit-function-declaration') component.add_cflags('-Wno-unused-function') component.add_includes(...
3360892
import json def generate_json(split): source_path = "../../dataset/final_data/commongen/commongen." + split + ".src_alpha.txt" target_path = "../../dataset/final_data/commongen/commongen." + split + ".tgt.txt" out_path = "commongen." + split + ".json" with open(source_path) as source, open(target_pat...
3360937
import pytest from motor.motor_asyncio import AsyncIOMotorClient # mongo can be ran locally or using the docker-compose file at the repository's root mongo_dsn = "mongodb://localhost:27017" postgres_dsn = "postgresql+asyncpg://pydantic-factories:pydantic-factories@postgres:5432/pydantic-factories" @pytest.fixture(s...
3360953
import numpy as np from deep500.lv0.operators.operator_interface import CustomPythonOp class SqueezeOp(CustomPythonOp): def __init__(self, input_descriptors, output_descriptors, axes): super(SqueezeOp, self).__init__(input_descriptors, output_descriptors) self._input_desc = input_descriptors ...
3360974
from typing import Dict from django import forms from guardian.shortcuts import get_objects_for_user from grandchallenge.cases.forms import IMAGE_UPLOAD_HELP_TEXT from grandchallenge.components.models import InterfaceKind from grandchallenge.components.schemas import INTERFACE_VALUE_SCHEMA from grandchallenge.core.va...
3360977
import unittest import riemann from unittest import mock from riemann.tests import helpers from riemann.tx import tx_builder as tb class TestTxBuilder(unittest.TestCase): def setUp(self): pass def tearDown(self): riemann.select_network('bitcoin_main') def test_make_sh_output_script(self...
3360979
import hazelcast # Connect client = hazelcast.HazelcastClient(cluster_members=["127.0.0.1:5701"]) # Get a map that is stored on the server side. We can access it from the client greetings_map = client.get_map("greetings-map").blocking() # Map is empty on the first run. It will be non-empty if Hazelcast has data on t...
3361026
import logging import os import uuid from datetime import datetime, timedelta from typing import Any, Dict, List, Optional from fastapi import Cookie, Depends, FastAPI, HTTPException, Request, Response, status from fastapi.routing import APIRouter from fastapi.staticfiles import StaticFiles from fastapi.templating imp...
3361040
import pytest from app.test.factory import FixtureFactory from app.test.mixer import mixer as _mixer @pytest.fixture def mixer(): return _mixer @pytest.fixture def factory(): return FixtureFactory()
3361057
from pylab import * import sys matplotlib.rcParams['axes.linewidth'] = 0.75 trace = sys.argv[1] typ = sys.argv[2] assert(trace in ["ripple", "lightning"]) assert(typ in ["ratio", "volume"]) num_flows = 2000 scale_factor = ['1', '10', '20', '30', '40', '50', '60'] volumes = [] ratios = [] msgs = [] schemes = ['s...
3361120
import random import itertools import numpy as np import collections def statistics(x_train, y_train, x_test, y_test, y_pred): train_size = len(x_train) test_size = len(x_test) # num non-zero preds num_preds = len([p for p in y_pred if p]) return { 'training_set__size': train_size, ...
3361122
import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from mlserver.handlers import DataPlane, ModelRepositoryHandlers from mlserver.registry import MultiModelRegistry from mlserver.rest import RESTServer from mlserver.repository import ModelRepository from mlserver import Settings from...
3361157
from numpy import array from .matrices import trimesh_cotangent_laplacian_matrix __all__ = ['trimesh_smooth_laplacian_cotangent'] def trimesh_smooth_laplacian_cotangent(trimesh, fixed, kmax=10): """Smooth a triangle mesh using a laplacian matrix with cotangent weights. Parameters ---------- trimes...
3361176
global glb_dict glb_dict = {} def addItem(key, value): glb_dict[key]=value def getItem(key): return glb_dict[key]
3361212
import torch from vformer.utils import DECODER_REGISTRY decoder_modules = DECODER_REGISTRY.get_list() def test_MLPDecoder(): test_tensor = torch.randn(2, 3, 100) decoder = DECODER_REGISTRY.get("MLPDecoder")(config=100, n_classes=10) out = decoder(test_tensor) assert out.shape == (2, 3, 10) del...
3361285
from celery import Celery, Task from glide.extensions.celery import * app = Celery("app", broker="redis://localhost", backend="redis://localhost") app.conf.update( result_expires=3600, accept_content=["pickle", "json"], worker_hijack_root_logger=False, ) # Celery tries to do a ping and relies on a ping ...
3361334
from __future__ import print_function from os import environ as ENV import sys DEBUG="DEBUG" in ENV VERBOSE=False def debug(*args): if DEBUG: print(" ".join(map(str, args)), file=sys.stderr) def verbose(*args): if VERBOSE: print(" ".join(map(str, args)), file=sys.stderr)
3361352
from snhp.logic.database import DatabaseFast class XMFRDatabaseFast(DatabaseFast): def __init__(self, datalog): super(XMFRDatabaseFast, self).__init__(datalog) def make_transform_idx_and_dim(self, fact, transform_idx_and_dim, datalog): """ each fact has form : term, subgoals, rule_i, ...
3361380
import os import gzip import zipfile from urllib import request import yaml import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from ilp.constants import DATA_DIR CWD = os.path.split(__file__)[0] DATASET_CONFIG_PATH = os.path.join(CWD, 'datasets.ym...
3361414
from unittest import mock import pytest from ozy import OzyError from ozy.installers.pip import PipInstaller def test_raises_on_missing_keys(): with pytest.raises(OzyError): PipInstaller('test', dict()) with pytest.raises(OzyError): PipInstaller('test', dict(package='p')) with pytest.rai...
3361471
import wx.adv import wx from .wxControl import * class 超级列表框(wx.ListCtrl, 公用方法): pass @property def 行数(self): return self.取行数() @行数.setter def 行数(self, value): self.SetItemCount(value) @property def 列数(self): return self.GetColumnCount() @列数.setter def 列数...
3361473
from rllab.envs.mujoco.maze.maze_env import MazeEnv from rllab.envs.mujoco.point_env import PointEnv class PointMazeEnv(MazeEnv): MODEL_CLASS = PointEnv ORI_IND = 2 MAZE_HEIGHT = 2 MAZE_SIZE_SCALING = 3.0 MANUAL_COLLISION = True
3361478
import collections from arekit.common.entities.base import Entity from arekit.common.frames.text_variant import TextFrameVariant from arekit.processing.text.token import Token class TextTermsMapper(object): def iter_mapped(self, terms): """ Performs mapping operation of each terms in a sequence ...
3361496
class ListMaker: def __init__(self, title, prefix='- ', indent=3): self._title = title self._prefix = prefix self._indent = indent self._current_indent = 0 print(title) def __enter__(self): self._current_indent += self._indent return self def __exit_...
3361499
import json import os from nltk.tokenize import TreebankWordTokenizer, sent_tokenize t = TreebankWordTokenizer() with open(os.path.join('testdata', 'tokenize.json')) as d: data = json.load(d) words = [] sents = [] for text in data: for s in sent_tokenize(text): sents.append(s) words.append(t....