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
python/seldon_core/__init__.py
juldou/seldon-core
3,049
12793436
from seldon_core.version import __version__ from .storage import Storage
第11章/program/baidu/pipelines.py
kingname/SourceCodeOfBook
274
12793461
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymongo from scrapy.conf import settings class BaiduPipeline(object): def __init__(self): host = settings[...
reactivated/apps.py
silviogutierrez/reactivated
178
12793464
import importlib import json import logging import os import subprocess from typing import Any, Dict, NamedTuple, Tuple from django.apps import AppConfig from django.conf import settings from . import ( definitions_registry, extract_views_from_urlpatterns, global_types, template_registry, type_reg...
examples/sync_cmdclass_pyproject/sync_cmdclass_pyproject/__init__.py
linshoK/pysen
423
12793467
from typing import Any, Callable, Optional, Sequence, Set, Tuple def foo( a: Any, b: Callable[[], Tuple[int, int, str]], c: Set[str], d: Optional[Sequence[int]] = None, e: Any = None, ) -> None: pass print("Hello world") foo(a=1, b=lambda: (1, 2, "hoge"), c=set(), d=None, e=None)
mmdet/ops/corner_pool/__init__.py
vanyalzr/mmdetection
274
12793477
<reponame>vanyalzr/mmdetection from .corner_pool import CornerPool __all__ = ['CornerPool']
plugin/lighthouse/reader/__init__.py
x9090/lighthouse
1,741
12793490
from .coverage_reader import CoverageReader
nn/framework.py
thunlp/Chinese_NRE
272
12793497
import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import numpy as np from .encoder import BiLstmEncoder from .classifier import AttClassifier from torch.autograd import Variable from torch.nn import functional, init class MGLattice_model(nn.Module): def...
src/sklearn_evaluation/SQLiteTracker.py
abcnishant007/sklearn-evaluation
351
12793506
<gh_stars>100-1000 from uuid import uuid4 import sqlite3 import json import pandas as pd from sklearn_evaluation.table import Table class SQLiteTracker: """A simple experiment tracker using SQLite :doc:`Click here <../user_guide/SQLiteTracker>` to see the user guide. Parameters ---------- path ...
multipole-graph-neural-operator/utilities.py
vir-k01/graph-pde
121
12793514
<gh_stars>100-1000 import torch import numpy as np import scipy.io import h5py import sklearn.metrics from torch_geometric.data import Data import torch.nn as nn from scipy.ndimage import gaussian_filter ################################################# # # Utilities # #################################################...
backend/src/baserow/config/asgi.py
ashishdhngr/baserow
839
12793518
import django from channels.routing import ProtocolTypeRouter from baserow.ws.routers import websocket_router from django.core.asgi import get_asgi_application django.setup() django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( {"http": django_asgi_app, "websocket": websocket_router} )
threedod/benchmark_scripts/utils/box_utils.py
Levintsky/ARKitScenes
237
12793620
# TODO: Explain 8 corners logic at the top and use it consistently # Add comments of explanation import numpy as np import scipy.spatial from .rotation import rotate_points_along_z def get_size(box): """ Args: box: 8x3 Returns: size: [dx, dy, dz] """ distance = scipy.spatial.dist...
src/fal/cli/fal_runner.py
emekdahl/fal
360
12793626
<gh_stars>100-1000 import argparse from pathlib import Path from typing import Any, Dict, List import os from dbt.config.profile import DEFAULT_PROFILES_DIR from fal.run_scripts import raise_for_run_results_failures, run_scripts from fal.fal_script import FalScript from faldbt.project import DbtModel, FalDbt, FalGene...
lightbus/utilities/io.py
gcollard/lightbus
178
12793641
import logging logger = logging.getLogger(__name__) def make_file_safe_api_name(api_name): """Make an api name safe for use in a file name""" return "".join([c for c in api_name if c.isalpha() or c.isdigit() or c in (".", "_", "-")])
python/mxnet/gluon/probability/transformation/domain_map.py
pioy/incubator-mxnet
211
12793693
<filename>python/mxnet/gluon/probability/transformation/domain_map.py # 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 ...
pytools/lib/readqc_report.py
virtualparadox/bbmap
134
12793700
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Readqc report: record stat key-value in readqc-stats.txt ### JGI_Analysis_Utility_Illumina::illumina_read_level_report Created: Jul 24 2013 sulsj (<EMAIL>) """ import os import sys ## custom libs in "../lib/" srcDir = os.path.dirname(__file__) sys.path.appe...
bookwyrm/tests/templatetags/test_notification_page_tags.py
mouse-reeve/fedireads
270
12793706
<gh_stars>100-1000 """ style fixes and lookups for templates """ from unittest.mock import patch from django.test import TestCase from bookwyrm import models from bookwyrm.templatetags import notification_page_tags @patch("bookwyrm.activitystreams.add_status_task.delay") @patch("bookwyrm.activitystreams.remove_stat...
a06_Seq2seqWithAttention/a1_seq2seq.py
sunshinenum/text_classification
7,723
12793729
# -*- coding: utf-8 -*- import tensorflow as tf # 【该方法测试的时候使用】返回一个方法。这个方法根据输入的值,得到对应的索引,再得到这个词的embedding. def extract_argmax_and_embed(embedding, output_projection=None): """ Get a loop_function that extracts the previous symbol and embeds it. Used by decoder. :param embedding: embedding tensor for symbol ...
kitsune/users/migrations/0025_auto_20200926_0638.py
The-smooth-operator/kitsune
929
12793730
# Generated by Django 2.2.14 on 2020-09-26 06:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0024_auto_20200914_0433'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'permissions': ...
examples/example_GenericSignal.py
ishine/acoular
294
12793742
# -*- coding: utf-8 -*- """ """ from pylab import * from acoular import * # files datafile = 'example_data.h5' t1 = MaskedTimeSamples(name=datafile) t1.start = 0 # first sample, default t1.stop = 16000 # last valid sample = 15999 invalid = [1,7] # list of invalid channels (unwanted microphones etc...
openspeech/datasets/librispeech/preprocess/subword.py
CanYouImagine/openspeech
207
12793746
# MIT License # # Copyright (c) 2021 <NAME> and <NAME> and <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...
seurat/generation/maya/seurat_rig.py
Asteur/vrhelper
819
12793751
<reponame>Asteur/vrhelper # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
tools/agile-machine-learning-api/codes/trainer/utils/metric_utils.py
ruchirjain86/professional-services
2,116
12793759
<gh_stars>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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
recipes/Python/389203_Series_generator_using_multiple_generators_/recipe-389203.py
tdiprima/code
2,023
12793788
<gh_stars>1000+ # Simple series generator with # multiple generators & decorators. # Author : <NAME> def myfunc(**kwds): def func(f): cond = kwds['condition'] proc = kwds['process'] num = kwds['number'] x = 0 for item in f(): if cond and cond(item)...
rpcpy/openapi.py
william-wambua/rpc.py
152
12793804
<reponame>william-wambua/rpc.py<gh_stars>100-1000 import functools import inspect import typing import warnings __all__ = [ "BaseModel", "create_model", "validate_arguments", "set_type_model", "is_typed_dict_type", "parse_typed_dict", "TEMPLATE", ] Callable = typing.TypeVar("Callable", bou...
deskwork_detector.py
sgarbirodrigo/ml-sound-classifier
118
12793806
from realtime_predictor import * emoji = {'Writing': '\U0001F4DD ', 'Scissors': '\u2701 ', 'Computer_keyboard': '\u2328 '} def on_predicted_deskwork(ensembled_pred): result = np.argmax(ensembled_pred) label = conf.labels[result] if label in ['Writing', 'Scissors', 'Computer_keyboard']: p ...
benchmarks/v3-app-note/run_benchmarks_pll_empirical.py
ayresdl/beagle-lib
110
12793820
<filename>benchmarks/v3-app-note/run_benchmarks_pll_empirical.py #!/usr/bin/env python2.7 # <NAME> import sys import argparse import subprocess import re from math import log, exp # def gen_log_site_list(min, max, samples): # log_range=(log(max) - log(min)) # samples_list = [] # for i in range(0, samples...
app/dashapp1/callbacks.py
rseed42/dash_on_flask
258
12793847
from datetime import datetime as dt from dash.dependencies import Input from dash.dependencies import Output from dash.dependencies import State from flask_login import current_user import pandas_datareader as pdr def register_callbacks(dashapp): @dashapp.callback( Output('my-graph', 'figure'), I...
model-ms/benchmark/make_fixture_models.py
ncoop57/deep_parking
126
12793849
<reponame>ncoop57/deep_parking<filename>model-ms/benchmark/make_fixture_models.py import torchvision from fastai.vision import ImageDataBunch, cnn_learner, unet_learner, SegmentationItemList, imagenet_stats data = ImageDataBunch.from_csv('fixtures/classification').normalize(imagenet_stats) learner = cnn_learner(data, ...
src/autogen/eigs.py
ldXiao/polyfem
228
12793858
from sympy import * from sympy.matrices import * import os import re import argparse # local import pretty_print def sqr(a): return a * a def trunc_acos(x): tmp = Piecewise((0.0, x >= 1.0), (pi, x <= -1.0), (acos(x), True)) return tmp.subs(x, x) def eigs_2d(mat): a = mat[0, 0] + mat[1, 1] del...
PopStats/model.py
haoruilee/DeepSets
213
12793860
<filename>PopStats/model.py import torch import torch.nn as nn import torch.nn.functional as F # from loglinear import LogLinear class DeepSet(nn.Module): def __init__(self, in_features, set_features=50): super(DeepSet, self).__init__() self.in_features = in_features self.out_features = se...
test/hummingbot/core/data_type/test_trade_fee.py
pecuniafinance/hummingbot
542
12793864
from decimal import Decimal from unittest import TestCase from hummingbot.core.data_type.common import TradeType, PositionAction from hummingbot.core.data_type.in_flight_order import TradeUpdate from hummingbot.core.data_type.trade_fee import ( AddedToCostTradeFee, DeductedFromReturnsTradeFee, TokenAmount,...
mmdnn/conversion/examples/darknet/extractor.py
kmader/MMdnn
3,442
12793886
#---------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #------------------------------------------------------------------...
data/transcoder_evaluation_gfg/python/SCHEDULE_JOBS_SERVER_GETS_EQUAL_LOAD.py
mxl1n/CodeGen
241
12793887
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( a , b , n ) : s = 0 for i in range ( 0 , n ) : s += a [ i ] + b [ i ] if n == 1 : retur...
autograd/scipy/stats/beta.py
gautam1858/autograd
6,119
12793911
<gh_stars>1000+ from __future__ import absolute_import import autograd.numpy as np import scipy.stats from autograd.extend import primitive, defvjp from autograd.numpy.numpy_vjps import unbroadcast_f from autograd.scipy.special import beta, psi cdf = primitive(scipy.stats.beta.cdf) logpdf = primitive(scipy.stats.beta...
alembic/versions/140a25d5f185_create_tokens_table.py
alvierahman90/matrix-registration
160
12793914
"""create tokens table Revision ID: 1<PASSWORD> Revises: Create Date: 2020-12-12 01:44:28.195736 """ from alembic import op import sqlalchemy as sa from sqlalchemy import Table, Column, Integer, String, Boolean, DateTime, ForeignKey from sqlalchemy.engine.reflection import Inspector from flask_sqlalchemy import SQLA...
earth_enterprise/src/scons/packageUtils_test.py
ezeeyahoo/earthenterprise
2,661
12793916
<reponame>ezeeyahoo/earthenterprise #-*- Python -*- # # Copyright 2017 Google 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 # # Unle...
ch13/myproject_virtualenv/src/django-myproject/myproject/apps/likes/views.py
PacktPublishing/Django-3-Web-Development-Cookbook
159
12793928
<reponame>PacktPublishing/Django-3-Web-Development-Cookbook import structlog from django.contrib.contenttypes.models import ContentType from django.http import JsonResponse from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exempt from .models import Like from .templat...
notebooks-text-format/cond_bmm_emnist.py
arpitvaghela/probml-notebooks
166
12793940
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.3 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="M_qo7DmLJKLP" # #Class-Conditional Bernoulli Mixture Model...
python/tests/test_base.py
JLLeitschuh/DDF
160
12793941
from __future__ import unicode_literals import unittest from ddf import DDFManager, DDF_HOME class BaseTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.dm_spark = DDFManager('spark') cls.airlines = cls.loadAirlines(cls.dm_spark) cls.mtcars = cls.loadMtCars(cls.dm_spark) ...
datasets/code_x_glue_cc_cloze_testing_all/generated_definitions.py
WojciechKusa/datasets
10,608
12793960
DEFINITIONS = { "go": { "class_name": "CodeXGlueCcClozeTestingAll", "dataset_type": "Code-Code", "description": "CodeXGLUE ClozeTesting-all dataset, available at https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/ClozeTesting-all", "dir_name": "ClozeTesting-all", "nam...
docs/source/plots/var_plot_forecast.py
madhushree14/statsmodels
6,931
12793970
from var_plots import plot_forecast plot_forecast()
tests/anomaly/test_default.py
cnll0075/Merlion
2,215
12793976
# # Copyright (c) 2022 salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause # from abc import ABC import logging import os from os.path import abspath, dirname, join import sys i...
hal_fuzz/hal_fuzz/handlers/debug.py
diagprov/hal-fuzz
117
12793997
<gh_stars>100-1000 from unicorn.arm_const import * def stop(uc): print_context(uc) input("...") def print_context(uc): print("==== State ====") r0 = uc.reg_read(UC_ARM_REG_R0) r1 = uc.reg_read(UC_ARM_REG_R1) r2 = uc.reg_read(UC_ARM_REG_R2) r3 = uc.reg_read(UC_ARM_REG_R3) r4 = uc.reg_re...
python/interpret-core/interpret/ext/glassbox/__init__.py
prateekiiest/interpret
2,674
12794003
<reponame>prateekiiest/interpret<gh_stars>1000+ # Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license import sys from interpret.ext.extension_utils import load_class_extensions from interpret.ext.extension import GLASSBOX_EXTENSION_KEY, _is_valid_glassbox_explainer load_class_extensi...
awacs/devicefarm.py
alanjjenkins/awacs
358
12794005
<filename>awacs/devicefarm.py # 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 = "AWS Device Farm" prefix = "devicefarm" class Action(BaseAction): def __init__(self, action: str =...
tools/tube.py
fsanges/glTools
165
12794006
<filename>tools/tube.py<gh_stars>100-1000 import maya.cmds as mc import glTools.tools.controlBuilder import glTools.utils.attach import glTools.utils.base import glTools.utils.attribute import glTools.utils.component import glTools.utils.stringUtils def buildProfile(radius=1,spans=8): ''' Create tube profile curve...
program_synthesis/karel/scripts/eval_refinement.py
kavigupta/program_synthesis
123
12794018
import collections import cPickle as pickle import glob import itertools import json import operator import os import re import sys from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset.karel_runtime import KarelRuntime from progra...
第5章/program/Chapter_5_xpath_special.py
kingname/SourceCodeOfBook
274
12794048
import lxml.html html1 = ''' <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div id="test-1-k">需要的内容1</div> <div id="test-2-k">需要的内容2</div> <div id="testfault-k">需要的内容3</div> <div id="useless">这是我不需要的内容</div> </body> </html> ''' # selector = lxml...
examples/stockquotes-old/phase1/stockmarket.py
brubbel/Pyro4
638
12794051
<filename>examples/stockquotes-old/phase1/stockmarket.py import random class StockMarket(object): def __init__(self, marketname, symbols): self.name = marketname self.symbolmeans = {} for symbol in symbols: self.symbolmeans[symbol] = random.uniform(20, 200) self.aggrega...
env/lib/python3.6/site-packages/dal_queryset_sequence/tests/test_views.py
anthowen/duplify
1,368
12794099
<gh_stars>1000+ import json from dal import autocomplete from django import test from django.contrib.auth.models import Group class Select2QuerySetSequenceViewTestCase(test.TestCase): def setUp(self): self.expected = { 'pagination': { 'more': False }, ...
third_party/blink/renderer/bindings/scripts/idl_types.py
Ron423c/chromium
575
12794143
<filename>third_party/blink/renderer/bindings/scripts/idl_types.py # Copyright 2014 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. """IDL type handling. Classes: IdlTypeBase IdlType IdlUnionType IdlArrayOrSequenceType ...
src/rpdk/core/jsonutils/utils.py
zjinmei/cloudformation-cli
200
12794162
import hashlib import json import logging from collections.abc import Mapping, Sequence from typing import Any, List, Tuple from nested_lookup import nested_lookup from ordered_set import OrderedSet from .pointer import fragment_decode, fragment_encode LOG = logging.getLogger(__name__) NON_MERGABLE_KEYS = ("uniqueI...
src/nsupdate/utils/_tests/test_mail.py
mirzazulfan/nsupdate.info
774
12794179
<reponame>mirzazulfan/nsupdate.info """ Tests for mail module. """ from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from ..mail import translate_for_user class TestTransUser(object): def test(self): User = get_user_model() user = User.objects...
readthedocs/config/utils.py
tkoyama010/readthedocs.org
4,054
12794215
"""Shared functions for the config module.""" def to_dict(value): """Recursively transform a class from `config.models` to a dict.""" if hasattr(value, 'as_dict'): return value.as_dict() if isinstance(value, list): return [ to_dict(v) for v in value ] if...
tensorflow_graphics/projects/nasa/lib/utils.py
Liang813/graphics
2,759
12794237
# Copyright 2020 The TensorFlow 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
examples/exception.py
pawelmhm/scrapy-playwright
155
12794242
import logging from pathlib import Path from scrapy import Spider, Request from scrapy.crawler import CrawlerProcess from scrapy_playwright.page import PageCoroutine class HandleTimeoutMiddleware: def process_exception(self, request, exception, spider): logging.info("Caught exception: %s", exception.__cl...
tests/opening_test.py
karlch/vimiv
268
12794257
<reponame>karlch/vimiv # vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Test the opening of different file-types with vimiv.""" import os from unittest import main from vimiv_testcase import VimivTestCase class OpeningTest(VimivTestCase): """Open with different file-types Test.""" @classmethod def ...
docs/examples/robot_motion_1.py
codecademy-engineering/gpiozero
743
12794290
from gpiozero import Robot, Motor, MotionSensor from signal import pause robot = Robot(left=Motor(4, 14), right=Motor(17, 18)) pir = MotionSensor(5) pir.when_motion = robot.forward pir.when_no_motion = robot.stop pause()
doge/filter/__init__.py
zhu327/doge
163
12794336
from typing import Any from gevent.monkey import patch_thread # type: ignore from doge.common.doge import Executer, Request, Response from doge.common.utils import import_string patch_thread() class BaseFilter(Executer): def __init__(self, context: Any, _next: Executer): self.next = _next def exe...
DPGAnalysis/Skims/python/DoubleMuon_cfg.py
ckamtsikis/cmssw
852
12794360
<reponame>ckamtsikis/cmssw<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:/afs/cern.ch/cms/CAF/CMSCOMM/COMM_GLOBAL/CRUZET3/CMSSW_2_1_2/src/DPGAnalysis/Skims/python/re...
tests/spot/sub_account/test_sub_account_api_get_ip_restriction.py
Banging12/binance-connector-python
512
12794389
import responses import pytest from binance.spot import Spot as Client from tests.util import mock_http_response from tests.util import random_str from binance.lib.utils import encoded_string from binance.error import ParameterRequiredError mock_item = {"key_1": "value_1", "key_2": "value_2"} key = random_str() secr...
zella-graphics/animation/main.py
whitmans-max/python-examples
140
12794406
#!/usr/bin/env python3 # date: 2020.05.29 # It use normal loop to animate point and checkMouse to close program on click from graphics import * # PEP8: `import *` is not preferred import random import time # --- main --- win = GraphWin("My Window",500,500) win.setBackground(color_rgb(0,0,0)) pt = Point(250, 250) ...
parsifal/apps/activities/migrations/0003_auto_20210906_0158.py
ShivamPytho/parsifal
342
12794438
<reponame>ShivamPytho/parsifal # Generated by Django 3.2.6 on 2021-09-06 01:58 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reviews', '0035_auto_20210829_0005'), migrations.swa...
labs/03_neural_recsys/movielens_paramsearch_results.py
soufiomario/labs-Deep-learning
1,398
12794501
<filename>labs/03_neural_recsys/movielens_paramsearch_results.py import pandas as pd from pathlib import Path import json def load_results_df(folder='results'): folder = Path(folder) results_dicts = [] for p in sorted(folder.glob('**/results.json')): with p.open('r') as f: results_dicts...
bin/ipynb2rst.py
albapa/QUIP
229
12794512
#!/usr/bin/env python3 import sys import os import glob if len(sys.argv[1:]) == 0: dirs = [os.getcwd()] else: dirs = sys.argv[1:] for dir in dirs: for notebook in glob.glob(os.path.join(dir, '*.ipynb')): cmd = 'ipython nbconvert --to rst {0}'.format(notebook) print(cmd) os.system(...
tasks/__init__.py
vladcorneci/golden-gate
262
12794530
# Copyright 2017-2020 Fitbit, Inc # SPDX-License-Identifier: Apache-2.0 """ Invoke configuration for Golden Gate """ # First check that we are running in a Python >= 3.5 environment from __future__ import print_function import sys if not sys.version_info.major == 3 and sys.version_info.minor >= 5: print( """You a...
blackstone/rules/citation_rules.py
goro53467/Blackstone
541
12794535
CITATION_PATTERNS = [ { "label": "GENERIC_CASE_CITATION", "pattern": [ {"IS_BRACKET": True, "OP": "?"}, {"SHAPE": "dddd"}, {"IS_BRACKET": True, "OP": "?"}, {"LIKE_NUM": True, "OP": "?"}, {"TEXT": {"REGEX": "^[A-Z]"}, "OP": "?"}, ...
testing/adios2/bindings/python/TestBPSelectSteps_nompi.py
taniabanerjee/ADIOS2
190
12794560
<filename>testing/adios2/bindings/python/TestBPSelectSteps_nompi.py #!/usr/bin/env python # # Distributed under the OSI-approved Apache License, Version 2.0. See # accompanying file Copyright.txt for details. # # TestBPSelectSteps_nompi.py: test step selection by reading in Python # in ADIOS2 File Write # Created on:...
build/lib/pyconfluent/kafka_streams/processor/serialization/_bytes.py
newellp2019/pyconfluent
330
12794616
<reponame>newellp2019/pyconfluent from .deserializer import Deserializer from .serializer import Serializer class BytesSerializer(Serializer[bytes]): def serialize(self, topic: str, data: bytes) -> bytes: return data def configure(self, configs, is_key): pass def close(self): pas...
pytorchvideo/models/net.py
kevinmtian/pytorchvideo
2,391
12794664
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from typing import List, Optional import torch import torch.nn as nn from pytorchvideo.layers.utils import set_attributes from pytorchvideo.models.weight_init import init_net_weights class Net(nn.Module): """ Build a general Net models ...
scripts/legacy/make_maestro_index.py
lucaspbastos/mirdata
224
12794719
import argparse import hashlib import json import csv import os MAESTRO_INDEX_PATH = '../mirdata/indexes/maestro_index.json' def md5(file_path): """Get md5 hash of a file. Parameters ---------- file_path: str File path. Returns ------- md5_hash: str md5 hash of data in ...
mmdnn/conversion/tensorflow/rewriter/lstm_rewriter.py
kmader/MMdnn
3,442
12794728
from mmdnn.conversion.rewriter.rewriter import UnitRewriterBase import numpy as np import re class LSTMRewriter(UnitRewriterBase): def __init__(self, graph, weights_dict): return super(LSTMRewriter, self).__init__(graph, weights_dict) def process_lstm_cell(self, match_result): if 'lstm_cell...
esphome/components/nextion/base_component.py
OttoWinter/esphomeyaml
249
12794740
from string import ascii_letters, digits import esphome.config_validation as cv import esphome.codegen as cg from esphome.components import color from esphome.const import ( CONF_VISIBLE, ) from . import CONF_NEXTION_ID from . import Nextion CONF_VARIABLE_NAME = "variable_name" CONF_COMPONENT_NAME = "component_nam...
benchmark/bench_dd.py
Watch-Later/recipes
1,418
12794764
<reponame>Watch-Later/recipes #!/usr/bin/python3 import re, subprocess bs = 1 count = 1024 * 1024 while bs <= 1024 * 1024 * 8: args = ['dd', 'if=/dev/zero', 'of=/dev/null', 'bs=%d' % bs, 'count=%d' % count] result = subprocess.run(args, capture_output=True) seconds = 0 message = str(result.stderr) ...
library/connecter/ansible/yaml/read2file.py
GNHJM/lykops
141
12794776
import os from library.connecter.ansible.yaml import Yaml_Base from library.utils.file import read_file from library.utils.path import get_pathlist class Read_File(Yaml_Base): def router(self, this_path, this_basedir=None, yaml_tpye='main', preserve=True, together=False, name='', describe=''): ...
lib-other/pylib/consensus/test/test_consensus.py
endolith/Truthcoin
161
12794789
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for Truthcoin's consensus functions. Verifies that the consensus algorithm works as expected. Check test_answers.txt for expected results. """ from __future__ import division, unicode_literals, absolute_import import os import sys import platform import json impo...
ikalog/ui/panel/preview.py
fetus-hina/IkaLog
285
12794808
<gh_stars>100-1000 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 <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 # # http://www.apa...
3d-tracking/tools/visualize_kitti.py
sadjadasghari/3d-vehicle-tracking
603
12794829
import os import re import sys import argparse import json import numpy as np from glob import glob import cv2 from utils.plot_utils import RandomColor def parse_args(): parser = argparse.ArgumentParser( description='Monocular 3D Tracking Visualizer', formatter_class=argpa...
test/single/test_task_service.py
Infi-zc/horovod
7,676
12794832
# Copyright 2021 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
cut_twist_process/cut_part.py
ericosmic/2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement
886
12794837
# -*- coding: utf-8 -*- # @Time : 19-11-19 22:25 # @Author : <NAME> # @Reference : None # @File : cut_twist_join.py # @IDE : PyCharm Community Edition """ 将身份证正反面从原始图片中切分出来。 需要的参数有: 1.图片所在路径。 输出结果为: 切分后的身份证正反面图片。 """ import os import cv2 import numpy ...
finance_ml/sampling/utils.py
BTETON/finance_ml
446
12794839
<gh_stars>100-1000 import pandas as pd def get_ind_matrix(bar_idx, t1): ind_m = pd.DataFrame(0, index=bar_idx, columns=range(t1.shape[0])) for i, (t0_, t1_) in enumerate(t1.iteritems()): ind_m.loc[t0_:t1_, i] = 1 return ind_m def get_avg_uniq(ind_m, c=None): if c is ...
atlas/foundations_contrib/src/test/helpers/test_lazy_redis.py
DeepLearnI/atlas
296
12794846
<filename>atlas/foundations_contrib/src/test/helpers/test_lazy_redis.py import unittest from mock import Mock from foundations_contrib.helpers.lazy_redis import LazyRedis class TestLazyRedis(unittest.TestCase): class MockObject(object): def __init__(self): self.value = 5 self.nam...
OnlineStudy/rbac/service/routers.py
NanRenTeam-9/MongoMicroCourse
132
12794873
from collections import OrderedDict from django.utils.module_loading import import_string from django.conf import settings from django.urls.resolvers import URLResolver, URLPattern import re def check_url_exclude(url): for regex in settings.AUTO_DISCOVER_EXCLUDE: if re.match(regex, url): retur...
baselines/neural_best_buddies/get_missing.py
iviazovetskyi/rewriting
526
12794875
<reponame>iviazovetskyi/rewriting import os from netdissect import pidfile from options.options import Options from tqdm import tqdm opt = Options().parse() def get_imgs(): img_nums = sorted([int(f.strip().split(f'{base_name}_')[1].split('.')[0]) for f in os.listdir(opt.source)]) file_names = [f'{base_name}_{...
scripts/deepimpact/brute-force.py
d1shs0ap/pyserini
451
12794942
import argparse import json import os from scipy.sparse import csr_matrix from tqdm import tqdm import numpy as np from multiprocessing import Pool, Manager def token_dict_to_sparse_vector(token_dict, token2id): matrix_row, matrix_col, matrix_data = [], [], [] tokens = token_dict.keys() col = [] data...
notebooks/snippets/nbody/create_n.py
IsabelAverill/Scipy-2017---Numba
149
12794944
@njit def create_n_random_particles(n, m, domain=1): ''' Creates `n` particles with mass `m` with random coordinates between 0 and `domain` ''' parts = numpy.zeros((n), dtype=particle_dtype) #attribute access only in @jitted function for p in parts: p.x = numpy.random.random() * doma...
A1014280203/6/6.py
saurabh896/python-1
3,976
12794947
<filename>A1014280203/6/6.py import nltk import string import os # simply extend word like: it's => it is def extend_word(text): if text.find('\'') > 0: old2new = dict() words = text.split() for word in words: if word.find('\'') > 0: parts = word.spl...
tests/test_logic/test_tree/test_functions.py
cdhiraj40/wemake-python-styleguide
1,931
12794962
import pytest from wemake_python_styleguide.logic.tree import functions @pytest.mark.parametrize(('function_call', 'function_name'), [ # Simple builtin functions ('print("Hello world!")', 'print'), ('int("10")', 'int'), ('bool(1)', 'bool'), ('open("/tmp/file.txt", "r")', 'open'), ('str(10)', ...
microsoft_problems/problem_9.py
loftwah/Daily-Coding-Problem
129
12794964
"""This problem was asked Microsoft. Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters. For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”. """
weld-python/weld/grizzly/core/indexes/base.py
tustvold/weld
2,912
12794966
<gh_stars>1000+ from abc import ABC class Index(ABC): """ Base class for an index in Grizzly. """ pass
tests/pyconverter-test/cases/array_generics2.py
jaydeetay/pxt
977
12794984
<gh_stars>100-1000 obstacles: List[List[number]] = [] obstacles.removeAt(0).removeAt(0)
tests/test_model_field_list.py
havron/wtforms-alchemy
161
12795024
<gh_stars>100-1000 import sqlalchemy as sa from wtforms.fields import FormField from wtforms_components import PassiveHiddenField from tests import FormRelationsTestCase, MultiDict from wtforms_alchemy import ModelFieldList, ModelForm class ModelFieldListTestCase(FormRelationsTestCase): def create_models(self): ...
alipay/aop/api/domain/SsdataDataserviceDatapropertyBatchqueryModel.py
antopen/alipay-sdk-python-all
213
12795081
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class SsdataDataserviceDatapropertyBatchqueryModel(object): def __init__(self): self._action = None self._action_param = None self._base = None self._data_channel = None...
ajax_datatable/templatetags/ajax_datatable_tags.py
ivi3/django-ajax-datatable
101
12795100
<gh_stars>100-1000 from django import template register = template.Library() ################################################################################ # Support for generic editing in the front-end @register.filter def model_verbose_name(model): """ Sample usage: {{model|model_name}} """ ...
Machine Learning/TensorflowExamples/simple_gradient_descent.py
sarojjethva/Learning-Resources
639
12795104
""" Author: <NAME> Github: github.com/yashbmewada Program for demonstrating simple line fitting using Tensorflow and Gradient Descent Algorithm This program trains the model to fit two values, slope(m) and x-intercept(b) in the equation of line y=mx+b. Here we would provide very small dataset of randomly generated po...
admin/client.py
stackriot/flocker
2,690
12795128
# Copyright 2015 ClusterHQ Inc. See LICENSE file for details. """ Run the client installation tests. """ import os import shutil import sys import tempfile from characteristic import attributes import docker from effect import TypeDispatcher, sync_performer, perform from twisted.python.usage import Options, UsageErr...
Notebooks/Visualization/DataReader.py
keuntaeklee/pytorch-PPUU
159
12795171
"""A class with static methods which can be used to access the data about experiments. This includes reading logs to parse success cases, reading images, costs and speed. """ import numpy as np from glob import glob import torch import pandas import re import json from functools import lru_cache import imageio EPISO...
src/genie/libs/parser/iosxe/tests/ShowLldpNeighborsDetail/cli/equal/golden_output_3_expected.py
balmasea/genieparser
204
12795172
expected_output = { "interfaces": { "GigabitEthernet1/0/32": { "if_name": "GigabitEthernet1/0/32", "port_id": { "222": { "neighbors": { "not advertised": { "neighbor_id": "not advertised", ...
tests/contrib/backends/hbase/test_domain_cache.py
buildfail/frontera
1,267
12795213
<filename>tests/contrib/backends/hbase/test_domain_cache.py<gh_stars>1000+ # -*- coding: utf-8 -*- from frontera.contrib.backends.hbase.domaincache import DomainCache from happybase import Connection import logging import unittest class TestDomainCache(unittest.TestCase): def setUp(self): logging.basicCon...
examples/util/lookups.py
OptionMetrics/petl
495
12795257
from __future__ import division, print_function, absolute_import # lookup() ########## import petl as etl table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['b', 3]] lkp = etl.lookup(table1, 'foo', 'bar') lkp['a'] lkp['b'] # if no valuespec argument is given, defaults to the whole # row ...