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
libweasyl/libweasyl/alembic/versions/f9226a83bbb6_remove_dead_ads_table.py
akash143143/weasyl
111
61186
"""Remove dead ads table Revision ID: <KEY> Revises: 1307b62614a4 Create Date: 2020-02-27 23:14:41.314000 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '1307b62614a4' from alembic import op # lgtm[py/unused-import] import sqlalchemy as sa # lgtm[py/unused-import] from sqlalchemy...
test/testdata/malformed.py
Scartography/mapchete
161
61209
# contains neither Process object nor execute() function
report_builder_scheduled/migrations/0002_auto_20180413_0747.py
nazmizorlu/django-report-builder
560
61224
# Generated by Django 2.0.4 on 2018-04-13 07:47 from django.conf import settings from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('report_builder_scheduled', '0001_initial'), ] operations = [ migrations.AlterF...
lav/models/rgb.py
Kin-Zhang/LAV
122
61247
import torch from torch import nn from torch.nn import functional as F from .resnet import resnet18, resnet34 from .segmentation import SegmentationHead from .attention import Attention from .erfnet import ERFNet class Normalize(nn.Module): """ ImageNet normalization """ def __init__(self, mean, std): ...
Validation/RecoB/python/bTagAnalysis_harvesting_cfi.py
ckamtsikis/cmssw
852
61273
import FWCore.ParameterSet.Config as cms # BTagPerformanceAnalyzer configuration from Validation.RecoB.bTagAnalysis_cfi import * bTagValidationHarvest = bTagHarvestMC.clone() from DQMOffline.RecoB.bTagAnalysisData_cfi import * bTagValidationHarvestData = bTagHarvest.clone()
scapy/syn-flood/syn_flood.py
caesarcc/python-code-tutorials
1,059
61294
from scapy.all import * import argparse parser = argparse.ArgumentParser(description="Simple SYN Flood Script") parser.add_argument("target_ip", help="Target IP address (e.g router's IP)") parser.add_argument("-p", "--port", help="Destination port (the port of the target's machine service, \ e.g 80 for HTTP, 22 for SS...
Python/data_exchange.py
PushpneetSingh/Hello-world
1,428
61318
<filename>Python/data_exchange.py a = 1 b = 2 print('a = ' + str(a) + ',' + 'b = ' + str(b)) temp = a a = b b = temp print('a = ' + str(a) + ',' + 'b = ' + str(b))
visualize_ML/relation.py
weme123/visualize_ML
195
61349
import pandas as pd import numpy as np from numpy import corrcoef import matplotlib.pyplot as plt from sklearn.feature_selection import chi2 from sklearn.feature_selection import f_classif from math import * plt.style.use('ggplot') fig = plt.figure() COUNTER = 1 #Return the category dictionary,categorical variables l...
engineer/utils/gallery.py
lingtengqiu/Open-PIFuhd
191
61356
import os import numpy as np def save_samples_truncted_prob(fname, points, prob): ''' Save the visualization of sampling to a ply file. Red points represent positive predictions. Green points represent negative predictions. Parameters fname: File name to save points: [N, 3] array o...
exchange_rates/cbr_ru_parse.py
gil9red/SimplePyScripts
117
61409
<reponame>gil9red/SimplePyScripts #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' """Парсер курса доллара и евро за текущую дату от сайта центробанка России.""" import sys from datetime import date # pip install robobrowser from robobrowser import RoboBrowser date_req = date.today().strft...
tests/unit/butterfree/extract/pre_processing/test_explode_json_column.py
fossabot/butterfree
208
61464
from pyspark.sql.types import ( ArrayType, IntegerType, StringType, StructField, StructType, ) from butterfree.extract.pre_processing import explode_json_column from butterfree.testing.dataframe import ( assert_dataframe_equality, create_df_from_collection, ) def test_explode_json_column(...
ui/file_manager/video_player/js/cast/compiled_resources2.gyp
google-ar/chromium
777
61477
<filename>ui/file_manager/video_player/js/cast/compiled_resources2.gyp # 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. { 'targets': [ # { # 'target_name': 'cast_extension_discoverer', # 'incl...
backend/resources/calendar.py
sleepingAnt/viewfinder
645
61486
<reponame>sleepingAnt/viewfinder # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Calendar datamodel. Calendars provide color to a chronology such as the Viewfinder search/ browse tool. Calendars are parsed from the "resources/calendars/" subdirectory on demand and cached. TODO(spencer): this is a very roug...
roles/openshift_health_checker/test/aos_version_test.py
shgriffi/openshift-ansible
164
61554
import pytest import aos_version from collections import namedtuple Package = namedtuple('Package', ['name', 'version']) expected_pkgs = { "spam": { "name": "spam", "version": "3.2.1", "check_multi": False, }, "eggs": { "name": "eggs", "version": "3.2.1", "c...
chrome/test/mini_installer/verifier_runner.py
kjthegod/chromium
2,151
61555
# Copyright 2013 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. import file_verifier import process_verifier import registry_verifier class VerifierRunner: """Runs all Verifiers.""" def __init__(self): """Const...
src/quicknlp/callbacks.py
jalajthanaki/quick-nlp
287
61563
from fastai.sgdr import Callback class CVAELossCallback(Callback): pass
modules/functional/loss.py
Masterchef365/pvcnn
477
61564
import torch import torch.nn.functional as F __all__ = ['kl_loss', 'huber_loss'] def kl_loss(x, y): x = F.softmax(x.detach(), dim=1) y = F.log_softmax(y, dim=1) return torch.mean(torch.sum(x * (torch.log(x) - y), dim=1)) def huber_loss(error, delta): abs_error = torch.abs(error) quadratic = tor...
src/genie/libs/parser/iosxe/tests/ShowPlatformHardwareQfpStatisticsDrop/cli/equal/golden_output_active_expected.py
balmasea/genieparser
204
61635
<reponame>balmasea/genieparser expected_output = { "global_drop_stats": { "Ipv4NoAdj": {"octets": 296, "packets": 7}, "Ipv4NoRoute": {"octets": 7964, "packets": 181}, "PuntPerCausePolicerDrops": {"octets": 184230, "packets": 2003}, "UidbNotCfgd": {"octets": 29312827, "packets": 46639...
generator/transformers/common_producer.py
jordynmackool/sdl_java_suite
138
61644
<reponame>jordynmackool/sdl_java_suite<gh_stars>100-1000 """ Common transformation """ import logging import re from abc import ABC from collections import namedtuple, OrderedDict from model.array import Array from model.enum import Enum from model.struct import Struct class InterfaceProducerCommon(ABC): """ ...
tests/sample7args.py
anki-code/python-hunter
707
61645
from __future__ import print_function def one(a=123, b='234', c={'3': [4, '5']}): for i in range(1): # one a = b = c['side'] = 'effect' two() def two(a=123, b='234', c={'3': [4, '5']}): for i in range(1): # two a = b = c['side'] = 'effect' three() def three(a=123, b='234'...
test/com/facebook/buck/cli/testdata/run-command/cmd/echo_var.py
Unknoob/buck
8,027
61670
from __future__ import absolute_import, division, print_function, unicode_literals import os print("VAR is '{}'".format(os.environ["VAR"]))
src/chapter-4/test_ids.py
luizyao/pytest-chinese-doc
283
61699
<gh_stars>100-1000 #!/usr/bin/env python3 # -*- coding:utf-8 -*- ''' Author: <NAME> (<EMAIL>) Created Date: 2019-10-04 7:05:16 ----- Last Modified: 2019-10-04 7:29:59 Modified By: <NAME> (<EMAIL>) ----- THIS PROGRAM IS FREE SOFTWARE, IS LICENSED UNDER MIT. A short and simple permissive license with conditions only req...
src/netappfiles-preview/azext_netappfiles_preview/_help.py
Mannan2812/azure-cli-extensions
207
61751
<filename>src/netappfiles-preview/azext_netappfiles_preview/_help.py # coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license...
coding_interviews/leetcode/easy/lucky_numbers_in_a_matrix/lucky_numbers_in_a_matrix.py
LeandroTk/Algorithms
205
61779
<gh_stars>100-1000 # https://leetcode.com/problems/lucky-numbers-in-a-matrix def lucky_numbers(matrix): all_lucky_numbers, all_mins = [], [] for row in matrix: found_min, col_index = float('Inf'), -1 for index, column in enumerate(row): if column < found_min: ...
sdk/python/pulumi_azure/domainservices/outputs.py
henriktao/pulumi-azure
109
61800
<gh_stars>100-1000 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, over...
tests/opytimizer/optimizers/swarm/test_sso.py
anukaal/opytimizer
528
61827
import numpy as np from opytimizer.optimizers.swarm import sso from opytimizer.spaces import search def test_sso_params(): params = { 'C_w': 0.1, 'C_p': 0.4, 'C_g': 0.9 } new_sso = sso.SSO(params=params) assert new_sso.C_w == 0.1 assert new_sso.C_p == 0.4 assert ne...
utils/eval_mrr.py
BaoLocPham/hum2song
108
61831
import argparse import csv import sys import os sys.path.append(os.path.dirname(os.path.dirname(__file__))) from modules.metric import mean_reciprocal_rank def main(csv_path): acc = 0 num = 0 with open(csv_path, "r") as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count ...
rl/util.py
AsimKhan2019/OpenAI-Lab
340
61832
<filename>rl/util.py import argparse import collections import inspect import json import logging import multiprocessing as mp import numpy as np import re import sys import zipfile from datetime import datetime, timedelta from os import path, listdir, environ, getpid from textwrap import wrap PARALLEL_PROCESS_NUM = m...
ufora/FORA/python/PurePython/StringTestCases.py
ufora/ufora
571
61852
# Copyright 2015 Ufora 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 agreed to i...
djangoerp/pluggets/pluggets.py
xarala221/django-erp
345
61877
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals """This file is part of the django ERP project. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PART...
tests/contrib/test_cached_dataset.py
mmathys/bagua
635
61948
from bagua.torch_api.contrib.cached_dataset import CachedDataset from torch.utils.data.dataset import Dataset import numpy as np import logging import unittest from tests import skip_if_cuda_available logging.basicConfig(level=logging.DEBUG) class MyDataset(Dataset): def __init__(self, size): self.size =...
rupo/metre/metre_classifier.py
dagrigorev/rupo
171
61954
<filename>rupo/metre/metre_classifier.py # -*- coding: utf-8 -*- # Автор: <NAME> # Описание: Классификатор метра. from collections import OrderedDict from typing import List, Dict, Tuple import jsonpickle import logging from rupo.main.markup import Line, Markup from rupo.util.mixins import CommonMixin from rupo.metre...
nautobot/dcim/migrations/0003_initial_part_3.py
psmware-ltd/nautobot
384
61966
# Generated by Django 3.1.7 on 2021-04-01 06:35 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import mptt.fields import nautobot.extras.models.statuses import taggit.managers class Migration(migrations.Migration): initial = True dependencies = [ ...
client/tests/test_proof.py
mithril-security/blindai
121
62033
from copy import deepcopy from hashlib import sha256 import os import unittest from google.protobuf.timestamp_pb2 import Timestamp from blindai.pb.securedexchange_pb2 import ( Payload, ) from blindai.client import ( RunModelResponse, UploadModelResponse, ) from blindai.dcap_attestation import Policy from ...
problems/first-non-repeated-character/first-non-repeated-character-answer.py
lhayhurst/interview-with-python
201
62114
##$$## ---------- TAGS ----------- ##$$## ##$$## first,non,repeated,character ##$$## --------- ENDTAGS --------- ##$$## ###### - Write your answer below - ######
momentumnet-main/examples/drop_in_replacement_tutorial.py
ZhuFanCheng/Thesis
188
62118
<reponame>ZhuFanCheng/Thesis """ ====================================================== From ResNets to Momentum ResNets 1) ====================================================== This is a tutorial to use the transform_to_momentumnet method: <NAME>, <NAME>, <NAME>, <NAME>. Momentum Residual Neural Networks. Proceedin...
macarico/tasks/cartpole.py
bgalbraith/macarico
121
62193
<gh_stars>100-1000 """ Largely based on the OpenAI Gym Implementation https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py """ from __future__ import division, generators, print_function import numpy as np import macarico import math import torch import torch.nn as nn import torch.nn.function...
tests/test_torchy.py
sagnik/baseline
241
62200
<reponame>sagnik/baseline import pytest import numpy as np torch = pytest.importorskip('torch') from baseline.utils import Offsets from baseline.pytorch.torchy import SequenceCriterion C = 10 B = 50 S = 20 @pytest.fixture def lengths(): lengths = torch.randint(1, S, size=(B,)).long() return lengths @pytest...
multimedia/gui/lvgl/lvgl_img.py
708yamaguchi/MaixPy_scripts
485
62208
<reponame>708yamaguchi/MaixPy_scripts<gh_stars>100-1000 import lvgl as lv import lvgl_helper as lv_h import lcd import time from machine import Timer from machine import I2C import touchscreen as ts i2c = I2C(I2C.I2C0, freq=400000, scl=30, sda=31) lcd.init() ts.init(i2c) lv.init() disp_buf1 = lv.disp_buf_t() buf1_...
script/dumpdex.py
4ch12dy/xadb
326
62220
<filename>script/dumpdex.py import json import os import sys import frida import time import re if len(sys.argv) <= 1: print("[Dumpdex]: you should pass pid/packageName") exit() device = frida.get_usb_device() pkg_name = device.get_frontmost_application().identifier # check is package or pid pattern = re.compile...
recipes/Python/576735_How_to_use_twisted_pb_FilePager/recipe-576735.py
tdiprima/code
2,023
62224
<reponame>tdiprima/code from twisted.spread.util import FilePager from twisted.spread.flavors import Referenceable from twisted.internet.defer import Deferred import os PATH = r"C:\temp\very_large_file.exe" ### Server Side class ResultsPager(FilePager): def __init__(self, collector, path): self._deferred...
RecoPixelVertexing/PixelLowPtUtilities/python/StripSubClusterShapeSeedFilter_cfi.py
ckamtsikis/cmssw
852
62267
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms from RecoPixelVertexing.PixelLowPtUtilities.StripSubClusterShapeFilter_cfi import StripSubClusterShapeFilterParams StripSubClusterShapeSeedFilter = cms.PSet( StripSubClusterShapeFilterParams, ComponentName = cms.string('StripSubClusterShapeSeedFilter'...
src/protocols/MQTT/attacks/mqtt_generation_based_fuzzing.py
QWERTSKIHACK/peniot
143
62346
<filename>src/protocols/MQTT/attacks/mqtt_generation_based_fuzzing.py import multiprocessing import unittest import paho.mqtt.client as paho import logging import random import signal import struct import time from Entity.attack import Attack from Entity.input_format import InputFormat from Utils.RandomUtil import r...
tests/chainer_tests/functions_tests/normalization_tests/test_layer_normalization.py
zaltoprofen/chainer
3,705
62351
import numpy from chainer import functions from chainer import testing @testing.parameterize(*(testing.product({ 'batchsize': [1, 5], 'size': [10, 20], 'dtype': [numpy.float32], 'eps': [1e-5, 1e-1], }))) @testing.inject_backend_tests( None, # CPU tests [ {}, ] # GPU tests ...
tests/integration/test_indices.py
fduguet-nv/cunumeric
304
62373
# Copyright 2022 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
tools/SDKTool/src/WrappedDeviceAPI/deviceAPI/pcDevice/windows/windowsDeviceAPI.py
Passer-D/GameAISDK
1,210
62389
<filename>tools/SDKTool/src/WrappedDeviceAPI/deviceAPI/pcDevice/windows/windowsDeviceAPI.py<gh_stars>1000+ # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full detail...
examples/calibration_registration/register.py
seanyen/Azure-Kinect-Sensor-SDK
1,120
62400
""" An app script to run registration between two cameras from the command line. Copyright (C) Microsoft Corporation. All rights reserved. """ # Standard Libraries. import argparse # Calibration tools. from camera_tools import register # ------------------------------------------------------------------------------...
VulnerableScan/migrations/0004_remove_exploitregister_file_object_and_more.py
b0bac/ApolloScanner
289
62433
# Generated by Django 4.0.1 on 2022-03-10 17:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Assets', '0003_alter_assetlist_timestamp_alter_assettask_timestamp'), ('VulnerableScan', '0003_alter_exploitregister...
tests/framework/CodeInterfaceTests/RAVEN/ReturnDatabase/innerRunDir/nd_data.py
rinelson456/raven
159
62469
# Copyright 2017 Battelle Energy Alliance, 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 t...
db_bascline.py
wstart/DB_BaseLine
152
62546
<reponame>wstart/DB_BaseLine # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') from script.mysql_baseline import * from loghandle import * import getopt if __name__ == "__main__": bannber = ''' ____ ____ ____ _ _ {''' + db_baseline_basic.getVersion() + '''} | ...
data-processing/scripts/fetch_arxiv_sources.py
hhchi13/scholarphi
285
62553
<filename>data-processing/scripts/fetch_arxiv_sources.py import argparse import os from common import directories from common.fetch_arxiv import fetch_from_arxiv from common.unpack import unpack, unpack_archive if __name__ == "__main__": parser = argparse.ArgumentParser( "Fetch and unpack sources for a si...
src/gfl/shell/shell.py
mingt2019/GFL
123
62578
<gh_stars>100-1000 import os import sys import requests from gfl.conf import GflConf class Shell(object): __host = "127.0.0.1" __port = 9434 @classmethod def welcome(cls, **kwargs): print("------- GFL -------") print("%-20s:%s" % ("pid", str(os.getpid()))) @classmethod def...
tests/ignite/distributed/utils/test_serial.py
Juddd/ignite
4,119
62607
import torch import ignite.distributed as idist from tests.ignite.distributed.utils import ( _sanity_check, _test_distrib__get_max_length, _test_distrib_all_gather, _test_distrib_all_reduce, _test_distrib_barrier, _test_distrib_broadcast, _test_sync, ) def test_no_distrib(capsys): as...
src/train.py
anirbanlahiri2017/Tartarus
104
62624
from __future__ import print_function import argparse from collections import OrderedDict import json import os import logging from keras.callbacks import EarlyStopping from sklearn.preprocessing import normalize from sklearn.metrics import roc_curve, auc, roc_auc_score, precision_score, recall_score, f1_score, accurac...
torba/torba/client/errors.py
mittalkartik2000/lbry-sdk
4,076
62699
<reponame>mittalkartik2000/lbry-sdk class InsufficientFundsError(Exception): pass
kafka_influxdb/tests/encoder_test/test_heapster_json_encoder.py
gldnspud/kafka-influxdb
224
62715
import unittest from kafka_influxdb.encoder import heapster_json_encoder class TestHeapsterJsonEncoder(unittest.TestCase): def setUp(self): self.encoder = heapster_json_encoder.Encoder() def testEncoder(self): msg = b'{ "MetricsName":"memory/major_page_faults","MetricsValue":{"value":56}, "...
hail/python/cluster-tests/cluster-write-many-partitions.py
tdeboer-ilmn/hail
789
62717
<gh_stars>100-1000 import hail as hl ht = hl.utils.range_table(1_000_000, n_partitions=10_000) # use HDFS so as not to create garbage on GS ht.write('/tmp/many_partitions.ht') mt = hl.utils.range_matrix_table(1_000_000, 2, n_partitions=10_000) mt.write('/tmp/many_partitions.mt')
src/dev/steve/Escape_T6/logs/statsDistances.py
wvat/NTRTsim
148
62721
""" Prints the min, avg, max of the numbers on each line """ import sys try: f = open(sys.argv[1], 'r') lines = 0 sum = 0 max = 0 min = 9999999 for line in f: lines += 1 x = float(line.partition(',')[0]) sum += x if x < min: min = x if x > ma...
tests/unit/test_results.py
diadochos/elfi
166
62722
<gh_stars>100-1000 import numpy as np import pytest import elfi def test_sample(): n_samples = 10 parameter_names = ['a', 'b'] distance_name = 'dist' samples = [ np.random.random(n_samples), np.random.random(n_samples), np.random.random(n_samples) ] outputs = dict(zip(...
Anaconda-files/Program_03a.py
arvidl/dynamical-systems-with-applications-using-python
106
62800
<filename>Anaconda-files/Program_03a.py # Program 03a: Phase portrait of a linear system. # See Figure 3.8(a). import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint import pylab as pl # The 2-dimensional linear system a, b, c, d = 2, 1, 1, 2 def dx_dt(x, t): return [a*x[0] + b*x[1...
zerver/tests/test_thumbnail.py
Pulkit007/zulip
17,004
62815
<gh_stars>1000+ from io import StringIO import orjson from zerver.lib.test_classes import ZulipTestCase class ThumbnailTest(ZulipTestCase): def test_thumbnail_redirect(self) -> None: self.login("hamlet") fp = StringIO("zulip!") fp.name = "zulip.jpeg" result = self.client_post("/...
specutils/tests/test_utils.py
havok2063/specutils
118
62823
import pickle import pytest import numpy as np from astropy import units as u from astropy import modeling from specutils.utils import QuantityModel from ..utils.wcs_utils import refraction_index, vac_to_air, air_to_vac wavelengths = [300, 500, 1000] * u.nm data_index_refraction = { 'Griesen2006': np.array([3.073...
tools/bin/pythonSrc/pychecker-0.8.18/test_input/import37.py
YangHao666666/hawq
450
62846
'd' class Test: 'doc' def x(self): import struct print struct
unmaintain/benchmark/benchmark_seaweedfs.py
zuzhi/rssant
1,176
62985
import aiohttp import asyncio import os import sys import time import random import contextlib seaweedfs_url = 'http://127.0.0.1:9081' def random_content(): return os.urandom(random.randint(1, 10) * 1024) def random_fid(volumes): volume_id = random.choice(volumes) file_key = random.randint(0, 1 << 24)...
tools/migrate_chart/migrate_chart.py
kschu91/harbor
12,706
63034
#!/usr/local/bin/python3 import subprocess import signal import sys from pathlib import Path import click import requests MIGRATE_CHART_SCRIPT = '/migrate_chart.sh' HELM_CMD = '/linux-amd64/helm' CA_UPDATE_CMD = 'update-ca-certificates' CHART_URL_PATTERN = "https://{host}/api/v2.0/projects/{project}/repositories/{na...
opal_common/authentication/types.py
NateKat/opal
367
63068
from enum import Enum from typing import Dict, Any from jwt.algorithms import get_default_algorithms from cryptography.hazmat._types import ( _PRIVATE_KEY_TYPES, _PUBLIC_KEY_TYPES, ) # custom types PrivateKey = _PRIVATE_KEY_TYPES PublicKey = _PUBLIC_KEY_TYPES JWTClaims = Dict[str, Any] class EncryptionKeyFo...
bigchaindb/exceptions.py
AbhishaB/bigchaindb
474
63111
<filename>bigchaindb/exceptions.py # Copyright BigchainDB GmbH and BigchainDB contributors # SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) # Code is Apache-2.0 and docs are CC-BY-4.0 class BigchainDBError(Exception): """Base class for BigchainDB exceptions.""" class CriticalDoubleSpend(BigchainDBError): ...
examples/med_sts_clinical.py
anwar1103/semantic-text-similarit
167
63230
<reponame>anwar1103/semantic-text-similarit<filename>examples/med_sts_clinical.py from semantic_text_similarity.models import ClinicalBertSimilarity from scipy.stats import pearsonr model = ClinicalBertSimilarity() predictions = model.predict([("The patient is sick.", "Grass is green."), (...
Chapter2/ex_2_36.py
zxjzxj9/PyTorchIntroduction
205
63240
<gh_stars>100-1000 """ 该代码仅为演示函数签名所用,并不能实际运行 """ save_info = { # 保存的信息 "iter_num": iter_num, # 迭代步数 "optimizer": optimizer.state_dict(), # 优化器的状态字典 "model": model.state_dict(), # 模型的状态字典 } # 保存信息 torch.save(save_info, save_path) # 载入信息 save_info = torch.load(save_path) optimizer.load_state_dict(save_info...
utils/wrappers.py
pacificlion/world_models
106
63252
<reponame>pacificlion/world_models # Copyright 2020 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 appli...
pytorch_pfn_extras/distributed/__init__.py
belltailjp/pytorch-pfn-extras
243
63275
<gh_stars>100-1000 from pytorch_pfn_extras.distributed._dataset_util import create_distributed_subset_indices # NOQA
lightnet/__init__.py
rversaw/lightnet
345
63279
<reponame>rversaw/lightnet<gh_stars>100-1000 # coding: utf8 from __future__ import unicode_literals from .lightnet import Network, Image, BoxLabels from .about import __version__ def load(name, path=None): return Network.load(name, path=path)
ghida_plugin/ghidra_plugin/FunctionDecompile.py
wumb0/GhIDA
675
63288
<filename>ghida_plugin/ghidra_plugin/FunctionDecompile.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################## # # # FunctionDecompile - Ghidra plugin ...
spyql/output_handler.py
alin23/spyql
432
63315
<reponame>alin23/spyql from spyql.nulltype import Null class OutputHandler: """Mediates data processing with data writting""" @staticmethod def make_handler(prs): """ Chooses the right handler depending on the kind of query and eventual optimization opportunities """ ...
tests/gamestonk_terminal/stocks/quantitative_analysis/test_factors_view.py
elan17/GamestonkTerminal
1,835
63326
<filename>tests/gamestonk_terminal/stocks/quantitative_analysis/test_factors_view.py<gh_stars>1000+ # IMPORTATION STANDARD # IMPORTATION THIRDPARTY import pytest # IMPORTATION INTERNAL from gamestonk_terminal.stocks.quantitative_analysis import factors_view @pytest.fixture(scope="module") def vcr_config(): retu...
wikum/statistics/analyze_initiators.py
xuericlin/wikum
114
63375
<reponame>xuericlin/wikum from __future__ import print_function # coding: utf-8 # In[1]: from builtins import zip get_ipython().magic(u'matplotlib inline') import MySQLdb import pandas as pd import matplotlib import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [20,12] # In[2]: conn = MySQLdb.connect...
experimental/gradient_noise/plot_noise.py
Pandinosaurus/KungFu
291
63386
<filename>experimental/gradient_noise/plot_noise.py import re import matplotlib import matplotlib.cm as cm import matplotlib.patches as mpatches import matplotlib.pyplot as plt import numpy as np # Regex used to match relevant loglines (in this case, a specific IP address) line_regex = re.compile(r".*$") def get_ex...
python/intro.py
surabhi226005/functional-programming-learning-path
627
63389
# Assign functions to a variable def add(a, b): return a + b plus = add value = plus(1, 2) print(value) # 3 # Lambda value = (lambda a, b: a + b)(1, 2) print(value) # 3 addition = lambda a, b: a + b value = addition(1, 2) print(value) # 3 authors = [ '<NAME>', '<NAME>', '<NAME>', '<NAME>', ...
basic-example/test.py
tr4r3x/remora
206
63409
#!/usr/bin/python import requests def check(): data = {} consumers = requests.get('http://localhost:9000/consumers').json() for consumer_group in consumers: consumer_infos = requests.get( 'http://localhost:9000/consumers/{consumer_group}'.format( consumer_group=cons...
flexbe_core/test/test_proxies.py
duwke/flexbe_behavior_engine
119
63430
<reponame>duwke/flexbe_behavior_engine<gh_stars>100-1000 #!/usr/bin/env python import unittest import rospy import actionlib from flexbe_core.proxy import ProxyPublisher, ProxySubscriberCached, ProxyActionClient, ProxyServiceCaller from std_msgs.msg import String from std_srvs.srv import Trigger, TriggerRequest from f...
tests/test_activations.py
themantalope/DLTK
1,397
63441
import tensorflow as tf from dltk.core.activations import leaky_relu import numpy as np def test_leaky_relu(): test_alpha = tf.constant(0.1) test_inp_1 = tf.constant(1.) test_inp_2 = tf.constant(-1.) test_relu_1 = leaky_relu(test_inp_1, test_alpha) test_relu_2 = leaky_relu(test_inp_2, test_alpha)...
text_extensions_for_pandas/array/thing_table.py
ZachEichen/text-extensions-for-pandas
193
63468
# # Copyright (c) 2021 IBM Corp. # 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 writi...
flash2560.py
kaleidoscopeit/esp-link
2,522
63482
#!/usr/bin/env python # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # <NAME> wrote this file. As long as you retain # this notice you can do whatever you want with this stuff. If we meet some day, # and you think this stuff is worth it, you ca...
openbook_categories/serializers.py
TamaraAbells/okuna-api
164
63484
from rest_framework import serializers from openbook_categories.models import Category class GetCategoriesCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ( 'id', 'name', 'title', 'description', 'avat...
lightnlp/sl/ner/utils/convert.py
CNLPT/lightNLP
889
63490
def iob_ranges(words, tags): """ IOB -> Ranges """ assert len(words) == len(tags) ranges = [] def check_if_closing_range(): if i == len(tags) - 1 or tags[i + 1].split('_')[0] == 'O': ranges.append({ 'entity': ''.join(words[begin: i + 1]), 'typ...
CGI/simple-server-with-different-languages/cgi-bin/download.py
whitmans-max/python-examples
140
63557
<filename>CGI/simple-server-with-different-languages/cgi-bin/download.py #!/usr/bin/env python import os import sys fullpath = 'images/normal.png' filename = 'hello_world.png' # headers print 'Content-Type: application/octet-stream; name="%s"' % filename print 'Content-Disposition: attachment; filename="%s"' % filen...
foreman/data_refinery_foreman/foreman/management/commands/test_import_external_sample_attributes.py
AlexsLemonade/refinebio
106
63570
from unittest.mock import patch from django.test import TestCase import vcr from data_refinery_common.models import ( Contribution, Experiment, ExperimentSampleAssociation, OntologyTerm, Sample, SampleAttribute, ) from data_refinery_foreman.foreman.management.commands.import_external_sample_a...
flags/tests/test_management_commands_enable_flag.py
mdunc/django-flags
142
63660
from io import StringIO from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase from flags.state import flag_enabled class EnableFlagTestCase(TestCase): def test_enable_flag(self): out = StringIO() self.assertFalse(fla...
test/loader/test_link_neighbor_loader.py
NucciTheBoss/pytorch_geometric
2,350
63665
<filename>test/loader/test_link_neighbor_loader.py import pytest import torch from torch_geometric.data import Data, HeteroData from torch_geometric.loader import LinkNeighborLoader def get_edge_index(num_src_nodes, num_dst_nodes, num_edges): row = torch.randint(num_src_nodes, (num_edges, ), dtype=torch.long) ...
chakin/downloader.py
massongit/chakin
334
63675
# -*- coding: utf-8 -*- import os import pandas as pd from progressbar import Bar, ETA, FileTransferSpeed, ProgressBar, Percentage, RotatingMarker from six.moves.urllib.request import urlretrieve def load_datasets(path=os.path.join(os.path.dirname(__file__), 'datasets.csv')): datasets = pd.read_csv(path) ret...
script/build_day_stat.py
khamdamoff/daysandbox_bot
101
63689
<gh_stars>100-1000 from collections import Counter from datetime import datetime, timedelta from database import connect_db def setup_arg_parser(parser): parser.add_argument('days_ago', type=int, default=0) def get_chat_id(event): return event.get('chat_id', event['chat']['id']) def main(days_ago, **kwa...
asreview/query_strategies.py
DominiqueMaciejewski/asreview
280
63702
# Copyright 2019-2020 The ASReview 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.org/licenses/LICENSE-2.0 # # Unless required by appl...
sunrgbd/prepare_data.py
lemontyc/frustum-convnet
247
63710
''' Helper class and functions for loading SUN RGB-D objects Author: <NAME> Date: October 2017 Modified by <NAME> ''' import os import sys import numpy as np import pickle import argparse from PIL import Image BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) import sunrgbd_utils as u...
program_synthesis/karel/dataset/coverage.py
kavigupta/program_synthesis
123
63720
from program_synthesis.karel.dataset import executor from program_synthesis.karel.dataset import parser_for_synthesis branch_types = {'if', 'ifElse', 'while'} stmt_types = {'move', 'turnLeft', 'turnRight', 'putMarker', 'pickMarker'} class CoverageMeasurer(object): def __init__(self, code): self.parser = p...
test/augmenter/word/test_back_translation.py
techthiyanes/nlpaug
3,121
63741
<gh_stars>1000+ import unittest import os import torch from dotenv import load_dotenv import nlpaug.augmenter.word as naw import nlpaug.model.lang_models as nml class TestBackTranslationAug(unittest.TestCase): @classmethod def setUpClass(cls): env_config_path = os.path.abspath(os.path.join( ...
snaek/ffi.py
mitsuhiko/snaek
272
63742
import os import re import sys import cffi from ._compat import PY2 _directive_re = re.compile(r'^\s*#.*?$(?m)') def make_ffi(module_path, crate_path, cached_header_filename=None): """Creates a FFI instance for the given configuration.""" if cached_header_filename is not None and \ os.path.isfile(ca...
google-api-client-generator/src/googleapis/codegen/cpp_import_manager_test.py
cclauss/discovery-artifact-manager
178
63751
#!/usr/bin/python2.7 # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
pynacl/lib/__init__.py
cohortfsllc/cohort-cocl2-sandbox
2,151
63823
#!/usr/bin/python # Copyright (c) 2014 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Unfortunately python does not have a good way to deal with module name # clashes. The easiest way to get around it is to use a l...
autograd/numpy/__init__.py
gautam1858/autograd
6,119
63893
<filename>autograd/numpy/__init__.py<gh_stars>1000+ from __future__ import absolute_import from .numpy_wrapper import * from . import numpy_boxes from . import numpy_vspaces from . import numpy_vjps from . import numpy_jvps from . import linalg from . import fft from . import random
tests/test_bpe.py
Pimax1/keras-gpt-2
131
63902
import os from unittest import TestCase from keras_gpt_2 import get_bpe_from_files class TestBPE(TestCase): def test_encode_and_decode(self): current_path = os.path.dirname(os.path.abspath(__file__)) toy_checkpoint_path = os.path.join(current_path, 'toy_checkpoint') encoder_path = os.path...