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
cruft/__main__.py
tdhopper/cruft
293
98356
<filename>cruft/__main__.py from cruft import _cli _cli.app(prog_name="cruft")
packages/pytea/pylib/torch/backends/cudnn/__init__.py
Sehun0819/pytea
241
98362
enabled = True deterministic = False benchmark = False
src/opendr/perception/compressive_learning/multilinear_compressive_learning/algorithm/backbones/model_utils.py
ad-daniel/opendr
217
98388
<reponame>ad-daniel/opendr<gh_stars>100-1000 # Copyright 2020-2022 OpenDR European Project # # 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 #...
myia/debug/traceback.py
strint/myia
222
98389
<reponame>strint/myia """Tools to print a traceback for an error in Myia.""" import ast import sys import warnings import prettyprinter as pp from colorama import Fore, Style from ..abstract import Reference, data, format_abstract, pretty_struct from ..ir import ANFNode, Graph from ..parser import Location, MyiaDisc...
scripts/crimson_rewriter.py
upenderadepu/crimson
108
98395
# coding: utf-8 # # ### CREATED BY KARMAZ # ### FUNCTIONS # # 1. CHECK IF X-Original-Url AND X-Rewrite-Url IS HANDLED BY THE SERVER # ### import sys, getopt, requests, urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) from tqdm import tqdm ### OPTIONS --- argument_list = sys.argv[1:] short_o...
examples/volumetric/streamlines2.py
hadivafaii/vedo
836
98396
"""Load an existing vtkStructuredGrid and draw the streamlines of the velocity field""" from vedo import * ######################## vtk import vtk # Read the data and specify which scalars and vectors to read. pl3d = vtk.vtkMultiBlockPLOT3DReader() fpath = download(dataurl+"combxyz.bin") pl3d.SetXYZFileName(fpath) fpa...
api/conftest.py
SolidStateGroup/Bullet-Train-API
126
98430
import pytest from django.core.cache import cache from rest_framework.test import APIClient from environments.identities.models import Identity from environments.identities.traits.models import Trait from environments.models import Environment from features.feature_types import MULTIVARIATE from features.models import...
tests/trac/trac-0196/check.py
eLBati/pyxb
123
98435
# -*- coding: utf-8 -*- from __future__ import print_function import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import unittest import qq0196 as qq import qu0196 as qu import uq0196 as uq import uu0196 as uu import mix from pyxb.utils.domutils import BindingDOMSuppo...
homeassistant/components/radio_browser/__init__.py
MrDelik/core
30,023
98437
<reponame>MrDelik/core<filename>homeassistant/components/radio_browser/__init__.py """The Radio Browser integration.""" from __future__ import annotations from radios import RadioBrowser, RadioBrowserError from homeassistant.config_entries import ConfigEntry from homeassistant.const import __version__ from homeassist...
preprocess/crop_video_sequences.py
ashish-roopan/fsgan
599
98503
import os import sys import pickle from tqdm import tqdm import numpy as np import cv2 from fsgan.utils.bbox_utils import scale_bbox, crop_img from fsgan.utils.video_utils import Sequence def main(input_path, output_dir=None, cache_path=None, seq_postfix='_dsfd_seq.pkl', resolution=256, crop_scale=2.0, selec...
Day3/Python/hamming.py
Grace0Hud/dailycodebase
249
98507
""" @author : udisinghania @date : 24/12/2018 """ string1 = input() string2 = input() a = 0 if len(string1)!=len(string2): print("Strings are of different length") else: for i in range (len(string1)): if string1[i]!=string2[i]: a+=1 print(a)
networkx/algorithms/centrality/tests/test_second_order_centrality.py
rakschahsa/networkx
445
98524
""" Tests for second order centrality. """ import networkx as nx from nose import SkipTest from nose.tools import raises, assert_almost_equal class TestSecondOrderCentrality(object): numpy = 1 # nosetests attribute, use nosetests -a 'not numpy' to skip test @classmethod def setupClass(cls): glo...
mindspore_hub/_utils/download.py
mindspore-ai/hub
153
98541
<filename>mindspore_hub/_utils/download.py # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
collection/models.py
mihaivavram/twitterbots
141
98548
from sqlalchemy import (create_engine, Column, Integer, String, DateTime, Boolean, BigInteger) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session from datetime import datetime import os """A cache for storing account details as they a...
media/tools/constrained_network_server/traffic_control_test.py
zealoussnow/chromium
14,668
98554
#!/usr/bin/env python # Copyright (c) 2012 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. """End-to-end tests for traffic control library.""" import os import re import sys import unittest import traffic_control class...
artemis/plotting/fast.py
peteroconnor-bc/artemis
235
98561
<reponame>peteroconnor-bc/artemis try: from scipy import weave except ImportError: print("Cannot Import scipy weave. That's ok for now, you won't be able to use the fastplot function.") __author__ = 'peter' import numpy as np import matplotlib.pyplot as plt """ Functions to speed up pylab plotting, which can ...
tests/test_cli.py
pgjones/quart
1,085
98606
<gh_stars>1000+ from __future__ import annotations import code import os from unittest.mock import Mock import pytest from _pytest.monkeypatch import MonkeyPatch from click.testing import CliRunner import quart.cli from quart.app import Quart from quart.cli import __version__, AppGroup, cli, NoAppException, ScriptIn...
tests/api/endpoints/admin/test_abuse_reports.py
weimens/seahub
420
98621
# -*- coding: utf-8 -*- import json from mock import patch, MagicMock from django.urls import reverse from seahub.test_utils import BaseTestCase from seahub.abuse_reports.models import AbuseReport class AdminAbuseReportsTest(BaseTestCase): def setUp(self): self.login_as(self.admin) self.url = re...
openmdao/test_suite/matrices/dl_matrix.py
friedenhe/OpenMDAO
451
98645
<gh_stars>100-1000 """ Download a Matlab matrix file from sparse.tamu.edu and save it locally. """ import sys import scipy.io import urllib.request def download_matfile(group, name, outfile="matrix.out"): """ Downloads a matrix file (matlab format) from sparse.tamu.edu and returns the matrix. """ with...
tests/api/conftest.py
corvust/strawberryfields
646
98651
# Copyright 2020 Xanadu Quantum Technologies 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 agre...
configs/mmpose/pose-detection_static.py
xizi/mmdeploy
746
98665
_base_ = ['../_base_/onnx_config.py'] codebase_config = dict(type='mmpose', task='PoseDetection')
flatdata-generator/flatdata/generator/tree/nodes/explicit_reference.py
gferon/flatdata
140
98730
from flatdata.generator.tree.nodes.node import Node from flatdata.generator.tree.nodes.references import ResourceReference, FieldReference, StructureReference class ExplicitReference(Node): def __init__(self, name, properties=None): super().__init__(name=name, properties=properties) @staticmethod ...
torchdiffeq/_impl/fixed_adams.py
MaricelaM/torchdiffeq
4,088
98735
<reponame>MaricelaM/torchdiffeq import collections import sys import torch import warnings from .solvers import FixedGridODESolver from .misc import _compute_error_ratio, _linf_norm from .misc import Perturb from .rk_common import rk4_alt_step_func _BASHFORTH_COEFFICIENTS = [ [], # order 0 [11], [3, -1], ...
test/test_group_model.py
zuarbase/server-client-python
470
98780
<reponame>zuarbase/server-client-python import unittest import tableauserverclient as TSC class GroupModelTests(unittest.TestCase): def test_invalid_name(self): self.assertRaises(ValueError, TSC.GroupItem, None) self.assertRaises(ValueError, TSC.GroupItem, "") group = TSC.GroupItem("grp") ...
run.py
liushengzhong1023/multihead-siamese-nets
175
98788
<filename>run.py import time from argparse import ArgumentParser import tensorflow as tf from tqdm import tqdm from data import dataset_type from data.dataset import Dataset from models import model_type from models.model_type import MODELS from utils.batch_helper import BatchHelper from utils.config_helpers import M...
polaris_common/topology.py
gribnut/polaris-gslb
225
98869
# -*- coding: utf-8 -*- import ipaddress __all__ = [ 'config_to_map', 'get_region' ] def config_to_map(topology_config): """ args: topology_config: dict { 'region1': [ '10.1.1.0/24', '10.1.10.0/24', '172.1...
58.左旋转字符串/58.左旋转字符串.py
shenweichen/coding_interviews
483
98878
# -*- coding:utf-8 -*- class Solution: def LeftRotateString(self, s, n): # write code here if len(s)==0: return s s = list(s) def flip(s,start,end): for i in range(start,(start+end)//2 + 1): s[i],s[end-i+start] = s[end - i+start],s[i] ...
examples/wav2vec/unsupervised/scripts/mean_pool.py
Shiguang-Guo/fairseq
16,259
98880
#!/usr/bin/env python3 -u # 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. import argparse import os import os.path as osp import math import numpy as np import tqdm import torch import torch...
openbook_moderation/migrations/0014_auto_20191205_1704.py
TamaraAbells/okuna-api
164
98947
# Generated by Django 2.2.5 on 2019-12-05 16:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('openbook_moderation', '0013_auto_20190909_1236'), ] operations = [ migrations.AlterField( model_name='moderatedobject', ...
examples/04_krige_geometric.py
ehxan139/PyKrige
280
98955
# -*- coding: utf-8 -*- """ Geometric example ================= A small example script showing the usage of the 'geographic' coordinates type for ordinary kriging on a sphere. """ from pykrige.ok import OrdinaryKriging import numpy as np from matplotlib import pyplot as plt # Make this example reproducible: np.rand...
functorch/_src/cse.py
pytorch/functorch
423
98981
import torch import torch.fx as fx from torch.utils._pytree import tree_flatten aten = torch.ops.aten rand_ops = [aten.dropout, aten._fused_dropout, aten._standard_gamma, aten.bernoulli, aten.multinomial, aten.native_dropout, aten.normal, aten.poisson, aten.binomial, aten.rrelu, ate...
moshmosh/rewrite_helper.py
Aloxaf/moshmosh
114
99020
<gh_stars>100-1000 import ast def ast_to_literal(node): """ Convert an AST to a python literal. We avoid the use of comprehension expressions here to get more human-friendly call stacks. """ if isinstance(node, ast.AST): field_names = node._fields res = {'constructor': node.__c...
rpython/jit/backend/ppc/test/test_ztranslation_call_assembler.py
nanjekyejoannah/pypy
381
99031
from rpython.jit.backend.llsupport.test.ztranslation_test import TranslationTestCallAssembler class TestTranslationCallAssemblerPPC(TranslationTestCallAssembler): pass
cockpit/instruments/grad_norm_gauge.py
wx-b/cockpit
367
99036
<reponame>wx-b/cockpit """Gradient Norm Gauge.""" import warnings from cockpit.instruments.utils_instruments import check_data, create_basic_plot from cockpit.quantities.utils_quantities import _root_sum_of_squares def grad_norm_gauge(self, fig, gridspec): """Showing the gradient norm versus iteration. If ...
tests/r/test_macdonell_df.py
hajime9652/observations
199
99058
<gh_stars>100-1000 from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.macdonell_df import macdonell_df def test_macdonell_df(): """Test module macdonell_df.py by downloading macdonell_df.csv a...
xnu-4903.241.1/tools/lldbmacros/ntstat.py
DogeCoding/iOSCompiledRuntime
672
99080
<filename>xnu-4903.241.1/tools/lldbmacros/ntstat.py """ Please make sure you read the README COMPLETELY BEFORE reading anything below. It is very critical that you read coding guidelines in Section E in README file. """ from xnu import * from utils import * from string import * from socket import * import xnudefi...
tests/cloudcraft_graph_test.py
tjunnone/modules.tf-lambda
312
99087
<filename>tests/cloudcraft_graph_test.py<gh_stars>100-1000 # #!/usr/bin/env pytest # # from json import loads # from os import environ # # import pytest # from modulestf.cloudcraft.graph import populate_graph # # events = ( # ( # { # "AlarmType": "Unsupported alarm type", # "AWSAccountId": "00...
source/speech/priorities.py
marlon-sousa/nvda
1,592
99097
<filename>source/speech/priorities.py # -*- coding: UTF-8 -*- # A part of NonVisual Desktop Access (NVDA) # This file is covered by the GNU General Public License. # See the file COPYING for more details. # Copyright (C) 2017-2019 NV Access Limited, Babbage B.V. """Speech priority enumeration.""" from enum import Int...
scripts/obtain_video_id.py
shirayu/jtubespeech
108
99175
<filename>scripts/obtain_video_id.py import time import requests import argparse import re import sys from pathlib import Path from util import make_query_url from tqdm import tqdm def parse_args(): parser = argparse.ArgumentParser( description="Obtaining video IDs from search words", formatter_class=argpar...
build/build/void/makepkg/astroid/src/astroid/site_scons/site_tools/notmuch_test_db.py
scobiehague/dotfiles
117
99185
import SCons.Builder import os import shutil from subprocess import Popen def nmAction(target, source, env): ''' set up notmuch test db in target directory ''' config = os.path.abspath(os.path.join (os.path.curdir, 'test/mail/test_config')) env['ENV']['NOTMUCH_CONFIG'] = config # run notmuch myenv = o...
earth_enterprise/src/server/wsgi/search/common/exceptions.py
ezeeyahoo/earthenterprise
2,661
99205
<reponame>ezeeyahoo/earthenterprise #!/usr/bin/env python2.7 # # 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...
examples/three_link_conical_pendulum/derive.py
JanMV/pydy
298
99207
<reponame>JanMV/pydy<gh_stars>100-1000 #!/usr/bin/env python from sympy import symbols import sympy.physics.mechanics as me print("Defining the problem.") # The conical pendulum will have three links and three bobs. n = 3 # Each link's orientation is described by two spaced fixed angles: alpha and # beta. # Genera...
Coach.py
morozig/muzero
111
99225
""" Define the base self-play/ data gathering class. This class should work with any MCTS-based neural network learning algorithm like AlphaZero or MuZero. Self-play, model-fitting, and pitting is performed sequentially on a single-thread in this default implementation. Notes: - Code adapted from https://github.com/s...
scripts/pyxtal_test.py
ubikpt/PyXtal
127
99228
<filename>scripts/pyxtal_test.py #!/usr/bin/env python # encoding: utf-8 # Test script for pyXtal v-0.1.4. Tests core functions for all modules. import sys import numpy as np import warnings from time import time from copy import deepcopy from spglib import get_symmetry_dataset from pymatgen.symmetry.analyzer imp...
recipes/Python/578828_Indexing_text_files_with_Python/recipe-578828.py
tdiprima/code
2,023
99249
<reponame>tdiprima/code """ text_file_indexer.py A program to index a text file. Author: <NAME> - www.dancingbison.com Copyright 2014 <NAME> Given a text file somefile.txt, the program will read it completely, and while doing so, record the occurrences of each unique word, and the line numbers on which they occur. Th...
imapfw/conf/__init__.py
paralax/imapfw
492
99250
<reponame>paralax/imapfw from .conf import ImapfwConfig from .clioptions import Parser
src/sage/categories/commutative_algebras.py
bopopescu/sage
1,742
99295
r""" Commutative algebras """ #***************************************************************************** # Copyright (C) 2005 <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # 2008-2009 <NAME> <nthiery at users.sf.net> # # Distributed under the terms of the GNU General Public Lice...
test/integration/expected_out_single_line/percent_dict.py
Inveracity/flynt
487
99344
<reponame>Inveracity/flynt<gh_stars>100-1000 a = 2 b = "wuga" print(f'{a:f} {b}')
parsifal/apps/reviews/tests/test_new_review_view.py
ShivamPytho/parsifal
342
99352
<filename>parsifal/apps/reviews/tests/test_new_review_view.py<gh_stars>100-1000 from django.test.testcases import TestCase from django.urls import reverse from parsifal.apps.authentication.tests.factories import UserFactory from parsifal.apps.reviews.tests.factories import ReviewFactory from parsifal.utils.test import...
Unit 9 Dry-Gas Reservoirs/functions/drygas_equivalence.py
datasolver/reservoir-engineering
139
99354
def condensate_to_gas_equivalence(api, stb): "Derivation from real gas equation" Tsc = 519.57 # standard temp in Rankine psc = 14.7 # standard pressure in psi R = 10.732 rho_w = 350.16 # water density in lbm/STB so = 141.5 / (api + 131.5) # so: specific gravity of oil (dimensionless) Mo = 5854 / (api - 8...
solutions/problem_008.py
ksvr444/daily-coding-problem
1,921
99376
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def __repr__(self): return str(self.data) def count_unival_trees(root): if not root: return 0 elif not root.left and not root.right: return 1 elif not root....
plugins/logging/syslog/__init__.py
madflojo/automon
414
99382
''' Syslog logging handler ''' import logging import logging.handlers import sys from core.logs import BaseLogging class Logger(BaseLogging): ''' Handler class for Syslog Logging ''' def setup(self): ''' Setup class for handler ''' lh = logging.handlers.SysLogHandler( facility=sel...
driver_55x4.py
mpi3d/goodix-fp-dump
136
99392
from hashlib import sha256 from hmac import new as hmac from random import randint from re import fullmatch from socket import socket from struct import pack as encode from subprocess import PIPE, STDOUT, Popen from crcmod.predefined import mkCrcFun from goodix import FLAGS_TRANSPORT_LAYER_SECURITY_DATA, Device from ...
updater/reports/ReportGitVersionsNew.py
eisenhowerj/hubble
146
99406
from .ReportDaily import * # Lists which git version was used by how many users yesterday class ReportGitVersionsNew(ReportDaily): def name(self): return "git-versions-new" def updateDailyData(self): newHeader, newData = self.parseData( self.executeScript(self.scriptPath("git-versions.sh"))) self.header =...
meshpy/meshpy/lighting.py
peter0749/PointNetGPD
193
99427
""" Classes for lighting in renderer Author: <NAME> """ import numpy as np from autolab_core import RigidTransform class Color(object): WHITE = np.array([255, 255, 255]) BLACK = np.array([0, 0, 0]) RED = np.array([255, 0, 0]) GREEN = np.array([0, 255, 0]) BLUE = np.array([0, 0, 255]) class Mat...
CalibMuon/DTCalibration/python/dtVDriftSegmentCalibration_cfi.py
ckamtsikis/cmssw
852
99453
import FWCore.ParameterSet.Config as cms from CalibMuon.DTCalibration.dtSegmentSelection_cfi import dtSegmentSelection dtVDriftSegmentCalibration = cms.EDAnalyzer("DTVDriftSegmentCalibration", # Segment selection dtSegmentSelection, recHits4DLabel = cms.InputTag('dt4DSegments'), rootFileName = cms.unt...
ichnaea/models/api.py
mikiec84/ichnaea
348
99469
from sqlalchemy import Boolean, Column, String from sqlalchemy.dialects.mysql import INTEGER as Integer, TINYINT as TinyInteger from ichnaea.models.base import _Model class ApiKey(_Model): """ ApiKey model. The allow_fallback and fallback columns determine if and what fallback location provider shou...
profiles/views/billing_group_views.py
Sispheor/squest
112
99509
<filename>profiles/views/billing_group_views.py from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.models import User from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from django.utils.safestring import mark_safe from profiles.forms impo...
keras/downstream_tasks/BraTS/DataSet.py
joeranbosma/ModelsGenesis
574
99510
#!/usr/bin/env python """ File: DataSet Date: 5/1/18 Author: <NAME> (<EMAIL>) This file provides loading of the BraTS datasets for ease of use in TensorFlow models. """ import os import pandas as pd import numpy as np import nibabel as nib from tqdm import tqdm from BraTS.Patient import * from BraTS.structure impo...
components/gcp/container/component_sdk/python/kfp_component/google/dataproc/_submit_job.py
TheDutchDevil/pipelines
102
99581
# Copyright 2018 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 to in writing, ...
samples/advanced/authentication.py
amerkel2/azure-storage-python
348
99582
# coding: utf-8 from azure.storage.blob import BlockBlobService # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------...
examples/mhsa.py
Siyuan89/self-attention-cv
759
99597
<gh_stars>100-1000 import torch from self_attention_cv import MultiHeadSelfAttention model = MultiHeadSelfAttention(dim=64) x = torch.rand(16, 10, 64) # [batch, tokens, dim] mask = torch.zeros(10, 10) # tokens X tokens mask[5:8, 5:8] = 1 y = model(x, mask) assert y.shape == x.shape print("MultiHeadSelfAttentionAISu...
pyocd/utility/server.py
claymation/pyOCD
276
99639
<filename>pyocd/utility/server.py # pyOCD debugger # Copyright (c) 2015-2019 Arm Limited # Copyright (c) 2021 <NAME> # SPDX-License-Identifier: Apache-2.0 # # 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...
epg.py
jerocobo/LegalStream
365
99656
<reponame>jerocobo/LegalStream<filename>epg.py import datetime import string import math def ToDay(): global year year = datetime.datetime.now().year global month month = '%02d' % datetime.datetime.now().month global day day = '%02d' % datetime.datetime.today().day global hour hour = '%0...
survae/tests/transforms/bijections/coupling/coupling_linear.py
alisiahkoohi/survae_flows
262
99673
import numpy as np import torch import torch.nn as nn import torchtestcase import unittest from survae.transforms.bijections.coupling import * from survae.nn.layers import ElementwiseParams, ElementwiseParams2d from survae.tests.transforms.bijections import BijectionTest class AdditiveCouplingBijectionTest(BijectionT...
examples/reverb.py
Bakkom/micropython
594
99689
<reponame>Bakkom/micropython import audio def from_file(file, frame): ln = -1 while ln: ln = file.readinto(frame) yield frame def reverb_gen(src, buckets, reflect, fadeout): bucket_count = len(buckets) bucket = 0 for frame in src: echo = buckets[bucket] echo *= refl...
WebMirror/management/rss_parser_funcs/feed_parse_extractThehlifestyleCom.py
fake-name/ReadableWebProxy
193
99731
def extractThehlifestyleCom(item): ''' Parser for 'thehlifestyle.com' ''' tstr = str(item['tags']).lower() if 'review' in tstr: return None if 'actors' in tstr: return None if 'game' in tstr: return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "...
alipay/aop/api/domain/AlipayMarketingCampaignRuleCrowdCreateModel.py
snowxmas/alipay-sdk-python-all
213
99733
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayMarketingCampaignRuleCrowdCreateModel(object): def __init__(self): self._mdatacrowdsource = None self._mpid = None self._ruledesc = None @property def mdata...
corehq/apps/userreports/tests/test_report_data.py
dimagilg/commcare-hq
471
99755
<gh_stars>100-1000 import uuid from collections import namedtuple from django.test import TestCase from corehq.apps.userreports.models import ( DataSourceConfiguration, ReportConfiguration, ) from corehq.apps.userreports.reports.data_source import ( ConfigurableReportDataSource, ) from corehq.apps.userrep...
janitor/functions/to_datetime.py
thatlittleboy/pyjanitor
225
99832
from typing import Hashable import pandas_flavor as pf import pandas as pd from janitor.utils import deprecated_alias @pf.register_dataframe_method @deprecated_alias(column="column_name") def to_datetime( df: pd.DataFrame, column_name: Hashable, **kwargs ) -> pd.DataFrame: """Convert column to a datetime typ...
babi/cached_property.py
ClasherKasten/babi
223
99875
<reponame>ClasherKasten/babi from __future__ import annotations import sys if sys.version_info >= (3, 8): # pragma: >=3.8 cover from functools import cached_property else: # pragma: <3.8 cover from typing import Callable from typing import Generic from typing import TypeVar TSelf = TypeVar('TSe...
cookbook/mesher_tesseroidmesh.py
XuesongDing/fatiando
179
99876
""" Meshing: Make and plot a tesseroid mesh """ from fatiando import mesher from fatiando.vis import myv mesh = mesher.TesseroidMesh((-60, 60, -30, 30, 100000, -500000), (10, 10, 10)) myv.figure(zdown=False) myv.tesseroids(mesh) myv.earth(opacity=0.3) myv.continents() myv.meridians(range(-180, 180, 30)) myv.parallels...
alipay/aop/api/domain/HealthServiceSku.py
antopen/alipay-sdk-python-all
213
99913
<filename>alipay/aop/api/domain/HealthServiceSku.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class HealthServiceSku(object): def __init__(self): self._merchant_item_sku_bar_code = None self._sku_id = None @property de...
examples/pytorch/diffpool/model/dgl_layers/__init__.py
ketyi/dgl
9,516
99930
<reponame>ketyi/dgl from .gnn import GraphSage, GraphSageLayer, DiffPoolBatchedGraphLayer
kmip/tests/unit/core/messages/payloads/test_modify_attribute.py
ondrap/PyKMIP
179
99960
<gh_stars>100-1000 # Copyright (c) 2019 The Johns Hopkins University/Applied Physics Laboratory # 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...
devices/filters.py
maznu/peering-manager
127
99978
import django_filters from django.db.models import Q from devices.enums import PasswordAlgorithm from devices.models import Configuration, Platform from utils.filters import ( BaseFilterSet, CreatedUpdatedFilterSet, NameSlugSearchFilterSet, TagFilter, ) class ConfigurationFilterSet(BaseFilterSet, Cre...
tests/helper.py
rahulbahal7/restricted-python
236
99990
from RestrictedPython import compile_restricted_eval from RestrictedPython import compile_restricted_exec import RestrictedPython.Guards def _compile(compile_func, source): """Compile some source with a compile func.""" result = compile_func(source) assert result.errors == (), result.errors assert re...
src/sensing/drivers/radar/umrr_driver/src/smartmicro/Services/basicCanServices/canService.py
P4nos/Aslan
227
100017
import queue import struct class CanIDService: """ Can ID service interface class. This interface class has to be used to implement any can id based service that shall have be able to be registered with the communication module :class:`test_framework.communication.communication` """ ...
spconv/pytorch/__init__.py
xiaobaishu0097/spconv
909
100053
import platform from pathlib import Path import numpy as np import torch from spconv.pytorch import ops from spconv.pytorch.conv import (SparseConv2d, SparseConv3d, SparseConvTranspose2d, SparseConvTranspose3d, SparseInverseConv2d, SparseInverseConv3d, SubMConv2d, Sub...
peregrinearb/__init__.py
kecheon/peregrine
954
100056
from .async_find_opportunities import * from .async_build_markets import * from .bellman_multi_graph import bellman_ford_multi, NegativeWeightFinderMulti from .bellmannx import bellman_ford, calculate_profit_ratio_for_path, NegativeWeightFinder, NegativeWeightDepthFinder, \ find_opportunities_on_exchange, get_start...
libs/fuel/fuel/iterator.py
dendisuhubdy/attention-lvcsr
767
100058
<filename>libs/fuel/fuel/iterator.py<gh_stars>100-1000 import six class DataIterator(six.Iterator): """An iterator over data, representing a single epoch. Parameters ---------- data_stream : :class:`DataStream` or :class:`Transformer` The data stream over which to iterate. request_iterato...
test/test_trace.py
chellvs/PyPCAPKit
131
100073
<filename>test/test_trace.py # -*- coding: utf-8 -*- import pprint import pcapkit trace = pcapkit.extract(fin='../sample/http.pcap', nofile=True, verbose=True, trace=True, trace_format='json', trace_fout='../sample/trace') pprint.pprint(trace.trace)
pylightgbm/models.py
ArdalanM/pyLightGBM
390
100084
# -*- coding: utf-8 -*- """ @author: <NAME> <<EMAIL>> @brief: """ from __future__ import print_function import os import re import sys import shutil import tempfile import subprocess import numpy as np import scipy.sparse as sps from pylightgbm.utils import io_utils from sklearn.base import BaseEstimator, ClassifierMix...
slack_bolt/workflows/step/utilities/async_update.py
hirosassa/bolt-python
504
100085
from slack_sdk.web.async_client import AsyncWebClient class AsyncUpdate: """`update()` utility to tell Slack the processing results of a `save` listener. async def save(ack, view, update): await ack() values = view["state"]["values"] task_name = values["task_name_inpu...
servicecatalog_factory/workflow/portfolios/associate_product_with_portfolio_task.py
RobBrazier/aws-service-catalog-factory
116
100100
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import luigi from servicecatalog_factory import aws from servicecatalog_factory.workflow.portfolios.create_portfolio_task import ( CreatePortfolioTask, ) from servicecatalog_factory.workfl...
autotest/gdrivers/heif.py
jpapadakis/gdal
3,100
100116
#!/usr/bin/env pytest # -*- coding: utf-8 -*- ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test HEIF driver # Author: <NAME>, <even dot rouault at spatialys.com> # ##################################################################...
sfaira/versions/topologies/mouse/embedding/__init__.py
theislab/sfaira
110
100125
from sfaira.versions.topologies.mouse.embedding.ae import AE_TOPOLOGIES from sfaira.versions.topologies.mouse.embedding.linear import LINEAR_TOPOLOGIES from sfaira.versions.topologies.mouse.embedding.nmf import NMF_TOPOLOGIES from sfaira.versions.topologies.mouse.embedding.vae import VAE_TOPOLOGIES from sfaira.versions...
env/Lib/site-packages/prompt_toolkit/cursor_shapes.py
andresgreen-byte/Laboratorio-1--Inversion-de-Capital
4,028
100155
from abc import ABC, abstractmethod from enum import Enum from typing import TYPE_CHECKING, Any, Callable, Union from prompt_toolkit.enums import EditingMode from prompt_toolkit.key_binding.vi_state import InputMode if TYPE_CHECKING: from .application import Application __all__ = [ "CursorShape", "Cursor...
psonic/psonic.py
m-roberts/python-sonic
263
100164
import random from .samples import Sample from .synthesizers import SAW from .notes import C5 from .internals.chords import _CHORD_QUALITY from .internals.scales import _SCALE_MODE from .synth_server import ( SonicPi, use_synth, ) __debug = False def synth(name, note=None, attack=None, decay=None, sustain...
tests/common/checks_infra/test_registry.py
jamesholland-uk/checkov
4,013
100211
<filename>tests/common/checks_infra/test_registry.py import os import unittest from checkov.common.checks_infra.registry import Registry from checkov.common.checks_infra.checks_parser import NXGraphCheckParser class TestRegistry(unittest.TestCase): def test_invalid_check_yaml_does_not_throw_exception(self): ...
dsgcn/datasets/cluster_processor.py
LLLjun/learn-to-cluster
620
100231
import numpy as np class ClusterProcessor(object): def __init__(self, dataset): self.dataset = dataset self.dtype = np.float32 def __len__(self): return self.dataset.size def build_adj(self, node, edge): node = list(node) abs2rel = {} rel2abs = {} ...
flyingsquid/_observables.py
oxu2/flyingsquid
269
100236
from pgmpy.models import MarkovModel from pgmpy.factors.discrete import JointProbabilityDistribution, DiscreteFactor from itertools import combinations from flyingsquid.helpers import * import numpy as np import math from tqdm import tqdm import sys import random class Mixin: ''' Functions to compute observabl...
ue4docker/dockerfiles/ue4-minimal/windows/fix-targets.py
meetakshay99/ue4-docker
579
100266
<filename>ue4docker/dockerfiles/ue4-minimal/windows/fix-targets.py #!/usr/bin/env python3 import os, re, sys def readFile(filename): with open(filename, "rb") as f: return f.read().decode("utf-8") def writeFile(filename, data): with open(filename, "wb") as f: f.write(data.encode("utf-8")) ...
cupy/sparse/__init__.py
prkhrsrvstv1/cupy
6,180
100283
<gh_stars>1000+ import sys import warnings import cupyx.scipy.sparse # Raise a `DeprecationWarning` for `cupy.sparse` submodule when its functions # are called. We could raise the warning on importing the submodule, but we # use module level `__getattr__` function here as the submodule is also # imported in cupy/__i...
lib/django-1.4/django/contrib/localflavor/fr/fr_department.py
MiCHiLU/google_appengine_sdk
790
100295
# -*- coding: utf-8 -*- # See the "Code officiel gΓ©ographique" on the INSEE website <www.insee.fr>. DEPARTMENT_CHOICES = ( # Metropolitan departments ('01', u'01 - Ain'), ('02', u'02 - Aisne'), ('03', u'03 - Allier'), ('04', u'04 - Alpes-de-Haute-Provence'), ('05', u'05 - Hautes-Alpes'), (...
Python/zip-bomb/get_filesize.py
MartinThoma/algorithms
209
100316
<gh_stars>100-1000 import zipfile zp = zipfile.ZipFile("example.zip") size = sum([zinfo.file_size for zinfo in zp.filelist]) zip_kb = float(size) / 1000 # kB
qf_lib/analysis/strategy_monitoring/assets_monitoring_sheet.py
webclinic017/qf-lib
198
100317
# 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...
colors_script/calc_colormap.py
cemlyn007/mindboggle
118
100319
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse import numpy as np from mindboggle.mio.colors import distinguishable_colors, label_adjacency_matrix if __name__ == "__main__": description = ('calculate colormap for labeled image;' 'calculated result is stored in outpu...
staplelib/__init__.py
pivotman/stapler
186
100360
class CommandError(Exception): """ Exception class indicating a problem while executing a stapler command. """ pass OPTIONS = None # optparse options def main(arguments=None): from . import stapler stapler.main(arguments)
xfel/ui/components/timeit.py
dperl-sol/cctbx_project
155
100399
<filename>xfel/ui/components/timeit.py from __future__ import absolute_import, division, print_function import time, math def now(): return "%02d:%02d:%02d" % (time.localtime().tm_hour, time.localtime().tm_min, time.localtime().tm_sec) def duration(t1, t2): diff = t2 - t1 seconds = int(math.floor(diff)) frac...