id
stringlengths
3
8
content
stringlengths
100
981k
88564
import os import wandb import torch import torchvision from config import set_params from kws.utils import set_random_seed, transforms from kws.utils.data import SpeechCommandsDataset, load_data, split_data from kws.model import treasure_net from kws.train import train def main(): # set parameters and random seed...
88595
import flux import pytest import requests from flask_app import models from .utils import model_for def test_start_session_with_subjects(client, subjects): session = client.report_session_start( subjects=subjects ) assert session.refresh().subjects == [dict(s) for s in subjects] def test_add_su...
88605
from __future__ import absolute_import from __future__ import print_function import veriloggen import types_axi_slave_readwrite_lite_simultaneous expected_verilog = """ module test; reg CLK; reg RST; wire [32-1:0] sum; reg [32-1:0] myaxi_awaddr; reg [4-1:0] myaxi_awcache; reg [3-1:0] myaxi_awprot; reg m...
88622
import unittest import datetime from unittest.mock import MagicMock from osgar.drivers.winsen_gas_detector import WinsenCO2 class WinsenCO2Test(unittest.TestCase): def test_parse_packet(self): ref_packet = bytes.fromhex('ff86063b3d000000fc') sensor = WinsenCO2(config={}, bus=MagicMock()) ...
88643
from boa3.builtin.nativecontract.stdlib import StdLib def main() -> int: return StdLib.atoi('100', 10, 'extra')
88666
import numpy import matplotlib.pylab as plt class LinearHeadHead(object): """ Solves the system: \div \frac{\rho}{\mu} k \grad (p + \rho g z) = 0 on the domain [x_0, x_1] \cross [z_0,z_1] Boundary conditions are given by: h(x_0,z,t) = h_0 [m] => p(x_0,z,t)=(h_0-z) \rho g h(x_1,...
88712
import requests from bs4 import BeautifulSoup # WHY # The SearchRequest module contains all the internal logic for the library. # # This encapsulates the logic, # ensuring users can work at a higher level of abstraction. # USAGE # req = search_request.SearchRequest("[QUERY]", search_type="[title]") class SearchRequ...
88732
import re def get_query(): query = { "_source": [ "text", "full_text", "extended_tweet.full_text", "quoted_status.text", "quoted_status.full_text", "quoted_status.extended_tweet.full_text" ], "query": { "bool": { "filter": [ { ...
88733
import hashlib import pickle import os import sys import subprocess import time class Colors: HEADER = '\033[95m' BLUE = '\033[94m' GREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' cache = {} hashes = [] def get_cache(...
88737
import pandas as pd import os from tqdm import tqdm from model.bert_things.pytorch_pretrained_bert.tokenization import BertTokenizer from model.bert_things.pytorch_pretrained_bert import BertConfig, BertModel, BertPreTrainedModel from model.bert_text_model import BertTextModel from data_loader.utils.vocab import Vocab ...
88742
from .generic_wrappers import * # NOQA from .lambda_wrappers import action_lambda_v1, observation_lambda_v0, reward_lambda_v0 # NOQA from .multiagent_wrappers import agent_indicator_v0, black_death_v2, \ pad_action_space_v0, pad_observations_v0 # NOQA from supersuit.generic_wrappers import frame_skip_v0, color_redu...
88774
import os try: basestring except NameError: basestring = str class ListenImports: ROBOT_LISTENER_API_VERSION = 2 def __init__(self, imports): self.imports = open(imports, 'w') def library_import(self, name, attrs): self._imported("Library", name, attrs) def resource_import(...
88791
class Solution: def depthSumInverse(self, nestedList: List[NestedInteger]) -> int: dic = {} level = 0 q = collections.deque() q.append(nestedList) res = 0 while q: size = len(q) level += 1 sums = 0 for _ in range(size): ...
88826
import os import csv import pkg_resources import re import traceback import nbformat as nf import nbconvert as nc from urllib.parse import quote as urlquote def isdir(path): ''' Checks whether given path is a directory ''' if not os.path.isdir(path): raise OSError('"' + path + '"' + ' is not ...
88832
import pytest config = """ from universum.configuration_support import Configuration def step(name, cmd=False): return Configuration([dict(name=name, command=[] if not cmd else ["bash", "-c", '''echo "run step"'''])]) configs = step('parent 1 ') * (step('step 1', True) + step('step 2', True)) configs += step('pa...
88839
def isExistingClassification(t): pass def getSrcNodeName(dst): """ Get the name of the node connected to the argument dst plug. """ pass def getCollectionsRecursive(parent): pass def disconnect(src, dst): pass def findVolumeShader(shadingEngine, search='False'): """ Returns ...
88920
import apache_beam as beam import tensorflow as tf from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from regnety.utils.image_utils import * def _bytes_feature(value): """Returns a bytes_list from a string / byte.""" if isinstance(v...
88921
from mock import AsyncMock import pytest from opentrons.drivers.smoothie_drivers import SmoothieDriver from opentrons.tools import write_pipette_memory @pytest.fixture def mock_driver() -> AsyncMock: return AsyncMock(spec=SmoothieDriver) async def test_write_identifiers(mock_driver: AsyncMock) -> None: """...
88934
import os from pyfakefs.fake_filesystem_unittest import TestCase from starwhale.utils import config as sw_config from starwhale.utils.error import NotFoundError from starwhale.utils.config import ( SWCliConfigMixed, load_swcli_config, get_swcli_config_path, ) from .. import get_predefined_config_yaml _e...
88944
from xweb import App, Model, RESTController class UserModel(Model): schema = { "type": "object", "properties": { "username": {"type": "string"}, "password": {"type": "string"}, }, "required": ['username'] } class EventController(RESTController): as...
88954
import math from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from apis.betterself.v1.constants import UNIQUE_KEY_CONSTANT from apis.betterself.v1.signup.fixtures.builders import DemoHistoricalDataBuilder from even...
88975
import datetime import logging from airflow import DAG from airflow.models import Variable from airflow.operators.python_operator import PythonOperator from airflow.hooks.S3_hook import S3Hook def list_keys(): hook = S3Hook(aws_conn_id='aws_credentials') bucket = Variable.get('s3_bucket') logging.info(f"...
88978
class ListView: __slots__ = ['_list'] def __init__(self, list_object): self._list = list_object def __add__(self, other): return self._list.__add__(other) def __getitem__(self, other): return self._list.__getitem__(other) def __contains__(self, item): return self....
89007
import unittest from asq.queryables import Queryable __author__ = "<NAME>" class TestToSet(unittest.TestCase): def test_to_set(self): a = [1, 2, 4, 8, 16, 32] b = Queryable(a).to_set() c = set([1, 2, 4, 8, 16, 32]) self.assertEqual(b, c) def test_to_set_closed(self): ...
89024
from pylanguagetool import converters markdown = """# Heading This is *a* Sentence. """ html = """<h1>Heading</h1> <p>This is <em>a</em> Sentence.</p> """ plaintext = """Heading This is a Sentence. """ ipython = """{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "#...
89026
import time import requests from urllib.parse import urljoin from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter import pytest pytest_plugins = ["docker_compose"] @pytest.fixture(scope="module") def wait_for_api(module_scoped_container_getter): """Wait for the api from my_api_service ...
89038
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize("installed_packages", [ ("httpd"), ("mod_ssl"), ]) def test_packages_installed(host, installed_pa...
89043
import unittest from katas.kyu_6.multiples_of_3_and_5 import solution class MultiplesOfThreeAndFiveTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(solution(10), 23) def test_equals_2(self): self.assertEqual(solution(100), 2318) def test_equals_3(self): self....
89051
from .misc.utils import sqlalchemy_to_pydantic from .crud_router import crud_router_builder from .misc.type import CrudMethods
89053
import gzip import os import os.path import data_algebra import data_algebra.data_ops import data_algebra.db_model _have_bigquery = False try: # noinspection PyUnresolvedReferences import google.cloud.bigquery _have_bigquery = True except ImportError: pass def _bigquery_median_expr(dbmodel, express...
89070
import pytest def test_import_vdjtools_beta_w_validation(): import pandas as pd import numpy as np import os from tcrdist.paths import path_to_base from tcrdist.vdjtools_funcs import import_vdjtools from tcrdist.repertoire import TCRrep # Reformat vdj_tools input format for tcrdist3 ...
89077
import rdkit.Chem as Chem import numpy as np import os ''' This script is meant to split the Tox21 train dataset into the individual target datasets for training single-task models. ''' if __name__ == '__main__': # Read SDF suppl = Chem.SDMolSupplier( os.path.join( os.path.dirname(os.path.dirname(__file__)...
89104
from __future__ import print_function import sys from subprocess import call from unittest import TestCase from testfixtures import OutputCapture, compare from .test_compare import CompareHelper class TestOutputCapture(CompareHelper, TestCase): def test_compare_strips(self): with OutputCapture() as o: ...
89122
import behave import os @behave.when(u'I upload item using data frame from "{upload_path}"') def step_impl(context, upload_path): import pandas upload_path = os.path.join(os.environ['DATALOOP_TEST_ASSETS'], upload_path) # get filepathes filepaths = list() # go over all file and run ".feature" fil...
89136
import click from esque.cli.autocomplete import list_brokers from esque.cli.helpers import fallback_to_stdin from esque.cli.options import State, default_options, output_format_option from esque.cli.output import format_output from esque.errors import ValidationException from esque.resources.broker import Broker @cl...
89148
import questionary if __name__ == "__main__": path = questionary.path("Path to the projects version file").ask() if path: print(f"Found version file at {path} 🦄") else: print("No version file it is then!")
89160
orders = ["daisies", "periwinkle"] print(orders) orders.append("tulips") orders.append("roses") print(orders)
89162
from ..utils import dataset_utils class TestDatasetUtils(object): """Collects all unit tests for `utils.model_utils`. """ def test_load_wikihop(self, dataset): """Asserts that `data_utils.load_wikihop()` returns the expected value when `masked == True`. """ expected = {'train': [ ...
89184
import serial """ # VE.Direct parser inspired by https://github.com/karioja/vedirect/blob/master/vedirect.py """ class Vedirect: # The error code of the device (relevant when the device is in the fault state). # # Error 19 can be ignored, this condition regularly occurs during start-up or shutdown of the ...
89199
from typing import Dict, Optional, Union import numpy as np from werkzeug import ImmutableMultiDict from .endpoint import Endpoint def predict(model, input_data: Union[Dict, ImmutableMultiDict], config: Endpoint): # new model if hasattr(model, "public_inputs"): sample = {} for k, v in dict(i...
89251
from ipywidgets import widgets from pandas_profiling.report.presentation.core import Variable class WidgetVariable(Variable): def render(self) -> widgets.VBox: items = [self.content["top"].render()] if self.content["bottom"] is not None: items.append(self.content["bottom"].render()) ...
89277
import pytest import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from pandas.testing import assert_frame_equal import pandas as pd import matplotlib from pdpbox.pdp import pdp_isolate, pdp_plot class TestPDPIsolateBinary(object): def test_pdp_isolate_binary_feature( ...
89282
from collections import Iterable, OrderedDict, Mapping from functools import reduce from devito.tools.utils import filter_sorted, flatten __all__ = ['toposort'] def build_dependence_lists(elements): """ Given an iterable of dependences, return the dependence lists as a mapper suitable for graph-like alg...
89326
from abc import ABC import scipy.sparse from rasa.nlu.featurizers.featurizer import Featurizer class SparseFeaturizer(Featurizer[scipy.sparse.spmatrix], ABC): """Base class for all sparse featurizers.""" pass
89395
import pygame from pygame.locals import * from sys import exit from random import * pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) screen.lock() for count in range(10): random_color = (randint(0,255), randint(0,255), randint(0,255)) random_pos = (randint(0,639), randint(0,479)) random...
89425
from garuda_dir.garuda_pb2 import Void class GarudaCustom(object): def CustomCallDemo(self, context, void): ''' rpc CustomCallDemo(Void) returns (Void); ''' print("Just a dummy RPC call") return Void()
89489
from typing import List, Union import pytest from mockito import mock, unstub, verifyStubbedInvocationsAreUsed, when from ...config import config from ...core.entities.mod import Mod from ...core.entities.sites import Sites from ...core.entities.version_info import Stabilities, VersionInfo from .update import Update ...
89536
from pymodelica import compile_fmu fmu_name = compile_fmu("{{model_name}}", "{{model_name}}.mo", version="{{fmi_version}}", target="{{fmi_api}}", compiler_options={'extra_lib_dirs':["{{sim_lib_path}}"]})
89538
from django.conf import settings from portia_api.jsonapi import JSONResponse from portia_api.jsonapi.renderers import JSONRenderer from .models import (Job, Log, Schedule,JobItem) import time, datetime import requests from storage import (get_storage_class,create_project_storage) from portia_orm.models import Projec...
89574
import pytest from django.core.exceptions import ImproperlyConfigured from django.db import connection, models from psqlextra.backend.schema import PostgresSchemaEditor from psqlextra.types import PostgresPartitioningMethod from . import db_introspection from .fake_model import define_fake_partitioned_model def te...
89581
import fiona import numpy as np import os import pytest import rasterio import mapchete from mapchete.index import zoom_index_gen from mapchete.io import get_boto3_bucket @pytest.mark.remote def test_remote_indexes(mp_s3_tmpdir, gtiff_s3): zoom = 7 gtiff_s3.dict.update(zoom_levels=zoom) def gen_indexes...
89589
from math import sqrt, pi as PI import tensorflow as tf from .feature_extraction import feature_extraction class FeaturesTest(tf.test.TestCase): def test_features(self): image = tf.constant([ [[255, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [...
89625
import json import jinja2 def tojson(obj, **kwargs): return jinja2.Markup(json.dumps(obj, **kwargs))
89642
version https://git-lfs.github.com/spec/v1 oid sha256:1eaa715583d925005051963b4060c72e79f474a068a74ee5a9831c55e6dff8ac size 713
89686
import enum import pathlib from typing import DefaultDict, Dict, List, Optional, Sequence, Tuple from pysen import ComponentBase from pysen.command import CommandBase from pysen.diagnostic import Diagnostic from pysen.reporter import Reporter from pysen.runner_options import PathContext, RunOptions from pysen.setting ...
89719
import os import re import torch CHECKPOINTS_DIR = 'checkpoints' def find_last_checkpoint_epoch(savedir, prefix = None): root = os.path.join(savedir, CHECKPOINTS_DIR) if not os.path.exists(root): return -1 if prefix is None: r = re.compile(r'(\d+)_.*') else: r = re.compile(r'(...
89727
class Solution: """ @param A: an array @return: divide the array into 3 non-empty parts """ def threeEqualParts(self, A): total = A.count(1) if total == 0: return [0, 2] if total % 3: return [-1, -1] k = total // 3 count = ...
89745
from picamera.array import PiRGBArray import picamera from picamera import PiCamera import time import cv2 def CaptureImage(camera, rawCapture): print('Capturing frames...') print('Press Ctrl-C to end') try: # capture frames from the camera for frame in camera.capture_continuous(rawCapture...
89769
import torch import torch.nn as nn import torch.nn.functional as F from pytorch_transformers.modeling_bert import BertPreTrainedModel, BertModel from configs.basic_config import config as basic_config class BertFCForMultiLable(BertPreTrainedModel): def __init__(self, config): super(BertFCForMul...
89777
import os from homeassistant.core import HomeAssistant import pytest from custom_components.hacs.websocket import ( acknowledge_critical_repository, get_critical_repositories, hacs_config, hacs_removed, hacs_repositories, hacs_repository, hacs_repository_data, hacs_settings, hacs_s...
89785
from sqlalchemy import Column, DateTime, Enum, Integer, String from sqlalchemy.sql.schema import UniqueConstraint from virtool.pg.base import Base from virtool.samples.models import ArtifactType class SampleArtifactCache(Base): """ SQL model to store a cached sample artifact """ __tablename__ = "sa...
89792
import re from sklearn.utils.validation import check_is_fitted from gensim.models.word2vec import Word2Vec import sys from owl2vec_star.rdf2vec.walkers.random import RandomWalker import numpy as np import multiprocessing class RDF2VecTransformer(): """Project random walks or subtrees in graphs into embeddings, s...
89808
import tvm import numpy as np from tvm import relay from tvm.relay.ir_pass import infer_type from tvm.relay.ir_builder import IRBuilder, func_type from tvm.relay.ir_builder import scalar_type, convert, tensor_type from tvm.relay.env import Environment def assert_has_type(expr, typ, env=Environment({})): checked_ex...
89880
import tensorflow as tf k = tf.constant([ [1, 0, 1], [2, 1, 0], [0, 0, 1] ], dtype=tf.float32, name='k') i = tf.constant([ [4, 3, 1, 0], [2, 1, 0, 1], [1, 2, 4, 1], [3, 1, 0, 2] ], dtype=tf.float32, name='i') kernel = tf.reshape(k, [3, 3, 1, 1], name='kernel') image = tf.reshape(i, [1, 4, 4...
89932
from rest_framework import serializers from django.contrib.auth.models import User from oms_gallery.models import Photo, Gallery from oms_cms.backend.pages.models import Pages, BlockPage class PagesListSerializer(serializers.ModelSerializer): """Сериализация всех страниц""" class Meta: model = Pages ...
89968
import os # face_data (directory) represents the path component to be joined. FACE_DATA_PATH = os.path.join(os.getcwd(),'face_cluster') ENCODINGS_PATH = os.path.join(os.getcwd(),'encodings.pickle') CLUSTERING_RESULT_PATH = os.getcwd()
90011
def celciusToFahrenheit(celcius: float, ndigits: int = 2)->float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit """ return round((floa...
90016
from __future__ import absolute_import import json import os import pytest import requests import time from rancher_gen.compat import b64encode @pytest.fixture(scope='session') def stack_service(request): host = os.getenv('RANCHER_HOST') port = int(os.getenv('RANCHER_PORT', 80)) access_key = os.getenv('...
90029
import base64 import time import requests import yaml from sawtooth_sdk.protobuf import batch_pb2 from sawtooth_signing import ParseError, CryptoFactory, create_context from sawtooth_signing.secp256k1 import Secp256k1PrivateKey from cli.common.protobuf import payload_pb2 from cli.common import transaction, helper fro...
90037
import gzip import struct import os import logging import logging.handlers import sys import json def getBootstraps(quantDir): logging.basicConfig(level=logging.INFO) bootstrapFile = os.path.sep.join([quantDir, "aux_info", "bootstrap", "bootstraps.gz"]) nameFile = os.path.sep.join([quantDir, "aux_info", "...
90052
from enn import * import numpy as np from grid_LSTM import netLSTM, netLSTM_full from grid_data_v2 import TextDataset import grid_data_v2 as grid_data from grid_configuration import config from util import Record, save_var, get_file_list, Regeneralize, list_to_csv from torch.autograd import Variable from torch.utils.da...
90077
def remove_smallest(n, lst): if n <= 0: return lst elif n > len(lst): return [] dex = [b[1] for b in sorted((a, i) for i, a in enumerate(lst))[:n]] return [c for i, c in enumerate(lst) if i not in dex]
90102
import tensorflow as tf def complex_to_real(tensor): """Returns tensor converted from a complex dtype with shape (...,) to a real dtype with shape (..., 2), where last index marks real [0] and imag [1] parts of a complex valued tensor. Args: tensor: complex valued tensor of shape (...,). ...
90104
import requests import re from urllib import parse headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", "referer": "https://tb.alicdn.com/snapshot/index.html", 'cookie': 't=884491259d4aed9aac3cd83e5798c433; cna=UU81F...
90139
import torch import torch.nn as nn from torch.autograd import Variable import math import torch.nn.functional as F class GMMLogLoss(nn.Module): ''' compute the GMM loss between model output and the groundtruth data. Args: ncenter: numbers of gaussian distribution ndim: dimension of ...
90146
from tornado.web import StaticFileHandler from cloudtunes import settings from cloudtunes.base.handlers import BaseHandler class MainHandler(BaseHandler): def get(self): webapp_dir = self.settings['static_path'] homepage_dir = settings.HOMEPAGE_SITE_DIR if self.current_user: ...
90167
from .base import * from .bitfinex import * from .bitstamp import * from .buda import * from .kraken import *
90177
import logging import os import ray import time from enum import Enum from ray.actor import ActorHandle from ray.streaming.generated import remote_call_pb2 from ray.streaming.runtime.command\ import WorkerCommitReport, WorkerRollbackRequest logger = logging.getLogger(__name__) class CallResult: """ Call...
90184
from setuptools import find_packages, setup try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except ImportError: long_description = open('README.md').read() setup( use_scm_version=True, setup_requires=['setuptools_scm'], name='django-super-deduper', description=...
90217
import sys import storage import json import texttable as tt protocol = "https" nbmaster = "" username = "" password = "" domainname = "" domaintype = "" port = 1556 def print_usage(): print("Example:") print( "python -W ignore get_storage_server_by_id.py -nbmaster <master_server> -username <usernam...
90285
import numpy as np from gym import utils, spaces from gym.envs.mujoco import mujoco_env from gym.envs.robotics.rotations import quat2euler, euler2quat, mat2euler import os # import random from random import uniform, randint, randrange from mjremote import mjremote import time from doorenv2.envs.doorenv import DoorEnv ...
90306
from decimal import Decimal from typing import Iterable, Optional, TypeVar from stock_indicators._cslib import CsIndicator from stock_indicators._cstypes import List as CsList from stock_indicators._cstypes import Decimal as CsDecimal from stock_indicators._cstypes import to_pydecimal from stock_indicators.indicators....
90353
from allennlp.common.util import JsonDict from allennlp.data import DatasetReader from allennlp.data.tokenizers import WordTokenizer from allennlp.models import Model from allennlp.service.predictors.predictor import Predictor from overrides import overrides from allennlp.data.tokenizers.word_splitter import SpacyWordS...
90365
from enum import IntEnum class RedisStatus(IntEnum): """Connection status for the redis client.""" NONE = 0 CONNECTED = 1 AUTH_ERROR = 2 CONN_ERROR = 3 class RedisEvent(IntEnum): """Redis client events.""" CONNECT_BEGIN = 1 CONNECT_SUCCESS = 2 CONNECT_FAIL = 3 KEY_ADDED_TO_...
90377
from common_fixtures import * # NOQA import websocket as ws import base64 import pytest VOLUME_DRIVER = "rancher-longhorn" STACK_NAME_PREFIX = "volume-" CONTROLLER = "controller" REPLICA = "replica" def test_container_with_volume_execute(client, test_name): volume_name = 'vol' + test_name cleanup_items = ...
90408
from boa_test.tests.boa_test import BoaTest from boa.compiler import Compiler from neo.Prompt.Commands.BuildNRun import TestBuild class TestContract(BoaTest): def test_binops(self): output = Compiler.instance().load('%s/boa_test/example/BinopTest.py' % TestContract.dirname).default out = output....
90412
import pytest from dagster import Any, String, usable_as_dagster_type from dagster.check import CheckError from dagster.core.types.dagster_type import resolve_dagster_type from dagster.utils import safe_tempfile_path from dagstermill.serialize import read_value, write_value def test_scalar(): with safe_tempfile_p...
90432
import argparse import re if not hasattr(re, '_pattern_type'): re._pattern_type = re.Pattern import os.path import sys from ygo import globals from ygo.exceptions import LanguageError from ygo.language_handler import LanguageHandler from ygo.parsers.login_parser import LoginParser from ygo.server import Se...
90510
class View(dict): """A View contains the content displayed in the main window.""" def __init__(self, d=None): """ View constructor. Keyword arguments: d=None: Initial keys and values to initialize the view with. Regardless of the value of d, keys 'songs', 'artists' an...
90544
def lcs(s1, s2, x, y): if arr[x-1][y-1] != -1: return arr[x-1][y-1] if x==0 or y==0: arr[x-1][y-1] = 0 return 0 elif s1[x-1] == s2[y-1]: arr[x-1][y-1] = 1 + lcs(s1, s2, x-1, y-1) return arr[x-1][y-1] else: arr[x-1][y-1] = max(lcs(s1, s2, x-1, y), lcs(s...
90557
import numpy as np import argparse from run_search import region_search if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--image_dir', dest='im_filepath') parser.add_argument('--results_dir', dest='res_filepath') parser.add_argument('--results_suffix', ...
90561
import torch import torch.nn as nn from .encoders import LBSNet, LEAPOccupancyDecoder, BaseModule class INVLBS(LBSNet): def __init__(self, num_joints, hidden_size, pn_dim, fwd_trans_cond_dim): self.fwd_trans_cond_dim = fwd_trans_cond_dim super().__init__(num_joints, hidden_size, pn_dim) ...
90597
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn # import torch.nn.functional as F import torch.optim as optim import utils.utils as util import utils.quantizati...
90609
import kfp from kfp import dsl from kfp.components import func_to_container_op @func_to_container_op def show_results(decision_tree : float, logistic_regression : float) -> None: # Given the outputs from decision_tree and logistic regression components # the results are shown. print(f"Decision tree (accur...
90659
import numpy as np def softmax(x): """Stable softmax""" x -= np.max(x, axis=0) e_x = np.exp(x) return e_x / np.sum(e_x, axis=0) def get_idx_aug_baseline(LOO_influences): """Returns points randomly""" idxs = np.random.choice( len(LOO_influences), len(LOO_influences), ...
90672
import errno import os import logging import urllib2 import httplib import urlparse import m3u8 import shutil import crypto from futures import ThreadPoolExecutor, TimeoutError import helpers import atomic from transcode import transcode_playlist config = helpers.load_config() NUM_THREAD_WORKERS = config.getint('hls...
90690
import urllib from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods import posts import xmlrpclib from wordpress_xmlrpc.compat import xmlrpc_client from wordpress_xmlrpc.methods import media, posts import os ########################### Read Me First ############################### ''' -------...
90692
from bpy_speckle.convert.to_native import convert_to_native def get_speckle_subobjects(attr, scale, name): subobjects = [] for key in attr.keys(): if isinstance(attr[key], dict): subtype = attr[key].get("type", None) if subtype: name = f"{name}.{key}" ...
90715
from recon.core.module import BaseModule from recon.utils.crypto import aes_decrypt class Module(BaseModule): meta = { 'name': 'PwnedList - Pwned Domain Credentials Fetcher', 'author': '<NAME> (@LaNMaSteR53)', 'description': 'Queries the PwnedList API to fetch all credentials for a domain....
90725
from .LevenshteinMixin import LevenshteinMixin from .SimpleSearchMixin import SimpleSearchMixin from .YearsMixin import YearsMixin