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 |
|---|---|---|---|---|
test/IECore/BasicPreset.py | ericmehl/cortex | 386 | 27 | ##########################################################################
#
# Copyright (c) 2010-2012, 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:
#
# * Redis... |
src/biotite/copyable.py | danijoo/biotite | 208 | 56 | <filename>src/biotite/copyable.py
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite"
__author__ = "<NAME>"
__all__ = ["Copyable"]
import abc
class Copyable(metaclass=abc.ABCMeta):
"""
... |
tests/keras/layers/wrappers_test.py | kalyc/keras-apache-mxnet | 300 | 59 | <filename>tests/keras/layers/wrappers_test.py<gh_stars>100-1000
import pytest
import numpy as np
import copy
from numpy.testing import assert_allclose
from keras.utils import CustomObjectScope
from keras.layers import wrappers, Input, Layer
from keras.layers import RNN
from keras import layers
from keras.models import ... |
src/tornado-3.2.2/tornado/platform/common.py | code-annotator/tornado-annotated | 645 | 60 | <gh_stars>100-1000
"""Lowest-common-denominator implementations of platform functionality."""
from __future__ import absolute_import, division, print_function, with_statement
import errno
import socket
from tornado.platform import interface
class Waker(interface.Waker):
"""Create an OS independent asynchronous ... |
docs/source/auto_examples/plot_usage.py | ruhugu/brokenaxes | 362 | 81 | """
Basic usage
===========
This example presents the basic usage of brokenaxes
"""
import matplotlib.pyplot as plt
from brokenaxes import brokenaxes
import numpy as np
fig = plt.figure(figsize=(5,2))
bax = brokenaxes(xlims=((0, .1), (.4, .7)), ylims=((-1, .7), (.79, 1)), hspace=.05)
x = np.linspace(0, 1, 100)
bax... |
clpy/sparse/util.py | fixstars/clpy | 142 | 116 | <filename>clpy/sparse/util.py
import clpy
import clpy.sparse.base
_preamble_atomic_add = '''
#if __CUDA_ARCH__ < 600
__device__ double atomicAdd(double* address, double val) {
unsigned long long* address_as_ull =
(unsigned long long*)address;
unsigned long long old = ... |
test/test_cartesian.py | hwazni/discopy | 205 | 117 | from pytest import raises
from discopy.cartesian import *
def test_Box_repr():
f = Box('f', 1, 2, lambda x: (x, x))
assert "Box('f', 1, 2" in repr(f)
def test_Function_str():
f = Function(2, 1, lambda x, y: x + y)
assert 'Function(dom=2, cod=1,' in str(f)
def test_Function_call():
f = Swap(2, ... |
bsp/nrf5x/tools/sdk_dist.py | BreederBai/rt-thread | 7,482 | 136 | import os
import sys
import shutil
cwd_path = os.getcwd()
sys.path.append(os.path.join(os.path.dirname(cwd_path), 'rt-thread', 'tools'))
# BSP dist function
def dist_do_building(BSP_ROOT, dist_dir):
from mkdist import bsp_copy_files
import rtconfig
library_dir = os.path.join(dist_dir, 'libraries')
p... |
splash/render_options.py | tashidexiaoL/splashnew | 3,612 | 178 | <reponame>tashidexiaoL/splashnew
# -*- coding: utf-8 -*-
import os
import json
from splash import defaults
from splash.utils import to_bytes, path_join_secure
from splash.errors import BadOption
class RenderOptions(object):
"""
Options that control how to render a response.
"""
_REQUIRED = object()
... |
glue/__init__.py | HPLegion/glue | 550 | 186 | <reponame>HPLegion/glue<filename>glue/__init__.py
# Set up configuration variables
__all__ = ['custom_viewer', 'qglue', 'test']
import os
import sys
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('glue-core').version
except DistributionNotFound:
__versi... |
djangox/lib/python3.8/site-packages/allauth/socialaccount/providers/dropbox/views.py | DemarcusL/django_wiki_lab | 6,342 | 201 | import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import DropboxOAuth2Provider
class DropboxOAuth2Adapter(OAuth2Adapter):
provider_id = DropboxOAuth2Provider.id
access_token_url = "https://api.dropbox.c... |
src/ros_comm/rosmsg/setup.py | jungleni/ros_code_reading | 742 | 212 | <reponame>jungleni/ros_code_reading
#!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['rosmsg'],
package_dir={'': 'src'},
scripts=['scripts/rosmsg', 'scripts/rosmsg-proto', 'scripts/rossrv'],
requ... |
pixloc/visualization/viz_3d.py | jmorlana/pixloc | 457 | 227 | <filename>pixloc/visualization/viz_3d.py
"""
3D visualization primitives based on Plotly.
We might want to instead use a more powerful library like Open3D.
Plotly however supports animations, buttons and sliders.
1) Initialize a figure with `fig = init_figure()`
2) Plot points, cameras, lines, or create a slider anima... |
tests/test_subpixel_upsample.py | Project-MONAI/MONAI | 2,971 | 244 | # Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
nemo/collections/asr/parts/numba/rnnt_loss/rnnt_numpy.py | madhukarkm/NeMo | 4,145 | 257 | # Copyright (c) 2021, NVIDIA CORPORATION. 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... |
gfirefly/dbentrust/dbutils.py | handsome3163/H2Dgame-Firefly | 675 | 270 | <reponame>handsome3163/H2Dgame-Firefly<gh_stars>100-1000
#coding:utf8
'''
Created on 2013-8-21
@author: lan (www.9miao.com)
'''
import itertools
import datetime
def safeunicode(obj, encoding='utf-8'):
r"""
Converts any given object to unicode string.
>>> safeunicode('hello')
u'hello'
... |
Arrays/LeftRotation.py | anand722000/algo_ds_101 | 175 | 286 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the rotLeft function below.
def rotLeft(a, d):
alist = list(a)
b = alist[d:]+alist[:d]
return b
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nd = input().split()
n... |
nearpy/examples/example2.py | samyoo78/NearPy | 624 | 289 | # -*- coding: utf-8 -*-
# Copyright (c) 2013 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merg... |
src/mem/slicc/ast/TypeDeclAST.py | qianlong4526888/haha | 135 | 299 | # Copyright (c) 1999-2008 <NAME> and <NAME>
# Copyright (c) 2009 The Hewlett-Packard Development Company
# All rights reserved.
#
# 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 retai... |
src/biotite/file.py | danijoo/biotite | 208 | 308 | <reponame>danijoo/biotite
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite"
__author__ = "<NAME>"
__all__ = ["File", "TextFile", "InvalidFileError"]
import abc
import io
import warnings
from .... |
electrum/dnssec.py | Jesusown/electrum | 5,905 | 321 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 <NAME>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitati... |
TopQuarkAnalysis/TopJetCombination/python/TtSemiLepJetCombMaxSumPtWMass_cfi.py | ckamtsikis/cmssw | 852 | 340 | import FWCore.ParameterSet.Config as cms
#
# module to make the MaxSumPtWMass jet combination
#
findTtSemiLepJetCombMaxSumPtWMass = cms.EDProducer("TtSemiLepJetCombMaxSumPtWMass",
## jet input
jets = cms.InputTag("selectedPatJets"),
## lepton input
leps = cms.InputTag("selectedPatMuons"),
## ma... |
libsaas/services/twilio/applications.py | MidtownFellowship/libsaas | 155 | 344 | <gh_stars>100-1000
from libsaas import http, parsers
from libsaas.services import base
from libsaas.services.twilio import resource
class ApplicationsBase(resource.TwilioResource):
path = 'Applications'
class Application(ApplicationsBase):
def create(self, *args, **kwargs):
raise base.MethodNotSu... |
tests/ast/nodes/test_from_node.py | upgradvisor/vyper | 1,471 | 351 | from vyper import ast as vy_ast
def test_output_class():
old_node = vy_ast.parse_to_ast("foo = 42")
new_node = vy_ast.Int.from_node(old_node, value=666)
assert isinstance(new_node, vy_ast.Int)
def test_source():
old_node = vy_ast.parse_to_ast("foo = 42")
new_node = vy_ast.Int.from_node(old_node... |
Python/Examples/Macros/SettingsAxesOptimization.py | archformco/RoboDK-API | 161 | 425 | # This example shows how to read or modify the Axes Optimization settings using the RoboDK API and a JSON string.
# You can select "Axes optimization" in a robot machining menu or the robot parameters to view the axes optimization settings.
# It is possible to update the axes optimization settings attached to a robot o... |
tests/test.py | kjanik70/tflearn | 10,882 | 433 | '''
This file contains test cases for tflearn
'''
import tensorflow.compat.v1 as tf
import tflearn
import unittest
class TestActivations(unittest.TestCase):
'''
This class contains test cases for the functions in tflearn/activations.py
'''
PLACES = 4 # Number of places to match when testing fl... |
venv/Lib/site-packages/patsy/test_regressions.py | EkremBayar/bayar | 710 | 443 | # This file is part of Patsy
# Copyright (C) 2013 <NAME> <<EMAIL>>
# See file LICENSE.txt for license information.
# Regression tests for fixed bugs (when not otherwise better covered somewhere
# else)
from patsy import (EvalEnvironment, dmatrix, build_design_matrices,
PatsyError, Origin)
def test... |
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/s/super/super_with_arguments.py | ciskoinch8/vimrc | 463 | 447 | <filename>vimfiles/bundle/vim-python/submodules/pylint/tests/functional/s/super/super_with_arguments.py
class Foo:
pass
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__() # [super-with-arguments]
class Baz(Foo):
def __init__(self):
super().__init__()
class Qux(Foo):
d... |
examples/cmrc2018_example/main.trainer.py | fangd123/TextBrewer | 1,121 | 480 | <filename>examples/cmrc2018_example/main.trainer.py<gh_stars>1000+
import logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
level=logging.INFO,
)
logger = logging.getLogger("Main")
import os,random
import numpy as np
import torch
f... |
gn/gn_to_bp.py | despairblue/esy-skia | 2,151 | 485 | <reponame>despairblue/esy-skia
#!/usr/bin/env python
#
# Copyright 2016 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Generate Android.bp for Skia from GN configuration.
import json
import os
import pprint
import string
import subprocess
import t... |
python/ray/autoscaler/tags.py | firebolt55439/ray | 21,382 | 486 | """The Ray autoscaler uses tags/labels to associate metadata with instances."""
# Tag for the name of the node
TAG_RAY_NODE_NAME = "ray-node-name"
# Tag for the kind of node (e.g. Head, Worker). For legacy reasons, the tag
# value says 'type' instead of 'kind'.
TAG_RAY_NODE_KIND = "ray-node-type"
NODE_KIND_HEAD = "he... |
third_party/google-endpoints/dogpile/cache/region.py | tingshao/catapult | 2,151 | 493 | <gh_stars>1000+
from __future__ import with_statement
from .. import Lock, NeedRegenerationException
from ..util import NameRegistry
from . import exception
from ..util import PluginLoader, memoized_property, coerce_string_conf
from .util import function_key_generator, function_multi_key_generator
from .api import NO_V... |
tests/optims/distributed_adamw_test.py | AswinRetnakumar/Machina | 302 | 522 | import os
import unittest
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import torch.nn as nn
from machina.optims import DistributedAdamW
def init_processes(rank, world_size,
function, backend='tcp'):
os.environ['MASTER_ADDR'] = '127.0.0.1'
os.env... |
tests/functional/test_soft_round_inverse.py | tallamjr/NeuralCompression | 233 | 543 | <gh_stars>100-1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from neuralcompression.functional import soft_round, soft_round_inverse
def test_soft_round_inverse():
... |
lingvo/tasks/car/car_layers_test.py | Harshs27/lingvo | 2,611 | 559 | # Lint as: python3
# Copyright 2019 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 ... |
starry/_core/ops/lib/include/oblate/tests/test_derivs.py | rodluger/starry | 116 | 560 | <reponame>rodluger/starry<filename>starry/_core/ops/lib/include/oblate/tests/test_derivs.py
import oblate
import numpy as np
import pytest
# TODO!
|
Packs/Pwned/Integrations/PwnedV2/PwnedV2.py | diCagri/content | 799 | 571 | from CommonServerPython import *
''' IMPORTS '''
import re
import requests
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBALS/PARAMS '''
VENDOR = 'Have I Been Pwned? V2'
MAX_RETRY_ALLOWED = demisto.params().get('max_retry_time', -1)
API_KEY = demisto.params().get('api_key')
USE_SS... |
moshmosh/extensions/pipelines.py | Aloxaf/moshmosh | 114 | 572 | <reponame>Aloxaf/moshmosh<gh_stars>100-1000
from moshmosh.extension import Extension
from moshmosh.ast_compat import ast
class PipelineVisitor(ast.NodeTransformer):
"""
`a | f -> f(a)`, recursively
"""
def __init__(self, activation):
self.activation = activation
def visit_BinOp(self, n: a... |
alibi_detect/utils/tests/test_discretize.py | Clusks/alibi-detect | 1,227 | 596 | from itertools import product
import numpy as np
import pytest
from alibi_detect.utils.discretizer import Discretizer
x = np.random.rand(10, 4)
n_features = x.shape[1]
feature_names = [str(_) for _ in range(n_features)]
categorical_features = [[], [1, 3]]
percentiles = [list(np.arange(25, 100, 25)), list(np.arange(10... |
nuplan/planning/simulation/observation/idm/test/test_profile_idm_observation.py | motional/nuplan-devkit | 128 | 608 | import logging
import unittest
from pyinstrument import Profiler
from nuplan.planning.scenario_builder.nuplan_db.test.nuplan_scenario_test_utils import get_test_nuplan_scenario
from nuplan.planning.simulation.history.simulation_history_buffer import SimulationHistoryBuffer
from nuplan.planning.simulation.observation.... |
pypy/interpreter/test/test_generator.py | m4sterchain/mesapy | 381 | 625 | <filename>pypy/interpreter/test/test_generator.py
class AppTestGenerator:
def test_generator(self):
def f():
yield 1
assert f().next() == 1
def test_generator2(self):
def f():
yield 1
g = f()
assert g.next() == 1
raises(StopIteration, g.n... |
test/test_data_processor/test_condition_generation_dataset.py | puraminy/OpenPrompt | 979 | 627 | <reponame>puraminy/OpenPrompt
import os, sys
from os.path import dirname as d
from os.path import abspath, join
root_dir = d(d(d(abspath(__file__))))
sys.path.append(root_dir)
from openprompt.data_utils.conditional_generation_dataset import PROCESSORS
base_path = os.path.join(root_dir, "datasets/CondGen")
def test_We... |
PhysicsTools/Heppy/python/analyzers/objects/TauAnalyzer.py | ckamtsikis/cmssw | 852 | 643 | from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer
from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle
from PhysicsTools.Heppy.physicsobjects.Tau import Tau
from PhysicsTools.HeppyCore.utils.deltar import deltaR, matchObjectCollection3
import PhysicsTools.HeppyCore.framework.config as cfg... |
tutorial/deprecated/tutorial_recurrent_policy/main_a2c.py | Purple-PI/rlstructures | 281 | 652 | <gh_stars>100-1000
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from rlstructures import logging
from rlstructures.env_wrappers import GymEnv, GymEnvInf
from rlstructures.tools impor... |
desktop/core/ext-py/python-openid-2.2.5/openid/test/test_htmldiscover.py | kokosing/hue | 5,079 | 662 | <filename>desktop/core/ext-py/python-openid-2.2.5/openid/test/test_htmldiscover.py
from openid.consumer.discover import OpenIDServiceEndpoint
import datadriven
class BadLinksTestCase(datadriven.DataDrivenTestCase):
cases = [
'',
"http://not.in.a.link.tag/",
'<link rel="openid.server" href="... |
fightchurn/listings/chap9/listing_9_4_regression_cparam.py | guy4261/fight-churn | 151 | 677 | from sklearn.linear_model import LogisticRegression
from fightchurn.listings.chap8.listing_8_2_logistic_regression import prepare_data, save_regression_model
from fightchurn.listings.chap8.listing_8_2_logistic_regression import save_regression_summary, save_dataset_predictions
def regression_cparam(data_set_path, C_pa... |
homeassistant/components/zamg/weather.py | MrDelik/core | 30,023 | 733 | """Sensor for data from Austrian Zentralanstalt für Meteorologie."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.components.weather import (
ATTR_WEATHER_HUMIDITY,
ATTR_WEATHER_PRESSURE,
ATTR_WEATHER_TEMPERATURE,
ATTR_WEATHER_WIND_BEARING,
ATTR_WE... |
tf-2-data-parallelism/src/utils.py | Amirosimani/amazon-sagemaker-script-mode | 144 | 747 | import os
import numpy as np
import tensorflow as tf
def get_train_data(train_dir, batch_size):
train_images = np.load(os.path.join(train_dir, 'train_images.npy'))
train_labels = np.load(os.path.join(train_dir, 'train_labels.npy'))
print('train_images', train_images.shape, 'train_labels', train_labels.sha... |
streams/readers/arff_reader.py | JanSurft/tornado | 103 | 761 | """
The Tornado Framework
By <NAME>
University of Ottawa, Ontario, Canada
E-mail: apesaran -at- uottawa -dot- ca / alipsgh -at- gmail -dot- com
"""
import re
from data_structures.attribute import Attribute
from dictionary.tornado_dictionary import TornadoDic
class ARFFReader:
"""This class is used... |
smarts/zoo/worker.py | idsc-frazzoli/SMARTS | 554 | 768 | # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
configs/mmdet/detection/detection_tensorrt_static-300x300.py | zhiqwang/mmdeploy | 746 | 774 | <reponame>zhiqwang/mmdeploy
_base_ = ['../_base_/base_tensorrt_static-300x300.py']
|
tencentcloud/dbbrain/v20210527/models.py | lleiyyang/tencentcloud-sdk-python | 465 | 794 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
oauth/provider.py | giuseppe/quay | 2,027 | 795 | <filename>oauth/provider.py<gh_stars>1000+
# Ported to Python 3
# Originally from https://github.com/DeprecatedCode/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py
import json
import logging
from requests import Response
from io import StringIO
try:
from werkzeug.exceptions import Un... |
tests/dummies.py | arvindmuralie77/gradsflow | 253 | 797 | # Copyright (c) 2021 GradsFlow. 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 ... |
python/flexflow/keras/datasets/cifar.py | zmxdream/FlexFlow | 455 | 829 | # -*- coding: utf-8 -*-
"""Utilities common to CIFAR10 and CIFAR100 datasets.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from six.moves import cPickle
def load_batch(fpath, label_key='labels'):
"""Internal utility for parsing CIFAR ... |
tests/api/serializer/test_user.py | armandomeeuwenoord/freight | 562 | 845 | from freight.api.serializer import serialize
from freight.testutils import TestCase
class UserSerializerTest(TestCase):
def test_simple(self):
user = self.create_user()
result = serialize(user)
assert result["id"] == str(user.id)
assert result["name"] == user.name
|
tests/test_custom_experts.py | protagohhz/hivemind | 1,026 | 855 | import os
import pytest
import torch
from hivemind import RemoteExpert
from hivemind.moe.server import background_server
CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), "test_utils", "custom_networks.py")
@pytest.mark.forked
def test_custom_expert(hid_dim=16):
with background_server(
expe... |
data_structures/stack/largest_rectangle_area_in_histogram.py | ruler30cm/python-ds | 1,723 | 865 | <gh_stars>1000+
'''
Largest rectangle area in a histogram::
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars.
For simplicity, assume that all bars have same width and the width is 1 unit.
'''
def max_area_histogram(histogram):
... |
src/tools/types/obj.py | loongson-zn/build | 215 | 868 | <filename>src/tools/types/obj.py<gh_stars>100-1000
# Copyright <NAME> 2004. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE.txt or copy at https://www.bfgroup.xyz/b2/LICENSE.txt)
from b2.build import type
def register ():
type.register_type ('OBJ', ['obj'], None, ['NT... |
timm/utils/checkpoint_saver.py | Robert-JunWang/pytorch-image-models | 17,769 | 879 | <filename>timm/utils/checkpoint_saver.py
""" Checkpoint Saver
Track top-n training checkpoints and maintain recovery checkpoints on specified intervals.
Hacked together by / Copyright 2020 <NAME>
"""
import glob
import operator
import os
import logging
import torch
from .model import unwrap_model, get_state_dict
... |
src/python/pants/core/goals/check_test.py | yoav-orca/pants | 1,806 | 884 | <reponame>yoav-orca/pants
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from abc import ABCMeta, abstractmethod
from pathlib import Path
from textwrap import dedent
from typing import ClassVar, Iterable, List, Optional, Tuple, Type
f... |
fairseq/models/bart/model.py | samsontmr/fairseq | 172 | 888 | <reponame>samsontmr/fairseq<gh_stars>100-1000
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
BART: Denoising Sequence-to-Sequence Pre-training for
Natural Language Generation, Translatio... |
scibert/models/text_classifier.py | tomhoper/scibert | 1,143 | 905 | from typing import Dict, Optional, List, Any
import torch
import torch.nn.functional as F
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder
from allennlp.nn import InitializerApplicator, RegularizerApplicator
from al... |
plugins/template/tasks.py | crotwell/cmd2 | 469 | 906 | #
# -*- coding: utf-8 -*-
"""Development related tasks to be run with 'invoke'"""
import os
import pathlib
import shutil
import invoke
TASK_ROOT = pathlib.Path(__file__).resolve().parent
TASK_ROOT_STR = str(TASK_ROOT)
# shared function
def rmrf(items, verbose=True):
"""Silently remove a list of directories or ... |
scripts/automation/trex_control_plane/interactive/trex/examples/stl/ndr_plugin.py | timgates42/trex-core | 956 | 907 | import stl_path
class MyNDRPlugin():
def __init__(self):
pass
def pre_iteration(self, finding_max_rate, run_results=None, **kwargs):
""" Function ran before each iteration.
:parameters:
finding_max_rate: boolean
Indicates whether we are running ... |
GPT-distributed.py | wenhuchen/LogicNLG | 141 | 961 | <filename>GPT-distributed.py<gh_stars>100-1000
import argparse
import logging
import torch
import torch.nn.functional as F
import numpy as np
from torch import nn
from torch.autograd import Variable
from transformers import GPT2Config
from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer
from DataLoade... |
bentoml/saved_bundle/loader.py | niits/BentoML | 3,451 | 962 | <gh_stars>1000+
# Copyright 2019 Atalaya Tech, 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 applicable law or agreed... |
ice/consoles.py | reavessm/Ice | 578 | 969 | <reponame>reavessm/Ice<gh_stars>100-1000
# encoding: utf-8
import os
import roms
def console_roms_directory(configuration, console):
"""
If the user has specified a custom ROMs directory in consoles.txt then
return that.
Otherwise, append the shortname of the console to the default ROMs
directory given by... |
tools/perf/contrib/oop_raster/oop_raster.py | zipated/src | 2,151 | 971 | <filename>tools/perf/contrib/oop_raster/oop_raster.py
# Copyright 2018 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.
from benchmarks import smoothness,thread_times
import page_sets
from telemetry import benchmark
# pylin... |
tests/test_std.py | ashwini-balnaves/python-consul | 469 | 988 | <filename>tests/test_std.py
import base64
import operator
import struct
import time
import pytest
import six
import consul
import consul.std
Check = consul.Check
class TestHTTPClient(object):
def test_uri(self):
http = consul.std.HTTPClient()
assert http.uri('/v1/kv') == 'http://127.0.0.1:8500... |
sdk/python/pulumi_kubernetes/coordination/v1/_inputs.py | polivbr/pulumi-kubernetes | 277 | 1001 | <reponame>polivbr/pulumi-kubernetes
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... ... |
log_system_information.py | ibaiGorordo/depthai | 476 | 1009 | #!/usr/bin/env python3
import json
import platform
def make_sys_report(anonymous=False, skipUsb=False, skipPackages=False):
def get_usb():
try:
import usb.core
except ImportError:
yield "NoLib"
return
speeds = ["Unknown", "Low", "Full", "High", "Super",... |
lemur/deployment/service.py | rajatsharma94/lemur | 1,656 | 1014 | from lemur import database
def rotate_certificate(endpoint, new_cert):
"""
Rotates a certificate on a given endpoint.
:param endpoint:
:param new_cert:
:return:
"""
# ensure that certificate is available for rotation
endpoint.source.plugin.update_endpoint(endpoint, new_cert)
endpo... |
cinder/tests/unit/fake_group_snapshot.py | lightsey/cinder | 571 | 1028 | <filename>cinder/tests/unit/fake_group_snapshot.py
# Copyright 2016 EMC 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/LICE... |
MicroPython_BUILD/components/micropython/esp32/modules_examples/mqtt_example.py | FlorianPoot/MicroPython_ESP32_psRAM_LoBo | 838 | 1057 | import network
def conncb(task):
print("[{}] Connected".format(task))
def disconncb(task):
print("[{}] Disconnected".format(task))
def subscb(task):
print("[{}] Subscribed".format(task))
def pubcb(pub):
print("[{}] Published: {}".format(pub[0], pub[1]))
def datacb(msg):
print("[{}] Data arrived... |
render/PC_Normalisation.py | sun-pyo/OcCo | 158 | 1070 | <reponame>sun-pyo/OcCo<gh_stars>100-1000
# Copyright (c) 2020. <NAME>, <EMAIL>
import os, open3d, numpy as np
File_ = open('ModelNet_flist_short.txt', 'w')
if __name__ == "__main__":
root_dir = "../data/ModelNet_subset/"
for root, dirs, files in os.walk(root_dir, topdown=False):
for file in files:
... |
python/GafferUI/ColorSwatchPlugValueWidget.py | ddesmond/gaffer | 561 | 1072 | ##########################################################################
#
# Copyright (c) 2013, <NAME>. All rights reserved.
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the f... |
test/integration/component/test_browse_templates2.py | ycyun/ablestack-cloud | 1,131 | 1083 | # 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
# "License"); you may not u... |
Adafruit_BluefruitLE/interfaces/__init__.py | acoomans/Adafruit_Python_BluefruitLE | 415 | 1087 | <reponame>acoomans/Adafruit_Python_BluefruitLE
from .provider import Provider
from .adapter import Adapter
from .device import Device
from .gatt import GattService, GattCharacteristic, GattDescriptor
|
parallelformers/policies/base/auto.py | Oaklight/parallelformers | 454 | 1098 | <filename>parallelformers/policies/base/auto.py
# Copyright 2021 TUNiB 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 ... |
venv/Lib/site-packages/toolz/sandbox/__init__.py | ajayiagbebaku/NFL-Model | 3,749 | 1118 | from .core import EqualityHashKey, unzip
from .parallel import fold
|
lm/validate.py | ericlin8545/grover | 864 | 1124 | <reponame>ericlin8545/grover
# Original work Copyright 2018 The Google AI Language Team Authors.
# Modified work Copyright 2019 <NAME>
#
# 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
#
# ... |
Z - Tool Box/LaZagne/Windows/lazagne/softwares/windows/ppypykatz.py | dfirpaul/Active-Directory-Exploitation-Cheat-Sheet-1 | 1,290 | 1153 | # -*- coding: utf-8 -*-
# Thanks to @skelsec for his awesome tool Pypykatz
# Checks his project here: https://github.com/skelsec/pypykatz
import codecs
import traceback
from lazagne.config.module_info import ModuleInfo
from lazagne.config.constant import constant
from pypykatz.pypykatz import pypykatz
... |
qf_lib/containers/futures/future_contract.py | webclinic017/qf-lib | 198 | 1164 | # Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... |
pytorch-frontend/benchmarks/operator_benchmark/pt/embeddingbag_test.py | AndreasKaratzas/stonne | 206 | 1175 | <reponame>AndreasKaratzas/stonne<filename>pytorch-frontend/benchmarks/operator_benchmark/pt/embeddingbag_test.py
import operator_benchmark as op_bench
import torch
import numpy
from . import configs
"""EmbeddingBag Operator Benchmark"""
class EmbeddingBagBenchmark(op_bench.TorchBenchmarkBase):
def init(self, embe... |
python/dgl/geometry/capi.py | lfchener/dgl | 9,516 | 1176 | """Python interfaces to DGL farthest point sampler."""
from dgl._ffi.base import DGLError
import numpy as np
from .._ffi.function import _init_api
from .. import backend as F
from .. import ndarray as nd
def _farthest_point_sampler(data, batch_size, sample_points, dist, start_idx, result):
r"""Farthest Point Samp... |
tools/accuracy_checker/openvino/tools/accuracy_checker/postprocessor/clip_segmentation_mask.py | TolyaTalamanov/open_model_zoo | 2,201 | 1204 | <gh_stars>1000+
"""
Copyright (c) 2018-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 ... |
tests/test_utils.py | isabella232/pynacl | 756 | 1205 | <filename>tests/test_utils.py
# Copyright 2013 <NAME> and individual contributors
#
# 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 req... |
drybell/drybell_lfs_spark.py | jsnlp/snorkel-tutorials | 315 | 1224 | <filename>drybell/drybell_lfs_spark.py
from pyspark.sql import Row
from snorkel.labeling.lf import labeling_function
from snorkel.labeling.lf.nlp_spark import spark_nlp_labeling_function
from snorkel.preprocess import preprocessor
from drybell_lfs import load_celebrity_knowledge_base
ABSTAIN = -1
NEGATIVE = 0
POSITIV... |
terrascript/resource/sematext.py | mjuenema/python-terrascript | 507 | 1230 | <filename>terrascript/resource/sematext.py
# terrascript/resource/sematext.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:26:36 UTC)
#
# For imports without namespace, e.g.
#
# >>> import terrascript.resource.sematext
#
# instead of
#
# >>> import terrascript.resource.sematext.sematext
#
# This i... |
tests/space_test.py | hadrianmontes/jax-md | 713 | 1267 | <reponame>hadrianmontes/jax-md<gh_stars>100-1000
# Copyright 2019 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... |
Python/hello-world-pt-BR.py | PushpneetSingh/Hello-world | 1,428 | 1299 | print(u"Ol<NAME>!") |
shared/templates/grub2_bootloader_argument/template.py | justchris1/scap-security-guide | 1,138 | 1319 | import ssg.utils
def preprocess(data, lang):
data["arg_name_value"] = data["arg_name"] + "=" + data["arg_value"]
if lang == "oval":
# escape dot, this is used in oval regex
data["escaped_arg_name_value"] = data["arg_name_value"].replace(".", "\\.")
# replace . with _, this is used in t... |
inverse_warp.py | ZephyrII/competitive_colaboration | 357 | 1374 | # Author: <NAME>
# Copyright (c) 2019, <NAME>
# All rights reserved.
# based on github.com/ClementPinard/SfMLearner-Pytorch
from __future__ import division
import torch
from torch.autograd import Variable
pixel_coords = None
def set_id_grid(depth):
global pixel_coords
b, h, w = depth.size()
i_range = Va... |
examples/nn_cudamat.py | cloudspectatordevelopment/cudamat | 526 | 1376 | <filename>examples/nn_cudamat.py
# This file shows how to implement a single hidden layer neural network for
# performing binary classification on the GPU using cudamat.
from __future__ import division
import pdb
import time
import numpy as np
import cudamat as cm
from cudamat import learn as cl
import util
# initial... |
scripts/49-cat-logs.py | jmviz/xd | 179 | 1391 | #!/usr/bin/env python3
# Usage:
# $0 -o log.txt products/
#
# concatenates .log files (even those in subdirs or .zip) and combines into a single combined.log
from xdfile.utils import find_files_with_time, open_output, get_args
import boto3
# from boto.s3.connection import S3Connection
import os
def main():
a... |
manuscript/link_checker.py | wuyang1002431655/tango_with_django_19 | 244 | 1392 | # Checks for broken links in the book chapters, printing the status of each link found to stdout.
# The Python package 'requests' must be installed and available for this simple module to work.
# Author: <NAME>
# Date: 2017-02-14
import re
import requests
def main(chapters_list_filename, hide_success=True):
"""
hide... |
pommerman/__init__.py | rmccann01/playground | 725 | 1407 | <filename>pommerman/__init__.py
'''Entry point into the pommerman module'''
import gym
import inspect
from . import agents
from . import configs
from . import constants
from . import forward_model
from . import helpers
from . import utility
from . import network
gym.logger.set_level(40)
REGISTRY = None
def _register... |
tests/components/mysensors/conftest.py | liangleslie/core | 30,023 | 1412 | <filename>tests/components/mysensors/conftest.py
"""Provide common mysensors fixtures."""
from __future__ import annotations
from collections.abc import AsyncGenerator, Callable, Generator
import json
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from mysensors import BaseSyncGateway
fr... |
nlpgnn/gnn/RGCNConv.py | ojipadeson/NLPGNN | 263 | 1447 | <gh_stars>100-1000
#! usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author:<NAME>
Usage:
node_embeddings = tf.random.normal(shape=(5, 3))
adjacency_lists = [
tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32),
tf.constant([[0, 1], [2, 4], [2, 4]], dtype=tf.int32)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.