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 |
|---|---|---|---|---|
torba/torba/client/cli.py | mittalkartik2000/lbry-sdk | 4,076 | 9591531 | import logging
import argparse
import asyncio
import aiohttp
from torba.orchstr8.node import Conductor, get_ledger_from_environment, get_blockchain_node_from_ledger
from torba.orchstr8.service import ConductorService
def get_argument_parser():
parser = argparse.ArgumentParser(
prog="torba"
)
subp... |
openstackclient/object/v1/container.py | mydevice/python-openstackclient | 262 | 9591532 | <filename>openstackclient/object/v1/container.py
# Copyright 2013 Nebula 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
#
#... |
tsa/src/test/python/thalesians/tsa/teststats.py | mikimaus78/ml_monorepo | 117 | 9591555 | <filename>tsa/src/test/python/thalesians/tsa/teststats.py<gh_stars>100-1000
import unittest
import numpy as np
import numpy.testing as npt
import thalesians.tsa.stats as stats
import thalesians.tsa.utils as utils
class TestStats(unittest.TestCase):
def test_cor_to_cov(self):
cors = utils.SubdiagonalArray... |
wradlib/vpr.py | wradlib/wradlib | 180 | 9591556 | <filename>wradlib/vpr.py
#!/usr/bin/env python
# Copyright (c) 2011-2020, wradlib developers.
# Distributed under the MIT License. See LICENSE.txt for more info.
"""
Vertical Profile of Reflectivity (VPR)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Precipitation is 3-dimensional in space. The vertical distribution of
prec... |
finrl/finrl_meta/preprocessor/tusharedownloader.py | SaadSaeed150/local_finrl2 | 1,822 | 9591560 | """Contains methods and classes to collect data from
tushare API
"""
import pandas as pd
import tushare as ts
from tqdm import tqdm
class TushareDownloader :
"""Provides methods for retrieving daily stock data from
tushare API
Attributes
----------
start_date : str
start date of th... |
sample/pytorch/run_squad.py | dujiangsu/FasterTransformer | 777 | 9591568 | # coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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 cop... |
cirq-core/cirq/ops/qubit_order_test.py | Saibaba-Alapati/Cirq | 3,326 | 9591572 | # Copyright 2018 The Cirq Developers
#
# 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 required by applicable law or agreed to in ... |
minidump/utils/winapi/version.py | mrexodia/minidump | 215 | 9591593 | from minidump.utils.winapi.defines import *
import ctypes
from ctypes import windll, byref, Structure
class _SYSTEM_INFO_OEM_ID_STRUCT(Structure):
_fields_ = [
("wProcessorArchitecture", WORD),
("wReserved", WORD),
]
class _SYSTEM_INFO_OEM_ID(Union):
_fields_ = [
("dwOem... |
sdl2/test/sdl_test.py | papagiannakis/py-sdl2 | 222 | 9591605 | import sys
import pytest
from sdl2 import SDL_Init, SDL_WasInit, SDL_InitSubSystem, SDL_QuitSubSystem, \
SDL_Quit, SDL_INIT_AUDIO, SDL_INIT_EVERYTHING, SDL_INIT_GAMECONTROLLER, \
SDL_INIT_HAPTIC, SDL_INIT_JOYSTICK, SDL_INIT_NOPARACHUTE, SDL_INIT_TIMER, \
SDL_INIT_VIDEO, SDL_GetError
class TestSDL(object):... |
tacker/vnfm/nfvo_client.py | takahashi-tsc/tacker | 116 | 9591611 | <reponame>takahashi-tsc/tacker
# 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... |
snippets/07 - Case study - air quality data55.py | joshuagottardogalvani/pandas-tutorial | 183 | 9591616 | data.resample('A').mean().plot()
data.mean(axis=1).resample('A').mean().plot(color='k', linestyle='--', linewidth=4) |
Validation/Mixing/test/mixCollectionTest_Step2_cfg.py | ckamtsikis/cmssw | 852 | 9591626 | <gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
process = cms.Process("GlobalVal")
process.load("SimGeneral.MixingModule.mixLowLumPU_mixProdStep2_cfi")
process.load("Configuration.StandardSequences.Services_cff")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.load("Configuration.StandardS... |
scanpy/tests/external/test_harmony_timeseries.py | mkmkryu/scanpy2 | 1,171 | 9591658 | from itertools import product
import pytest
from anndata import AnnData
import scanpy as sc
import scanpy.external as sce
pytest.importorskip("harmony")
def test_load_timepoints_from_anndata_list():
adata_ref = sc.datasets.pbmc3k()
start = [596, 615, 1682, 1663, 1409, 1432]
adata = AnnData.concatenate(... |
src/robusta/integrations/scheduled/playbook_scheduler_manager_impl.py | kandahk/robusta | 273 | 9591662 | import logging
from typing import Union, cast, List, Callable
from pydantic import BaseModel
from ...utils.function_hashes import action_hash
from .playbook_scheduler_manager import PlaybooksSchedulerManager
from .trigger import ScheduledTrigger
from ...model.playbook_definition import PlaybookDefinition
from ...model... |
account/middleware.py | sokoide/OnlineJudge | 5,237 | 9591663 | <gh_stars>1000+
from django.conf import settings
from django.db import connection
from django.utils.timezone import now
from django.utils.deprecation import MiddlewareMixin
from utils.api import JSONResponse
from account.models import User
class APITokenAuthMiddleware(MiddlewareMixin):
def process_request(self, ... |
tests/test_utils/perf/perf_kit/sqlalchemy.py | ChaseKnowlden/airflow | 15,947 | 9591668 | # 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... |
papers/cats/utility/srm.py | Ark-kun/vowpal_wabbit | 4,332 | 9591669 | import sys
import getopt
import math
class SRM:
def __init__(self, data_file_name, predict_file_name, min_val, max_val, k, h):
self.data_file_name = data_file_name
self.predict_file_name = predict_file_name
self.min_val = min_val
self.max_val = max_val
self.hh = h * (max_va... |
Contents/Libraries/Shared/plex/objects/library/extra/genre.py | jippo015/Sub-Zero.bundle | 1,553 | 9591690 | <reponame>jippo015/Sub-Zero.bundle<filename>Contents/Libraries/Shared/plex/objects/library/extra/genre.py<gh_stars>1000+
from plex.objects.core.base import Descriptor, Property
class Genre(Descriptor):
id = Property(type=int)
tag = Property
@classmethod
def from_node(cls, client, node):
items... |
pretrain/PyTorch/dataprep/split_data_into_files.py | eephus101/AzureML-BERT | 340 | 9591706 | from tqdm import tqdm
input_file = "wikipedia.segmented.nltk.txt"
output_file = "./data_shards/wikipedia.segmented.part."
doc_seperator = "\n"
total_partitions = 100 # Mostly will create 1 extra partition
# shard_size = 396000 # Approximate, will split at next article break
with open(input_file, encoding="UTF-8") a... |
examples/util.py | wsy4665/cudamat | 626 | 9591717 | import gzip
import cPickle as pickle
def save(fname, var_list, source_dict):
var_list = [var.strip() for var in var_list.split() if len(var.strip())>0]
fo = gzip.GzipFile(fname, 'wb')
pickle.dump(var_list, fo)
for var in var_list:
pickle.dump(source_dict[var], fo, protocol=2)
fo.close()
de... |
vel/api/model.py | galatolofederico/vel | 273 | 9591736 | <filename>vel/api/model.py
import hashlib
import torch
import torch.nn as nn
import vel.util.module_util as mu
from vel.metrics.loss_metric import Loss
from vel.util.summary import summary
class Model(nn.Module):
""" Class representing full neural network model """
def metrics(self) -> list:
""" Se... |
plex_trakt_sync/commands/sync.py | Taxel/PlexTraktSync | 631 | 9591755 | import click
from tqdm import tqdm
from plex_trakt_sync.commands.login import ensure_login
from plex_trakt_sync.decorators.measure_time import measure_time
from plex_trakt_sync.factory import factory
from plex_trakt_sync.logging import logger
from plex_trakt_sync.plex_api import PlexApi
from plex_trakt_sync.sync impor... |
backend/config/site.py | KuanWeiLee/froggy-service | 174 | 9591765 | <reponame>KuanWeiLee/froggy-service
from django.contrib.admin.sites import AdminSite
from django.urls import path
from .views import DashboardMainView
class DashboardSite(AdminSite):
"""A Django AdminSite to allow registering custom dashboard views."""
def get_urls(self):
urls = super(DashboardSite,... |
examples/color_example.py | ntezak/plotille | 157 | 9591769 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
# The MIT License
# Copyright (c) 2017 - 2021 <NAME>, <EMAIL>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"... |
examples/santander-trans/data-reduce.py | DATA602/jh-kaggle-util | 273 | 9591772 | <reponame>DATA602/jh-kaggle-util<filename>examples/santander-trans/data-reduce.py
# <NAME>'s Kaggle Utilities
# Copyright 2019 by <NAME>, Open Source, Released under the Apache License
# For more information: https://github.com/jeffheaton/jh-kaggle-util
#
# The data- files are used to generate features from the raw da... |
src/robusta/core/reporting/utils.py | Rutam21/robusta | 273 | 9591778 | from typing import List
from .blocks import *
JPG_SUFFIX = ".jpg"
PNG_SUFFIX = ".png"
SVG_SUFFIX = ".svg"
def file_suffix_match(file_name: str, suffix: str) -> bool:
return file_name.lower().endswith(suffix)
def is_image(file_name: str):
return file_suffix_match(file_name, JPG_SUFFIX) \
or file_s... |
egs/esc50/get_esc_result.py | RicodesS/ast | 372 | 9591792 | # -*- coding: utf-8 -*-
# @Time : 11/15/20 1:04 AM
# @Author : <NAME>
# @Affiliation : Massachusetts Institute of Technology
# @Email : <EMAIL>
# @File : get_esc_result.py
# summarize esc 5-fold cross validation result
import argparse
import numpy as np
parser = argparse.ArgumentParser(formatter_class=argp... |
tools/unicode_dbl_width.py | akinomyoga/terminology | 101 | 9591807 | <filename>tools/unicode_dbl_width.py
#!/usr/bin/env python3
"""
Generate src/bin/termptydbl.{c,h} from unicode files
used with ucd.all.flat.xml from
https://www.unicode.org/Public/UCD/latest/ucdxml/ucd.all.flat.zip
"""
import argparse
from collections import namedtuple
import xml.etree.ElementTree as ET
URange = nam... |
pynq/uio.py | michalkouril/PYNQ | 1,537 | 9591842 | # Copyright (c) 2017, Xilinx, 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:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
depth_upsampling/models/msg/blocks.py | Levintsky/ARKitScenes | 237 | 9591852 | <filename>depth_upsampling/models/msg/blocks.py
import torch.nn as nn
class ConvPReLu(nn.Module):
def __init__(self, in_channels, out_channels, kernel=5, stride=1, padding=2):
super().__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel, stride=stride, padding=padding)
... |
unet3d/models/keras/senet/se_resnet.py | Crush18/3DUnetCNN | 1,624 | 9591894 | '''
Squeeze-and-Excitation ResNets
References:
- [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)
- []() # added when paper is published on Arxiv
'''
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from keras.models i... |
Python/djaccard_simmiliarity.py | muthusk07/cs-algorithms | 239 | 9591910 | '''
Given a list of sentence with same topics (or from a news), this function will return
a text which have score similiar between sentences. It will be useful to find the main sentence.
'''
import numpy as np
def jaccard_similarity(str_1, str_2):
""" compute of intersection to get similraity score between wor... |
examples/simulations/bloch.py | hadivafaii/vedo | 836 | 9591921 | """Animate text and meshes"""
from vedo import *
v = Arrow([0,0,0],[0,.71,.71]).addTrail(maxlength=0.1, c='k').addShadow(z=-1)
s = Sphere().c('red5', 0.1)
cam = dict(pos=(4.14, -4.25, 2.35),
focalPoint=(0.167, -0.287, 0.400),
viewup=(-0.230, 0.235, 0.944),
distance=5.94)
# (press "C" ... |
dbdb/core/management/commands/compute_score.py | cmu-db/dbms-library | 271 | 9591926 | # stdlib imports
# django imports
from django.core.management import BaseCommand
from django.conf import settings
from django.contrib.auth import get_user_model
from dbdb.core.models import System
from dbdb.core.models import SystemFeature
from dbdb.core.models import SystemVersion
from dbdb.core.models import SystemV... |
pyray/audio.py | FGDBTKD/pyray | 715 | 9591930 | import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile # get the api
import numpy as np
import scipy.fftpack as fftp
from PIL import Image, ImageDraw, ImageFont, ImageMath
from pyray.axes import *
def plt_fft(filename, plot=False):
fs, data = wavfile.read(filename) # load the data... |
next_steps/data_science/diagnose/diagnose.py | kamoljan/amazon-personalize-samples | 442 | 9591932 | <reponame>kamoljan/amazon-personalize-samples<filename>next_steps/data_science/diagnose/diagnose.py
import pandas as pd
import pylab as pl
import numpy as np
import warnings
import traceback
import scipy.sparse as ss
import time
INTERACTIONS_REQUIRED_FIELDS = ["USER_ID", "ITEM_ID", "TIMESTAMP"]
# general
NA_RATE_THRE... |
src/Stochastic_Gradient_Langevin_Dynamics/model.py | JavierAntoran/Bayesain-Neural-Networks | 1,299 | 9591942 | from src.base_net import *
from optimizers import *
import torch.nn as nn
import torch.nn.functional as F
import copy
class Linear_2L(nn.Module):
def __init__(self, input_dim, output_dim, n_hid):
super(Linear_2L, self).__init__()
self.n_hid = n_hid
self.input_dim = input_dim
self... |
pose/utils/__init__.py | xiang-zhe/Fast_Human_Pose_Estimation_Pytorch | 337 | 9591963 | from __future__ import absolute_import
from .evaluation import *
from .imutils import *
from .logger import *
from .misc import *
from .osutils import *
from .transforms import *
|
lib/python/moteus/test/moteus_test.py | TTN-/moteus | 347 | 9591974 | <filename>lib/python/moteus/test/moteus_test.py
#!/usr/bin/python3 -B
# Copyright 2020 <NAME>, <EMAIL>.
#
# 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... |
tests/test_restrictions.py | leonarduschen/zipline | 14,525 | 9591989 | import pandas as pd
from pandas.util.testing import assert_series_equal
from six import iteritems
from functools import partial
from toolz import groupby
from zipline.finance.asset_restrictions import (
RESTRICTION_STATES,
Restriction,
HistoricalRestrictions,
StaticRestrictions,
SecurityListRestri... |
tensorflow_probability/python/experimental/mcmc/preconditioned_hmc.py | jakee417/probability-1 | 3,670 | 9591995 | # Copyright 2018 The TensorFlow Probability 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 o... |
hata/discord/application/flags.py | Multiface24111/hata | 173 | 9592022 | __all__ = ('FlagBase', 'SKUFlag',)
from ..bases import FlagBase
class ApplicationFlag(FlagBase):
"""
Represents an application's flags.
The implemented application flags are the following:
+-----------------------------------+-------------------+
| Respective name | Bit... |
prody/chromatin/functions.py | grandevelia/ProDy | 210 | 9592025 | import numpy as np
from prody.dynamics import NMA, MaskedGNM
from prody.dynamics.mode import Mode
from prody.dynamics.modeset import ModeSet
from prody.utilities import importLA, copy, showFigure, div0
from prody import LOGGER, SETTINGS
__all__ = ['showDomains', 'showEmbedding', 'getDomainList']
## normalization me... |
demos/face_recognition_demo/python/landmarks_detector.py | alpkn/open_model_zoo | 2,201 | 9592033 | <reponame>alpkn/open_model_zoo<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
Un... |
bidaf/helpers/file_logger.py | davidgolub/QuestionGeneration | 117 | 9592051 | <gh_stars>100-1000
class FileLogger(object):
""" Simple logger to insert stuff into a file """
def __init__(self, path):
self.file = open(path, 'w')
def write(self, text, print_text=True):
if print_text:
print("FILE LOGGER: %s" % text)
self.file.write(str(text) + "\n")
... |
tutorials/W1D3_ModelFitting/solutions/W1D3_Tutorial4_Solution_25849be9.py | eduardojdiniz/CompNeuro | 2,294 | 9592068 | <reponame>eduardojdiniz/CompNeuro
def ordinary_least_squares(X, y):
"""Ordinary least squares estimator for linear regression.
Args:
X (ndarray): design matrix of shape (n_samples, n_regressors)
y (ndarray): vector of measurements of shape (n_samples)
Returns:
ndarray: estimated parameter values of... |
sudo_rm_rf/dnn/experiments/run_improved_sudormrf.py | ishine/sudo_rm_rf | 134 | 9592076 | """!
@brief Running an experiment with the improved version of SuDoRmRf
@author <NAME> {<EMAIL>}
@copyright University of Illinois at Urbana-Champaign
"""
import os
import sys
current_dir = os.path.dirname(os.path.abspath('__file__'))
root_dir = os.path.abspath(os.path.join(current_dir, '../../../'))
sys.path.append... |
deep_privacy/modeling/models/iconv.py | skoskjei/DP-ATT | 1,128 | 9592083 | <reponame>skoskjei/DP-ATT<gh_stars>1000+
import torch
from . import layers
eps = 1e-2
pconv_settings = {
4: {"dilation": 1, "kernel_size": 3},
8: {"dilation": 1, "kernel_size": 3},
16: {"dilation": 1, "kernel_size": 5},
32: {"dilation": 1, "kernel_size": 5},
64: {"dilation": 1, "kernel_size": 5},... |
fer2013/fer2013/src/rect_util.py | ctiger34/BASIC-EMOTION-DETECTION | 326 | 9592093 | #
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
#
import math
class Point(object):
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __add__(self, p):
"""Point(x... |
tests/components/harmony/__init__.py | domwillcode/home-assistant | 30,023 | 9592110 | """Tests for the Logitech Harmony Hub integration."""
|
tools/build_stdlib_report.py | jacebrowning/voc | 850 | 9592124 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Build report with stdlib modules status
"""
from __future__ import print_function, absolute_import, division
import glob
import jinja2
# ugly hack to avoid duplicating code:
import sys, os
sys.path.append(os.path.dirname(__file__))
from compile_stdlib import module_lis... |
PythonAPI/carissma_project/lib/python3.5/site-packages/matplotlib/testing/determinism.py | AbdulHoffmann/carla_carissma | 445 | 9592126 | <reponame>AbdulHoffmann/carla_carissma
"""
Provides utilities to test output reproducibility.
"""
import io
import os
import re
import subprocess
import sys
import pytest
import matplotlib
from matplotlib import pyplot as plt
def _determinism_save(objects='mhi', format="pdf", usetex=False):
# save current valu... |
lldb/test/API/commands/platform/file/close/TestPlatformFileClose.py | mkinsner/llvm | 2,338 | 9592139 | <filename>lldb/test/API/commands/platform/file/close/TestPlatformFileClose.py
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@no_debug_info_test
def test_file_... |
tests/cupy_tests/random_tests/test_permutations.py | prkhrsrvstv1/cupy | 6,180 | 9592159 | <reponame>prkhrsrvstv1/cupy<filename>tests/cupy_tests/random_tests/test_permutations.py<gh_stars>1000+
import unittest
import numpy
import pytest
import cupy
from cupy import testing
from cupy.testing import _condition
@testing.parameterize(
{'seed': None},
{'seed': 0},
)
@testing.gpu
class TestPermutations... |
examples/sagemaker_whylabs_example/code/api/__init__.py | cswarth/whylogs | 603 | 9592174 | # -*- coding: utf-8 -*-
"""API module v1."""
# from .views import blueprint
|
cpmpy/smugglers_knapsack.py | hakank/hakank | 279 | 9592180 | """
Smuggler's knapsack problem in cpmpy.
Marriott & Stucker: 'Programming with constraints', page 101f, 115f
Smuggler's knapsack.
A smuggler has a knapsack with a capacity of 9 units.
Unit Profit
Whisky: 4 units 15 dollars
Perfume: 3 units 10 dollars
Cigarettes: 2 units 7 dolla... |
src/main/python/rlbot/matchcomms/common_uses/common_keys.py | VirxEC/RLBot | 408 | 9592225 | <filename>src/main/python/rlbot/matchcomms/common_uses/common_keys.py<gh_stars>100-1000
TARGET_PLAYER_INDEX = 'target_player_index'
|
pypykatz/smb/printer.py | wisdark/pypykatz | 1,861 | 9592226 | import asyncio
import os
from pypykatz import logging
async def printnightmare(url, dll_path, driverpath = None):
try:
from aiosmb.commons.connection.url import SMBConnectionURL
from aiosmb.commons.interfaces.machine import SMBMachine
smburl = SMBConnectionURL(url)
connect... |
atlas/aws_utils/src/foundations_aws/__init__.py | DeepLearnI/atlas | 296 | 9592229 |
from foundations_aws.aws_pipeline_archive import AWSPipelineArchive
from foundations_aws.aws_pipeline_archive_listing import AWSPipelineArchiveListing
from foundations_aws.aws_bucket import AWSBucket
from foundations_aws.global_state import *
def _append_module():
import sys
from foundations_internal.global_... |
gailtf/common/statistics.py | liytt85/gail-tf-pro | 201 | 9592236 | <filename>gailtf/common/statistics.py
# the code is similar to https://github.com/carpedm20/deep-rl-tensorflow/blob/master/agents/statistic.py
# in my implementation, I use one statistics for recording immediate results and
# another one for episodic results.
import gailtf.baselines.common.tf_util as U
imp... |
code/model/util.py | philipshurpik/deep-trading-agent | 671 | 9592240 | <reponame>philipshurpik/deep-trading-agent<filename>code/model/util.py
"""Code adapted from https://github.com/devsisters/DQN-tensorflow/tree/master/dqn/utils.py"""
try:
import cPickle as pickle
except:
import pickle
import tensorflow as tf
from utils.strings import *
def clipped_error(x):
# Huber loss
... |
envi/tests/msp430/iret.py | rnui2k/vivisect | 716 | 9592261 | <filename>envi/tests/msp430/iret.py
from envi.archs.msp430.regs import *
checks = [
# RET
(
'RET',
{ 'regs': [(REG_SP, 0x1000)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "3041", 'data': "11223344" },
{ 'regs': [(REG_SP, 0x1002), (REG_PC, 0x2211)], 'flags': [(SR_N, ... |
tapiriik/messagequeue/__init__.py | pmenzel/tapiriik | 1,445 | 9592262 | <filename>tapiriik/messagequeue/__init__.py
from kombu import Connection
from tapiriik.settings import RABBITMQ_BROKER_URL
mq = Connection(RABBITMQ_BROKER_URL, transport_options={'confirm_publish': True})
#mq.connect()
|
MNIST-pytorch/data.py | LaudateCorpus1/inverse-compositional-STN | 201 | 9592280 | <reponame>LaudateCorpus1/inverse-compositional-STN
import numpy as np
import scipy.linalg
import os,time
import torch
import torchvision
import warp,util
# load MNIST data
def loadMNIST(opt,path):
os.makedirs(path,exist_ok=True)
trainDataset = torchvision.datasets.MNIST(path,train=True,download=True)
testDataset =... |
FWCore/Framework/test/testOptions3_cfg.py | Purva-Chaudhari/cmssw | 852 | 9592291 | <filename>FWCore/Framework/test/testOptions3_cfg.py<gh_stars>100-1000
# Test of options when concurrentIOVs and concurrentLumis are too big
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.source = cms.Source("EmptySource")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.... |
smartsim/entity/strategies.py | neuralvis/SmartSim | 117 | 9592297 | # BSD 2-Clause License
#
# Copyright (c) 2021, Hewlett Packard Enterprise
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright noti... |
alipay/aop/api/domain/AlipayEcoLogisticsExpressOrderModifyModel.py | snowxmas/alipay-sdk-python-all | 213 | 9592328 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayEcoLogisticsExpressOrderModifyModel(object):
def __init__(self):
self._accept_type = None
self._courier_alipay_account = None
self._courier_emp_num = None
se... |
cup/services/buffers.py | liu0208xuan/CUP | 900 | 9592341 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Copyright: [CUP] - See LICENSE for details.
# Authors: <NAME> (@mythmgn),
"""
:description:
buffer pool
"""
import threading
from cup import platforms
SMALL_BLOCK_SIZE = 4096 # 4kb
MEDIUM_BLOCK_SIZE = (128 + 4) * 1024 # (128 + 4) K
LARGE_BLOCK_SI... |
sdk/azurearcdata/azure-mgmt-azurearcdata/azure/mgmt/azurearcdata/models/__init__.py | rsdoherty/azure-sdk-for-python | 2,728 | 9592343 | <filename>sdk/azurearcdata/azure-mgmt-azurearcdata/azure/mgmt/azurearcdata/models/__init__.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for ... |
awacs/s3_object_lambda.py | michael-k/awacs | 358 | 9592361 | # Copyright (c) 2012-2021, <NAME> <<EMAIL>>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon S3 Object Lambda"
prefix = "s3-object-lambda"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
... |
backend/chat/tornado/tornado_handler.py | illegalbyte/pychat | 197 | 9592369 | <reponame>illegalbyte/pychat<gh_stars>100-1000
import json
import logging
from datetime import timedelta
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models import F, Q, Count, Prefetch
from itertools import chain
from tornado import ioloop, gen
from tornado.websoc... |
.venv/lib/python3.8/site-packages/pandas/tests/series/test_reductions.py | acrucetta/Chicago_COVI_WebApp | 115 | 9592389 | <reponame>acrucetta/Chicago_COVI_WebApp<filename>.venv/lib/python3.8/site-packages/pandas/tests/series/test_reductions.py
import pandas as pd
from pandas import Series
def test_reductions_td64_with_nat():
# GH#8617
ser = Series([0, pd.NaT], dtype="m8[ns]")
exp = ser[0]
assert ser.median() == exp
a... |
crits/services/urls.py | dutrow/crits | 738 | 9592395 | <reponame>dutrow/crits
import os
from django.conf import settings
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^list/$', views.list, name='crits-services-views-list'),
url(r'^analysis_results/list/$', views.analysis_results_listing, name='crits-services-views-analysis_r... |
effdet/data/parsers/__init__.py | AgentVi/efficientdet-pytorch | 1,386 | 9592409 | from .parser_config import OpenImagesParserCfg, CocoParserCfg, VocParserCfg
from .parser_factory import create_parser
|
examples/opencl/stencil.py | sakehl/kernel_tuner | 104 | 9592418 | #!/usr/bin/env python
import numpy
import kernel_tuner
from collections import OrderedDict
def tune():
with open('stencil.cl', 'r') as f:
kernel_string = f.read()
problem_size = (4096, 2048)
size = numpy.prod(problem_size)
x_old = numpy.random.randn(size).astype(numpy.float32)
x_new = nu... |
src/api/tieba/__init__.py | ANONSENSEBOT/HibiAPI | 394 | 9592464 | # flake8:noqa:F401
from .api import Config, EndpointsType, TiebaEndpoint
from .net import NetRequest
|
tests/utils.py | Liang813/pytorch-cnn-finetune | 735 | 9592476 | import numpy as np
import torch
def assert_equal_model_outputs(input_var, model1, model2):
model1.eval()
model2.eval()
model1_output = model1(input_var)
model2_output = model2(input_var)
assert torch.equal(model1_output, model2_output)
def assert_almost_equal_model_outputs(input_var, model1, mod... |
fomalhaut/tests/__init__.py | restran/fomalhaut | 159 | 9592493 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# created by restran on 2015/12/21
|
lib/config.py | nladuo/taobao_bra_crawler | 219 | 9592499 | <reponame>nladuo/taobao_bra_crawler
# -*- coding:utf-8 -*-
""" 数据库配置文件 """
config = {
'timeout': 3,
'db_user': '', # 无密码
'db_pass': '',
'db_host': 'localhost',
'db_port': 27017,
'db_name': 'taobao',
'use_tor_proxy': False,
'tor_proxy_port': 9050
} |
dist/BitTornado/BT1/HTTPDownloader.py | HelloRambo/murder | 758 | 9592503 | # Written by <NAME>
# see LICENSE.txt for license information
from BitTornado.CurrentRateMeasure import Measure
from random import randint
from urlparse import urlparse
from httplib import HTTPConnection
from urllib import quote
from threading import Thread
from BitTornado.__init__ import product_name,version_short
tr... |
tests/test_data/test_pipelines/test_loadings/__init__.py | rlleshi/mmaction2 | 1,870 | 9592531 | <reponame>rlleshi/mmaction2
# Copyright (c) OpenMMLab. All rights reserved.
from .base import BaseTestLoading
__all__ = ['BaseTestLoading']
|
rotkehlchen/tests/db/test_ranges.py | rotkehlchenio/rotkehlchen | 137 | 9592554 | <reponame>rotkehlchenio/rotkehlchen
from rotkehlchen.db.ranges import DBQueryRanges
def test_get_location_query_ranges(database):
dbranges = DBQueryRanges(database)
location1 = 'location1'
location2 = 'location2'
database.update_used_query_range(location1, 15, 25)
database.update_used_query_range... |
utils/remove_dev_unk.py | paynesa/rnng-incremental | 187 | 9592571 | <reponame>paynesa/rnng-incremental
import sys
def is_next_open_bracket(line, start_idx):
for char in line[(start_idx + 1):]:
if char == '(':
return True
elif char == ')':
return False
raise IndexError('Bracket possibly not balanced, open bracket not followed by closed br... |
SRT/cache_data/CREATE_DATA.py | yerang823/landmark-detection | 612 | 9592578 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
#
import os, sys, cv2, torch
from os import path as osp
from pathlib import Path
lib_dir = (Path(__file__).parent / '..' /... |
testing/testapp/models.py | theY4Kman/django-jinja | 210 | 9592582 | <reponame>theY4Kman/django-jinja<gh_stars>100-1000
from django.db.models import Model, DateTimeField
class TestModel(Model):
date = DateTimeField(null=True)
|
rdkit/Chem/MACCSkeys.py | kazuyaujihara/rdkit | 1,609 | 9592586 | # $Id$
#
# Copyright (C) 2001-2011 <NAME> and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
""" SMARTS definitions for th... |
Lesson14/min_max_division.py | nawang87/codility_lessons | 114 | 9592606 | <gh_stars>100-1000
"""
Task:MinMaxDivision
Divide array A into K blocks and minimize the largest sum of any block.
You are given integers K, M and a non-empty array A consisting of N integers. Every element of the array is not greater than M.
You should divide this array into K blocks of consecutive elements. The siz... |
applications/tensorflow/dynamic_sparsity/ipu_sparse_ops/layers/fully_connected.py | payoto/graphcore_examples | 260 | 9592626 | <gh_stars>100-1000
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
"""
This module exposes dynamic sparse layers through simple classes with a consistent API.
There are also dense layers wrapped in the same interface in order to make it easier
to build models where the layers can be switched from sparse to den... |
pyrad/__init__.py | cspengl/pyrad | 144 | 9592630 | """Python RADIUS client code.
pyrad is an implementation of a RADIUS client as described in RFC2865.
It takes care of all the details like building RADIUS packets, sending
them and decoding responses.
Here is an example of doing a authentication request::
import pyrad.packet
from pyrad.client import Client
fro... |
tests/test_utils.py | cknd/talkative_tracebacks | 1,233 | 9592636 | import re
from stackprinter.utils import match
def test_match():
assert match('my/ignored/path', None) is False
assert match('my/ignored/path', ['not']) is False
assert match('my/ignored/path', [re.compile('not ignored')]) is False
assert match('my/ignored/path', 'ignored')
assert match('my/igno... |
locations/spiders/mobilelink.py | davidchiles/alltheplaces | 297 | 9592643 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import json
import re
import scrapy
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
class MobilelinkSpider(scrapy.Spider):
name = "mobilelink"
item_attributes = { 'brand': "Mobilelink" }
allowed_domains = ['mobilelinkusa.co... |
dd_1/Part 1/Section 09 - Modules, Packages and Namespaces/08 - structuring_package_imports/common/models/__init__.py | Rebell-Leader/bg | 3,266 | 9592699 | <reponame>Rebell-Leader/bg
# models
from .posts import *
from .users import *
__all__ = (posts.__all__ +
users.__all__) |
metadata-ingestion/src/datahub/ingestion/source/confluent_schema_registry.py | pppsunil/datahub | 289 | 9592706 | <filename>metadata-ingestion/src/datahub/ingestion/source/confluent_schema_registry.py
import json
import logging
from hashlib import md5
from typing import List, Optional, Set, Tuple
import confluent_kafka
from confluent_kafka.schema_registry.schema_registry_client import (
RegisteredSchema,
Schema,
Schem... |
backend/tests/subscriber/aggregation/test_contributions.py | rutvikpadhiyar000/github-trends | 157 | 9592709 | from datetime import date, timedelta
from aiounittest.case import AsyncTestCase
from src.constants import TEST_TOKEN as TOKEN, TEST_USER_ID as USER_ID
from src.models import UserContributions
from src.subscriber.aggregation import get_contributions
class TestTemplate(AsyncTestCase):
async def test_get_contribut... |
maml/models/gated_net.py | Manifold-Computing/MMAML-Classification | 130 | 9592737 | <filename>maml/models/gated_net.py
from collections import OrderedDict
import torch
import torch.nn.functional as F
from maml.models.model import Model
from IPython import embed
def weight_init(module):
if isinstance(module, torch.nn.Linear):
torch.nn.init.normal_(module.weight, mean=0, std=0.01)
... |
scripts/benchmark/_utils/meters.py | ggs134/py-evm | 1,641 | 9592743 | <reponame>ggs134/py-evm
import time
from typing import (
Any,
Callable,
NamedTuple
)
# FIXME: Couldn't get generics to work here. Sticking with `Any` for now
# See: https://stackoverflow.com/questions/50530959/generic-namedtuple-in-python-3-6
class TimedResult(NamedTuple):
duration: float
wrapped_... |
dev/count_usage_freq.py | Erotemic/ubelt | 604 | 9592749 |
import scriptconfig as scfg
class UsageConfig(scfg.Config):
default = {
'print_packages': False,
'remove_zeros': True,
'hardcoded_ubelt_hack': True,
'extra_modnames': [],
}
def count_ubelt_usage():
config = UsageConfig(cmdline=True)
import ubelt as ub
import gl... |
dotnet/workspace.bzl | TamsilAmani/selenium | 25,151 | 9592766 | load(
"@d2l_rules_csharp//csharp:defs.bzl",
"csharp_register_toolchains",
"csharp_repositories",
"import_nuget_package",
)
def selenium_register_dotnet():
csharp_register_toolchains()
csharp_repositories()
native.register_toolchains("//third_party/dotnet/ilmerge:all")
import_nuget_pac... |
tests/distributions/test_1d_dependencies.py | utsekaj42/chaospy | 333 | 9592775 | """Test dependent distributions with 1-D components."""
from pytest import raises
import numpy
import chaospy
DIST1 = chaospy.Uniform(1, 2)
DIST2 = chaospy.Gamma(DIST1)
JOINT1 = chaospy.J(DIST1, DIST2)
JOINT2 = chaospy.J(DIST2, DIST1)
def test_1d_stochastic_dependencies():
"""Ensure ``stochastic_dependencies`` b... |
extensions/donjayamanne.python-0.6.9/pythonFiles/preview/jedi/parser/__init__.py | Sunshengjin/RoboWare-Studio | 239 | 9592794 | <reponame>Sunshengjin/RoboWare-Studio
"""
The ``Parser`` tries to convert the available Python code in an easy to read
format, something like an abstract syntax tree. The classes who represent this
tree, are sitting in the :mod:`jedi.parser.tree` module.
The Python module ``tokenize`` is a very important part in the `... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.