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
elephant/cell_assembly_detection.py
Moritz-Alexander-Kern/elephant-1
121
11015075
""" CAD :cite:`cad-Russo2017_e19428` is a method aimed to capture structures of higher-order correlation in massively parallel spike trains. In particular, it is able to extract patterns of spikes with arbitrary configuration of time lags (time interval between spikes in a pattern), and at multiple time scales, e.g. fr...
test-framework/test-suites/integration/tests/dump/test_dump_bootaction.py
knutsonchris/stacki
123
11015078
import pytest import json class TestDumpBootaction: """ Test that dumping the bootaction data works properly by adding a bootaction then dumping it and checking that it is valid """ def test_dump_bootaction(self, host): # first lets add some data so we have something to check for results = host.run('stack ...
tests/issues/test_issue_410.py
zzzDavid/heterocl
236
11015090
import heterocl as hcl import numpy as np def test_issue_410(): A = hcl.Struct ({'foo': hcl.UInt(16) }) B = hcl.Struct ({'foo': 'uint16' }) assert A['foo'] == B['foo'] def test_issue_410_2(): A = hcl.placeholder((10,), dtype="uint16") def f(A): t = hcl.Struct ({'foo': 'uint16' }) ...
eliot/tests/test_prettyprint.py
srinivas32/eliot
598
11015129
""" Tests for C{eliot.prettyprint}. """ from unittest import TestCase from subprocess import check_output, Popen, PIPE from collections import OrderedDict from datetime import datetime from pyrsistent import pmap from .._bytesjson import dumps from ..prettyprint import pretty_format, compact_format, REQUIRED_FIELDS ...
chainer_chemistry/saliency/calculator/gradient_calculator.py
pfnet/chainerchem
184
11015152
import chainer # NOQA from chainer import functions from chainer_chemistry.saliency.calculator.base_calculator import BaseCalculator # NOQA class GradientCalculator(BaseCalculator): """Gradient saliency calculator Use `compute`, `aggregate` method to calculate saliency. See: <NAME>, <NAME>, <NAME>, <...
micromamba/tests/test_login.py
martinRenou/mamba
405
11015201
<gh_stars>100-1000 import base64 import json import os import re import shutil import subprocess import sys from pathlib import Path import pytest from xprocess import ProcessStarter from .helpers import create as umamba_create from .helpers import get_env, get_umamba, login, logout, random_string here = Path(__file...
notebooks/nb_utils/line_macros.py
roannav/learntools
359
11015223
""" A family of macros that take a line of text (and possibly some other arguments) and return a transformed version to replace it with. """ import re def RM(line): # Returning None meaning "delete this" is a little dangerous (it's easy to do # this accidentally by forgetting a return statement). Could also c...
openbook_hashtags/views/hashtag/views.py
TamaraAbells/okuna-api
164
11015224
# Create your views here. from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from openbook_common.serializers import CommonHashtagSerializer from openbook_hashtags.views.hashtag.serializers impor...
sleekxmpp/plugins/xep_0047/stream.py
E-Tahta/sleekxmpp
499
11015233
import socket import threading import logging from sleekxmpp.stanza import Iq from sleekxmpp.util import Queue from sleekxmpp.exceptions import XMPPError log = logging.getLogger(__name__) class IBBytestream(object): def __init__(self, xmpp, sid, block_size, jid, peer, window_size=1, use_messages=False): ...
Python/Rotate-array-by-D-elements/code.py
ieternalleo/AlgoCode
151
11015234
def rotateByd(lst): lst[0:d] = reversed(lst[0:d]) lst[d: ] = reversed(lst[d: ]) lst.reverse() print(lst) print("enter the array of numbers:", end=" ") lst = [int(i) for i in input().split()] print() print("enter the value of d:", end=" ") d = int(input()) rotateByd(lst) #In this algo we first reverse...
tests/test_zsh.py
maralla/validator.vim
255
11015235
<reponame>maralla/validator.vim<filename>tests/test_zsh.py<gh_stars>100-1000 import json from lints.zsh import ZshLint def test_zsh(): msg = [ '.zshrc:598: no such file or directory: /etc/ssh/ssh_known_hosts2', ] res = ZshLint().parse_loclist(msg, 1) assert json.loads(res)[0] == { "ln...
playground/semantic_segmentation/cityscapes/dynamic_routing/Seg.Layer16/config.py
hanqiu-hq/cvpods
548
11015257
import os.path as osp from cvpods.configs.dynamic_routing_config import SemanticSegmentationConfig _config_dict = dict( MODEL=dict( WEIGHTS="", CAL_FLOPS=True, BACKBONE=dict( CELL_TYPE=['sep_conv_3x3', 'skip_connect'], LAYER_NUM=16, CELL_NUM_LIST=[2, 3, ...
qiskit_optimization/applications/optimization_application.py
renier/qiskit-optimization
109
11015282
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
circus/commands/errors.py
BradleyKirton/circus
820
11015307
<filename>circus/commands/errors.py NOT_SPECIFIED = 0 INVALID_JSON = 1 UNKNOWN_COMMAND = 2 MESSAGE_ERROR = 3 OS_ERROR = 4 COMMAND_ERROR = 5 BAD_MSG_DATA_ERROR = 6
pkg/filament/cpython/_fixtures/top_hives_io.py
Monkeyman21/fibratus
1,604
11015310
<gh_stars>1000+ # Copyright 2016 by <NAME> (RabbitStack) # All Rights Reserved. # http://rabbitstack.github.io # 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/license...
coherence/upnp/devices/dimmable_light_client.py
stonewell/Coherence
112
11015315
<reponame>stonewell/Coherence<filename>coherence/upnp/devices/dimmable_light_client.py # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2008, <NAME> <<EMAIL>> # Copyright 2014, <NAME> <<EMAIL>> from .basics import BasicClient from ..services.clients.switch_power_client imp...
src/django-nonrel/django/middleware/transaction.py
adamjmcgrath/glancydesign
790
11015347
from django.db import transaction class TransactionMiddleware(object): """ Transaction middleware. If this is enabled, each view function will be run with commit_on_response activated - that way a save() doesn't do a direct commit, the commit is done when a successful response is created. If an exc...
lib/spack/spack/environment/shell.py
LiamBindle/spack
2,360
11015352
<gh_stars>1000+ # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os import llnl.util.tty as tty from llnl.util.tty.color import colorize import spack.environment a...
CalibMuon/Configuration/python/RPC_FrontierConditions_IntDB_cff.py
ckamtsikis/cmssw
852
11015354
# The following comments couldn't be translated into the new config version: #cms_conditions_data/CMS_COND_20X_RPC" import FWCore.ParameterSet.Config as cms # #RPC calibrations #For now, no t0 corrections are applied in the reconstruction if fake calibration is used #(the replace should be moved to main cfg in order ...
cinder/policies/backups.py
arunvinodqmco/cinder
571
11015370
<filename>cinder/policies/backups.py # Copyright (c) 2017 Huawei Technologies Co., Ltd. # 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....
tests/providers/microsoft/azure/operators/test_azure_data_factory.py
npodewitz/airflow
8,092
11015372
<reponame>npodewitz/airflow # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the...
tests/test_oom_logger.py
sobolevn/paasta
1,711
11015402
<filename>tests/test_oom_logger.py # Copyright 2015-2017 Yelp Inc. # # 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 ap...
smbprotocol/lznt1.py
allblue147/CVE-2020-0796-PoC
306
11015419
<reponame>allblue147/CVE-2020-0796-PoC<filename>smbprotocol/lznt1.py<gh_stars>100-1000 import struct import sys import copy def _decompress_chunk(chunk): size = len(chunk) out = bytearray() pow2 = 0x10 while chunk: flags = chunk[0] chunk = chunk[1:] for i in range(8): ...
src/datasets/exemplars_dataset.py
francesco-p/FACIL
243
11015427
<reponame>francesco-p/FACIL<filename>src/datasets/exemplars_dataset.py import importlib from argparse import ArgumentParser from datasets.memory_dataset import MemoryDataset class ExemplarsDataset(MemoryDataset): """Exemplar storage for approaches with an interface of Dataset""" def __init__(self, transform...
up/tasks/cls/models/losses/cls_loss.py
ModelTC/EOD
196
11015441
import torch from torch.nn.modules.loss import _Loss import torch.nn.functional as F import math from up.utils.general.registry_factory import LOSSES_REGISTRY __all__ = ['LabelSmoothCELoss', 'BCE_LOSS', 'CrossEntropyLoss', 'SoftTargetCrossEntropy'] @LOSSES_REGISTRY.register('label_smooth_ce') class LabelSmoothCELos...
Models/dataloader/cifar_fs/sampling/cifar_fs.py
icoz69/DeepEMD
444
11015460
<filename>Models/dataloader/cifar_fs/sampling/cifar_fs.py<gh_stars>100-1000 import os import os.path as osp from PIL import Image from torch.utils.data import Dataset from torchvision import transforms import numpy as np import torch class DatasetLoader(Dataset): def __init__(self, setname, args=None): ...
flexget/components/emby/api_emby.py
astrotee/Flexget
1,322
11015461
import copy import functools import re from abc import ABC, abstractmethod, abstractstaticmethod from collections.abc import MutableSet from datetime import datetime from urllib.parse import urlencode from loguru import logger from requests.exceptions import HTTPError, RequestException from flexget.components.emby.em...
cmd_line/autoencoders/run_stacked_autoencoder_unsupervised.py
akmeraki/deep-learning-
1,093
11015507
import numpy as np import os import tensorflow as tf from yadlt.models.autoencoders import deep_autoencoder from yadlt.utils import datasets, utilities # #################### # # Flags definition # # #################### # flags = tf.app.flags FLAGS = flags.FLAGS # Global configuration flags.DEFINE_string('datas...
tests/applicator-utils/test_applicators.py
tserg/eth-utils
234
11015553
import collections import pytest import eth_utils from eth_utils.curried import ( apply_formatter_at_index, apply_formatter_if, apply_formatter_to_array, apply_formatters_to_dict, apply_formatters_to_sequence, apply_key_map, apply_one_of_formatters, is_list_like, is_string, ) def...
regtests/loop/yield.py
bpmbank/PythonJS
319
11015585
<filename>regtests/loop/yield.py<gh_stars>100-1000 ''' generator function ''' def fib(n): a, b = 0, 1 for x in range(n): yield a a,b = b, a+b yield 'world' def main(): arr = [] for n in fib(20): arr.append( n ) TestError( arr[0]==0 ) TestError( arr[1]==1 ) TestError( arr[2]==1 ) TestError( arr[3]==2 )...
tests/syntax/scripts/zeros.py
dina-fouad/pyccel
206
11015595
# pylint: disable=missing-function-docstring, missing-module-docstring/ from numpy import zeros from numpy import ones n = 5 x1 = zeros(4) x2 = zeros(n) #x3 = zeros(n, 'int') y1 = zeros((4, 3)) y2 = zeros((n, 2*n)) m = 5 a1 = ones(4) a2 = ones(n) #a3 = ones(n, 'int') b1 = ones((4, 3)) b2 = ones((n, 2*n))
mnist-transfer-cnn/python/mnist_transfer_cnn_test.py
kikko/tfjs-examples
5,798
11015624
# Copyright 2018 Google LLC. 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 a...
src/util/convert_weights.py
29ayush/simple_dqn
767
11015635
<gh_stars>100-1000 import pickle import argparse parser = argparse.ArgumentParser() parser.add_argument("file") args = parser.parse_args() with open(args.file, 'r') as fid: model_param = pickle.load(fid) for lay_param in model_param['layer_params_states']: w = lay_param['params'] lay_param['params'] ...
testing/mock_server.py
bbhunter/fuzz-lightyear
169
11015660
import json import logging import multiprocessing as mp import os from contextlib import contextmanager from contextlib import redirect_stdout from time import sleep import requests from testing.vulnerable_app.__main__ import main as start_server PORT = int(os.environ.get('PORT', 5000)) URL = 'http://localhost:{}'....
census/tensorflowcore/trainer/model.py
tmatsuo/cloudml-samples
1,552
11015661
# Copyright 2016 The TensorFlow 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/LICENSE-2.0 # # Unless required by applica...
nncf/experimental/tensorflow/graph/node_attributes.py
GreenWaves-Technologies/nncf
136
11015676
""" Copyright (c) 2022 Intel Corporation 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 in writin...
bin/test_args.py
hyvyys/gftools
150
11015705
<reponame>hyvyys/gftools #!/usr/bin/env python3 import sys target_modules = [ "gftools-build-font2ttf", "gftools-fix-ascii-fontmetadata", "gftools-fix-familymetadata", "gftools-fix-fsselection", "gftools-fix-gasp", "gftools-fix-glyph-private-encoding", "gftools-fix-glyphs", "gftools-fix-nameids", # "gft...
pyabc/sge/cleanup_sge_array_job.py
wdwang/pyABC
144
11015758
import sys from pyabc.sge.db import job_db_factory tmp_path = sys.argv[1] job_nr = sys.argv[2] # save end time to database job_db = job_db_factory(tmp_path) job_db.finish(int(job_nr))
tests/test_gs_specific.py
kabirkhan/cloudpathlib
128
11015776
import pytest from cloudpathlib import GSPath from cloudpathlib.local import LocalGSPath @pytest.mark.parametrize("path_class", [GSPath, LocalGSPath]) def test_gspath_properties(path_class): p = path_class("gs://mybucket") assert p.blob == "" assert p.bucket == "mybucket" p2 = path_class("gs://mybuc...
tensorflow_datasets/image/downsampled_imagenet.py
jvishnuvardhan/datasets
3,380
11015783
<filename>tensorflow_datasets/image/downsampled_imagenet.py # coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # 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...
samcli/lib/pipeline/bootstrap/resource.py
zhuhaow/aws-sam-cli
2,959
11015785
<reponame>zhuhaow/aws-sam-cli """ Represents AWS resource""" from typing import Optional class ARNParts: """ Decompose a given ARN into its parts https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html Attributes ---------- partition: str the partition part(AWS, aws-cn ...
test/test_pipeline/components/classification/test_bernoulli_nb.py
Louquinze/auto-sklearn
6,390
11015791
import sklearn.naive_bayes from autosklearn.pipeline.components.classification.bernoulli_nb import \ BernoulliNB from .test_base import BaseClassificationComponentTest class BernoulliNBComponentTest(BaseClassificationComponentTest): __test__ = True res = dict() res["default_iris"] = 0.26 res["...
applications/ATOM/utils/compute_sample_lengths.py
jonesholger/lbann
194
11015799
import sys if len(sys.argv) != 3 : print(F''' usage: {sys.argv[0]} input_fn output_fn function: computes the length of each SMILES string output: each line of output contains a file name, followed by the length of each string where: "input_fn" contains the names of one or more smil...
django_migration_linter/management/utils.py
christianbundy/django-migration-linter
357
11015813
<filename>django_migration_linter/management/utils.py def register_linting_configuration_options(parser): parser.add_argument( "--database", type=str, nargs="?", help=( "specify the database for which to generate the SQL. Defaults to default" ), ) parser....
src/python/analyzer_executor/src/analyzer_executor_lib/sqs_types.py
msilvey/grapl
313
11015820
<filename>src/python/analyzer_executor/src/analyzer_executor_lib/sqs_types.py<gh_stars>100-1000 from __future__ import annotations import json from typing import TYPE_CHECKING, Dict, List, NewType from typing_extensions import TypedDict if TYPE_CHECKING: from mypy_boto3_sqs.type_defs import MessageTypeDef clas...
robogym/envs/rearrange/tests/test_rearrange_robots.py
0xflotus/robogym
288
11015845
<reponame>0xflotus/robogym from typing import Optional import numpy as np import pytest from gym.envs.robotics import utils from robogym.envs.rearrange.simulation.blocks import ( BlockRearrangeSim, BlockRearrangeSimParameters, ) from robogym.robot.control.tcp.solver import PrincipalAxis from robogym.robot.rob...
examples/pxScene2d/external/libnode-v6.9.0/deps/v8/build/has_valgrind.py
madanagopaltcomcast/pxCore
5,964
11015854
<reponame>madanagopaltcomcast/pxCore<gh_stars>1000+ #!/usr/bin/env python # Copyright 2016 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))...
features/steps/callbacks.py
e11it/pgmigrate
551
11015874
import os from behave import given, when @given('callbacks') def step_impl(context): for row in context.table: path = os.path.join('callbacks', row['file']) context.callbacks.append(row['type'] + ':' + path) if row.get('code', False): with open(os.path.join(context.migr_dir, p...
python/IECoreMaya/NumericVectorParameterUI.py
bradleyhenke/cortex
386
11015887
########################################################################## # # Copyright (c) 2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
examples/docs_code_snippets/data_types_any.py
scroix/MUNIT-runway
109
11015905
import yaml import runway from runway.data_types import any # from your_code import model # an example of passing your own yaml configuration using an "any" data_type and PyYAML @runway.setup(options={ "configuration": any() }) def setup(opts): config = yaml.load(opts["configuration"]) print(config) # retu...
packages/pyright-internal/src/tests/samples/variadicTypeVar4.py
Jasha10/pyright
3,934
11015920
<gh_stars>1000+ # This sample tests packing and unpacking operations with # variadic type variables. # pyright: reportMissingModuleSource=false from typing import Generic, NewType, Tuple, Union from typing_extensions import TypeVarTuple, Unpack Shape = TypeVarTuple("Shape") class Array(Generic[Unpack[Shape]]): ...
termpdf.py
DPDmancul/termpdf.py
216
11015932
<filename>termpdf.py #!/usr/bin/env python3 # vim:fileencoding=utf-8 """\ Usage: termpdf.py [options] example.pdf Options: -p n, --page-number n : open to page n -f n, --first-page n : set logical page number for page 1 to n --citekey key : associate file with bibtex citekey -o, --open citekey : op...
true_coders/migrations/0041_auto_20210703_1246.py
horacexd/clist
166
11015960
<gh_stars>100-1000 # Generated by Django 3.1.12 on 2021-07-03 12:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('true_coders', '0040_auto_20210703_1208'), ] operations = [ migrations.AlterField( ...
tests/tests_geomstats/test_beta.py
qbarthelemy/geomstats
743
11015984
"""Unit tests for the beta manifold.""" import warnings from scipy.stats import beta import geomstats.backend as gs import geomstats.tests from geomstats.information_geometry.beta import BetaDistributions, BetaMetric class TestBetaDistributions(geomstats.tests.TestCase): """Class defining the beta distribution...
cook/core/misc.py
jachris/cook
130
11016001
<filename>cook/core/misc.py<gh_stars>100-1000 import glob as _glob import hashlib import os import platform import random as _random import struct import subprocess import sys import threading from . import log system = platform.system() linux = system == 'Linux' windows = system == 'Windows' mac = system == 'darwin'...
src/test/test_sun_golden_blue.py
SoftXperience/astral
152
11016017
<filename>src/test/test_sun_golden_blue.py<gh_stars>100-1000 # -*- coding: utf-8 -*- # Test data taken from http://www.timeanddate.com/sun/uk/london import datetime import freezegun import pytest import pytz from almost_equal import datetime_almost_equal from astral import sun from astral.sun import SunDirection c...
Configuration/StandardSequences/python/L1HwVal_cff.py
ckamtsikis/cmssw
852
11016031
<reponame>ckamtsikis/cmssw<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms from L1Trigger.Configuration.L1HwVal_cff import *
oauth_example/rp/modules/as_choice.mako.py
kschu91/pyoidc
373
11016040
from mako import cache from mako import filters from mako import runtime UNDEFINED = runtime.UNDEFINED STOP_RENDERING = runtime.STOP_RENDERING __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1474925155.284777 _enable_loop = True _template_filename = 'htdocs/as_choice.mako' _temp...
docs/papers/sc2013/hyantes_core.py
davidbrochart/pythran
1,647
11016044
#pythran export run(float, float, float, float, float, float, int, int, float [][]) import math from numpy import zeros def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t): pt = zeros((range_x, range_y, 3)) "omp parallel for private(i,j,k,tmp)" for i in xrange(range_x): for j in xrang...
tests/test_conv_internal.py
CalebBell/ht
118
11016046
<reponame>CalebBell/ht # -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, 2017, 2018, 2019, <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "So...
tests/test_curlies_in_attrs_2.py
gvanrossum/pyxl3
150
11016047
# coding: pyxl from pyxl import html def test(): assert str(<frag><img src="barbaz{'foo'}" /></frag>) == """<img src="barbazfoo" />"""
actions/get_cluster_configs.py
cognifloyd/stackstorm-opscenter
164
11016048
<reponame>cognifloyd/stackstorm-opscenter<gh_stars>100-1000 import requests from lib.base import OpscenterAction class GetClustersAction(OpscenterAction): def run(self): url = self._get_full_url(['cluster-configs']) return requests.get(url).json()
src/attack_flow/scripts/graphviz.py
center-for-threat-informed-defense/attack-flow
165
11016057
<gh_stars>100-1000 """ Convert ATT&CK Flow documents to GraphViz format. """ import argparse import json import attack_flow.graphviz def parse_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('attack_flow', help='The Attack Flow document to convert.') ...
xfel/amo/pnccd_ana/mpi_fxs_mask.py
dperl-sol/cctbx_project
155
11016080
<filename>xfel/amo/pnccd_ana/mpi_fxs_mask.py from __future__ import absolute_import, division, print_function from six.moves import range from psana import * import sys import numpy as np from xfel.amo.pnccd_ana import pnccd_tbx from xfel.amo.pnccd_ana import pnccd_hit from xfel.amo.pnc...
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/nnvm/python/nnvm/compiler/lr_scheduler.py
mengkai94/training_results_v0.6
1,872
11016088
# pylint: disable=too-few-public-methods, no-member """API for scheduling learning rate.""" from .. import symbol as sym class LRScheduler(object): """Base class of a learning rate scheduler. A scheduler returns a new learning rate based on the number of updates that have been performed. Parameters ...
examples/contracts/get_abi.py
adamzhang1987/py-etherscan-api
458
11016109
from etherscan.contracts import Contract import json with open('../../api_key.json', mode='r') as key_file: key = json.loads(key_file.read())['key'] address = '0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359' api = Contract(address=address, api_key=key) abi = api.get_abi() print(abi)
installation/input.py
fekblom/critic
216
11016120
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2012 <NAME>, Opera Software ASA # # 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 # # Unl...
packaging/setup/plugins/ovirt-engine-setup/vmconsole_proxy_helper/__init__.py
jihwahn1018/ovirt-engine
347
11016131
# # ovirt-engine-setup -- ovirt engine setup # # Copyright oVirt Authors # SPDX-License-Identifier: Apache-2.0 # # """ovirt-host-setup vmconsole_proxy plugin.""" from otopi import util from . import config from . import pki from . import system @util.export def createPlugins(context): config.Plugin(context=c...
tensorflow_model_optimization/python/core/common/keras/compression/algorithm.py
arovir01/model-optimization
1,318
11016134
# Copyright 2020 The TensorFlow 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/LICENSE-2.0 # # Unless required by applica...
tests/basics/memoryview_itemsize.py
iotctl/pycopy
663
11016235
try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit try: memoryview(b'a').itemsize except: print("SKIP") raise SystemExit for code in ['b', 'h', 'i', 'q', 'f', 'd']: print(memoryview(array...
qtrader/simulation/aaft.py
aaron8tang/qtrader
381
11016237
import numpy as np import pandas as pd def AAFT(df, random=np.random.uniform, random_state=None): """Amplitude Adjusted Fourier Transform Baseline Generator.""" # set random seed np.random.seed(random_state) # Operate on numpy.ndarray ts = df.values # 2d time-series format _ts = ts.reshape...
dynamic_dynamodb/test_scaling_metrics.py
Afterverse/dynamic-dynamodb
518
11016241
<filename>dynamic_dynamodb/test_scaling_metrics.py<gh_stars>100-1000 # -*- coding: utf-8 -*- """ Testing the Dynamic DynamoDB scaling methods """ import unittest from dynamic_dynamodb.core.table import scale_reader class TestScaleReader(unittest.TestCase): """ Test the scale reader method """ def __init__(s...
models/mgnet/modules/network.py
Jerrypiglet/Total3DUnderstanding
288
11016246
# Mesh Generation Net: model loader # author: ynie # date: Feb, 2020 from models.registers import METHODS, MODULES, LOSSES from models.network import BaseNetwork import torch from torch import nn @METHODS.register_module class MGNet(BaseNetwork): def __init__(self, cfg): ''' load submodules for t...
build/toolchain/wrapper_utils.py
Flameeyes/nojs
2,151
11016249
<filename>build/toolchain/wrapper_utils.py # Copyright (c) 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Helper functions for gcc_toolchain.gni wrappers.""" import gzip import os import re import subprocess impo...
crudbuilder/views.py
xlfds/django-crudbuilder
186
11016262
from django.forms.models import modelform_factory from django.views.generic import ( DetailView, CreateView, UpdateView, DeleteView, TemplateView ) from django_tables2 import SingleTableView from crudbuilder.registry import registry from crudbuilder.mixins import ( CrudBuilderMixin, BaseLis...
src/html5_parser/encoding_parser.py
ddeka2910/html5-parser
677
11016295
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, <NAME> <kovid at kovidgoyal.net> from __future__ import (absolute_import, division, print_function, unicode_literals) import string from .encoding_names import encodings space_chars = frozenset(("\t", "\n", "\u000C", " ", "\r")) s...
docs/examples/fig6p2.py
uluturki/Mathematics-of-Epidemics-on-Networks
136
11016323
import networkx as nx import EoN from collections import defaultdict import matplotlib.pyplot as plt import scipy colors = ['#5AB3E6','#FF2000','#009A80','#E69A00', '#CD9AB3', '#0073B3','#F0E442'] iterations = 5*10**5 N=6400 kave = 5 G = nx.fast_gnp_random_graph(N, kave/(N-1.)) for index, p in enumerate([0.18, 0...
src/examples/python/example_save_load_state.py
NTForked/GridFluidSim3D
761
11016365
# Copyright (c) 2016 <NAME> # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applicatio...
train_linear_evaluation.py
neuralsyn/self-supervised-relational-reasoning
130
11016398
#!/usr/bin/env python # The MIT License (MIT) # Copyright (c) 2020 <NAME> # Paper: "Self-Supervised Relational Reasoning for Representation Learning", <NAME> & <NAME>, NeurIPS 2020 # GitHub: https://github.com/mpatacchiola/self-supervised-relational-reasoning # Manage the linear evaluation phase on different datasets...
third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github.py
google-ar/chromium
777
11016431
<gh_stars>100-1000 # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import base64 import json import logging import os import sys import urllib2 from webkitpy.common.system.filesystem import FileSystem fro...
tests/network/contract/test_default_sender.py
ActorForth/brownie
1,595
11016478
import pytest from brownie.project import compile_source TEST_SOURCE = """ pragma solidity ^0.6.0; contract Foo { constructor () public {} function bar() public {} } """ @pytest.fixture def Foo(): yield compile_source(TEST_SOURCE).Foo def test_cli_no_owner(Foo, accounts, test_mode, config): confi...
pulsar-functions/instance/src/main/python/python_instance_main.py
Zod705/pulsar
778
11016508
#!/usr/bin/env python3 # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ...
src/out/ICFP18evaluation/evaluationTreeLSTM/PyTorch/metrics.py
faradaym/Lantern
158
11016515
from copy import deepcopy import torch import torch.nn as nn from torch.autograd import Variable as Var class Metrics(): def __init__(self, num_classes): self.num_classes = num_classes def pearson(self, predictions, labels): #hack cai nay cho no thanh accuracy x = deepcopy(predictions)...
tests/test_to_sqla.py
pglass/sqlitis
135
11016538
import logging import unittest from sqlitis.convert import to_sqla import ddt import sqlparse LOG = logging.getLogger(__name__) @ddt.ddt class TestToSqla(unittest.TestCase): @ddt.file_data("data.yaml") def test_to_sqla(self, sql, sqla, exception=None, *args, **kwargs): if not isinstance(sql, list):...
wavetorch/utils.py
Kshitiz-Bansal/wavetorch
470
11016541
import numpy as np import torch from sklearn.metrics import confusion_matrix def to_tensor(x, dtype=None): dtype = dtype if dtype is not None else torch.get_default_dtype() if type(x) is np.ndarray: return torch.from_numpy(x).type(dtype=dtype) else: return torch.tensor(x, dtype=dtype) def set_dtype(dtype=Non...
tests/unit/asr/deepspeech2_model_test.py
JiehangXie/PaddleSpeech
1,540
11016550
# Copyright (c) 2021 PaddlePaddle 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/LICENSE-2.0 # # Unless required by appli...
src/test/morestack_unwind.py
jalapenopuzzle/rr
5,156
11016584
<filename>src/test/morestack_unwind.py from util import * send_gdb('break main') expect_gdb('Breakpoint 1') send_gdb('c') expect_gdb('Breakpoint 1') send_gdb('break _syscall_hook_trampoline') expect_gdb('Breakpoint 2') send_gdb('c') expect_gdb('Breakpoint 2') send_gdb('fin') send_gdb('fin') send_gdb('fin') # Verify...
samples/tools/serviceutil.py
ArpitSharma2800/pyvmomi-community-samples
931
11016609
# VMware vSphere Python SDK # Copyright (c) 2008-2021 VMware, 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 # # ...
concourse/build_and_test.py
hsyuan/gporca
466
11016630
#!/usr/bin/python import optparse import os import subprocess import sys def num_cpus(): # Use multiprocessing module, available in Python 2.6+ try: import multiprocessing return multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass # Get POSIX system con...
src/azure-cli/azure/cli/command_modules/feedback/tests/latest/test_feedback.py
YuanyuanNi/azure-cli
3,287
11016644
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
test_project/select2_tagging/urls.py
epoiate/django-autocomplete-light
1,368
11016657
<reponame>epoiate/django-autocomplete-light from dal import autocomplete from django.conf.urls import url from tagging.models import Tag urlpatterns = [ url( 'test-autocomplete/$', autocomplete.Select2QuerySetView.as_view( queryset=Tag.objects.all(), ), name='select2_...
sdk/communication/azure-communication-phonenumbers/samples/release_phone_number_sample_async.py
rsdoherty/azure-sdk-for-python
2,728
11016660
<reponame>rsdoherty/azure-sdk-for-python # coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ---------------------------...
runtime/python/Lib/lib2to3/tests/data/false_encoding.py
hwaipy/InteractionFreeNode
207
11016667
<filename>runtime/python/Lib/lib2to3/tests/data/false_encoding.py #!/usr/bin/env python print '#coding=0'
securityheaders/checkers/csp/cspcheck.py
th3cyb3rc0p/securityheaders
151
11016668
class CSPCheck(object): def check(self, opt_options=dict()): pass
Training/MOOC Tensorflow 2.0/BeiDa/class3/p15_mnist_class.py
church06/Pythons
177
11016672
<gh_stars>100-1000 import tensorflow as tf from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras import Model mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 class MnistModel(Model): def __init__(self): ...
hikyuu/test/Parameter.py
scanfyu/hikyuu
1,283
11016709
#!/usr/bin/python # -*- coding: utf8 -*- # gb18030 #=============================================================================== # 作者:fasiondog # 历史:1)20130220, Added by fasiondog #=============================================================================== from test_init import * import unittest from hikyuu im...
train.py
3keepmovingforward3/suiron
800
11016723
<reponame>3keepmovingforward3/suiron import sys, os import json import numpy as np from suiron.utils.datasets import get_servo_dataset from suiron.core.SuironML import get_cnn_model # Load image settings with open('settings.json') as d: SETTINGS = json.load(d) # Our datasets print('[!] Loading dataset...') X = ...
captum/attr/_core/feature_permutation.py
i-jones/captum
3,140
11016732
#!/usr/bin/env python3 from typing import Any, Callable, Tuple, Union import torch from captum._utils.typing import TargetType, TensorOrTupleOfTensorsGeneric from captum.attr._core.feature_ablation import FeatureAblation from captum.log import log_usage from torch import Tensor def _permute_feature(x: Tensor, featur...
tests/test_pytorch_variational_dropout.py
sagnik/baseline
241
11016741
import random import pytest import numpy as np torch = pytest.importorskip("torch") from eight_mile.pytorch.layers import VariationalDropout @pytest.fixture def input_(): SEQ_LEN = random.randint(20, 101) BATCH_SIZE = random.randint(5, 21) FEAT_SIZE = random.choice([128, 256, 300]) return torch.randn...
src/python/nimbusml/internal/core/preprocessing/datasettransformer.py
michaelgsharp/NimbusML
134
11016746
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------------------------- # - Generated by tools/entrypoint_co...