max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 7 115 | max_stars_count int64 101 368k | id stringlengths 2 8 | content stringlengths 6 1.03M |
|---|---|---|---|---|
sketchgraphs_models/nn/distributed.py | applied-exploration/contraint-based-parametric-modelling | 204 | 12659417 | """Utility modules for distributed and parallel training. """
import torch
class SingleDeviceDistributedParallel(torch.nn.parallel.distributed.DistributedDataParallel):
"""This module implements a module similar to `DistributedDataParallel`, but it accepts
inputs of any shape, and only supports a single devic... |
Python/Numba/Ufunc/julia_ufunc.py | Gjacquenot/training-material | 115 | 12659435 | '''Module containing function for computing Julia sets'''
from numba import guvectorize, void, complex128, int32, float64
@guvectorize([void(complex128[:], float64[:], int32[:], int32[:])],
'(n),(),()->(n)')
def julia_set(domain, max_norm, max_iters, iterations):
for i, z in enumerate(domain):
... |
apps/forms-flow-ai/forms-flow-api/migrations/versions/0b8739ab2097_cleanup_of_submission_id.py | saravanpa-aot/SBC_DivApps | 132 | 12659467 | """cleanup of submission id
Revision ID: 0b8739ab2097
Revises: <KEY>
Create Date: 2020-09-03 16:19:38.703377
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0b8739ab2097'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ###... |
deprecated/scripts/data/diff_vec_clustering_attempt/diff_explore.py | grahamwhiteuk/neutralizing-bias | 169 | 12659474 | <reponame>grahamwhiteuk/neutralizing-bias
import sys
import numpy as np
from sklearn.cluster import DBSCAN
import time
import matplotlib.pyplot as plt
def read_vecs(path):
out = []
for l in open(path):
out.append([float(x) for x in l.strip().split()])
return np.array(out)
difs = read_vecs(sys.argv[1])
mu = n... |
lib/indicators.py | CanadaMontreal/trading-with-python | 318 | 12659496 | '''
Created on Jul 3, 2014
author: <NAME>
License: BSD
Description: Module containing some (technical) indicators
'''
import pandas as pd
def rsi(price, n=14):
''' rsi indicator '''
gain = price.diff().fillna(0) # fifference between day n and n-1, replace nan (first value) with 0
d... |
unittest/scripts/auto/py_devapi/validation/mysqlx_type_norecord.py | mueller/mysql-shell | 119 | 12659505 | <gh_stars>100-1000
#@<OUT> Help on Type
NAME
Type - Data type constants.
SYNTAX
mysqlx.Type
DESCRIPTION
The data type constants assigned to a Column object retrieved through
RowResult.get_columns().
PROPERTIES
BIGINT
A large integer.
BIT
A bit-value type.
... |
pthflops/utils.py | thiagolermen/pytorch-estimate-flops | 194 | 12659517 | import functools
import inspect
import warnings
from typing import Iterable
import torch
def print_table(rows, header=['Operation', 'OPS']):
r"""Simple helper function to print a list of lists as a table
:param rows: a :class:`list` of :class:`list` containing the data to be printed. Each entry in the list
... |
data/wsj/recover_whitespace.py | thomaslu2000/Incremental-Parsing-Representations | 723 | 12659546 | import glob
import os
from nltk.corpus.reader.bracket_parse import BracketParseCorpusReader
import nltk
import tokenizations # pip install pytokenizations==0.7.2
TOKEN_MAPPING = {
"-LRB-": "(",
"-RRB-": ")",
"-LCB-": "{",
"-RCB-": "}",
"-LSB-": "[",
"-RSB-": "]",
"``": '"',
"''": '"'... |
rdkit/ML/Cluster/murtagh_test.py | kazuyaujihara/rdkit | 1,609 | 12659555 |
import numpy
from rdkit.ML.Cluster import Murtagh
print('1')
d = numpy.array([[10.0, 5.0], [20.0, 20.0], [30.0, 10.0], [30.0, 15.0], [5.0, 10.0]], numpy.float)
print('2')
# clusters = Murtagh.ClusterData(d,len(d),Murtagh.WARDS)
# for i in range(len(clusters)):
# clusters[i].Print()
# print('3')
dists = []
for i ... |
unittest/scripts/auto/py_mixed_versions/validation/cluster_multiple_server_versions.py | mueller/mysql-shell | 119 | 12659567 | #@<OUT> get cluster status
{
"clusterName": "testCluster",
"defaultReplicaSet": {
"name": "default",
"topology": [
{
"address": "<<<hostname>>>:<<<__mysql_sandbox_port2>>>",
"label": "<<<hostname>>>:<<<__mysql_sandbox_port2>>>",
"ro... |
PR_BCI_team/Team_StarLab/DKHan/examples/giga_cnn/main_triplet.py | PatternRecognition/OpenBMI | 217 | 12659589 | <reponame>PatternRecognition/OpenBMI
from __future__ import print_function
import argparse
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader
fro... |
bonobo/util/errors.py | Playfloor/bonobo | 1,573 | 12659614 | import logging
import re
from contextlib import contextmanager
from sys import exc_info
from mondrian import term
logger = logging.getLogger(__name__)
@contextmanager
def sweeten_errors():
try:
yield
except Exception as exc:
SPACES = 2
w = term.white
prefix = w("║" + " " * (S... |
scripts/test_wandb.py | mariatippler/haven-ai | 145 | 12659629 | <reponame>mariatippler/haven-ai
from haven import haven_wizard as hw
import wandb
import sys
import os
import pprint
path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, path)
if __name__ == "__main__":
# first way
score_dict = {"loss": loss}
wandb.send(score_dict)
... |
menpo/model/vectorizable.py | apapaion/menpo | 311 | 12659632 | class VectorizableBackedModel(object):
r"""
Mixin for models constructed from a set of :map:`Vectorizable` objects.
Supports models for which visualizing the meaning of a set of components
is trivial.
Requires that the following methods are implemented:
1. `component_vector(index)`
2. `ins... |
gitlab/tests/test_e2e.py | vbarbaresi/integrations-core | 663 | 12659686 | <reponame>vbarbaresi/integrations-core
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from datadog_checks.dev.utils import get_metadata_metrics
from .common import ALLOWED_METRICS, CONFIG, LEGACY_CONFIG, METRICS_TO_TEST, assert_check
... |
unittests/resources/checks_unlisted/fixtures_simple.py | CLIP-HPC/reframe | 167 | 12659697 | <gh_stars>100-1000
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import reframe as rfm
import reframe.utility.sanity as sn
import os
class HelloFixture(rfm.RunOnlyRegres... |
tick/robust/tests/serializing_test.py | sumau/tick | 411 | 12659722 | # License: BSD 3 clause
import io, unittest
import numpy as np
import pickle
from scipy.sparse import csr_matrix
from tick.base_model.tests.generalized_linear_model import TestGLM
from tick.prox import ProxL1
from tick.linear_model import ModelLinReg, SimuLinReg
from tick.linear_model import ModelLogReg, SimuLogReg... |
test/python/isolationtest/isolationTestHandler.py | faizol/babelfish_extensions | 115 | 12659745 | import traceback
from antlr4 import *
from .parser.specLexer import specLexer
from .parser.specParser import specParser
from .specParserVisitorImpl import *
def isolationTestHandler(testFile, fileWriter, logger):
testName = testFile.name.split('.')[0]
try:
logger.info("Starting : {}".format(testName... |
flatdata-generator/tests/generators/test_go_generator.py | gferon/flatdata | 140 | 12659746 | '''
Copyright (c) 2017 HERE Europe B.V.
See the LICENSE file in the root of this project for license details.
'''
import glob
from flatdata.generator.generators.go import GoGenerator
from .assertions import generate_and_assert_in
from .schemas import schemas_and_expectations
from nose.plugins.skip import SkipTest
... |
stock_model.py | murilobd/Deep-Convolution-Stock-Technical-Analysis | 312 | 12659778 | <filename>stock_model.py
import argparse
import sys
import tensorflow as tf
import functools
from ops import *
from loader import *
def doublewrap(function):
@functools.wraps(function)
def decorator(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return function(args[0])... |
sdk/python/feast/infra/online_stores/contrib/hbase_repo_configuration.py | ibnummuhammad/feast | 810 | 12659808 | from tests.integration.feature_repos.integration_test_repo_config import (
IntegrationTestRepoConfig,
)
from tests.integration.feature_repos.universal.online_store.hbase import (
HbaseOnlineStoreCreator,
)
FULL_REPO_CONFIGS = [
IntegrationTestRepoConfig(online_store_creator=HbaseOnlineStoreCreator),
]
|
alipay/aop/api/domain/DiscountModel.py | snowxmas/alipay-sdk-python-all | 213 | 12659827 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class DiscountModel(object):
def __init__(self):
self._term_discount = None
self._term_no = None
@property
def term_discount(self):
return self._term... |
pixyz/models/vi.py | MokkeMeguru/pixyz-test | 453 | 12659839 | <reponame>MokkeMeguru/pixyz-test
from torch import optim
from ..models.model import Model
from ..utils import tolist
from ..losses import ELBO
class VI(Model):
"""
Variational Inference (Amortized inference)
The ELBO for given distributions (p, approximate_dist) is set as the loss class of this model.
... |
setup.py | EliFinkelshteyn/alphabet-detector | 152 | 12659850 | <reponame>EliFinkelshteyn/alphabet-detector<gh_stars>100-1000
from distutils.core import setup
setup(
name='alphabet-detector',
packages=['alphabet_detector'],
version='0.0.7',
description='A library to detect what alphabet something is written in.',
author='<NAME>',
author_email='<EMAIL>',
... |
ida_plugin/uefi_analyser/utils.py | fengjixuchui/UEFI_RETool | 240 | 12659870 | # SPDX-License-Identifier: MIT
import os
import ida_bytes
import idaapi
import idc
# definitions from PE file structure
IMAGE_FILE_MACHINE_IA64 = 0x8664
IMAGE_FILE_MACHINE_I386 = 0x014C
PE_OFFSET = 0x3C
IMAGE_SUBSYSTEM_EFI_APPLICATION = 0xA
IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 0xB
IMAGE_SUBSYSTEM_EFI_RUNTIME_DR... |
dataset/convert_coco_to_tfrecords.py | rickyHong/Light-Head-RCNN-enhanced-Xdetector | 116 | 12659877 | <gh_stars>100-1000
from pycocotools.coco import COCO
import os
import sys
import random
import numpy as np
import skimage.io as io
import scipy
import tensorflow as tf
from dataset_utils import int64_feature, float_feature, bytes_feature
# TFRecords convertion parameters.
SAMPLES_PER_FILES = 5000
class CoCoDataset... |
commons/validation.py | Bermuhz/DataMiningCompetitionFirstPrize | 128 | 12659884 | <gh_stars>100-1000
from commons import variables
def validate(prediction_y_list, actual_y_list):
right_num_dict = {}
prediction_num_dict = {}
actual_num_dict = {}
for (p_y, a_y) in zip(prediction_y_list, actual_y_list):
if not prediction_num_dict.has_key(p_y):
prediction_num_dict... |
seleniumbase/translate/__init__.py | AndriiMykytiuk/SeleniumBase | 2,745 | 12659893 | <reponame>AndriiMykytiuk/SeleniumBase
from seleniumbase.translate import chinese # noqa
from seleniumbase.translate import dutch # noqa
from seleniumbase.translate import french # noqa
from seleniumbase.translate import italian # noqa
from seleniumbase.translate import japanese # noqa
from seleniumbase.translate i... |
extend/upload2oss.py | fengzhongye/darknet_captcha | 348 | 12659930 | <gh_stars>100-1000
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import oss2
import os
import fire
class OSSHandle(object):
def __init__(self):
# 从环境变量获取密钥
AccessKeyId = os.getenv("AccessKeyId")
AccessKeySecret = os.getenv("AccessKeySecret")
BucketName = os.getenv("BucketName")
... |
droidlet/interpreter/robot/__init__.py | ali-senguel/fairo | 669 | 12659974 | <reponame>ali-senguel/fairo
from .loco_interpreter import LocoInterpreter
from .get_memory_handler import LocoGetMemoryHandler
from .put_memory_handler import PutMemoryHandler
__all__ = [LocoGetMemoryHandler, PutMemoryHandler, LocoInterpreter]
|
prjxray/node_model.py | common-config-bot/prjxray | 583 | 12659991 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
class NodeModel():
""" Node looku... |
lib/termineter/modules/set_meter_id.py | jayaram24/Termineter-Modified | 185 | 12660019 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# termineter/modules/set_meter_id.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above c... |
mailthon/response.py | seantis/mailthon | 230 | 12660032 | <reponame>seantis/mailthon
"""
mailthon.response
~~~~~~~~~~~~~~~~~
Response objects encapsulate responses returned
by SMTP servers.
:copyright: (c) 2015 by <NAME>
:license: MIT, see LICENSE for details.
"""
from collections import namedtuple
_ResponseBase = namedtuple('Response', ['status_c... |
terrascript/provider/clc.py | hugovk/python-terrascript | 507 | 12660036 | <gh_stars>100-1000
# terrascript/provider/clc.py
import terrascript
class clc(terrascript.Provider):
pass
__all__ = ["clc"]
|
metadata-ingestion/src/datahub/ingestion/source/iceberg/iceberg_profiler.py | ShubhamThakre/datahub | 1,603 | 12660039 | <reponame>ShubhamThakre/datahub
from datetime import datetime, timedelta
from typing import Any, Callable, Dict, Iterable, Union, cast
from iceberg.api import types as IcebergTypes
from iceberg.api.data_file import DataFile
from iceberg.api.manifest_file import ManifestFile
from iceberg.api.schema import Schema
from i... |
src/ploomber/tasks/_params.py | rehman000/ploomber | 2,141 | 12660040 | <gh_stars>1000+
import copy as copy_module
from collections import abc
class Params(abc.MutableMapping):
"""
Read-only mapping to represent params passed in Task constructor. It
initializes with a copy of the passed dictionary. It verifies that the
dictionary does not have a key "upstream" nor "produc... |
src/classifier/model_lib/char_cnn/char_cnn_keras.py | LeslieLeung/2c | 236 | 12660056 | <gh_stars>100-1000
#!/usr/bin/env python
"""
Created by howie.hu at 2021/4/25.
Description:模型实现
Changelog: all notable changes to this file will be documented
"""
from keras import layers
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.models import Sequential
from src.classifier.mode... |
Algo and DSA/LeetCode-Solutions-master/Python/generate-parentheses.py | Sourav692/FAANG-Interview-Preparation | 3,269 | 12660127 | <reponame>Sourav692/FAANG-Interview-Preparation
# Time: O(4^n / n^(3/2)) ~= Catalan numbers
# Space: O(n)
# iterative solution
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result, curr = [], []
stk = [(1, (n, n))]
... |
tcfcli/cmds/configure/get/cli.py | tencentyun/scfcli | 103 | 12660146 | <reponame>tencentyun/scfcli
# -*- coding: utf-8 -*-
import click
import platform
import tcfcli.common.base_infor as infor
from tcfcli.help.message import ConfigureHelp as help
from tcfcli.common.user_config import UserConfig
from tcfcli.common.operation_msg import Operation
version = platform.python_version()
if vers... |
env/lib/python3.6/site-packages/pip/_vendor/certifi/__main__.py | amogh-gulati/corona_dashboard | 9,953 | 12660148 | <filename>env/lib/python3.6/site-packages/pip/_vendor/certifi/__main__.py
from pip._vendor.certifi import where
print(where())
|
tests/test_weighted_search_vector.py | nitros12/sqlalchemy-searchable | 217 | 12660165 | <filename>tests/test_weighted_search_vector.py
import re
import sqlalchemy as sa
from sqlalchemy_utils import TSVectorType
from sqlalchemy_searchable import search
from tests import SchemaTestCase, TestCase
class WeightedBase(object):
def create_models(self):
class WeightedTextItem(self.Base):
... |
src/genie/libs/parser/iosxe/tests/ShowStandbyInternal/cli/equal/golden_output_expected.py | balmasea/genieparser | 204 | 12660171 | <reponame>balmasea/genieparser
expected_output = {
"hsrp_common_process_state": "not running",
"hsrp_ha_state": "capable",
"hsrp_ipv4_process_state": "not running",
"hsrp_ipv6_process_state": "not running",
"hsrp_timer_wheel_state": "running",
"mac_address_table": {
166: {"group": 10, "i... |
tests/PySys/misc_features/mqtt_port_change_connection_fails/run.py | PradeepKiruvale/localworkflow | 102 | 12660173 | import sys
import time
from pysys.basetest import BaseTest
"""
Validate changing the mqtt port using the tedge command that fails without restarting the mqtt server
Given a configured system, that is configured with certificate created and registered in a cloud
When `tedge mqtt.port set` with `sudo`
When the `sudo ... |
dart_fss/fs/__init__.py | dveamer/dart-fss | 243 | 12660285 | <reponame>dveamer/dart-fss
# -*- coding: utf-8 -*-
from dart_fss.fs.extract import extract
from dart_fss.fs.fs import FinancialStatement
__all__ = ['extract', 'FinancialStatement'] |
qucumber/rbm/purification_rbm.py | ZvonimirBandic/QuCumber | 163 | 12660296 | # Copyright 2019 PIQuIL - All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed ... |
experimental/rien/rk4_example/setup.py | mindThomas/acados | 322 | 12660303 | #!/usr/bin/env python
"""
setup.py file for SWIG example
"""
from distutils.core import setup, Extension
erk_integrator_module = Extension('_erk_integrator',
sources=['erk_integrator_wrap.c', 'erk_integrator.c', 'auxiliary_functions.c', 'model.c', 'timing_functions.c'],
... |
data/transcoder_evaluation_gfg/python/COUNT_NUMBER_WAYS_REACH_GIVEN_SCORE_GAME.py | mxl1n/CodeGen | 241 | 12660305 | # Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( n ) :
table = [ 0 for i in range ( n + 1 ) ]
table [ 0 ] = 1
for i in range ( 3 , n + 1 ) :
tab... |
ferminet/utils/scf.py | llxlr/ferminet | 469 | 12660315 | <filename>ferminet/utils/scf.py
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apa... |
pipeline/python/ion/reports/wells_beadogram.py | konradotto/TS | 125 | 12660320 | #!/usr/bin/python
# Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved
import os
import json
import logging
import ConfigParser
from matplotlib import use
use("Agg", warn=False)
from matplotlib import pyplot
from matplotlib.ticker import FuncFormatter, LinearLocator
from matplotlib import transforms
lo... |
tests/test_util.py | adger-me/you-get | 46,956 | 12660322 | <reponame>adger-me/you-get
#!/usr/bin/env python
import unittest
from you_get.util.fs import *
class TestUtil(unittest.TestCase):
def test_legitimize(self):
self.assertEqual(legitimize("1*2", os="linux"), "1*2")
self.assertEqual(legitimize("1*2", os="mac"), "1*2")
self.assertEqual(legitim... |
neurogym/envs/probabilisticreasoning.py | ruyuanzhang/neurogym | 112 | 12660332 | <filename>neurogym/envs/probabilisticreasoning.py
"""Random dot motion task."""
import numpy as np
import neurogym as ngym
from neurogym import spaces
class ProbabilisticReasoning(ngym.TrialEnv):
"""Probabilistic reasoning.
The agent is shown a sequence of stimuli. Each stimulus is associated
with a ce... |
data/tracking/post_processor/response_map.py | zhangzhengde0225/SwinTrack | 143 | 12660337 | import torch
class ResponseMapTrackingPostProcessing:
def __init__(self, enable_gaussian_score_map_penalty, search_feat_size, window_penalty_ratio=None):
self.enable_gaussian_score_map_penalty = enable_gaussian_score_map_penalty
self.search_feat_size = search_feat_size
if enable_gaussian_... |
Algo and DSA/LeetCode-Solutions-master/Python/best-position-for-a-service-centre.py | Sourav692/FAANG-Interview-Preparation | 3,269 | 12660338 | <filename>Algo and DSA/LeetCode-Solutions-master/Python/best-position-for-a-service-centre.py
# Time: O(n * iter), iter is the number of iterations
# Space: O(1)
# see reference:
# - https://en.wikipedia.org/wiki/Geometric_median
# - https://wikimedia.org/api/rest_v1/media/math/render/svg/b3fb215363358f12687100710caf... |
napari/plugins/_tests/test_builtin_get_writer.py | MaksHess/napari | 1,345 | 12660448 | import os
import pytest
from napari_plugin_engine import PluginCallError
from napari.plugins import _builtins
# test_plugin_manager fixture is provided by napari_plugin_engine._testsupport
def test_get_writer_succeeds(
napari_plugin_manager, tmpdir, layer_data_and_types
):
"""Test writing layers data."""
... |
clist/migrations/0039_auto_20200528_2349.py | horacexd/clist | 166 | 12660450 | # Generated by Django 2.2.10 on 2020-05-28 23:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('clist', '0038_problem_division'),
]
operations = [
migrations.RenameField(
model_name='problem',
old_name='division',
... |
Chapter10/service/libs/storage/src/storage/client.py | TranQuangDuc/Clean-Code-in-Python | 402 | 12660453 | <reponame>TranQuangDuc/Clean-Code-in-Python<filename>Chapter10/service/libs/storage/src/storage/client.py
"""Abstraction to the database.
Provide a client to connect to the database and expose a custom API, at the
convenience of the application.
"""
import os
import asyncpg
def _extract_from_env(variable, *, defau... |
blender/addons/2.8/mira_tools/mi_inputs.py | belzecue/mifthtools | 730 | 12660457 |
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distribut... |
adapters/tuya/TS0013.py | russdan/domoticz-zigbee2mqtt-plugin | 146 | 12660471 | <gh_stars>100-1000
from adapters.tuya.TS0012 import TS0012
from devices.switch.on_off_switch import OnOffSwitch
class TS0013(TS0012):
def __init__(self):
super().__init__()
self.devices.append(OnOffSwitch('center', 'state_center'))
|
src/convmlp.py | dumpmemory/Convolutional-MLPs | 117 | 12660488 | <filename>src/convmlp.py
from torch.hub import load_state_dict_from_url
import torch.nn as nn
from .utils.tokenizer import ConvTokenizer
from .utils.modules import ConvStage, BasicStage
__all__ = ['ConvMLP', 'convmlp_s', 'convmlp_m', 'convmlp_l']
model_urls = {
'convmlp_s': 'http://ix.cs.uoregon.edu/~alih/conv-... |
src/Simulation/Native/parseLog.py | Bradben/qsharp-runtime | 260 | 12660491 | <filename>src/Simulation/Native/parseLog.py<gh_stars>100-1000
import re
import sys
import numpy as np
logName = sys.argv[1]
reSched = re.compile(r"^==== sched:\s+(\S+)")
reFN = re.compile(r"^(\S+)\.")
reNQs = re.compile(r"nQs=(\d+) .*range=(\d+).*prb=(\d+)")
reSim = re.compile(' (Generic|AVX|AVX2|AVX512)$')
... |
spytest/spytest/tgen/scapy/dicts.py | shubav/sonic-mgmt | 132 | 12660523 | from collections import OrderedDict
class SpyTestDict(OrderedDict):
"""
todo: Update Documentation
"""
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
if not name.sta... |
tributary/lazy/node.py | ayakubov/tributary | 357 | 12660529 | <reponame>ayakubov/tributary
import inspect
from collections import namedtuple
from ..base import TributaryException
# from boltons.funcutils import wraps
from ..utils import _compare, _either_type, _ismethod
from .dd3 import _DagreD3Mixin
class Node(_DagreD3Mixin):
"""Class to represent an operation that is la... |
python/rootba/run.py | zeta1999/rootba | 139 | 12660556 | <reponame>zeta1999/rootba<filename>python/rootba/run.py<gh_stars>100-1000
#
# BSD 3-Clause License
#
# This file is part of the RootBA project.
# https://github.com/NikolausDemmel/rootba
#
# Copyright (c) 2021, <NAME>.
# All rights reserved.
#
import os
import re
from collections import Mapping
from .log import load_b... |
pymoo/util/termination/f_tol_single.py | gabicavalcante/pymoo | 762 | 12660591 | <reponame>gabicavalcante/pymoo
from pymoo.util.misc import to_numpy
from pymoo.util.termination.sliding_window_termination import SlidingWindowTermination
class SingleObjectiveSpaceToleranceTermination(SlidingWindowTermination):
def __init__(self,
tol=1e-6,
n_last=20,
... |
tests/test_COCOInstanceAPI.py | mintar/mseg-api | 213 | 12660607 | <reponame>mintar/mseg-api
#!/usr/bin/python3
from pathlib import Path
import numpy as np
from mseg.dataset_apis.COCOInstanceAPI import COCOInstanceAPI
_TEST_DIR = Path(__file__).parent
def test_constructor() -> None:
""" """
coco_dataroot = f"{_TEST_DIR}/test_data/COCOPanoptic_test_data"
c_api = COCO... |
tests/utils/test_audio.py | CostanzoPablo/audiomate | 133 | 12660634 | <filename>tests/utils/test_audio.py
import os
import numpy as np
import librosa
from audiomate import tracks
from audiomate.utils import audio
def test_read_blocks(tmpdir):
wav_path = os.path.join(tmpdir.strpath, 'file.wav')
wav_content = np.random.random(10000)
librosa.output.write_wav(wav_path, wav_co... |
library/oci_cross_connect_group.py | slmjy/oci-ansible-modules | 106 | 12660658 | #!/usr/bin/python
# Copyright (c) 2019, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for detail... |
tests/integration/test_actions.py | zhuhaow/aws-lambda-builders | 180 | 12660662 | import os
from pathlib import Path
import tempfile
from unittest import TestCase
from parameterized import parameterized
from aws_lambda_builders.actions import CopyDependenciesAction, MoveDependenciesAction
from aws_lambda_builders.utils import copytree
class TestCopyDependenciesAction(TestCase):
@parameterize... |
notebooks-text-format/funnel_pymc3.py | arpitvaghela/probml-notebooks | 166 | 12660726 | # -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
... |
loaner/deployments/lib/app_constants.py | gng-demo/travisfix | 175 | 12660735 | <reponame>gng-demo/travisfix
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
pyclustering/nnet/tests/unit/ut_fsync.py | JosephChataignon/pyclustering | 1,013 | 12660783 | """!
@brief Unit-tests for Oscillatory Neural Network based on Kuramoto model and Landau-Stuart.
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
import unittest;
# Generate images without having a window appear.
import matplotlib;
matplotlib.use('Agg');
from pyclustering.nn... |
helper.py | chenqifeng22/PhotographicImageSynthesis | 1,359 | 12660812 | <gh_stars>1000+
import os,numpy as np
from os.path import dirname, exists, join, splitext
import json,scipy
class Dataset(object):
def __init__(self, dataset_name):
self.work_dir = dirname(os.path.realpath('__file__'))
info_path = join(self.work_dir, 'datasets', dataset_name + '.json')
with ... |
tests/ut/python/dataset/test_biquad.py | PowerOlive/mindspore | 3,200 | 12660835 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
gan2shape/stylegan2/stylegan2-pytorch/generate.py | PeterouZh/GAN2Shape | 421 | 12660847 | import os
import argparse
import torch
import torch.nn.functional as F
from torchvision import utils
from model import Generator
from tqdm import tqdm
def generate(args, g_ema, device, mean_latent):
with torch.no_grad():
g_ema.eval()
count = 0
for i in tqdm(range(args.pics)):
s... |
projects/perception/object_detection_3d/demos/voxel_object_detection_3d/rplidar_processor.py | ad-daniel/opendr | 217 | 12660875 | <filename>projects/perception/object_detection_3d/demos/voxel_object_detection_3d/rplidar_processor.py
# Copyright 2020-2022 OpenDR European Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Licen... |
Tree/144. Binary Tree Preorder Traversal.py | beckswu/Leetcode | 138 | 12660879 | <reponame>beckswu/Leetcode
"""
144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
class ... |
tests/tensortrade/unit/feed/api/float/test_utils.py | nicomon24/tensortrade | 3,081 | 12660884 |
import numpy as np
import pandas as pd
from itertools import product
from tensortrade.feed import Stream
from tests.utils.ops import assert_op
arrays = [
[-1.5, 2.2, -3.3, 4.7, -5.1, 7.45, 8.8],
[-1.2, 2.3, np.nan, 4.4, -5.5, np.nan, np.nan],
]
def test_ceil():
for array in arrays:
s = Stream... |
redis-py/run_test.py | nikicc/anaconda-recipes | 130 | 12660992 | import redis
#r = redis.StrictRedis(host='localhost', port=6379, db=0)
#r.set('foo', 'bar')
#assert r.get('foo') == 'bar'
|
test/tests/bootstrap/test_api20_os_bootstrap_parallel_local.py | arunrordell/RackHD | 451 | 12661014 | '''
Copyright 2017 Dell Inc. or its subsidiaries. All Rights Reserved.
Author(s):
<NAME>
This script tests minimum payload base case of the RackHD API 2.0 OS bootstrap workflows using NFS mount or local repo method.
This routine runs OS bootstrap jobs simultaneously on multiple nodes.
For 12 tests to run, 12 nodes ar... |
depthnet-pytorch/prepare_dataset.py | dingyanna/DepthNets | 114 | 12661043 | from util import (get_data_from_id,
read_kpt_file)
import glob
import os
import numpy as np
from skimage.io import (imread,
imsave)
from skimage.transform import resize
root_dir = os.environ['DIR_3DFAW']
def prepare_train():
ids = glob.glob("%s/train_img/*.jpg" % root_dir... |
datadog_checks_base/tests/test_log.py | vbarbaresi/integrations-core | 663 | 12661055 | # -*- coding: utf-8 -*-
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import logging
import warnings
import mock
from datadog_checks import log
from datadog_checks.base import AgentCheck
from datadog_checks.base.log import DEFAULT_FALLBACK_LOGGER, ... |
2020_09_23/dojo_test.py | devppjr/dojo | 114 | 12661070 | import unittest
from dojo import remove_word, main
class DojoTest(unittest.TestCase):
def test_remove_word_1(self):
self.assertEqual(remove_word("bananauva", "banana"), "uva")
def test_remove_word_2(self):
self.assertEqual(remove_word("catdog", "dog"), "catdog")
def test_remove_word_3(se... |
src/segmentation.py | Mohamed-S-Helal/Arabic-OCR | 117 | 12661074 | <filename>src/segmentation.py<gh_stars>100-1000
import numpy as np
import cv2 as cv
from preprocessing import binary_otsus, deskew
from utilities import projection, save_image
from glob import glob
def preprocess(image):
# Maybe we end up using only gray level image.
gray_img = cv.cvtColor(image, cv.COLOR_BG... |
tests/__init__.py | sobolevn/py-enumerable | 144 | 12661150 | _empty = []
_simple = [1, 2, 3]
_complex = [{"value": 1}, {"value": 2}, {"value": 3}]
_locations = [
("Scotland", "Edinburgh", "Branch1", 20000),
("Scotland", "Glasgow", "Branch1", 12500),
("Scotland", "Glasgow", "Branch2", 12000),
("Wales", "Cardiff", "Branch1", 29700),
("Wales", "Cardiff", "Branc... |
app/iclass/views/dashboard.py | edisonlz/fastor | 285 | 12661151 | # coding=utf-8
import json
from django.contrib import messages
from django.shortcuts import render, get_object_or_404
from wi_model_util.imodel import get_object_or_none
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResp... |
ChasingTrainFramework_GeneralOneClassDetection/data_iterator_base/data_batch.py | CNN-NISER/lffd-pytorch | 220 | 12661169 | <filename>ChasingTrainFramework_GeneralOneClassDetection/data_iterator_base/data_batch.py
# coding: utf-8
class DataBatch:
def __init__(self, torch_module):
self._data = []
self._label = []
self.torch_module = torch_module
def append_data(self, new_data):
self._data.append(sel... |
src/debugging/XcodeExample/PythonSubclassList/PythonSubclassList/test_sclist.py | joelwhitehouse/PythonExtensionPatterns | 171 | 12661173 | <gh_stars>100-1000
""" Usage:
python3 setup.py build
Created on Apr 19, 2016
@author: paulross
"""
import ScList
def test():
s = ScList.ScList()
s.append(8)
print(s.appends)
print(s)
|
custom_components/garbage_collection/__init__.py | Nag94/HomeAssistantConfig | 271 | 12661213 | <reponame>Nag94/HomeAssistantConfig
"""Component to integrate with garbage_colection."""
import logging
from datetime import timedelta
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const... |
server/realms/migrations/0001_initial.py | arubdesu/zentral | 634 | 12661240 | <reponame>arubdesu/zentral<gh_stars>100-1000
# Generated by Django 2.2.9 on 2020-02-26 14:33
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
op... |
Configuration/Eras/python/Modifier_tracker_apv_vfp30_2016_cff.py | ckamtsikis/cmssw | 852 | 12661246 | import FWCore.ParameterSet.Config as cms
tracker_apv_vfp30_2016 = cms.Modifier()
|
test/slicing/test_monitor.py | melonwater211/snorkel | 2,906 | 12661264 | <reponame>melonwater211/snorkel<gh_stars>1000+
import unittest
import pandas as pd
from snorkel.slicing import slicing_function
from snorkel.slicing.monitor import slice_dataframe
DATA = [5, 10, 19, 22, 25]
@slicing_function()
def sf(x):
return x.num < 20
class PandasSlicerTest(unittest.TestCase):
@class... |
test/cpp/api/init_baseline.py | Hacky-DH/pytorch | 60,067 | 12661292 | """Script to generate baseline values from PyTorch initialization algorithms"""
import sys
import torch
HEADER = """
#include <torch/types.h>
#include <vector>
namespace expected_parameters {
"""
FOOTER = "} // namespace expected_parameters"
PARAMETERS = "inline std::vector<std::vector<torch::Tensor>> {}() {{"
I... |
src/ResNeXt/concateFeature.py | willyspinner/High-Performance-Face-Recognition | 300 | 12661340 | import scipy.io as sio
import pickle
import numpy as np
import os
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from scipy import spatial
from sklearn.externals import joblib
import time
reducedDim = 2048
pca = PCA(n_components = reducedDim, whiten = True)
p... |
recipes/Python/426543_oneliner_Multichop_data/recipe-426543.py | tdiprima/code | 2,023 | 12661377 | <reponame>tdiprima/code
>>> a,bite = "supercalifragalisticexpialidocious",3
>>> [(a[d:d+bite]) for d in range(len(a)-bite) if d%bite==0]
[('s', 'u', 'p'), ('e', 'r', 'c'), ('a', 'l', 'i'), ('f', 'r', 'a'), ('g', 'a', 'l'), ('i', 's', 't'), ('i', 'c', 'e'), ('x', 'p', 'i'), ('a', 'l', 'i'), ('d', 'o', 'c'), ('i', 'o', ... |
aat/__main__.py | mthomascarcamo/aat | 305 | 12661380 | from .config import parseConfig
from .engine import TradingEngine
def main() -> None:
# Parse the command line config
config = parseConfig()
# Instantiate trading engine
#
# The engine is responsible for managing the different components,
# including the strategies, the bank/risk engine, and ... |
test/cli/conftest.py | gluhar2006/schemathesis | 659 | 12661403 | import pytest
@pytest.fixture(params=["real", "wsgi"])
def app_type(request):
return request.param
@pytest.fixture
def cli_args(request, openapi_version, app_type):
if app_type == "real":
schema_url = request.getfixturevalue("schema_url")
args = (schema_url,)
else:
app_path = req... |
python/eggroll/core/io/io_utils.py | liszekei/eggroll | 209 | 12661415 | <reponame>liszekei/eggroll
# Copyright (c) 2019 - now, Eggroll Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... |
use-cases/customer_churn/dataflow.py | jerrypeng7773/amazon-sagemaker-examples | 2,610 | 12661433 | import pandas as pd
## convert to time
df["date"] = pd.to_datetime(df["ts"], unit="ms")
df["ts_year"] = df["date"].dt.year
df["ts_month"] = df["date"].dt.month
df["ts_week"] = df["date"].dt.week
df["ts_day"] = df["date"].dt.day
df["ts_dow"] = df["date"].dt.weekday
df["ts_hour"] = df["date"].dt.hour
df["ts_date_day"] =... |
warp/stubs.py | NVIDIA/warp | 306 | 12661453 | # Autogenerated file, do not edit, this file provides stubs for builtins autocomplete in VSCode, PyCharm, etc
from typing import Any
from typing import Tuple
from typing import Callable
from typing import overload
from warp.types import array, array2d, array3d, array4d, constant
from warp.types import int8, uint8, int... |
src/python/nimbusml/internal/entrypoints/models_schema.py | montehoover/NimbusML | 134 | 12661454 | # - Generated by tools/entrypoint_compiler.py: do not edit by hand
"""
Models.Schema
"""
from ..utils.entrypoints import EntryPoint
from ..utils.utils import try_set, unlist
def models_schema(
model,
schema=None,
**params):
"""
**Description**
Retrieve output model schema
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.