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
backend/www/test/auth_test.py
xuantan/viewfinder
645
12772984
#!/usr/bin/env python # # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Account authorization tests for Facebook and Google accounts. """ __authors__ = ['<EMAIL> (<NAME>)', '<EMAIL> (<NAME>)'] import json import mock import os import time import unittest import urllib from copy import deepco...
spider/python/word.py
ferryhang/spider_job
322
12773026
import jieba #分词库 import jieba.analyse import pymongo import redis import os import re import json client = pymongo.MongoClient(host="127.0.0.1", port=27017) db = client['job'] collection = db['position'] data = collection.find({}) text = "" for item in data: text += item['body'] pwd = os.path.sp...
migration/migrator/migrations/course/20190710182514_add_view_date_for_teams.py
elihschiff/Submitty
411
12773100
"""Migration for a given Submitty course database.""" def up(config, database, semester, course): if not database.table_has_column('teams', 'last_viewed_time'): database.execute('ALTER TABLE teams ADD COLUMN last_viewed_time timestamp with time zone') def down(config, database, semester, course): pass...
util/build_benchmarks_page.py
wenq1/duktape
4,268
12773101
#!/usr/bin/env python2 import os import sys import re import json def main(): # Adapt manually. duk = '/usr/local/bin/duk' lzstring = '/home/duktape/duktape/lz-string/libs/lz-string.js' duktape_repo = '/home/duktape/duktape' duktape_testrunner_repo = '/home/duktape/duktape-testrunner' duktape...
oandapyV20-examples-master/src/streaming_trans.py
cdibble2011/OANDA
127
12773115
# -*- coding: utf-8 -*- """Simple demo of streaming transaction data.""" from oandapyV20 import API from oandapyV20.exceptions import V20Error, StreamTerminated from oandapyV20.endpoints.transactions import TransactionsStream from exampleauth import exampleAuth accountID, access_token = exampleAuth() api = API(access_...
office365/onedrive/driveitems/thumbnail.py
rikeshtailor/Office365-REST-Python-Client
544
12773144
<reponame>rikeshtailor/Office365-REST-Python-Client from office365.runtime.client_value import ClientValue class Thumbnail(ClientValue): """ The thumbnail resource type represents a thumbnail for an image, video, document, or any item that has a bitmap representation. """ pass
kivy/input/provider.py
sirpercival/kivy
317
12773195
''' Motion Event Provider ===================== Abstract class for the implemention of a :class:`~kivy.input.motionevent.MotionEvent` provider. The implementation must support the :meth:`~MotionEventProvider.start`, :meth:`~MotionEventProvider.stop` and :meth:`~MotionEventProvider.update` methods. ''' __all__ = ('Mot...
easy_maps/admin.py
cyber-barrista/django-easy-maps
114
12773205
# -*- coding: utf-8 -*- from django import forms from django.contrib import admin from django.utils.translation import gettext_lazy as _ from .models import Address from .widgets import AddressWithMapWidget class HasExceptionFilter(admin.SimpleListFilter): title = _("exception") parameter_name = "has_except...
scripts/beam_decode.py
quangvy2703/Up-Down-Captioner
232
12773210
#!/usr/bin/env python """ Decode a language model using one GPU. """ import numpy as np import argparse import sys import json import caffe from evaluate import CaptionScorer from util import restore_weights def translate(vocab, blob): caption = ""; w = 0; while True: next_word = vocab[int(blob[w]...
tests/dicts/test_benedict_casting.py
next-franciscoalgaba/python-benedict
365
12773215
# -*- coding: utf-8 -*- from benedict import benedict import unittest class benedict_casting_test_case(unittest.TestCase): def test__getitem__(self): d = { 'a': 1, 'b': { 'c': { 'd': 2, }, }, } b = b...
tests/list_view.py
Aloxaf/moshmosh
114
12773217
<gh_stars>100-1000 from moshmosh.extensions.pattern_matching.runtime import ListView v = ListView([1, 2, 3, 5], range(1, 4)) v.sort(reverse=True) assert v == [5, 3, 2] v.sort(reverse=False) assert v == [2, 3, 5] v.sort(reverse=False, key=lambda x: -x) assert v == [5, 3, 2] assert isinstance(v, list)
recipes/Python/577233_Adding_directory_pythexecutable_system_PATH/recipe-577233.py
tdiprima/code
2,023
12773248
""" a small program to run after the installation of python on windows adds the directory path to the python executable to the PATH env. variable with optional parameter remove, removes it you have to open a new command prompt to see the effects (echo %PATH%) """ import sys import os import time import _winreg...
japonicus/interface.py
mczero80/japonicus
229
12773252
<reponame>mczero80/japonicus #!/bin/python import evaluation def showTitleDisclaimer(backtestsettings, VERSION): TITLE = """ ██╗ █████╗ ██████╗ ██████╗ ███╗ ██╗██╗ ██████╗██╗ ██╗███████╗ ██║██╔══██╗██╔══██╗██╔═══██╗████╗ ██║██║██╔════╝██║ ██║██╔════╝ ██║███████║██████╔╝██║ ██║██...
experiments/segmentation/unet_mcdropout_pascal.py
ElementAI/baal
575
12773260
import argparse from copy import deepcopy from pprint import pprint import torch.backends from PIL import Image from torch import optim from torchvision.transforms import transforms from tqdm import tqdm from baal import get_heuristic, ActiveLearningLoop from baal.bayesian.dropout import MCDropoutModule from baal imp...
backend/kale/tests/unit_tests/test_kfputils.py
brness/kale
502
12773277
<reponame>brness/kale # Copyright 2020 The Kale 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
classes/logger.py
tmcdonagh/Autorippr
162
12773290
# -*- coding: utf-8 -*- """ Simple logging class Released under the MIT license Copyright (c) 2012, <NAME> @category misc @version $Id: 1.7.0, 2016-08-22 14:53:29 ACST $; @author <NAME> @license http://opensource.org/licenses/MIT """ import logging import os import sys class Logger(object): def _...
rpcpy/exceptions.py
william-wambua/rpc.py
152
12773313
<gh_stars>100-1000 class SerializerNotFound(Exception): """ Serializer not found """
src/utils/pkldf2jsonl.py
fatterbetter/CodeSearchNet
1,681
12773349
<filename>src/utils/pkldf2jsonl.py import pandas as pd from .general_utils import chunkify from dpu_utils.utils import RichPath from multiprocessing import Pool, cpu_count def df_to_jsonl(df: pd.DataFrame, RichPath_obj: RichPath, i: int, basefilename='codedata') -> str: dest_filename = f'{basefilename}_{str(i).zf...
terrascript/data/davidji99/herokux.py
mjuenema/python-terrascript
507
12773401
# terrascript/data/davidji99/herokux.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:18:42 UTC) import terrascript class herokux_addons(terrascript.Data): pass class herokux_kafka_mtls_iprules(terrascript.Data): pass class herokux_postgres_mtls_certificate(terrascript.Data): pass c...
artemis/utils/basic.py
StanfordGeometryLab/artemis
254
12773408
""" Various simple (basic) functions in the "utilities". The MIT License (MIT) Originally created at 8/31/20, for Python 3.x Copyright (c) 2021 <NAME> (<EMAIL>) & Stanford Geometric Computing Lab """ import torch import multiprocessing as mp import dask.dataframe as dd from torch import nn from sklearn.model_selectio...
src/sage/groups/libgap_group.py
fchapoton/sage
1,742
12773422
<gh_stars>1000+ """ Generic LibGAP-based Group This is useful if you need to use a GAP group implementation in Sage that does not have a dedicated Sage interface. If you want to implement your own group class, you should not derive from this but directly from :class:`~sage.groups.libgap_wrapper.ParentLibGAP`. EXAMPL...
djangoerp/core/signals.py
xarala221/django-erp
345
12773426
#!/usr/bin/env python """This file is part of the django ERP project. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLD...
tests/unit/test_dist.py
olegklimov/DeepSpeed
6,728
12773461
import torch import torch.distributed as dist from common import distributed_test import pytest @distributed_test(world_size=3) def test_init(): assert dist.is_initialized() assert dist.get_world_size() == 3 assert dist.get_rank() < 3 # Demonstration of pytest's parameterization @pytest.mark.parametri...
tests/unit/test_app.py
davidjsherman/repo2docker
1,047
12773472
import errno import pytest from tempfile import TemporaryDirectory from unittest.mock import patch import docker import escapism from repo2docker.app import Repo2Docker from repo2docker.__main__ import make_r2d from repo2docker.utils import chdir def test_find_image(): images = [{"RepoTags": ["some-org/some-rep...
marketplaces/apps/market_community/urls.py
diassor/CollectorCity-Market-Place
135
12773488
<gh_stars>100-1000 from django.conf.urls.defaults import * urlpatterns = patterns('', url('^$', 'market_community.views.overview', name='market_community'), url(r'^overview/$', 'market_community.views.overview', name='community_overview'), url(r'^forums/$', 'market_community.views.forums', name='community...
mods/Commands.py
waffle620/fagyhal
494
12773532
import asyncio import discord import sys from discord.ext import commands from utils import checks from mods.cog import Cog class Commands(Cog): def __init__(self, bot): super().__init__(bot) self.cursor = bot.mysql.cursor self.escape = bot.escape @commands.group(pass_context=True, aliases=['setprefix', 'chan...
capstone/capdb/migrations/0114_auto_20210420_2105.py
rachelaus/capstone
134
12773553
<filename>capstone/capdb/migrations/0114_auto_20210420_2105.py<gh_stars>100-1000 # Generated by Django 3.2 on 2021-04-20 21:05 import capdb.storages from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('capdb', '0113_auto_20210414_1532'), ] operation...
test/components/stream_test.py
sytelus/longview
3,453
12773572
from tensorwatch.stream import Stream s1 = Stream(stream_name='s1', console_debug=True) s2 = Stream(stream_name='s2', console_debug=True) s3 = Stream(stream_name='s3', console_debug=True) s1.subscribe(s2) s2.subscribe(s3) s3.write('S3 wrote this') s2.write('S2 wrote this') s1.write('S1 wrote this')
report_builder_demo/demo_second_app/admin.py
nazmizorlu/django-report-builder
560
12773634
from django.contrib import admin from .models import Bar @admin.register(Bar) class BarAdmin(admin.ModelAdmin): pass
alephnull/live/broker.py
flatM/AlephNull
234
12773639
__author__ = 'oglebrandon' from logbook import Logger from ib.ext.Contract import Contract from ib.ext.ExecutionFilter import ExecutionFilter from ib.ext.Order import Order as IBOrder from alephnull.finance.blotter import Blotter from alephnull.utils.protocol_utils import Enum from alephnull.finance.slippage import T...
omnidet/train_semantic.py
AtlasGooo2/WoodScape
348
12773651
<filename>omnidet/train_semantic.py """ Semantic segmentation training for OmniDet. # author: <NAME> <<EMAIL>> This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; Authors provide no warranty with the software and are not liable for anything. """ import time import numpy as np i...
marlo/crowdai_helpers.py
spMohanty/marlo
214
12773693
#!/usr/bin/env python import os import crowdai_api ######################################################################## # Instatiate Event Notifier ######################################################################## crowdai_events = crowdai_api.events.CrowdAIEvents() class CrowdAIMarloEvents: REQUEST_ENV...
tfHub_sentence_similarity/tfHub_sentence_similarity.py
jae-yong-2/awesomeScripts
245
12773723
import re import string import tensorflow_hub as hub from scipy.spatial.distance import cdist module_url = "https://tfhub.dev/google/universal-sentence-encoder/4" class SimilarityModel(): def __init__(self): print("Loading model from tf hub...") self.model = hub.load(module_url) print("mo...
examples/pytorch/dimenet/modules/embedding_block.py
ketyi/dgl
9,516
12773725
import numpy as np import torch import torch.nn as nn from modules.envelope import Envelope from modules.initializers import GlorotOrthogonal class EmbeddingBlock(nn.Module): def __init__(self, emb_size, num_radial, bessel_funcs, cutoff, ...
malspider_django/dashboard/management/commands/del_alerts.py
andrewhenke/malspider
453
12773741
# # Copyright (c) 2016-present, Cisco Systems, Inc. All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # from django.core.management.base import BaseCommand, CommandError from dashboard.models import Alert from...
alipay/aop/api/response/AlipayMarketingRecruitPlanQueryResponse.py
antopen/alipay-sdk-python-all
213
12773752
<reponame>antopen/alipay-sdk-python-all<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.RecruitEnrollRule import RecruitEnrollRule class AlipayMarketingRecruitPlanQueryResponse(AlipayResponse): ...
examples/colors.py
edouard-lopez/colorful
517
12773862
# -*- coding: utf-8 -*- """ colorful ~~~~~~~~ Terminal string styling done right, in Python. :copyright: (c) 2017 by <NAME> <<EMAIL>> :license: MIT, see LICENSE for more details. """ import sys import colorful def show(): """ Show the modifiers and colors """ # modifiers s...
tests/python/test_jit_transform.py
ishine/aps
117
12773903
<gh_stars>100-1000 #!/usr/bin/env python # Copyright 2021 <NAME> # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import pytest import torch as th from aps.io import read_audio from aps.transform.utils import forward_stft, export_jit from aps.transform import AsrTransform egs1_wav = read_audio("tes...
src/transformers/models/roformer/tokenization_utils.py
liminghao1630/transformers
50,404
12773926
<filename>src/transformers/models/roformer/tokenization_utils.py # coding=utf-8 # Copyright 2021 The HuggingFace Inc. team. 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 a...
zfs/posix/__init__.py
mcclung/zfsp
600
12773930
<gh_stars>100-1000 import logging from .. import ondisk from .. import datasets from zfs.posix.attributes import POSIXAttrs_for logger = logging.getLogger(__name__) class PosixObject(object): def __init__(self, dnode: ondisk.DNode, dataset: datasets.Dataset) -> None: self.attrs = POSIXAttrs_for(dataset)...
ml_collections/config_dict/tests/field_reference_test.py
wyddmw/ViT-pytorch-1
311
12773966
# Copyright 2021 The ML Collections 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
OpenGL/lazywrapper.py
t20100/pyopengl
210
12773977
"""Simplistic wrapper decorator for Python-coded wrappers""" from OpenGL.latebind import Curry from OpenGL import MODULE_ANNOTATIONS class _LazyWrapper( Curry ): """Marker to tell us that an object is a lazy wrapper""" def lazy( baseFunction ): """Produce a lazy-binding decorator that uses baseFunction A...
Tests/EndToEndTests/CNTKv2Python/Examples/ConvNet_CIFAR10_DataAug_test.py
shyamalschandra/CNTK
17,702
12773997
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import numpy as np import os import sys from cntk.ops.tests.ops_test_utils import ...
config/common/all_params.py
leozz37/makani
1,178
12774012
# Copyright 2020 Makani Technologies LLC # # 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...
train/new_train.py
zeroAska/TFSegmentation
633
12774016
<filename>train/new_train.py """ New trainer faster than ever """ from metrics.metrics import Metrics from utils.reporter import Reporter from utils.misc import timeit from tqdm import tqdm import numpy as np import tensorflow as tf import matplotlib import time matplotlib.use('Agg') import matplotlib.pyplot as plt ...
algnuth/polynom.py
louisabraham/algnuth
290
12774025
""" Modular arithmetic """ from collections import defaultdict import numpy as np class ModInt: """ Integers of Z/pZ """ def __init__(self, a, n): self.v = a % n self.n = n def __eq__(a, b): if isinstance(b, ModInt): return not bool(a - b) else: ...
official/projects/edgetpu/vision/configs/mobilenet_edgetpu_config.py
62theories/tf-flask
82,518
12774029
# Copyright 2021 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...
jug/tests/jugfiles/custom_hash_function.py
dombrno/jug
309
12774039
<gh_stars>100-1000 from jug import TaskGenerator from jug.utils import CustomHash hash_called = 0 def bad_hash(x): global hash_called hash_called += 1 return ('%s' % x).encode('utf-8') @TaskGenerator def double(x): return 2*x one = CustomHash(1, bad_hash) two = double(one)
refinery/bnpy/bnpy-dev/bnpy/init/__init__.py
csa0001/Refinery
103
12774062
""" The :mod:`init` module gathers initialization procedures for model parameters """ import FromScratchGauss, FromScratchMult import FromScratchBernRel import FromSaved, FromTruth __all__ = ['FromScratchGauss', 'FromSaved', 'FromTruth', 'FromScratchMult', 'FromScratchBernRel']
Codes/Python32/Lib/test/test_timeout.py
eyantra/FireBird_Swiss_Knife
319
12774083
"""Unit tests for socket timeout feature.""" import unittest from test import support # This requires the 'network' resource as given on the regrtest command line. skip_expected = not support.is_resource_enabled('network') import time import errno import socket class CreationTestCase(unittest.TestCase): """Tes...
cx_Freeze/samples/advanced/advanced_1.py
lexa/cx_Freeze
358
12774086
<filename>cx_Freeze/samples/advanced/advanced_1.py #!/usr/bin/env python print("Hello from cx_Freeze Advanced #1\n") module = __import__("testfreeze_1")
cea/plots/colors.py
architecture-building-systems/cea-toolbox
121
12774087
""" This is the official list of CEA colors to use in plots """ import os import pandas as pd import yaml import warnings import functools from typing import List, Callable __author__ = "<NAME>" __copyright__ = "Copyright 2020, Architecture and Building Systems - ETH Zurich" __credits__ = ["<NAME>"] __license__ =...
ioflo/aid/aggregating.py
BradyHammond/ioflo
128
12774089
import math import statistics def fuzzyAnd(m): """ fuzzy anding m = list of membership values to be anded returns smallest value in the list """ return min(m) FuzzyAnd = fuzzyAnd def fuzzyOr(m): """ fuzzy oring m = list of membership values to be ored returns largest value...
segmentation/datasets.py
dataflowr/evaluating_bdl
110
12774106
# code-checked # server-checked import cv2 import numpy as np import os import os.path as osp import random import torch from torch.utils import data import pickle def generate_scale_label(image, label): f_scale = 0.5 + random.randint(0, 16)/10.0 image = cv2.resize(image, None, fx=f_scale, fy=f_scale, interp...
ISMLnextGen/retryTest.py
Ravenclaw-OIer/ISML_auto_voter
128
12774128
<reponame>Ravenclaw-OIer/ISML_auto_voter<filename>ISMLnextGen/retryTest.py #coding:utf-8 import logging,traceback from functools import wraps log = logging.getLogger(__name__) acceptStatus=(503,'其他接受的状态码') class RetryExhaustedError(Exception): pass #def __init__(self, funcname,args,kwargs): ...
python/src/main/python/drivers/run-browser-android.py
KishkinJ10/graphicsfuzz
519
12774133
<reponame>KishkinJ10/graphicsfuzz<filename>python/src/main/python/drivers/run-browser-android.py #!/usr/bin/env python3 # Copyright 2018 The GraphicsFuzz Project 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 obta...
src/lib/Encryption.py
gamesguru/vault
147
12774140
import base64 import string from random import randint, choice from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto import Random as CryptoRandom class Encryption(): def __init__(self, key): self.key = key # Key in bytes self.salted_key = None # Placeholder for optional sal...
deepconcolic/training.py
nberth/DeepConcolic
102
12774155
from __future__ import absolute_import, division, print_function, unicode_literals # NB: see head of `datasets.py' from training_utils import * from utils_io import os, tempdir from datasets import image_kinds print ("Using TensorFlow version:", tf.__version__) def train_n_save_classifier (model, class_names, input_k...
src/main/python/aut/udfs.py
ruebot/aut
113
12774161
<reponame>ruebot/aut<filename>src/main/python/aut/udfs.py from pyspark import SparkContext from pyspark.sql.column import Column, _to_java_column, _to_seq from pyspark.sql.functions import col def compute_image_size(col): sc = SparkContext.getOrCreate() udf = ( sc.getOrCreate()._jvm.io.archivesunleash...
python_raster_functions/ObjectDetector.py
ArcGIS/raster-deep-learning
154
12774167
<reponame>ArcGIS/raster-deep-learning<gh_stars>100-1000 ''' Copyright 2018 Esri 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 a...
test/praatio_test_case.py
timmahrt/praatIO
208
12774177
<filename>test/praatio_test_case.py import unittest import os class PraatioTestCase(unittest.TestCase): def __init__(self, *args, **kargs): super(PraatioTestCase, self).__init__(*args, **kargs) root = os.path.dirname(os.path.realpath(__file__)) self.dataRoot = os.path.join(root, "files") ...
waliki/git/urls.py
luzik/waliki
324
12774189
<filename>waliki/git/urls.py import django try: from django.conf.urls import patterns, url # django 1.8, 1.9 except ImportError: from django.conf.urls import url from waliki.settings import WALIKI_SLUG_PATTERN from waliki.git.views import whatchanged, WhatchangedFeed, webhook_pull, history, version, diff _p...
geocoder/here_reverse.py
termim/geocoder
1,506
12774226
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import from geocoder.location import Location from geocoder.here import HereResult, HereQuery class HereReverseResult(HereResult): @property def ok(self): return bool(self.address) class HereReverse(HereQuery): """ HERE Geoc...
Chapter04/4_1_download_data.py
shamir456/Python-Network-Programming-Cookbook-Second-Edition
125
12774228
#!/usr/bin/env python # Python Network Programming Cookbook -- Chapter - 4 # This program requires Python 3.5.2 or any later version # It may run on any other version with/without modifications. # # Follow the comments inline to make it run on Python 2.7.x. import argparse import urllib.request # Comment out the abov...
client/verta/verta/_cli/deployment/predict.py
stefan-petrov-toptal/modeldb
835
12774233
<gh_stars>100-1000 # -*- coding: utf-8 -*- import click import json from .deployment import deployment from ... import Client @deployment.group() def predict(): """Making prediction to a deployment-related entity. For example, to make a prediction to an endpoint, run `verta deployment predict endpoint...
changes/verification.py
michaeljoseph/changes
135
12774242
import logging from plumbum import CommandNotFound, local from changes import shell log = logging.getLogger(__name__) def get_test_runner(): test_runners = ['tox', 'nosetests', 'py.test'] test_runner = None for runner in test_runners: try: test_runner = local[runner] except ...
enn/losses/prior_losses.py
MaxGhenis/enn
130
12774263
# python3 # pylint: disable=g-bad-file-header # Copyright 2021 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 # # http://www.apache.org...
nameko/dependency_providers.py
vlcinsky/nameko
3,425
12774273
""" Nameko built-in dependencies. """ from nameko.extensions import DependencyProvider class Config(DependencyProvider): """ Dependency provider for accessing configuration values. """ def get_dependency(self, worker_ctx): return self.container.config.copy()
django/contrib/formtools/wizard/storage/exceptions.py
pomarec/django
285
12774282
<reponame>pomarec/django from django.core.exceptions import ImproperlyConfigured class MissingStorage(ImproperlyConfigured): pass class NoFileStorageConfigured(ImproperlyConfigured): pass
setup.py
truthiswill/wait4disney
106
12774306
from setuptools import setup, find_packages setup( name = "disney", version = "1.0", description = "A history of Shanghai Disney waiting time", long_description = "A history of Shanghai Disney waiting time", license = "Apache License", url = "http://s.gaott.info", author = "gtt116", au...
quarkchain/experimental/random_sampling_simulator.py
QuarkChain/pyquarkchain
237
12774326
<filename>quarkchain/experimental/random_sampling_simulator.py import random committee_size = 150 shard_size = 1024 pool_size = 150 * 1024 # Percentage of attackers in pool attacker_p = 0.15 attacker_n = int(attacker_p * pool_size) # Attack threshold (a committee with t percent of attackers) attacker_tn = int(commit...
tests/test_unpipe.py
python-pipe/hellp
123
12774349
from sspipe import p, px, unpipe def test_unpipe_active(): a_pipe = px + 1 | px * 5 func = unpipe(a_pipe) assert func(0) == 5 def test_unpipe_passive(): func = lambda x: (x + 1) * 5 func = unpipe(func) assert func(0) == 5
test/test_bridge.py
jasonpjacobs/systemrdl-compiler
141
12774358
from unittest_utils import RDLSourceTestCase class TestBridge(RDLSourceTestCase): def test_bridge(self): top = self.compile( ["rdl_src/bridge.rdl"], "some_bridge" ) self.assertEqual( top.find_by_path("some_bridge.ahb.ahb_credits").absolute_address, ...
PYTHON/Fibanacci_numbers_by_replacing_prime_numbers_and_multiples_of_5_by_0.py
ayushyado/HACKTOBERFEST2021-2
125
12774359
<gh_stars>100-1000 def is_prime(n): if n > 1: for i in range(2, n // 2 + 1): if (n % i) == 0: return False else: return True else: return False def fibonacci(n): n1, n2 = 1, 1 count = 0 if n == 1: print(n1) else: ...
cross3d/motionbuilder/motionbuilderscene.py
vedantirb/cross3d
129
12774362
## # \namespace cross3d.softimage.motionbuilderscene # # \remarks The MotionBuilderScene class will define all the operations for Motion Builder scene interaction. # # \author douglas # \author Blur Studio # \date 06/21/12 # import pyfbsdk as mob from cross3d.abstract.abstractscene import AbstractScene from PyQt...
craftassist/agent/voxel_models/detection-transformer/datasets/voc2012.py
kandluis/droidlet
669
12774370
""" Copyright (c) Facebook, Inc. and its affiliates. """ from .voc import VOCDetection from typing import Iterable import to_coco_api VOC_PATH = "/datasets01/VOC/060817/" class VOCDetection2012(VOCDetection): def __init__(self, image_set: str = "train", transforms: Iterable = None): super(VOCDetection, ...
src/encoded/tests/test_upgrade_organism.py
procha2/encoded
102
12774381
<filename>src/encoded/tests/test_upgrade_organism.py import pytest def test_organism_upgrade(upgrader, organism_1_0): value = upgrader.upgrade('organism', organism_1_0, target_version='2') assert value['schema_version'] == '2' assert value['status'] == 'current' def test_organism_upgrade_4_5(upgrader, o...
scripts/caffe/convert_caffe_weights_to_npy.py
nnmhuy/flownet2-tf
438
12774382
<reponame>nnmhuy/flownet2-tf<gh_stars>100-1000 """ Please read README.md for usage instructions. Extracts Caffe parameters from a given caffemodel/prototxt to a dictionary of numpy arrays, ready for conversion to TensorFlow variables. Writes the dictionary to a .npy file. """ import argparse import caffe import numpy ...
python/app/plugins/http/Tomcat/ajpy.py
taomujian/linbing
351
12774385
<gh_stars>100-1000 #!/usr/bin/env python import socket import struct def pack_string(s): if s is None: return struct.pack(">h", -1) l = len(s) return struct.pack(">H%dsb" % l, l, s.encode('utf8'), 0) def unpack(stream, fmt): size = struct.calcsize(fmt) buf = stream.read(size) return struct.unpack(fmt, buf) de...
scripts/soccer.py
jkurdys/ThinkBayes2
1,337
12774457
<gh_stars>1000+ """This file contains code for use with "Think Bayes", by <NAME>, available from greenteapress.com Copyright 2014 <NAME> License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from __future__ import print_function, division import numpy import thinkbayes2 import thinkplot class Soccer(thinkbay...
alembic/versions/2019102221_add_shared_file_system_column__75d4288ae265.py
kl-chou/codalab-worksheets
236
12774462
<filename>alembic/versions/2019102221_add_shared_file_system_column__75d4288ae265.py """Add shared-file-system column to workers Revision ID: 75d4288ae265 Revises: <PASSWORD> Create Date: 2019-10-22 21:05:26.580918 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision ...
swarmlib/abc/bees/onlooker_bee.py
alxfmpl/swarmlib
221
12774504
<filename>swarmlib/abc/bees/onlooker_bee.py # ------------------------------------------------------------------------------------------------------ # Copyright (c) <NAME>. All rights reserved. # Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information. # ------------------...
models/InitialBlock.py
JJavierga/ENet-Real-Time-Semantic-Segmentation
268
12774526
################################################### # Copyright (c) 2019 # # Authors: @iArunava <<EMAIL>> # # @AvivSham <<EMAIL>> # # # # License: BSD License 3.0 # # ...
ui/pypesvds/controllers/index.py
onfire73/pypeskg
117
12774550
import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort # added for auth from authkit.authorize.pylons_adaptors import authorize from authkit.permissions import RemoteUser, ValidAuthKitUser, UserIn from pypesvds.lib.base import BaseController, render ...
applications/CoSimulationApplication/mpi_extension/MPIExtension.py
clazaro/Kratos
778
12774561
import KratosMultiphysics.mpi # importing the MPI-Core, since the MPIExtension directly links to it from KratosCoSimulationMPIExtension import *
apps/Tests/algs/TestAlg.py
erinzm/NEXT-chemistry
155
12774621
<filename>apps/Tests/algs/TestAlg.py from apps.Tests.tests.test_api import set_and_get_alg, get_alg, get_exp class MyAlg: def initExp(self, butler, dummy): get_exp(butler) set_and_get_alg(butler) return "return_init_exp" def getQuery(self, butler): get_alg(butler) retu...
h2o-py/tests/testdir_apis/Data_Manipulation/pyunit_h2oH2OFrame_countmatches.py
vishalbelsare/h2o-3
6,098
12774631
<reponame>vishalbelsare/h2o-3<gh_stars>1000+ from __future__ import print_function import sys sys.path.insert(1,"../../../") from tests import pyunit_utils import h2o from h2o.utils.typechecks import assert_is_type from h2o.frame import H2OFrame def h2o_H2OFrame_countmatches(): """ Python API test: h2o.frame....
plenum/test/run_continuously.py
andkononykhin/plenum
148
12774637
import traceback import pytest from plenum.test.testing_utils import setupTestLogging setupTestLogging() def run(test, stopOnFail=True, maxTimes=None): count = 0 passes = 0 fails = 0 while maxTimes is None or count < maxTimes: exitcode = pytest.main(test) count += 1 if exitc...
pandoc-starter/MarkTex/marktex/rawrender/toRaw.py
riciche/SimpleCVReproduction
923
12774652
<gh_stars>100-1000 import os from marktex.markast.utils import ImageTool,CleanTool from marktex.markast.parser import Scanner from marktex import config from marktex.markast.document import Document from marktex.markast.environment import * from marktex.markast.line import * from marktex.markast.token import * from ma...
host-software/led/led_vm.py
dpejcha/keyplus
226
12774679
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2018 <EMAIL> # Licensed under the MIT license (http://opensource.org/licenses/MIT) from sexpr import sexp import pprint import copy import hexdump DEBUG = 0 def u8(x): return x & 0xff def i16(x): return x & 0xffff class LEDVMError(Exception): ...
model_compiler/src/model_compiler/tensorflow_util.py
yuanliya/Adlik
548
12774690
# Copyright 2019 ZTE corporation. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from typing import Any, Mapping, NamedTuple, Optional, Sequence from itertools import zip_longest from . import utilities from .models.data_format import DataFormat def get_tensor_by_fuzzy_name(graph, name): if ':' in n...
autoit_ripper/utils.py
nazywam/AutoIt-Ripper
112
12774697
from datetime import datetime, timezone from itertools import cycle from .lame import LAME from .mt import MT def filetime_to_dt(timestamp: int) -> datetime: return datetime.fromtimestamp(timestamp // 100000000, timezone.utc) def bytes_to_bitstring(data: bytes) -> str: return "".join(bin(x)[2:].zfill(8) fo...
ontobio/bin/timeit.py
alliance-genome/ontobio
101
12774744
#!/usr/bin/env python3 from ontobio.sparql2ontology import * from networkx.algorithms.dag import ancestors import time def r(): t1 = time.process_time() get_edges('pato') t2 = time.process_time() print(t2-t1) r() r() r() """ LRU is much faster, but does not persist. However, should be fast enough ...
tests/test_data/test_datasets/__init__.py
rlleshi/mmaction2
1,870
12774772
<filename>tests/test_data/test_datasets/__init__.py # Copyright (c) OpenMMLab. All rights reserved. from .base import BaseTestDataset __all__ = ['BaseTestDataset']
fluent.pygments/fluent/pygments/cli.py
shlomyb-di/python-fluent
155
12774778
import argparse import sys from pygments import highlight from pygments.formatters import Terminal256Formatter from fluent.pygments.lexer import FluentLexer def main(): parser = argparse.ArgumentParser() parser.add_argument('path') args = parser.parse_args() with open(args.path) as fh: code =...
pycozmo/tests/test_image_encoder.py
gimait/pycozmo
123
12774792
import unittest from pycozmo.image_encoder import ImageEncoder, str_to_image, ImageDecoder, image_to_str from pycozmo.util import hex_dump, hex_load from pycozmo.tests.image_encoder_fixtures import FIXTURES class TestImageEncoder(unittest.TestCase): @staticmethod def _encode(sim: str) -> str: im = ...
tridet/utils/train.py
flipson/dd3d
227
12774798
<gh_stars>100-1000 # Copyright 2021 Toyota Research Institute. All rights reserved. import logging import os from tabulate import tabulate from termcolor import colored from detectron2.utils.events import get_event_storage LOG = logging.getLogger(__name__) def get_inference_output_dir(dataset_name, is_last=False,...
recipes/Python/577611_edit_dictionary_values_possibly_restrained/recipe-577611.py
tdiprima/code
2,023
12774821
<filename>recipes/Python/577611_edit_dictionary_values_possibly_restrained/recipe-577611.py """ DICTIONNARY INTERFACE FOR EDITING VALUES creates labels/edits/menubutton widgets in a TkFrame to edit dictionary values use: apply(frame,dict,position) """ import Tkinter as tk def cbMenu(controlV,value,btn= None): con...
keanu-python/tests/test_cast.py
rs992214/keanu
153
12774830
<gh_stars>100-1000 from keanu.vertex.vertex_casting import (cast_tensor_arg_to_double, cast_tensor_arg_to_integer, cast_tensor_arg_to_boolean) from keanu.vertex import cast_to_boolean_vertex, cast_to_integer_vertex, cast_to_double_vertex from keanu.vartypes import (primitive_typ...
chap8/data/gen_mxnet_imglist.py
wang420349864/dlcv_for_beginners
1,424
12774831
import os import sys input_path = sys.argv[1].rstrip(os.sep) output_path = sys.argv[2] filenames = os.listdir(input_path) with open(output_path, 'w') as f: for i, filename in enumerate(filenames): filepath = os.sep.join([input_path, filename]) label = filename[:filename.rfind('.')].split('_')[1] ...