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
tests/r/test_intqrt.py
hajime9652/observations
199
11089058
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.intqrt import intqrt def test_intqrt(): """Test module intqrt.py by downloading intqrt.csv and testing shape of extracted data has 124 row...
test/964-default-iface-init-generated/util-src/generate_java.py
lifansama/xposed_art_n
234
11089099
#!/usr/bin/python3 # # Copyright (C) 2015 The Android Open Source 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 # # Unless require...
examples/books_to_scrape/persistence/__init__.py
awesome-archive/transistor
232
11089111
# -*- coding: utf-8 -*- """ transistor.examples.books_to_scrape.persistence ~~~~~~~~~~~~ This module serves as an example of how to setup a persistence model for Transistor with postgresql + newt.db. :copyright: Copyright (C) 2018 by BOM Quote Limited :license: The MIT License, see LICENSE for more details. ~~~~~~~~~~...
qinhaifang/src/tools/demo_seg_mss.py
SpaceNetChallenge/BuildingFootprintDetectors
161
11089191
<reponame>SpaceNetChallenge/BuildingFootprintDetectors<filename>qinhaifang/src/tools/demo_seg_mss.py #!/usr/bin/python # -------------------------------------------------------- # Multitask Network Cascade # Modified from py-faster-rcnn (https://github.com/rbgirshick/py-faster-rcnn) # Copyright (c) 2016, <NAME> # Lice...
examples/dataflow-production-ready/python/ml_preproc/pipeline/model/data_classes.py
ruchirjain86/professional-services
2,116
11089198
# Copyright 2021 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 i...
test/models/tensorflow/frozen_op_graph/tf_frozen.py
lynex/nnfusion
639
11089214
<reponame>lynex/nnfusion # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import tensorflow as tf import numpy as np from tensorflow.python.framework import graph_util from tensorflow.python.framework import graph_io tf.reset_default_graph() # input tensor x0 = tf.placeholder(tf.float32, sh...
jwt_auth/mixins.py
sundeepkumar/django-jwt-auth-master
175
11089225
from django.http import HttpResponse import jwt from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from jwt_auth import settings, exceptions from jwt_auth.utils import get_authorization_header from jwt_auth.compat import json, smart_text, User jwt_decode_handle...
hypergan/layers/pixel_shuffle.py
limberc/HyperGAN
889
11089235
<filename>hypergan/layers/pixel_shuffle.py import torch.nn as nn from hypergan.layer_shape import LayerShape import hypergan as hg class PixelShuffle(hg.Layer): """ --- description: 'layer pixel_shuffle for configurable component' --- # pixel_shuffle layer Implements Pixel...
rest/subaccounts/voice-example/subaccount-call.6.x.py
Tshisuaka/api-snippets
234
11089262
# Download the Python helper library from twilio.com/docs/python/install import os from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account # To set up environmental variables, see http://twil.io/secure sub_account_sid = os.environ['TWILIO_ACCOUNT_SID'] sub_auth_token = os.environ[...
mmseg/core/seg/sampler/__init__.py
HeqingZhang/mmsegmentation
903
11089273
from .base_pixel_sampler import BasePixelSampler from .ohem_pixel_sampler import OHEMPixelSampler __all__ = ['BasePixelSampler', 'OHEMPixelSampler']
src/dispatch/plugins/generic_workflow/plugin.py
axellaurelut/dispatch
3,417
11089285
<gh_stars>1000+ """ .. module: dispatch.plugins.generic_workflow.plugin :platform: Unix :copyright: (c) 2021 by <NAME>. :license: MIT, see LICENSE for more details. :description: The rest API needs to respond with JSON according to the JSON schema mentioned here https://github.com/Netfl...
src/data/osm/street_loader.py
grischard/OSMDeepOD
156
11089298
import logging from src.base.node import Node from src.base.street import Street from src.base.tag import Tag from src.data.osm.overpass_api import OverpassApi logger = logging.getLogger(__name__) class StreetLoader: street_categories = [ 'road', 'trunk', 'primary', 'secondary', ...
torchtext/models/roberta/transforms.py
nateanl/text
3,172
11089378
import os import torch from torch.nn import Module from torchtext._download_hooks import load_state_dict_from_url from torchtext import transforms from torchtext import functional from typing import List, Any class XLMRobertaModelTransform(Module): def __init__( self, vocab_path: str, spm...
Python/WxPython/list.py
Gjacquenot/training-material
115
11089394
<filename>Python/WxPython/list.py #!/usr/bin/env python import paramiko import time import sys import wx import wx.lib.mixins.listctrl as listmix class AutoWidthListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin): def __init__(self, parent, ID, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): wx.L...
alipay/aop/api/domain/LogisticsAccountInfo.py
antopen/alipay-sdk-python-all
213
11089416
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class LogisticsAccountInfo(object): def __init__(self): self._audit_desc = None self._logistics_account_id = None self._logistics_account_status = None self._pid = None ...
vilya/views/watching.py
mubashshirjamal/code
1,582
11089426
<reponame>mubashshirjamal/code # -*- coding: utf-8 -*- from vilya.libs.template import st _q_exports = [] def _q_index(request): user = request.user if user: watched_projects = user.watched_projects return st('/watching.html', **locals()) return request.redirect("/hub/teams")
moto/eks/utils.py
orenmazor/moto
5,460
11089427
<filename>moto/eks/utils.py import inspect import re from boto3 import Session from moto.eks.exceptions import InvalidParameterException def get_partition(region): valid_matches = [ # (region prefix, aws partition) ("cn-", "aws-cn"), ("us-gov-", "aws-us-gov"), ("us-gov-iso-", "aw...
tests/ut/python/parallel/test_comm_not_recompute.py
mindspore-ai/mindspore
3,200
11089506
# Copyright 2019 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 # # Unless required by applicable law or agreed to...
tests/test_lr_scheduler.py
CanYouImagine/openspeech
207
11089507
import unittest import torch import matplotlib.pyplot as plt from torch import optim from openspeech.optim.optimizer import Optimizer from openspeech.utils import build_dummy_configs from openspeech.optim.scheduler.warmup_scheduler import ( WarmupLRSchedulerConfigs, WarmupLRScheduler, ) from openspeech.optim.s...
tests/decoration_tests.py
dvzrv/softlayer-python
126
11089509
""" SoftLayer.tests.decoration_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ import logging from unittest import mock as mock from SoftLayer.decoration import retry from SoftLayer import exceptions from SoftLayer import testing class TestDecoration(testing.TestCase...
IronManFly/storage/db/utils.py
leepand/IronManFly
599
11089524
import os import json import base64 def profile_path(profile_id, profile): """Create full path to given provide for the current user.""" user = os.path.expanduser("~") return os.path.join(user, profile_id + profile) def load_profile(f): return json.loads(base64.decodestring(open(f, 'rb').read()).encod...
google/cloud/forseti/common/gcp_type/instance_group_manager.py
aarontp/forseti-security
921
11089526
<filename>google/cloud/forseti/common/gcp_type/instance_group_manager.py # Copyright 2017 The Forseti Security Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # ...
office365/sharepoint/changes/change_field.py
wreiner/Office365-REST-Python-Client
544
11089529
from office365.sharepoint.changes.change import Change class ChangeField(Change): @property def field_id(self): return self.properties.get("FieldId", None)
bindings/python/cntk/tests/onnx_model_test.py
rohankumardubey/CNTK
17,702
11089530
<filename>bindings/python/cntk/tests/onnx_model_test.py # Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import cntk as C import nump...
library/oci_export_set.py
slmjy/oci-ansible-modules
106
11089549
<reponame>slmjy/oci-ansible-modules #!/usr/bin/python # Copyright (c) 2018, Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache Licen...
teuthology/test/test_contextutil.py
varshar16/teuthology
117
11089561
from pytest import raises from teuthology import contextutil from logging import ERROR class TestSafeWhile(object): def setup(self): contextutil.log.setLevel(ERROR) self.fake_sleep = lambda s: True self.s_while = contextutil.safe_while def test_6_5_10_deal(self): with raises(...
third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py
google-ar/chromium
777
11089572
<filename>third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py # Copyright (C) 2013 Adobe Systems Incorporated. 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 ...
corehq/apps/aggregate_ucrs/urls.py
dimagilg/commcare-hq
471
11089595
<reponame>dimagilg/commcare-hq from django.conf.urls import url from . import views # these are included by the userreports urls urlpatterns = [ url(r'^view/(?P<table_id>[\w-]+)/$', views.AggregateUCRView.as_view(), name=views.AggregateUCRView.urlname), url(r'^preview/(?P<table_id>[\w-]+)/$', views.Pr...
libs/pipeline_logger/pipeline_logger/__init__.py
silentmonk/KubeFlow
2,527
11089615
<filename>libs/pipeline_logger/pipeline_logger/__init__.py from logging import Logger from datetime import datetime import json from typing import Callable __version__ = "1.0.2" # TODO: Handle batched inputs and outputs (using above custom fn's - match inputs to outputs!) # TODO: Add Monitors around these calls!! ...
cvnets/layers/activation/leaky_relu.py
apple/ml-cvnets
209
11089622
<gh_stars>100-1000 # # For licensing see accompanying LICENSE file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from torch import nn, Tensor from typing import Tuple, Optional from . import register_act_fn @register_act_fn(name="leaky_relu") class LeakyReLU(nn.LeakyReLU): """ Applies a leaky relu...
baseline/tf/remote.py
sagnik/baseline
241
11089650
import numpy as np from baseline.remote import ( RemoteModelREST, RemoteModelGRPC, register_remote, RemoteRESTClassifier, RemoteRESTTagger, RemoteRESTSeq2Seq, RemoteRESTEmbeddings, RemoteGRPCClassifier, RemoteGRPCTagger, RemoteGRPCSeq2Seq, RemoteGRPCEmbeddings, ) class Remo...
ants/utils/pad_image.py
xemio/ANTsPy
338
11089670
__all__ = ['pad_image'] import math from ..core import ants_image as iio from .. import utils def pad_image(image, shape=None, pad_width=None, value=0.0, return_padvals=False): """ Pad an image to have the given shape or to be isotropic. Arguments --------- image : ANTsImage image to p...
examples/pipeline/app_without_args.py
pichatelli/simple-settings
213
11089701
from simple_settings import LazySettings settings = LazySettings( 'first_settings', 'second_settings' ) print(settings.ONLY_IN_FIRST) print(settings.ONLY_IN_SECOND) print(settings.SIMPLE_CONF)
conftest.py
jiduque/scikit-fda
147
11089704
import pytest # https://github.com/scikit-learn/scikit-learn/issues/8959 import numpy as np try: np.set_printoptions(sign=' ') except TypeError: pass collect_ignore = ['setup.py', 'docs/conf.py'] pytest.register_assert_rewrite("skfda")
ghidra_9.0/Ghidra/Features/Python/data/jython-2.7.1/Lib/select.py
ChristopherMorrison/ghidra
577
11089709
# dispatches to _socket for actual implementation from _socket import ( POLLIN, POLLOUT, POLLPRI, POLLERR, POLLHUP, POLLNVAL, error, poll, select) # backwards compatibility with Jython 2.5 cpython_compatible_select = select __all__ = [ "POLLIN", "POLLOUT", "POLLPRI", "POLLERR"...
atcoder/abc078/b.py
Ashindustry007/competitive-programming
506
11089720
#!/usr/bin/env python2 # https://abc078.contest.atcoder.jp/tasks/abc078_b x, y, z = map(int, raw_input().split()) print (x - z) // (y + z)
spruned/application/migrations/__init__.py
darosior/spruned
152
11089731
<filename>spruned/application/migrations/__init__.py<gh_stars>100-1000 import os def get_version(sql): table_info = "PRAGMA table_info('migrations')" from sqlalchemy.exc import ResourceClosedError try: if not sql.execute(table_info).fetchall(): return 0 except ResourceClosedError a...
transpyle/general/parser.py
EraYaN/transpyle
107
11089746
<gh_stars>100-1000 """Definition of parser.""" import collections.abc import pathlib import re import textwrap import typing as t from .registry import Registry from .code_reader import CodeReader # def remove_trailing_whitespace(code: str) -> str: # raise NotImplementedError() def validate_indentation(code: s...
conda-recipe/run_test.py
ktanishqk/py-earth
360
11089771
<reponame>ktanishqk/py-earth<filename>conda-recipe/run_test.py<gh_stars>100-1000 import pyearth import nose import os pyearth_dir = os.path.dirname( os.path.abspath(pyearth.__file__)) os.chdir(pyearth_dir) nose.run(module=pyearth)
py/rest_tests/test_metadata.py
ahmedengu/h2o-3
6,098
11089857
import h2o import h2o_test_utils def test(a_node, pp): #################################### # test schemas collection GET if h2o_test_utils.isVerbose(): print('Testing /Metadata/schemas. . .') schemas = a_node.schemas(timeoutSecs=240) assert 'schemas' in schemas, "FAIL: failed to find 'schemas' fie...
tests/modules/test_marshal.py
ruby-compiler-survey/topaz
241
11089858
from ..base import BaseTopazTest class TestMarshal(BaseTopazTest): def test_version_constants(self, space): w_res = space.execute("return Marshal::MAJOR_VERSION") assert space.int_w(w_res) == 4 w_res = space.execute("return Marshal::MINOR_VERSION") assert space.int_w(w_res) == 8 ...
rkqc/tools/gui/items/ESOPSynthesisItem.py
clairechingching/ScaffCC
158
11089877
<gh_stars>100-1000 # RevKit: A Toolkit for Reversible Circuit Design (www.revkit.org) # Copyright (C) 2009-2011 The RevKit Developers <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation,...
causalml/propensity.py
rainfireliang/causalml
2,919
11089922
from abc import ABCMeta, abstractmethod import logging import numpy as np from pygam import LogisticGAM, s from sklearn.metrics import roc_auc_score as auc from sklearn.linear_model import LogisticRegressionCV from sklearn.model_selection import StratifiedKFold, train_test_split import xgboost as xgb logger = logging...
tests/local/warehouse/metrics/test_filter_and_group_by.py
pgoslatara/soda-sql
787
11089934
<reponame>pgoslatara/soda-sql<gh_stars>100-1000 # Copyright 2020 Soda # 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 ap...
exploit_nss.py
marcostolosa/CVE-2021-3156
473
11089939
#!/usr/bin/python3 ''' Exploit for CVE-2021-3156 with overwrite struct service_user by sleepya This exploit requires: - glibc with tcache - nscd service is not running Tested on: - Ubuntu 18.04 - Ubuntu 20.04 - Debian 10 - CentOS 8 ''' import os import subprocess import sys from ctypes import cdll, c_char_p, POINTER,...
chapter09/tests/airflowbook/operators/test_movielens_operator.py
add54/Data_PipeLine_Apache_Airflow
303
11089951
<filename>chapter09/tests/airflowbook/operators/test_movielens_operator.py import datetime import os from collections import namedtuple from pathlib import Path import pytest from airflow.models import DAG, Connection from pytest_docker_tools import fetch, container from pytest_mock import MockFixture from airflowboo...
local_data_api/resources/sqlite.py
roganov/local-data-api
102
11089961
from __future__ import annotations import sqlite3 from typing import TYPE_CHECKING, Any, Dict, List, Optional from sqlalchemy.dialects import sqlite from local_data_api.models import ColumnMetadata, Field from local_data_api.resources.resource import Resource, register_resource_type if TYPE_CHECKING: # pragma: no ...
dev/Gems/CloudGemMessageOfTheDay/AWS/lambda-code/ServiceLambda/message_utils.py
jeikabu/lumberyard
1,738
11089984
<filename>dev/Gems/CloudGemMessageOfTheDay/AWS/lambda-code/ServiceLambda/message_utils.py import importlib import boto3 import CloudCanvas import errors from cgf_utils import custom_resource_utils from datetime import datetime # Had to use these custom min and max rather than datetime.min because datetime.strttime wil...
src/pydybm/arraymath/__init__.py
ibm-research-tokyo/dybm
126
11089998
<filename>src/pydybm/arraymath/__init__.py # (C) Copyright IBM Corp. 2016 # # 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 requir...
test/utils/test_yaml.py
idoby/SimpleParsing
150
11090001
<reponame>idoby/SimpleParsing<gh_stars>100-1000 """ Tests for serialization to/from yaml files. """ from collections import OrderedDict from dataclasses import dataclass, field, fields from typing import Any, Dict, List, Optional, Tuple, Mapping, Type from pathlib import Path import pytest import textwrap from simple_p...
tests/debugpy/common/test_socket.py
r3m0t/debugpy
695
11090053
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. from __future__ import absolute_import, division, print_function, unicode_literals import pytest import sys from debugpy.common import sockets class TestSocketSer...
hivemind/dht/traverse.py
protagohhz/hivemind
1,026
11090055
""" Utility functions for crawling DHT nodes, used to get and store keys in a DHT """ import asyncio import heapq from collections import Counter from typing import Any, Awaitable, Callable, Collection, Dict, List, Optional, Set, Tuple from hivemind.dht.routing import DHTID ROOT = 0 # alias for heap root async def...
src/byro/common/templatetags/qrcode_inline.py
mv-idatalytics/jenkins-byro
114
11090091
import base64 import io import qrcode from django import template register = template.Library() @register.filter def qrcode_inline(value): qr = qrcode.QRCode( version=None, box_size=2, error_correction=qrcode.constants.ERROR_CORRECT_Q ) qr.add_data(value) qr.make(fit=True) img = qr.make_...
lightning/types/base.py
lightning-viz/lightning-python
176
11090110
from lightning import Visualization, VisualizationLocal import requests import six class Base(Visualization, VisualizationLocal): _name = 'base' _options = { 'width': {'default': None}, 'height': {'default': None}, 'description': {'default': None} } _doc = """ width ...
hacking/tests/__init__.py
UbuntuEvangelist/hacking
187
11090112
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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...
safe_rl/pg/utils.py
florisdenhengst/safety-starter-agents
216
11090136
<reponame>florisdenhengst/safety-starter-agents import numpy as np import scipy.signal EPS = 1e-8 def combined_shape(length, shape=None): if shape is None: return (length,) return (length, shape) if np.isscalar(shape) else (length, *shape) def keys_as_sorted_list(dict): return sorted(list(dict.ke...
Calibration/TkAlCaRecoProducers/python/AlcaBeamSpotProducerHP_cff.py
ckamtsikis/cmssw
852
11090151
import FWCore.ParameterSet.Config as cms from Calibration.TkAlCaRecoProducers.AlcaBeamSpotProducerHP_cfi import alcaBeamSpotProducerHP alcaBeamSpotHP = cms.Sequence( alcaBeamSpotProducerHP )
custom_components/hacs/helpers/network.py
svkowalski/HAcore_QNAP
297
11090174
"""Verify network.""" from socket import gaierror from integrationhelper import Logger def internet_connectivity_check(host="api.github.com"): """Verify network connectivity.""" return True
tests/bytecode/mp-tests/yield2.py
LabAixBidouille/micropython
303
11090176
<filename>tests/bytecode/mp-tests/yield2.py def f(): yield from a yield from (a, b) yield from f(a) lambda:(yield) lambda:(yield 1) + 2
alipay/aop/api/domain/AlipayUserPassTemplateCreateModel.py
alipay/alipay-sdk-python-all
213
11090186
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.TemplateEvoucherDTO import TemplateEvoucherDTO from alipay.aop.api.domain.TemplateFileDTO import TemplateFileDTO from alipay.aop.api.domain.TemplateImageDTO import TemplateImageDTO ...
doc/tutorials/shader_toy/shadertoy_demo_1.py
janscas/arcade
824
11090190
<reponame>janscas/arcade import arcade # Derive an application window from Arcade's parent Window class class MyGame(arcade.Window): def __init__(self): # Call the parent constructor super().__init__(width=1920, height=1080) def on_draw(self): # Clear the screen self.clear() ...
data_collection/gazette/spiders/sc_jupia.py
kaiocp/querido-diario
454
11090239
from gazette.spiders.base.fecam import FecamGazetteSpider class ScJupiaSpider(FecamGazetteSpider): name = "sc_jupia" FECAM_QUERY = "cod_entidade:143" TERRITORY_ID = "4209177"
smdebug/profiler/analysis/notebook_utils/heatmap.py
jsspric/sagemaker-debugger
133
11090243
<gh_stars>100-1000 # Standard Library import re from copy import deepcopy # Third Party import bokeh import numpy as np from bokeh.io import output_notebook, show from bokeh.models import ColumnDataSource, HoverTool from bokeh.models.glyphs import Image from bokeh.models.tickers import FixedTicker from bokeh.plotting ...
Ryven/packages/auto_generated/_pydecimal/nodes.py
tfroehlich82/Ryven
2,872
11090303
<filename>Ryven/packages/auto_generated/_pydecimal/nodes.py from NENV import * import _pydecimal class NodeBase(Node): pass class _All_Zeros_Node(NodeBase): """ Matches zero or more characters at the beginning of the string.""" title = '_all_zeros' type_ = '_pydecimal' init_inputs = [...
pursuit_policy.py
SurvivorT/SRTP
489
11090318
<filename>pursuit_policy.py import numpy as np import tensorflow as tf from rltools import nn, tfutil from rltools.distributions import Distribution from rltools.policy.stochastic import StochasticPolicy class FactoredCategorical(Distribution): def __init__(self, dim): self._dim = dim @property ...
Greedy Algorithm/ReverseShuffleMerge.py
WinterSoldier13/interview-preparation-kit
175
11090332
<filename>Greedy Algorithm/ReverseShuffleMerge.py #!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the reverseShuffleMerge function below. def reverseShuffleMerge(s): word = [] freqs = Counter(s) reqs = { k: v/2 for k, v in fre...
src/pythae/models/hvae/hvae_config.py
clementchadebec/benchmark_VAE
143
11090345
<gh_stars>100-1000 from pydantic.dataclasses import dataclass from ..vae import VAEConfig @dataclass class HVAEConfig(VAEConfig): r"""Hamiltonian Variational Autoencoder config class. Parameters: latent_dim (int): The latent dimension used for the latent space. Default: 10 n_lf (int): The nu...
Chapter18/train_ddpg.py
haohaoxiao/Deep-Reinforcement-Learning-Hands-On-Second-Edition
621
11090354
<reponame>haohaoxiao/Deep-Reinforcement-Learning-Hands-On-Second-Edition #!/usr/bin/env python3 import gym import gym.wrappers import ptan import time import torch import torch.optim as optim import torch.nn.functional as F import numpy as np import argparse from tensorboardX import SummaryWriter import os from lib i...
backend/db/test/contact_test.py
xuantan/viewfinder
645
11090366
<reponame>xuantan/viewfinder # -*- coding: utf-8 -*- # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Tests for Contact. """ __author__ = '<EMAIL> (<NAME>)' from viewfinder.backend.base import util from viewfinder.backend.db import versions from viewfinder.backend.db.contact import Contact from viewfinder.ba...
models/Loss.py
ishine/StyleSpeech-1
106
11090379
<reponame>ishine/StyleSpeech-1<filename>models/Loss.py import torch import torch.nn as nn class StyleSpeechLoss(nn.Module): """ StyleSpeech Loss """ def __init__(self): super(StyleSpeechLoss, self).__init__() self.mse_loss = nn.MSELoss() self.mae_loss = nn.L1Loss() def ...
src/curt/curt/modules/smarthome/smarthome_service.py
sanyaade-teachings/cep
108
11090385
""" Copyright (C) Cortic Technology Corp. - All Rights Reserved Written by <NAME> <<EMAIL>>, 2021 """ import traceback import logging from curt.base_service import BaseService class SmartHomeService(BaseService): def __init__(self): super().__init__() self.service_type = "SmartHome" def ...
mms/python/python-datatypes/python_data_types.py
zimnx/scylla-code-samples
158
11090387
#!/bin/env python3 from pathlib import Path from cassandra.cluster import Cluster from cassandra import ConsistencyLevel class App: def __init__(self): self.cluster = Cluster(contact_points=["scylla-node1", "scylla-node2", "scylla-node3"]) self.session = self.cluster.connect(keyspace="catalog") ...
tfimm/architectures/mlp_mixer.py
gietema/tensorflow-image-models
154
11090388
""" MLP-Mixer, ResMLP, and gMLP models This implementation is ported from the timm, which is based on the original implementation from the MLP-Mixer paper. Official JAX impl: https://github.com/google-research/vision_transformer/blob/linen/vit_jax/models_mixer.py Paper: MLP-Mixer: An all-MLP Architecture for Vision ...
menpo3d/rasterize/base.py
apapaion/menpo3d
134
11090395
<gh_stars>100-1000 def rasterize_mesh_from_barycentric_coordinate_images( mesh, bcoords_image, tri_indices_image ): r""" Renders an image of a `menpo.shape.TexturedTriMesh` or `menpo.shape.ColouredTriMesh` from a barycentric coordinate image pair. Note that the texture is rendered without any light...
yolo/vedanet/engine/_voc_test.py
hilman-dayo/ObjectDetection-OneStageDet
331
11090399
<filename>yolo/vedanet/engine/_voc_test.py import logging as log import torch from torchvision import transforms as tf from statistics import mean import os from .. import data as vn_data from .. import models from . import engine from utils.test import voc_wrapper __all__ = ['VOCTest'] class CustomDataset(vn_data.B...
datamol/fragment/_fragment.py
hengwei-chan/fragmentation_and_assemble
130
11090408
<filename>datamol/fragment/_fragment.py from typing import Set from typing import Optional from typing import Any from rdkit import Chem from rdkit.Chem import BRICS from rdkit.Chem import Recap from rdkit.Chem import rdMMPA from rdkit.Chem.Fraggle import FraggleSim import datamol as dm def brics( mol: Chem.rd...
galaxy/worker/tasks/collection.py
timblaktu/galaxy
904
11090446
# (c) 2012-2019, Ansible by Red Hat # # This file is part of Ansible Galaxy # # Ansible Galaxy is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by # the Apache Software Foundation, either version 2 of the License, or # (at your option) any later version. # ...
tests/io/test_input_bounds.py
fracek/OMLT
115
11090450
<reponame>fracek/OMLT import pytest import tempfile from omlt.io.input_bounds import write_input_bounds, load_input_bounds def test_input_bounds_reader_writer_with_list(): input_bounds = [(i*10.0, i*10.0 + 1.0) for i in range(10)] with tempfile.NamedTemporaryFile(suffix='.json', delete=False) as f: w...
amadeus/shopping/_hotel_offers_by_hotel.py
tsolakoua/amadeus-python
125
11090452
<reponame>tsolakoua/amadeus-python from amadeus.client.decorator import Decorator class HotelOffersByHotel(Decorator, object): def get(self, **params): ''' Get all offers for Holiday Inn Paris Notre Dame. .. code-block:: python amadeus.shopping.hotel_offers_by_hotel.get(hotel...
cls/networks/__init__.py
megvii-model/MABN
182
11090475
from . import MABN from . import resnet
py_feature/108_order_size.py
weiziyoung/instacart
290
11090481
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 16 21:04:09 2017 @author: konodera """ import pandas as pd import numpy as np from tqdm import tqdm import utils utils.start(__file__) #============================================================================== # load #======================...
device_e2e/aio/test_send_message.py
Azure/azure-iot-sdk-python
366
11090484
<gh_stars>100-1000 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. import asyncio import pytest import logging import json import uuid from azure.iot.device.exceptions import OperationCancelled logger = logging...
tests/python/unittest/test_meta_schedule_schedule_rule_auto_bind.py
gayatripk1/tvm
4,640
11090516
# 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...
tests/test_kube_api.py
funkypenguin/connaisseur
281
11090541
<gh_stars>100-1000 import pytest from . import conftest as fix import connaisseur.kube_api as k_api @pytest.mark.parametrize( "url, response", [ ( "https://samplenotray.io/apis/v1/namespaces/default/pods/sample-pod", fix.get_k8s_res("pods"), ), ( "ht...
setup.py
twocucao/danmu.fm
376
11090561
<reponame>twocucao/danmu.fm # -*- encoding: UTF-8 -*- from setuptools import setup, find_packages """ 打包的用的setup必须引入, """ VERSION = '0.3.6' setup(name='danmu.fm', version=VERSION, package_data={'danmufm': ['template/*', ]}, description="a tiny and smart cli player of douyu based on Python", l...
pyscf/pbc/gw/test/test_kugw.py
QuESt-Calculator/pyscf
501
11090574
#!/usr/bin/env python import unittest import numpy import os from pyscf import lib from pyscf.pbc import gto, dft, scf, df from pyscf.pbc.gw import kugw_ac cell = gto.Cell() cell.build( unit = 'B', a = [[ 0., 6.74027466, 6.74027466], [ 6.74027466, 0., 6.74027466], [ 6.740...
social_auth/backends/contrib/angel.py
merutak/django-social-auth
863
11090576
<reponame>merutak/django-social-auth from social.backends.angel import AngelOAuth2 as AngelBackend
euporie/box.py
joouha/euporie
505
11090578
# -*- coding: utf-8 -*- """Define box border constants.""" from typing import Optional from prompt_toolkit.layout.containers import Container from prompt_toolkit.layout.dimension import Dimension from prompt_toolkit.layout.mouse_handlers import MouseHandlers from prompt_toolkit.layout.screen import Char, Screen, Write...
Software/Python/grove_mini_motor_driver/driver_example.py
benmcclelland/GrovePi
482
11090587
<gh_stars>100-1000 #!/usr/bin/env python3 # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi # ''' ## License The MIT ...
predict.py
ahmedbesbes/character-based-cnn
233
11090605
<reponame>ahmedbesbes/character-based-cnn import argparse import torch import torch.nn.functional as F from src.model import CharacterLevelCNN from src import utils use_cuda = torch.cuda.is_available() def predict(args): model = CharacterLevelCNN(args, args.number_of_classes) state = torch.load(args.model) ...
benchmarks/operator_benchmark/common/tests/jit_forward_test.py
Hacky-DH/pytorch
60,067
11090610
<gh_stars>1000+ import operator_benchmark as op_bench import torch intraop_bench_configs = op_bench.config_list( attrs=[ [8, 16], ], attr_names=["M", "N"], tags=["short"], ) @torch.jit.script def torch_sumall(a, iterations): # type: (Tensor, int) result = 0.0 for _ in range(iterati...
tests/test_util_input.py
NoahH99/Warcoat
163
11090690
<filename>tests/test_util_input.py import unittest from datetime import datetime, timedelta from rowboat.util.input import parse_duration class TestRuleMatcher(unittest.TestCase): def test_basic_durations(self): dt = parse_duration('1w2d3h4m5s') self.assertTrue(dt < (datetime.utcnow() + timedelt...
examples/emboss_action.py
MrTeferi/photoshop-python-api
270
11090724
# Import local modules from photoshop import Session with Session() as ps: app = ps.app for index, x in enumerate(range(50)): # Execute an existing action from action palette. idPly = app.charIDToTypeID("Ply ") desc8 = ps.ActionDescriptor() idnull = app.charIDToTypeID("null") ...
src/causallift/nodes/estimate_propensity.py
Minyus/causallift
265
11090787
<reponame>Minyus/causallift<gh_stars>100-1000 import logging import pandas as pd from .utils import * # NOQA log = logging.getLogger(__name__) try: import matplotlib.pyplot as plt except: # NOQA print("[Warning] Could not import matplotlib.pyplot. ") def fit_propensity(args, df): X_train = df.xs("t...
plato/algorithms/mistnet.py
cuiboyuan/plato
135
11090807
""" The PyTorch-based MistNet algorithm, used by both the client and the server. Reference: <NAME>, et al. "MistNet: Towards Private Neural Network Training with Local Differential Privacy," found in docs/papers. """ import logging import time import torch from plato.algorithms import fedavg from plato.datasources ...
slam/odometry/posenet_odometry.py
Pandinosaurus/pyLiDAR-SLAM
130
11090836
<reponame>Pandinosaurus/pyLiDAR-SLAM from pathlib import Path from typing import Dict, Union, Any import numpy as np # Hydra and OmegaConf from hydra.core.config_store import ConfigStore from omegaconf import MISSING, DictConfig from hydra.conf import dataclass # Project Imports from slam.common.pose import Pose fro...
intro/matplotlib/examples/pretty_plots/plot_grid_ext.py
zmoon/scipy-lecture-notes
2,538
11090880
<gh_stars>1000+ """ Grid elaborate =============== An example displaying a grid on the axes and tweaking the layout. """ import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator fig = plt.figure(figsize=(8, 6), dpi=72, facecolor="white") axes = plt.subplot(111) axes.set_xlim(0, 4) axes.set_ylim(...
alipay/aop/api/domain/PassInstanceDetail.py
snowxmas/alipay-sdk-python-all
213
11090917
<filename>alipay/aop/api/domain/PassInstanceDetail.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.BizParamKeyValue import BizParamKeyValue class PassInstanceDetail(object): def __init__(self): self._biz_param_l...
docs/user_guide/main_usage/monte_carlo_integration.py
utsekaj42/chaospy
333
11090924
<gh_stars>100-1000 from problem_formulation import joint sobol_samples = joint.sample(10000, rule="sobol") antithetic_samples = joint.sample(10000, antithetic=True, seed=1234) halton_samples = joint.sample(10000, rule="halton")
test/nn/norm/test_instance_norm.py
mrmotallebi/pytorch_geometric
12,651
11090928
<reponame>mrmotallebi/pytorch_geometric import pytest import torch from torch_geometric.nn import InstanceNorm @pytest.mark.parametrize('conf', [True, False]) def test_instance_norm(conf): batch = torch.zeros(100, dtype=torch.long) x1 = torch.randn(100, 16) x2 = torch.randn(100, 16) norm1 = Instance...