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
kitsune/users/migrations/0027_profile_zendesk_id.py
erdal-pb/kitsune
929
11109791
<filename>kitsune/users/migrations/0027_profile_zendesk_id.py # Generated by Django 2.2.24 on 2021-09-02 06:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0026_profile_fxa_refresh_token'), ] operations = [ migrations.AddFie...
tests/unit/TestTypechecker.py
rainoftime/yinyang
143
11109798
<gh_stars>100-1000 # MIT License # # Copyright (c) [2020 - 2021] The yinyang authors # # 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 ri...
卷积模块/Res2Net.py
1044197988/TF.Keras-Commonly-used-models
160
11109809
<reponame>1044197988/TF.Keras-Commonly-used-models from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import Activation from tensorflow.keras.layers import concatenate from tensorflow.keras.layers import add def Conv_Relu_BN(num_filters,...
tools/third_party/websockets/tests/test_http.py
meyerweb/wpt
2,479
11109810
import asyncio import unittest from websockets.exceptions import SecurityError from websockets.http import * from websockets.http import read_headers from .utils import AsyncioTestCase class HTTPAsyncTests(AsyncioTestCase): def setUp(self): super().setUp() self.stream = asyncio.StreamReader(loop...
tests/not_tests.py
TakenBrandi/python-precisely
238
11109813
<reponame>TakenBrandi/python-precisely from nose.tools import istest, assert_equal from precisely import equal_to, not_ from precisely.results import matched, unmatched @istest def matches_when_negated_matcher_does_not_match(): assert_equal(matched(), not_(equal_to(1)).match(2)) @istest def does_not_match_when...
test/core/test_serde_flat.py
Xiaoxiong-Liu/gluon-ts
2,648
11109818
<gh_stars>1000+ # Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or...
skills_ml/job_postings/aggregate/pandas.py
bhagyaramgpo/skills-ml
147
11109824
"""Aggregation functions that can be used with pandas dataframes""" from collections import Counter class AggregateFunction(object): """Wrap a function with an attribute that indicates the return type name""" def __init__(self, returns): self.returns = returns def __call__(self, function, *params...
cinder/volume/drivers/dell_emc/unity/replication.py
lightsey/cinder
571
11109842
<filename>cinder/volume/drivers/dell_emc/unity/replication.py # Copyright (c) 2016 - 2019 Dell Inc. or its subsidiaries. # 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...
src/plugins/python/templates/tokenizer.template.py
ruby-on-rust/syntax
409
11109858
<filename>src/plugins/python/templates/tokenizer.template.py ## # Generic tokenizer used by the parser in the Syntax tool. # # https://www.npmjs.com/package/syntax-cli # # See `--custom-tokinzer` to skip this generation, and use a custom one. ## import re as _syntax_tool_re {{{LEX_RULE_HANDLERS}}} _lex_rules = {{{LE...
model/layers/deform_conv.py
destinyls/MonoFlex
131
11109921
import torch.nn.functional as F from torch import nn from .dcn_v2 import DCN class DeformConv(nn.Module): def __init__(self, in_channel, out_channel, norm_func, kernel_size=3, stride=1, padding=0): super(...
transparency/commands/settings.py
nevermorea/SublimeTextTrans
286
11109931
import sublime_plugin import sublime import os from os.path import dirname ST2 = int(sublime.version()) < 3000 if not ST2: PLUGIN_DIR = dirname(dirname(dirname(os.path.abspath(__file__)))) else: _st_pkgs_dir = sublime.packages_path() _cur_file_abspath = os.path.abspath(__file__) if _st_pkgs_dir not in _cur_file_...
pytweet/tweet.py
TheFarGG/PyTweet
614
11109941
from __future__ import annotations import datetime from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union from .attachments import Poll, Geo, File, Media from .enums import ReplySetting from .constants import ( TWEET_EXPANSION, TWEET_FIELD, USER_FIELD, PINNED_TWEET_EXPANSION, MEDIA_FIE...
wtf/static/static/settings.py
tigefa4u/wtfismyip
297
11109951
<filename>wtf/static/static/settings.py import base64 SECRET_KEY = base64.b64decode('<KEY>')
08_concurrency/cralwer/parallel_requests.py
siddheshmhatre/high_performance_python
698
11109967
<reponame>siddheshmhatre/high_performance_python<filename>08_concurrency/cralwer/parallel_requests.py<gh_stars>100-1000 from gevent import monkey monkey.patch_socket() import gevent from gevent.coros import Semaphore import urllib2 import string import random from contextlib import closing import numpy as np import p...
socialNetwork/test/TestUserService.py
rodrigo-bruno/DeathStarBench
364
11110051
import sys sys.path.append('../gen-py') import uuid from social_network import UserService from social_network.ttypes import ServiceException from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol def register(): socket = T...
alipay/aop/api/domain/AlipayIserviceCcmRoleModifyModel.py
antopen/alipay-sdk-python-all
213
11110055
<reponame>antopen/alipay-sdk-python-all<filename>alipay/aop/api/domain/AlipayIserviceCcmRoleModifyModel.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayIserviceCcmRoleModifyModel(object): def __init__(self): self._ccs_instance...
python-leetcode/laozhang/tree/leetcode_1302_.py
sweeneycai/cs-summary-reflection
227
11110105
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # coding=utf-8 """ 1302. 层数最深叶子节点的和 """ from laozhang import TreeNode class Solution: def deepestLeavesSum(self, root: TreeNode) -> int: max_depth = 0 map = {} def helper(root: TreeNode, depth: int): nonlocal max_depth, map ...
src/python/tests/unittests/test_common/test_config.py
annihilatethee/seedsync
255
11110108
# Copyright 2017, <NAME>, All rights reserved. import unittest import os import tempfile from common import Config, ConfigError, PersistError from common.config import InnerConfig, Checkers, Converters class TestConverters(unittest.TestCase): def test_int(self): self.assertEqual(0, Converters.int(None, ...
tests/preprocessing/test_replace.py
austinjp/textacy
1,929
11110110
import pytest from textacy import preprocessing @pytest.mark.parametrize( "text_in, text_out", [ ("$1.00 equals 100¢.", "_CUR_1.00 equals 100_CUR_."), ("How much is ¥100 in £?", "How much is _CUR_100 in _CUR_?"), ("My password is <PASSWORD>฿.", "My password is <PASSWORD>_CUR_<PASSWORD...
lib/utils.py
juliocamposmachado/gain2
242
11110136
import os import chainer.functions as F from chainer.dataset import download from chainer.serializers import npz from chainer.backends.cuda import get_array_module import numpy as np from PIL import Image from cupy import get_array_module def convert_caffemodel_to_npz(path_caffemodel, path_npz): from chainer.links....
sohu.py
1py/youku-lixian
445
11110156
#!/usr/bin/env python __all__ = ['sohu_download'] from common import * def real_url(host, prot, file, new): url = 'http://%s/?prot=%s&file=%s&new=%s' % (host, prot, file, new) start, _, host, key, _, _ = get_html(url).split('|') return '%s%s?key=%s' % (start[:-1], new, key) def sohu_download(url, merge=True): v...
pxr/usdImaging/bin/testusdview/testenv/testUsdviewInterpreterNoRender/testUsdviewInterpreterNoRender.py
DougRogers-DigitalFish/USD
3,680
11110163
#!/pxrpythonsubst # # Copyright 2017 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # ...
backend/avatar/service.py
restato/bunnybook
131
11110165
import glob import hashlib import random from pathlib import Path from typing import Any, List from PIL import Image from injector import singleton, inject from common.concurrency import cpu_bound_task from config import cfg @singleton class AvatarService: @inject def __init__(self): self._avatar_im...
test/point_tier_tests.py
timmahrt/praatIO
208
11110193
import unittest from praatio import textgrid from praatio.utilities.constants import Interval, Point, POINT_TIER from praatio.utilities import constants from praatio.utilities import errors from test.praatio_test_case import PraatioTestCase def makePointTier(name="pitch_values", points=None, minT=0, maxT=5.0): ...
ch08/birds.py
ricjuanflores/practice-of-the-python
319
11110226
class Bird: def fly(self): print('flying!') class Hummingbird(Bird): def fly(self): print('zzzzzooommm!') class Penguin(Bird): def fly(self): print('no can do.')
tensorflow_model_analysis/notebook/jupyter/renderer.py
rtg0795/model-analysis
1,118
11110257
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
tests/opytimizer/optimizers/evolutionary/test_es.py
anukaal/opytimizer
528
11110276
<gh_stars>100-1000 import numpy as np from opytimizer.optimizers.evolutionary import es from opytimizer.spaces import search def test_es_params(): params = { 'child_ratio': 0.5 } new_es = es.ES(params=params) assert new_es.child_ratio == 0.5 def test_es_params_setter(): new_es = es.ES...
caffe2/python/operator_test/mul_gradient_benchmark.py
raven38/pytorch
206
11110282
import argparse import numpy as np from caffe2.python import core, workspace def benchmark_mul_gradient(args): workspace.FeedBlob("dC", np.random.rand(args.m, args.n).astype(np.float32)) workspace.FeedBlob("A", np.random.rand(args.m, args.n).astype(np.float32)) workspace.FeedBlob("B", np.random.rand...
scripts/measure_classifier_score.py
BrandoZhang/alis
176
11110332
import os import argparse import random import pickle from shutil import copyfile from typing import Optional, Callable, List from torchvision.datasets import VisionDataset from torchvision.datasets.folder import pil_loader import numpy as np from PIL import Image import torchvision.transforms.functional as TVF from t...
src/Testing/utils.py
CMYanko/Zope
289
11110363
<reponame>CMYanko/Zope ############################################################################## # # Copyright (c) 2002 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
gratipay/models/participant/packages.py
kant/gratipay.com
517
11110382
<gh_stars>100-1000 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from gratipay.exceptions import NoPackages class Packages(object): def get_packages_for_claiming(self, manager): """Return a list of packages on the named ``manager`` for which ...
nmtpytorch/vocabulary.py
tejas1995/nmtpytorch
420
11110414
<reponame>tejas1995/nmtpytorch<filename>nmtpytorch/vocabulary.py<gh_stars>100-1000 # -*- coding: utf-8 -*- import json import pathlib import logging from collections import OrderedDict logger = logging.getLogger('nmtpytorch') class Vocabulary: r"""Vocabulary class for integer<->token mapping. Arguments: ...
exercises/zh/test_01_08_01.py
Jette16/spacy-course
2,085
11110416
def test(): assert ( "token_text = token.text" in __solution__ ), "你有正确拿到词符的文本吗?" assert ( "token_pos = token.pos_" in __solution__ ), "你有正确拿到词符的词性标注了吗?记着要用带下划线的属性。" assert ( "token_dep = token.dep_" in __solution__ ), "你有正确拿到词符的依存关系标签了吗?记着要用带下划线的属性。" __msg__.good("完美...
deprecated_gallery/ext2.py
guyongqiangx/construct
629
11110487
<filename>deprecated_gallery/ext2.py """ Extension 2 (ext2) used in Linux systems """ from construct import * Char = SLInt8 UChar = ULInt8 Short = SLInt16 UShort = ULInt16 Long = SLInt32 ULong = ULInt32 BlockPointer = Struct( "block_number" / ULong, # WARNING: unnamed field? OnDemandPointer(this.block_nu...
lldb/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntaxArray.py
medismailben/llvm-project
305
11110488
"""Test that the Objective-C syntax for dictionary/array literals and indexing works""" import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from ObjCNewSyntaxTest import ObjCNewSyntaxTest class ObjCNewSyntaxTestCaseArray(ObjCNewSyntaxTest): ...
tfne/encodings/codeepneat/modules/codeepneat_module_densedropout.py
githealthy18/Tensorflow-Neuroevolution
121
11110559
from __future__ import annotations import math import random import statistics import numpy as np import tensorflow as tf from .codeepneat_module_base import CoDeepNEATModuleBase from tfne.helper_functions import round_with_step class CoDeepNEATModuleDenseDropout(CoDeepNEATModuleBase): """ TFNE CoDeepNEAT ...
tools/bin/gppylib/test/regress/test_regress_gpssh.py
YangHao666666/hawq
450
11110598
#!/usr/bin/env python # 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 # "Li...
vumi/transports/tests/helpers.py
seidu626/vumi
199
11110615
<reponame>seidu626/vumi from twisted.internet.defer import inlineCallbacks from zope.interface import implements from vumi.transports.failures import FailureMessage from vumi.tests.helpers import ( MessageHelper, WorkerHelper, PersistenceHelper, MessageDispatchHelper, generate_proxies, IHelper, ) class Tran...
data/tracking/sampler/_sampling_algos/stateful/sequential.py
zhangzhengde0225/SwinTrack
143
11110648
<reponame>zhangzhengde0225/SwinTrack class SamplingAlgo_SequentialSampling: def __init__(self, length): assert length > 0 self.position = -1 self.length_ = length def __getstate__(self): return self.position, self.length_ def __setstate__(self, state): position, len...
tests/test_modeling_gpt2.py
legacyai/tf-transformers
116
11110666
<filename>tests/test_modeling_gpt2.py # coding=utf-8 # Copyright 2021 TF-Transformers Authors. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache...
examples/swap.py
bpmbank/pyql
488
11110683
<gh_stars>100-1000 """ Port of the swap example of QuantLib SWIG to PyQL. Warning: this is work in progress and currently not working. """ from __future__ import print_function from quantlib.indexes.api import Euribor6M from quantlib.instruments.swap import VanillaSwap, Payer from quantlib.pricingengines.swap import D...
boto3_type_annotations_with_docs/boto3_type_annotations/iot_jobs_data/client.py
cowboygneox/boto3_type_annotations
119
11110704
from typing import Optional from botocore.client import BaseClient from typing import Dict from botocore.paginate import Paginator from botocore.waiter import Waiter from typing import Union class Client(BaseClient): def can_paginate(self, operation_name: str = None): """ Check if an operation can...
butterfree/transform/transformations/__init__.py
fossabot/butterfree
208
11110713
"""Holds all transformations to be used by Features. A transformation must inherit from a TransformComponent and handle data modification, renaming and cast types using parent's (a Feature) information. """ from butterfree.transform.transformations.aggregated_transform import ( AggregatedTransform, ) from butterf...
model/third_party/HMNet/DataLoader/infinibatch/infinibatch/torch/data.py
NickSchoelkopf/SummerTime
178
11110727
<filename>model/third_party/HMNet/DataLoader/infinibatch/infinibatch/torch/data.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch from infinibatch.iterators import CheckpointableIterator from infinibatch.datasets import chunked_dataset_iterator from typing import Union, Iterable,...
Lib/test/test_compiler/testcorpus/60_try_except.py
diogommartins/cinder
1,886
11110742
try: a except Exc: b
ckg/report_manager/apps/apps_config.py
igg-bioinfo/CKG
189
11110776
<reponame>igg-bioinfo/CKG stats_file = "../../data/imports/stats/stats.hdf" logo = '../static/img/logo.png' footer = '<div id="PageFooter"><p> The Clinical Knowledge Graph has been implemented by <a href="mailto:<EMAIL>"><NAME></a>, <a><NAME></a> and <a href="mailto:<EMAIL>"><NAME></a></p></br> <p>This tool is used b...
pyvisa/rname.py
jpsecher/pyvisa
393
11110812
# -*- coding: utf-8 -*- """Functions and classes to parse and assemble resource name. :copyright: 2014-2020 by PyVISA Authors, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ import contextlib import re from collections import defaultdict from dataclasses import dataclass, field, fields...
utils/plot_debug.py
jswulff/mrflow
124
11110839
<reponame>jswulff/mrflow # -*- coding: utf-8 -*- """ Created on Sat Oct 24 18:16:46 2015 @author: jonas """ import numpy as np import flow_viz as viz import os have_plt=False try: from matplotlib import pyplot as plt plt._INSTALL_FIG_OBSERVER=True plt.rcParams['image.cmap'] = 'jet' plt.figure() p...
examples/showcase/src/demos_widgets/hyperlink.py
takipsizad/pyjs
739
11110846
<reponame>takipsizad/pyjs """ The ``ui.Hyperlink`` class acts as an "internal" hyperlink to a particular state of the application. These states are stored in the application's history, allowing for the use of the Back and Next buttons in the browser to move between application states. The ``ui.Hyperlink`` class only ...
health_check/conf.py
witold-gren/django-health-check
739
11110863
from django.conf import settings HEALTH_CHECK = getattr(settings, 'HEALTH_CHECK', {}) HEALTH_CHECK.setdefault('DISK_USAGE_MAX', 90) HEALTH_CHECK.setdefault('MEMORY_MIN', 100) HEALTH_CHECK.setdefault('WARNINGS_AS_ERRORS', True)
REST/python/Targets/register-listening-tentacle.py
gdesai1234/OctopusDeploy-Api
199
11110895
<reponame>gdesai1234/OctopusDeploy-Api import json import requests octopus_server_uri = 'https://your.octopus.app/api' octopus_api_key = 'API-YOURAPIKEY' headers = {'X-Octopus-ApiKey': octopus_api_key} def get_octopus_resource(uri): response = requests.get(uri, headers=headers) response.raise_for_status() ...
osf/migrations/0123_merge_20180803_1346.py
gaybro8777/osf.io
628
11110897
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-08-03 13:46 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('osf', '0122_auto_20180801_2105'), ('osf', '0121_generalize_schema_models'), ] oper...
examples/ls_hf_transformer_encoder_layer.py
HyeongminMoon/PatrickStar
494
11110903
<reponame>HyeongminMoon/PatrickStar # BSD 3-Clause License # # Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of sourc...
fast_arrow/resources/option_chain.py
jwschmo/fast_arrow
143
11110933
<reponame>jwschmo/fast_arrow<gh_stars>100-1000 class OptionChain(object): @classmethod def fetch(cls, client, _id, symbol): """ fetch option chain for instrument """ url = "https://api.robinhood.com/options/chains/" params = { "equity_instrument_ids": _id, ...
examples/tile.py
salt-die/nurses_2
171
11110961
<filename>examples/tile.py import asyncio from pathlib import Path from nurses_2.app import App from nurses_2.widgets.image import Image from nurses_2.widgets.tiled_image import TiledImage LOGO_PATH = Path("images") / "python_discord_logo.png" LOGO_FLAT = Path("images") / "logo_solo_flat_256.png" class MyApp(App): ...
tools/query_tabular/filters.py
supernord/tools-iuc
142
11110984
#!/usr/binsenv python from __future__ import print_function import re import sys from itertools import chain class LineFilter(object): def __init__(self, source, filter_dict): self.source = source self.filter_dict = filter_dict self.func = lambda i, l: l.rstrip('\r\n') if l else None ...
examples/highcharts/column-stacked-and-grouped.py
Jbrunn/python-highcharts
370
11110988
<gh_stars>100-1000 # -*- coding: utf-8 -*- """ Highcharts Demos Stacked and grouped column: http://www.highcharts.com/demo/column-stacked-and-grouped """ from highcharts import Highchart H = Highchart(width=750, height=600) data1 = [5, 3, 4, 7, 2] data2 = [3, 4, 4, 2, 5] data3 = [2, 5, 6, 2, 1] data4 = [3, 0, 4, 4, 3...
plugins/headings/__init__.py
GiovanH/MarkdownEditing
2,612
11111001
from .common import * from .goto import * from .level import * from .style import * from .underlined import *
tests/util/test_get_control_variate_coef.py
xiangze/edward
5,200
11111044
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from edward.util.tensorflow import get_control_variate_coef class test_get_control_variate_coef(tf.test.TestCase): def test_calculate_correct_coefficient(self): with self.test_...
state_representation/client.py
anonymous-authors-2018/robotics-repo
524
11111057
""" Client to communicate with SRL server """ import os import json from enum import Enum import zmq HOSTNAME = 'localhost' SERVER_PORT = 7777 class Command(Enum): HELLO = 0 LEARN = 1 READY = 2 ERROR = 3 EXIT = 4 class SRLClient(object): def __init__(self, data_folder, hostname='localhost'...
unicorn/tests/regress/mips_kernel_mmu.py
clayne/unicorn_pe
491
11111071
<filename>unicorn/tests/regress/mips_kernel_mmu.py #!/usr/bin/python from unicorn import * from unicorn.mips_const import * import regress class MipsSyscall(regress.RegressTest): def test(self): addr = 0x80000000 code = '34213456'.decode('hex') # ori $at, $at, 0x3456 uc = Uc(UC_ARCH_MIPS...
src/programy/nlp/stemming.py
cdoebler1/AIML2
345
11111077
""" Copyright (c) 2016-2020 <NAME> http://www.keithsterling.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, m...
nodes/0.9.x/python/Workset.Kind.py
jdehotin/Clockworkfordynamo
147
11111079
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument worksets = UnwrapElement(IN[0]) elementlist = list() for workset in worksets: try: el...
api/sdlc-integration/run_scan.py
knassar702/community-scripts
629
11111095
# This script should be used to run the actual ZAP scan import sys import core.scan_module.scan as scan scan.main(sys.argv[1:])
network/src/network/stream/visual_stream.py
dropitlikecross/looking-to-listen
123
11111138
<reponame>dropitlikecross/looking-to-listen import chainer import chainer.links as L import chainer.functions as F import env class Visual_Stream(chainer.Chain): # @chainer.static_graph def __call__(self, visual): b = F.leaky_relu(self.bn1(self.conv1(visual))) b = F.leaky_relu(self.bn2(self...
examples/synthetic/syn_cnn_1/syn_cnn_1.py
hase1128/dragonfly
675
11111156
""" A synthetic function on CNNs. -- <EMAIL> """ # pylint: disable=invalid-name # Local from dragonfly.nn.syn_nn_functions import cnn_syn_func1 def syn_cnn_1(x): """ Computes the Branin function. """ return cnn_syn_func1(x[0]) # Write a function like this called 'obj'. def objective(x): """ Objective. ""...
tests/r/test_wong.py
hajime9652/observations
199
11111169
<reponame>hajime9652/observations from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.wong import wong def test_wong(): """Test module wong.py by downloading wong.csv and testing shape of ex...
lahja/exceptions.py
ethereum/lahja
400
11111178
class LahjaError(Exception): """ Base class for all lahja errors """ pass class BindError(LahjaError): """ Raise when an attempt was made to bind an event that is already bound. """ class ConnectionAttemptRejected(LahjaError): """ Raised when an attempt was made to connect to an...
integration_tests/samples/socket_mode/bolt_adapter/websocket_client.py
priya1puresoftware/python-slack-sdk
2,486
11111208
<reponame>priya1puresoftware/python-slack-sdk import os from time import time from typing import Optional from slack_sdk.socket_mode.request import SocketModeRequest from slack_sdk.socket_mode.websocket_client import SocketModeClient from slack_bolt import App from .base_handler import BaseSocketModeHandler from .int...
MLFeatureSelection/__init__.py
yutiansut/Feature-Selection
596
11111279
<reponame>yutiansut/Feature-Selection # __init__.py __version__ = "0.0.9.5.1" __author__ = "<NAME>"
houdini/constants.py
Oblivion-Max/houdini
444
11111294
<filename>houdini/constants.py<gh_stars>100-1000 import enum class StatusField(enum.IntEnum): OpenedIglooViewer = 1 ActiveIglooLayoutOpenFlag = 2 PuffleTreasureInfographic = 512 PlayerOptInAbTestDayZero = 1024 PlayerSwapPuffle = 2048 MoreThanTenPufflesBackyardMessage = 4096 VisitBackyardFi...
optimus/helpers/debug.py
atwoodjw/Optimus
1,045
11111301
<reponame>atwoodjw/Optimus<filename>optimus/helpers/debug.py import inspect from inspect import getframeinfo, stack def get_var_name(var): """ Get the var name from the var passed to a function :param var: :return: """ _locals = inspect.stack()[2][0].f_locals for name in _locals: i...
examples/common_scenarios/sequence_without_tf_binding_sites.py
sukolsak/DnaChisel
124
11111306
from dnachisel import DnaOptimizationProblem, AvoidPattern, random_dna_sequence from urllib import request import pandas as pd from io import StringIO # DOWNLOAD THE LIST OF TF BINDING SITES url = "http://regulondb.ccg.unam.mx/menu/download/datasets/files/BindingSiteSet.txt" data = request.urlopen(url).read().decode("...
docs/gallery/tutorials/pipeshard_parallelism.py
alpa-projects/alpa
114
11111315
<reponame>alpa-projects/alpa """ Distributed Training with Both Shard and Pipeline Parallelism ============================================================= Alpa can automatically parallelizes jax functions with both shard parallelism (a.k.a. intra-operator parallelism) and pipeline parallelism (a.k.a. inter-operator ...
examples/AHEG.py
SignorMercurio/petlib
112
11111344
<reponame>SignorMercurio/petlib ## An implementation of an additivelly homomorphic ## ECC El-Gamal scheme, used in Privex. from petlib.ec import EcGroup import pytest def params_gen(nid=713): """Generates the AHEG for an EC group nid""" G = EcGroup(nid) g = G.generator() o = G.order() return (G, ...
src/genie/libs/parser/iosxe/tests/ShowBridgeDomain/cli/equal/golden_output_4_expected.py
balmasea/genieparser
204
11111346
<reponame>balmasea/genieparser<filename>src/genie/libs/parser/iosxe/tests/ShowBridgeDomain/cli/equal/golden_output_4_expected.py expected_output = { "bridge_domain": { 4050: { "aging_timer": 3600, "bd_domain_id": 4050, "mac_learning_state": "Enabled", "number_...
h2o-py/tests/testdir_algos/stackedensemble/pyunit_stackedensemble_gaussian.py
ahmedengu/h2o-3
6,098
11111362
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import print_function import h2o import sys sys.path.insert(1,"../../../") # allow us to run this standalone from h2o.estimators.random_forest import H2ORandomForestEstimator from h2o.estimators.gbm import H2OGradientBoostingEstimator from h2o.estimato...
dash/misc/misc_data_app.py
jingmouren/QuantResearch
623
11111364
<reponame>jingmouren/QuantResearch #!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import pandas as pd import numpy as np import scipy, scipy.stats from datetime import date, datetime, timedelta from dateutil.relativedelta import relativedelta from sklearn import linear_model import plotly.graph_obj...
app/grandchallenge/uploads/views.py
kaczmarj/grand-challenge.org
101
11111387
import logging from django.http import Http404 from rest_framework import mixins from rest_framework.decorators import action from rest_framework.permissions import DjangoObjectPermissions from rest_framework.response import Response from rest_framework.status import HTTP_400_BAD_REQUEST from rest_framework.viewsets i...
python3/monitor_console.py
charlesnchr/jupyter-vim
358
11111445
<filename>python3/monitor_console.py """ Feature to get a buffer with jupyter output """ # Standard import asyncio from queue import Queue # Local from jupyter_util import echom, unquote_string, str_to_vim, get_vim # Process local import vim class Monitor(): """Jupyter kernel monitor buffer and message line"""...
shadowproxy/proxies/socks/client.py
xiaoshihu/shadowproxy
180
11111470
<reponame>xiaoshihu/shadowproxy import random from curio import socket from ...protocols import socks4, socks5 from ...utils import run_parser_curio, set_disposable_recv from ..base.client import ClientBase class SocksClient(ClientBase): proto = "SOCKS" async def init(self): auth = getattr(self.ns,...
examples/contouring.py
JNDanielson/mplstereonet
120
11111562
<filename>examples/contouring.py<gh_stars>100-1000 """A basic example of producing a density contour plot of poles to planes.""" import matplotlib.pyplot as plt import numpy as np import mplstereonet # Fix random seed so that output is consistent np.random.seed(1977) fig, ax = mplstereonet.subplots() # Generate a ra...
tests/test_fields.py
Highpolar-Softwares/django-url-filter
303
11111590
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import pytest from django import forms from url_filter.fields import MultipleValuesField from url_filter.validators import MaxLengthValidator, MinLengthValidator class TestMultipleValuesField(object): def test_init(self): fi...
tests/test_import_concept_pairs.py
vishalbelsare/kgtk
222
11111611
import shutil import unittest import tempfile import pandas as pd from kgtk.cli_entry import cli_entry from kgtk.exceptions import KGTKException class TestKGTKImportConceptPairs(unittest.TestCase): def setUp(self) -> None: self.temp_dir=tempfile.mkdtemp() def tearDown(self) -> None: shutil.rmt...
python_modules/libraries/dagster-mysql/dagster_mysql/event_log/__init__.py
dbatten5/dagster
4,606
11111614
<filename>python_modules/libraries/dagster-mysql/dagster_mysql/event_log/__init__.py from .event_log import MySQLEventLogStorage
bokeh/sphinxext/util.py
kevin1kevin1k/bokeh
445
11111680
from ..settings import settings from ..resources import Resources def get_sphinx_resources(include_bokehjs_api=False): docs_cdn = settings.docs_cdn() # if BOKEH_DOCS_CDN is unset just use default CDN resources if docs_cdn is None: resources = Resources(mode="cdn") else: # "BOKEH_DOCS_C...
test/crc16.py
pengdao/simcc
108
11111729
<filename>test/crc16.py def crc16(x): b=0xA001 a=0xFFFF for byte in x: a=a^ord(byte) for i in range(8): last=a%2 a=a>>1 if last==1:a=a^b aa='0'*(6-len(hex(a)))+hex(a)[2:] ll,hh=int(aa[:2],16),int(aa[2:],16) return hh+ll*256 print crc16('hello'...
python/mask_detection/models/pd_model.py
windstamp/Paddle-Inference-Demo
115
11111730
import numpy as np from paddle.inference import Config from paddle.inference import create_predictor class Model: def __init__(self, model_file, params_file, use_mkldnn=True, use_gpu=False, device_id=0): config = Config(m...
examples/sharepoint/migration/export_list.py
theodoriss/Office365-REST-Python-Client
544
11111739
from office365.sharepoint.client_context import ClientContext from tests import test_team_site_url, test_client_credentials ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials) ctx.web.lists.get_by_title("Tasks").save_as_template("Tasks.stp", "Tasks", "", True).execute_query()
Lib/test/test_compiler/sbs_code_tests/06_funcall_varargs.py
diogommartins/cinder
1,886
11111750
c = (a, b) fun(a, b, *c) # EXPECTED: [ ..., BUILD_TUPLE_UNPACK_WITH_CALL(2), CALL_FUNCTION_EX(0), ..., ]
tools/perf/page_sets/loading_mobile.py
zipated/src
2,151
11111757
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from page_sets import page_cycler_story from telemetry.page import cache_temperature as cache_temperature_module from telemetry.page import shared_page_state...
lib/core/eval.py
frostinassiky/2D-TAN
249
11111764
import json import argparse import numpy as np from terminaltables import AsciiTable from core.config import config, update_config def iou(pred, gt): # require pred and gt is numpy assert isinstance(pred, list) and isinstance(gt,list) pred_is_list = isinstance(pred[0],list) gt_is_list = isinstance(gt[0],l...
examples/text_classification/model.py
mattolson93/wikipedia2vec
744
11111781
<reponame>mattolson93/wikipedia2vec import torch import torch.nn as nn import torch.nn.functional as F class NABoE(nn.Module): def __init__(self, word_embedding, entity_embedding, num_classes, dropout_prob, use_word): super(NABoE, self).__init__() self.use_word = use_word self.word_embed...
plecost_lib/libs/utils.py
enterstudio/plecost
363
11111808
<gh_stars>100-1000 #!/usr/bin/python # -*- coding: utf-8 -*- # # Plecost: Wordpress vulnerabilities finder # # @url: http://iniqua.com/labs/ # @url: https://github.com/iniqua/plecost # # @author:<NAME> aka ffranz (http://iniqua.com/) # @author:<NAME> aka cr0hn (http://www.cr0hn.com/me/) # # Copyright (c) 2015, Iniqua T...
test_inference.py
shintotm/breast_density_classifier
158
11111825
import argparse import numpy as np MODEL_PATH_DICT = { "cnn": { "tf": "saved_models/BreastDensity_BaselineBreastModel/model.ckpt", "torch": "saved_models/BreastDensity_BaselineBreastModel/model.p", }, "histogram": { "tf": "saved_models/BreastDensity_BaselineHistogramModel/model.ckp...
src/API/python_listener.py
parzival3/Surelog
156
11111852
<reponame>parzival3/Surelog # Sample listener SLregisterNewErrorType("[NOTE :PY0403]", "Module declaration \"%s\"", ""); SLoverrideSeverity("[NOTE :PY0403]", "INFO") def enterModule_nonansi_header(prog, ctx): SLaddErrorContext(prog, ctx, "[INFO :PY0403]", SLgetText(prog, ctx)) def enterModule_ansi_header(prog, ctx...
lib/pymedphys/_imports/slow/imports.py
ethanio12345/pymedphys
207
11111854
# pylint: disable = unused-import, reimported, import-error import tensorflow # type: ignore
koku/sources/test/test_sources_error_message.py
rubik-ai/koku
157
11111862
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Test the Sources Error Messages.""" from django.test import TestCase from rest_framework.serializers import ValidationError from api.common import error_obj from providers.provider_errors import ProviderErrors from sources.sources_error_message...
iPERCore/tools/utils/geometry/mesh.py
JSssssss/iPERCore
2,223
11111885
<reponame>JSssssss/iPERCore<filename>iPERCore/tools/utils/geometry/mesh.py<gh_stars>1000+ # Copyright (c) 2020-2021 impersonator.org authors (<NAME> and <NAME>). All rights reserved. import itertools import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import json def save_to_obj(pat...
recipes/Python/577366_TRAC_Interpreter__Sixties_programming/recipe-577366.py
tdiprima/code
2,023
11111889
import sys import unittest BEGIN_ACTIVE_FUNC = "\x80" BEGIN_NEUTRAL_FUNC = "\x81" END_FUNC = "\x8f" END_ARG = "\x8e" SEGMENT_GAP = "\xff" class TracError(Exception): pass def list_get(list_, index, default=""): try: return list_[index] except: return default def scan_char(list_, pos...