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/config/test_manager.py | NishanBanga/JobFunnel | 1,652 | 84327 | # FIXME: need to break down config manager testing a bit more
# @pytest.mark.parametrize('pass_del_cfg', (True, False))
# def test_config_manager_init(mocker, pass_del_cfg):
# """NOTE: unlike other configs this one validates itself on creation
# """
# # Mocks
# patch_del_cfg = mocker.patch('jobfunnel.co... |
components/stdproc/stdproc/offsetpoly/test/offpoly.py | vincentschut/isce2 | 1,133 | 84352 | <reponame>vincentschut/isce2<gh_stars>1000+
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2014 California Institute of Technology. ALL RIGHTS RESERVED.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wit... |
analysis/command_line.py | ebell495/nn_pruning | 250 | 84362 | <gh_stars>100-1000
#!/usr/bin/env python
import click
import json
import sh
from pathlib import Path
from datetime import datetime
from analyze_run import ModelAnalysis
from create_model import Packager
from plot import main_plot
import os
import sys
from aws_download import AWSExperienceDownloader
@click.group()
@cl... |
examples/Ternary-Net/ternary.py | skoppula/ternarynet | 109 | 84374 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tensorflow as tf
G = tf.get_default_graph()
def p_ternarize(x, p):
x = tf.tanh(x)
shape = x.get_shape()
thre = tf.get_variable('T', trainable=False, collections=[tf.GraphKeys.VARIABLES, 'thresholds'],
initializer=0.05)
flat_x = tf.res... |
melissa/actions/imgur_handler.py | blacksparrow6/Melissa-Core | 554 | 84378 | <filename>melissa/actions/imgur_handler.py
import os
import sqlite3
from datetime import datetime
from imgurpython import ImgurClient
# Melissa
from melissa import profile
from melissa.tts import tts
WORDS = {'image_uploader': {'groups': ['upload']},
'show_all_uploads': {'groups': [['all', 'uploads'],
... |
bot.py | Zwork101/tf2_trade_bot | 150 | 84396 | import os
import sys
import json
import time
from distutils.version import LooseVersion
import importlib
import pip
from enum import Enum
import logging
import csv
import subprocess
try:
main = pip.main
except AttributeError:
# module 'pip' has no attribute 'main'
from pip._internal import main
apikey = ''... |
examples/docs_examples/custom_transform.py | neuroailab/ffcv | 1,969 | 84410 | """
Example of defining a custom (image) transform using FFCV.
For tutorial, see https://docs.ffcv.io/ffcv_examples/custom_transforms.html.
"""
import time
import numpy as np
import torchvision
from ffcv.fields import IntField, RGBImageField
from ffcv.fields.decoders import SimpleRGBImageDecoder
from ffcv.loader impo... |
test/programytest/clients/events/test_client.py | cdoebler1/AIML2 | 345 | 84420 | import unittest.mock
from programy.clients.config import ClientConfigurationData
from programy.clients.events.client import EventBotClient
from programytest.clients.arguments import MockArgumentParser
class MockEventBotClient(EventBotClient):
def __init__(self, id, argument_parser=None):
EventBotClient.... |
basicsr/archs/edsr_arch.py | Cospel/BasicSR | 3,168 | 84422 | import torch
from torch import nn as nn
from basicsr.archs.arch_util import ResidualBlockNoBN, Upsample, make_layer
from basicsr.utils.registry import ARCH_REGISTRY
@ARCH_REGISTRY.register()
class EDSR(nn.Module):
"""EDSR network structure.
Paper: Enhanced Deep Residual Networks for Single Image Super-Resol... |
tests/packagedcode/data/pypi/setup.py/arpy_setup.py | s4-2/scancode-toolkit | 1,511 | 84432 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
setup(name='arpy',
version='0.1.1',
description='Library for accessing "ar" files',
author=u'<NAME>',
author_email='<EMAIL>',
url='http://bitbucket.org/viraptor/arpy',
py_modules=['arpy'],
license="Simplified BSD",
)
|
googleanalytics/commands/query.py | ruber0id/google-analytics | 170 | 84439 | # encoding: utf-8
import json
import yaml
import click
import googleanalytics as ga
from googleanalytics import utils
from .common import cli
# TODO: the blueprint stuff can probably be simplified so that
# it's little more than just a call to ga.describe
def from_blueprint(scope, src):
description = yaml.load(... |
colour/appearance/tests/test_hunt.py | colour-science/colour | 1,380 | 84490 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Defines the unit tests for the :mod:`colour.appearance.hunt` module.
"""
import numpy as np
from itertools import permutations
from colour.appearance import (VIEWING_CONDITIONS_HUNT, InductionFactors_Hunt,
XYZ_to_Hunt)
from colour.appea... |
tests/test_self_signed_jwt.py | Yoni-Mantzur/azure-activedirectory-library-for-python | 258 | 84493 | #------------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation.
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... |
backend/db/test/user_photo_test.py | sleepingAnt/viewfinder | 645 | 84537 | <filename>backend/db/test/user_photo_test.py
# Copyright 2013 Viewfinder Inc. All Rights Reserved
"""Tests for UserPhoto data object."""
__author__ = '<EMAIL> (<NAME>)'
from base_test import DBBaseTestCase
from viewfinder.backend.db.user_photo import UserPhoto
from viewfinder.backend.db import versions
class UserPh... |
tests/index_routines.py | Saran-nns/cunumeric | 118 | 84541 | <reponame>Saran-nns/cunumeric
# Copyright 2021 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 app... |
wrappers/python/tests/ledger/test_build_attrib_request.py | absltkaos/indy-sdk | 636 | 84554 | import json
import pytest
from indy import ledger, error
@pytest.mark.asyncio
async def test_build_attrib_request_works_for_raw_value():
identifier = "Th7MpTaRZVRYnPiabds81Y"
destination = "Th7MpTaRZVRYnPiabds81Y"
raw = '{"endpoint":{"ha":"127.0.0.1:5555"}}'
expected_response = {
"identifier... |
nebullvm/optimizers/quantization/utils.py | emilecourthoud/nebullvm | 821 | 84559 | import warnings
from typing import Tuple, Callable, Any, List
import numpy as np
from nebullvm.base import QuantizationType
from nebullvm.inference_learners.base import BaseInferenceLearner
from nebullvm.measure import compute_relative_difference
def check_precision(
optimized_learner: BaseInferenceLearner,
... |
tests/TestLogging.py | asukiaaa/cadquery | 403 | 84568 | import unittest
import mock
from copy import copy
from tests import BaseTest
import logging
# Units under test
import cadquery
from cadquery.freecad_impl import console_logging
class TestLogging(BaseTest):
def setUp(self):
# save root logger's state
root_logger = logging.getLogger()
self... |
test/regression/features/integers/unary_minus.py | ppelleti/berp | 137 | 84603 | <reponame>ppelleti/berp
print(-1)
print(-0)
print(-(6))
print(-(12*2))
print(- -10)
|
src/genie/libs/parser/iosxe/tests/ShowKeyChain/cli/equal/golden_output1_expected.py | balmasea/genieparser | 204 | 84617 | expected_output = {
"key_chains": {
"bla": {
"keys": {
1: {
"accept_lifetime": {
"end": "always valid",
"is_valid": True,
"start": "always valid",
},
... |
corehq/ex-submodules/phonelog/migrations/0013_delete_olddevicereportentry.py | dimagilg/commcare-hq | 471 | 84701 | # Generated by Django 1.10.7 on 2017-07-11 12:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('phonelog', '0012_server_date_not_null'),
]
operations = [
migrations.DeleteModel(
name='OldDeviceReportEntry',
),
]
|
i18naddress/__init__.py | rsat/google-i18n-address | 112 | 84702 | from __future__ import unicode_literals
import io
import json
import os
import re
from collections import OrderedDict
VALID_COUNTRY_CODE = re.compile(r"^\w{2,3}$")
VALIDATION_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
VALIDATION_DATA_PATH = os.path.join(VALIDATION_DATA_DIR, "%s.json")
FIELD_MAPPING =... |
generate/generate_sentihood_NLI_M.py | bubblemans/ABSA-BERT-pair | 462 | 84722 | <reponame>bubblemans/ABSA-BERT-pair
import os
from data_utils_sentihood import *
data_dir='../data/sentihood/'
aspect2idx = {
'general': 0,
'price': 1,
'transit-location': 2,
'safety': 3,
}
(train, train_aspect_idx), (val, val_aspect_idx), (test, test_aspect_idx) = load_task(data_dir, aspect2idx)
pr... |
WebMirror/management/rss_parser_funcs/feed_parse_extractLizonkanovelsWordpressCom.py | fake-name/ReadableWebProxy | 193 | 84748 | def extractLizonkanovelsWordpressCom(item):
'''
Parser for 'lizonkanovels.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('bestial blade by priest', ... |
ch49-计算摄影学-图像去噪/1-fastNlMeansDenoisingColored.py | makelove/OpenCV-Python-Tutorial | 2,875 | 84760 | <gh_stars>1000+
# -*- coding: utf-8 -*-
# @Time : 2017/7/13 下午9:56
# @Author : play4fun
# @File : 1-fastNlMeansDenoisingColored.py
# @Software: PyCharm
"""
1-fastNlMeansDenoisingColored.py:
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('die.png')
img = cv2.cvtColor(im... |
pythonforandroid/recipes/vk/vk/exceptions.py | alexben16/python-for-android | 119 | 84772 |
# API Error Codes
AUTHORIZATION_FAILED = 5 # Invalid access token
PERMISSION_IS_DENIED = 7
CAPTCHA_IS_NEEDED = 14
ACCESS_DENIED = 15 # No access to call this method
INVALID_USER_ID = 113 # User deactivated
class VkException(Exception):
pass
class VkAuthError(VkException):
pass
class VkA... |
sql/plugins/pt_archiver.py | PU-101/Archery | 3,458 | 84774 | # -*- coding: UTF-8 -*-
"""
@author: hhyo
@license: Apache Licence
@file: pt_archiver.py
@time: 2020/01/10
"""
from common.config import SysConfig
from sql.plugins.plugin import Plugin
__author__ = 'hhyo'
class PtArchiver(Plugin):
"""
pt-archiver归档数据
"""
def __init__(self):
self.path = 'pt-... |
calculate_paremeter_flop.py | Edward1900/Face-Detector-1MB-with-landmark | 907 | 84777 | from __future__ import print_function
import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from data import cfg_mnet, cfg_slim, cfg_rfb
from layers.functions.prior_box import PriorBox
from utils.nms.py_cpu_nms import py_cpu_nms
import cv2
from thop import profile
from thop impo... |
release/stubs.min/Grasshopper/Kernel/Geometry/ConvexHull.py | htlcnn/ironpython-stubs | 182 | 84794 | # encoding: utf-8
# module Grasshopper.Kernel.Geometry.ConvexHull calls itself ConvexHull
# from Grasshopper,Version=1.0.0.20,Culture=neutral,PublicKeyToken=dda4f5ec2cd80803
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. """
# no imports
# no functions
# classes
class Solver(object):
... |
zulip_botserver/tests/test_server.py | dimisjim/python-zulip-api | 351 | 84827 | <gh_stars>100-1000
import json
import os
import unittest
from collections import OrderedDict
from importlib import import_module
from pathlib import Path
from types import ModuleType
from typing import Any, Dict
from unittest import mock
from zulip_bots.finder import metadata
from zulip_bots.lib import BotHandler
from... |
InnerEye-DataQuality/InnerEyeDataQuality/selection/data_curation_utils.py | faz1993/InnerEye-DeepLearning | 402 | 84829 | <reponame>faz1993/InnerEye-DeepLearning
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ---------------------------... |
Packs/ServiceNow/Scripts/ServiceNowIncidentStatus/ServiceNowIncidentStatus.py | diCagri/content | 799 | 84841 | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
COLORS = {
'1 - New': '#00CD33', # (success green)
'2 - In Progress': '#7995D4', # (royal blue)
'3 - On Hold': '#FF9000', # (warning orange)
'4 - Awaiting Caller': '#FF9000', # (warning orange)
'5 - Await... |
lycheesync/utils/boilerplatecode.py | bezineb5/lycheesync | 110 | 84843 | <filename>lycheesync/utils/boilerplatecode.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
import logging
from lycheesync.utils.configuration import ConfBorg
import sys
logger = logging.getLogger(__name__)
def init_loggers(logconf, verbose=False):
with open(logconf, 'rt') as f:
config ... |
tests/test_api.py | gcollard/lightbus | 178 | 84885 | import pytest
from lightbus import Api, Event
from lightbus.api import ApiRegistry
from lightbus.exceptions import (
MisconfiguredApiOptions,
InvalidApiEventConfiguration,
InvalidApiRegistryEntry,
UnknownApi,
)
pytestmark = pytest.mark.unit
@pytest.fixture()
def SimpleApi():
class SimpleApi(Api)... |
zerver/migrations/0274_nullbooleanfield_to_booleanfield.py | TylerPham2000/zulip | 17,004 | 84892 | # Generated by Django 2.2.12 on 2020-04-26 17:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("zerver", "0273_migrate_old_bot_messages"),
]
operations = [
migrations.AlterField(
model_name="stream",
name="invit... |
examples/simple_eventlet_send.py | kaiix/kombu | 1,920 | 84932 | <filename>examples/simple_eventlet_send.py
"""
Example that sends a single message and exits using the simple interface.
You can use `simple_receive.py` (or `complete_receive.py`) to receive the
message sent.
"""
import eventlet
from kombu import Connection
eventlet.monkey_patch()
def send_many(n):
#: Crea... |
ext/scheduler/airflow2/tests/test_compiled_airflow_template.py | siddhanta-rath/optimus | 651 | 84935 | <gh_stars>100-1000
import unittest
import sys
sys.path.insert(1, '../resources')
import importlib.util
def load_file_as_module(filepath):
spec = importlib.util.spec_from_file_location("dag", filepath)
compiled_dag_lib = importlib.util.module_from_spec(spec)
spec.loader.exec_module(compiled_dag_lib)
r... |
03_SweynTooth/libs/scapy/layers/bluetooth4LE.py | Charmve/BLE-Security-Att-Def | 149 | 84941 | <filename>03_SweynTooth/libs/scapy/layers/bluetooth4LE.py
# This file is for use with Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Airbus DS CyberSecurity
# Authors: <NAME>, <NAME>, <NAME>
# This program is published under a GPLv2 license
"""Bluetooth 4LE layer"""
import struc... |
hippy/phpcompiler.py | jweinraub/hippyvm | 289 | 84967 | from rply.token import SourcePosition
from hippy.sourceparser import SourceParser, LexerWrapper, ParseError, get_lexer
from hippy.astcompiler import compile_ast
from rpython.rlib.objectmodel import we_are_translated
MODE_LITERAL = 0
MODE_EQUALSIGN = 1
MODE_PHPCODE = 2
class PHPLexerWrapper(LexerWrapper):
def __... |
legacy/a2c/agent.py | zuoxingdong/lagom | 383 | 84991 | <gh_stars>100-1000
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
from lagom.networks import BaseNetwork
from lagom.networks import make_fc
from lagom.networks import ortho_init
from lagom.networks import li... |
smu/parser/smu_utils_lib_test.py | xxdreck/google-research | 23,901 | 84992 | <reponame>xxdreck/google-research
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... |
Contents/Libraries/Shared/rebulk/utils.py | jippo015/Sub-Zero.bundle | 1,553 | 84993 | <gh_stars>1000+
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Various utilities functions
"""
from collections import MutableSet
from types import GeneratorType
def find_all(string, sub, start=None, end=None, ignore_case=False, **kwargs):
"""
Return all indices in string s where substring sub is
foun... |
modules/rnn.py | bckim92/sequential-knowledge-transformer | 135 | 84998 | <gh_stars>100-1000
import tensorflow as tf
def single_rnn_cell(units: int,
cell_type: str = "gru",
name: str = None):
if cell_type == "gru":
# Masking is not supported for CuDNN RNNs
return tf.keras.layers.GRU(
units,
return_sequences... |
tests/test_layers.py | MattBroach/channels | 4,277 | 85023 | import unittest
import pytest
from django.test import override_settings
from channels import DEFAULT_CHANNEL_LAYER
from channels.exceptions import InvalidChannelLayerError
from channels.layers import InMemoryChannelLayer, channel_layers, get_channel_layer
class TestChannelLayerManager(unittest.TestCase):
@overr... |
thirdparty/patchmatchnet/datasets/__init__.py | swershrimpy/gtsfm | 122 | 85035 | <filename>thirdparty/patchmatchnet/datasets/__init__.py
"""PatchmatchNet dataset module
reference: https://github.com/FangjinhuaWang/PatchmatchNet
"""
|
saboteur/cli.py | tomakehurst/saboteur | 258 | 85042 | <reponame>tomakehurst/saboteur
#!/usr/bin/env python
import sys
import httplib
import json
from optparse import OptionParser
import os
from os.path import expanduser
from apicommands import FAULT_TYPES
RESPONSES={ 200: 'OK', 400: 'Bad request', 500: 'Server error' }
def add_fault(hosts, options):
print('Adding f... |
examples/basic_usage/generic_driver.py | verbosemode/scrapli | 404 | 85071 | """examples.basic_usage.generic_driver"""
from scrapli.driver import GenericDriver
MY_DEVICE = {
"host": "172.18.0.11",
"auth_username": "scrapli",
"auth_password": "<PASSWORD>",
"auth_strict_key": False,
}
def main():
"""Simple example of connecting to an IOSXEDevice with the GenericDriver"""
... |
src/zvt/tag/tag.py | vishalbelsare/zvt | 2,032 | 85099 | <filename>src/zvt/tag/tag.py
# -*- coding: utf-8 -*-
import logging
from typing import Type
import pandas as pd
from zvt.contract import Mixin
from zvt.contract import TradableEntity
from zvt.contract.api import get_db_session
from zvt.contract.base import OneStateService
from zvt.contract.zvt_info import TaggerState... |
thirdparty/asyncio/examples/cacheclt.py | xan4/sa-nv | 402 | 85112 | <gh_stars>100-1000
"""Client for cache server.
See cachesvr.py for protocol description.
"""
import argparse
import asyncio
from asyncio import test_utils
import json
import logging
ARGS = argparse.ArgumentParser(description='Cache client example.')
ARGS.add_argument(
'--tls', action='store_true', dest='tls',
... |
locations/spiders/hopdoddy_burger_bar.py | boomerwv1/alltheplaces | 297 | 85118 | <reponame>boomerwv1/alltheplaces
# -*- coding: utf-8 -*-
import json
import re
import scrapy
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
class HopdoddyBurgerBarSpider(scrapy.Spider):
name = "hopdoddy_burger_bar"
allowed_domains = ["amazonaws.com"]
def start_req... |
faker/providers/phone_number/en_GB/__init__.py | mgorny/faker | 12,077 | 85158 | from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
# Source:
# https://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom
# Fake phone numbers should be fake - this provider has been rewritten to
# use numbers reserved for dramatic use by Ofcom. See the foll... |
halogen/halogen.py | wroersma/halogen | 174 | 85160 | <reponame>wroersma/halogen<filename>halogen/halogen.py<gh_stars>100-1000
# coding=utf-8
""" The mfbot Python3 CLI script """
from mfbot import MFBot
def main() -> None:
""" Main function to start things up for the command line use of mfbot """
mfbot = MFBot()
mfbot.parse_args()
if mfbot.dir:
... |
airlab/utils/imageFilters.py | jlevy44/airlab | 330 | 85162 | # Copyright 2018 University of Basel, Center for medical Image Analysis and Navigation
#
# 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
#
# U... |
inceptor/converters/sRDI.py | pwnmeow/inceptor | 743 | 85170 | <reponame>pwnmeow/inceptor<filename>inceptor/converters/sRDI.py
import base64
import struct
from converters.Transformer import Transformer
class sRDI(Transformer):
MACHINE_IA64 = 512
MACHINE_AMD64 = 34404
def __init__(self):
super().__init__()
self.flags = 0 | 0x1 | 0x4 | 30 << 16
... |
examples/custom_detection_video.py | vickyvava/ImageAI | 7,141 | 85187 | <filename>examples/custom_detection_video.py
from imageai.Detection.Custom import CustomVideoObjectDetection
import os
execution_path = os.getcwd()
video_detector = CustomVideoObjectDetection()
video_detector.setModelTypeAsYOLOv3()
video_detector.setModelPath("hololens-ex-60--loss-2.76.h5") # download via https://git... |
survae/distributions/conditional/categorical.py | alisiahkoohi/survae_flows | 262 | 85192 | import torch
from torch.distributions import Categorical
from survae.distributions.conditional import ConditionalDistribution
from survae.utils import sum_except_batch
class ConditionalCategorical(ConditionalDistribution):
"""A Categorical distribution with conditional logits."""
def __init__(self, net):
... |
mplsoccer/statsbomb.py | ThomasSeidl/mplsoccer | 157 | 85210 | """ `mplsoccer.statsbomb` is a python module for loading StatsBomb data. """
# Authors: <NAME>, https://twitter.com/numberstorm
# License: MIT
import os
import warnings
import numpy as np
import pandas as pd
EVENT_SLUG = 'https://raw.githubusercontent.com/statsbomb/open-data/master/data/events'
MATCH_SLUG = 'https:... |
CLIP-ViL-Pretrain/src/pretrain/lxmert_pretrain.py | OdedH/CLIP-ViL | 220 | 85237 | <reponame>OdedH/CLIP-ViL
# coding=utf-8
# Copyleft 2019 project LXRT.
import collections
import os
import random
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from param import args
from pretrain.lxmert_data import InputExample, LXMERTDataset, LXM... |
src/django_mysql/exceptions.py | harvardinformatics/django-mysql | 502 | 85239 | <reponame>harvardinformatics/django-mysql
class TimeoutError(Exception):
"""
Indicates a database operation timed out in some way.
"""
pass
|
fast_transformers/feature_maps/base.py | SamuelCahyawijaya/fast-transformers | 1,171 | 85242 | <filename>fast_transformers/feature_maps/base.py
#
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by <NAME> <<EMAIL>>
#
"""Create the feature map interface and some commonly used feature maps.
All attention implementations that expect a feature map shall receive a factory
function that ... |
fooltrader/rest/controller/tech.py | beaquant/fooltrader | 1,103 | 85249 | <filename>fooltrader/rest/controller/tech.py<gh_stars>1000+
# -*- coding: utf-8 -*-
from flask import request
from fooltrader.api.esapi import esapi
from fooltrader.rest import app
from fooltrader.rest.common import success, get_request_params_as_list
@app.route('/tech/kdata/<securityid>', methods=['GET'])
def get_k... |
models/__init__.py | tuzhucheng/sent-sim | 109 | 85287 | <reponame>tuzhucheng/sent-sim
import numpy as np
import torch
from models.sentence_embedding_baseline import SmoothInverseFrequencyBaseline
from models.mpcnn import MPCNN
from models.mpcnn_lite import MPCNNLite
from models.bimpm import BiMPM
def get_model(args, dataset_cls, embedding):
if args.model == 'sif':
... |
app/modules/ocr_utils/receiptparser.py | jasalt/kuittiskanneri | 131 | 85321 | <filename>app/modules/ocr_utils/receiptparser.py
# -*- coding: utf-8 -*-
import unittest
from datetime import datetime
testtext = u"""
k-supermarket länsiväylä
puh. 01042 33900
4 k4 m000004/1939 21:01 28-05-2014
sallinen maapähkinä lkg 4.40
valio rasvaton maito 1,51 1.55
elonen ruisevas 540g 9kpl 1.59
pirkka banaani ... |
python/dgllife/data/csv_dataset.py | siboehm/dgl-lifesci | 390 | 85369 | <filename>python/dgllife/data/csv_dataset.py
# -*- coding: utf-8 -*-
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Creating datasets from .csv files for molecular property prediction.
import dgl.backend as F
import numpy as np
import os
import pandas a... |
desktop/core/ext-py/nose-1.3.7/unit_tests/test_isolation_plugin.py | kokosing/hue | 5,079 | 85388 | <reponame>kokosing/hue
def test_lint():
import nose.plugins.isolate
|
demos/python/sdk_wireless_camera_control/open_gopro/wifi/adapters/__init__.py | Natureshadow/OpenGoPro | 210 | 85390 | <filename>demos/python/sdk_wireless_camera_control/open_gopro/wifi/adapters/__init__.py
# __init__.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue Sep 7 21:35:53 UTC 2021
"""Universal WiFi adapter implementation for Open GoPro WiFi int... |
atariari/benchmark/probe.py | tmoopenn/atari-representation-learning | 175 | 85415 | import torch
from torch import nn
from .utils import EarlyStopping, appendabledict, \
calculate_multiclass_accuracy, calculate_multiclass_f1_score,\
append_suffix, compute_dict_average
from copy import deepcopy
import numpy as np
from torch.utils.data import RandomSampler, BatchSampler
from .categorization imp... |
tests/migrations/0001_initial.py | wethegit/django-modelcluster | 278 | 85424 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import modelcluster.fields
import django.db.models.deletion
import modelcluster.contrib.taggit
class Migration(migrations.Migration):
dependencies = [
('taggit', '0001_initial'),
... |
fexm/seed_crawlers/pcap_crawler.py | fgsect/fexm | 105 | 85449 | #!/usr/bin/env python3
"""
Crawls all links on a webpage for pcaps.
"""
import argparse
import logging
from multiprocessing.pool import ThreadPool
from urllib.parse import urljoin
import os
import requests
from bs4 import BeautifulSoup
from functools import partial
from helpers import utils
from seed_crawlers import ... |
examples/recurrent/lightning_example.py | tforgaard/pytorch_geometric_temporal | 1,410 | 85450 | <filename>examples/recurrent/lightning_example.py<gh_stars>1000+
import torch
from torch.nn import functional as F
import pytorch_lightning as pl
from pytorch_lightning.callbacks.early_stopping import EarlyStopping
from torch_geometric_temporal.nn.recurrent import DCRNN
from torch_geometric_temporal.dataset import Ch... |
tests/modules/teams/resources/test_getting_teams_info.py | IsmaelJS/test-github-actions | 1,420 | 85465 | <filename>tests/modules/teams/resources/test_getting_teams_info.py
# encoding: utf-8
import pytest
@pytest.mark.parametrize('auth_scopes', (
None,
('teams:write', ),
))
def test_getting_list_of_teams_by_unauthorized_user_must_fail(
flask_app_client,
regular_user,
auth_scopes
):
wit... |
running_modes/validation/logging/local_validation_logger.py | lilleswing/Reinvent-1 | 183 | 85471 | <gh_stars>100-1000
from running_modes.configurations.general_configuration_envelope import GeneralConfigurationEnvelope
from running_modes.validation.logging.base_validation_logger import BaseValidationLogger
class LocalValidationLogger(BaseValidationLogger):
def __init__(self, configuration: GeneralConfiguration... |
src/bionev/utils.py | QustKcz/BioNEV | 195 | 85474 | <filename>src/bionev/utils.py
# -*- coding: utf-8 -*-
import copy
import itertools
import random
import networkx as nx
import numpy as np
import bionev.OpenNE.graph as og
import bionev.struc2vec.graph as sg
def read_for_OpenNE(filename, weighted=False):
G = og.Graph()
print("Loading training graph for lear... |
src/aiortc/exceptions.py | thedilletante/aiortc | 1,021 | 85491 | class InternalError(Exception):
pass
class InvalidAccessError(Exception):
pass
class InvalidStateError(Exception):
pass
|
rotkehlchen/chain/ethereum/manager.py | rotkehlchenio/rotkehlchen | 137 | 85519 | import json
import logging
import random
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union, overload
from urllib.parse import urlparse
import requests
from ens import ENS
from ens.abis import ENS as ENS_ABI, RESOLVER as ENS_RESOLVER_ABI
from ens.exceptions import InvalidName
from ... |
featuretools/tests/testing_utils/cluster.py | ridicolos/featuretools | 942 | 85549 | from psutil import virtual_memory
def mock_cluster(n_workers=1,
threads_per_worker=1,
diagnostics_port=8787,
memory_limit=None,
**dask_kwarg):
return (n_workers, threads_per_worker, diagnostics_port, memory_limit)
class MockClient():
def __... |
server/backend/app/db/utils/utils.py | chemetc/maskcam | 179 | 85569 | from datetime import datetime, timezone
from .enums import StatisticTypeEnum
def convert_timestamp_to_datetime(timestamp: float) -> datetime:
"""
Convert timestamp date format to datetime.
Arguments:
timestamp {float} -- Input timestamp.
Returns:
datetime -- Datetime formatted objec... |
examples/datasets/plot_volume2D.py | mvdoc/pycortex | 423 | 85570 | <reponame>mvdoc/pycortex
"""
===================
Plot 2D Volume Data
===================
This plots example volume data onto an example subject, S1, onto a flatmap
using quickflat. In order for this to run, you have to have a flatmap for
this subject in the pycortex filestore.
The cortex.Volume2D object is instantiat... |
mmocr/utils/data_convert_util.py | yuexy/mmocr | 2,261 | 85586 | <reponame>yuexy/mmocr
# Copyright (c) OpenMMLab. All rights reserved.
import mmcv
def convert_annotations(image_infos, out_json_name):
"""Convert the annotation into coco style.
Args:
image_infos(list): The list of image information dicts
out_json_name(str): The output json filename
Retu... |
sdk/python/pulumi_aws/secretsmanager/outputs.py | RafalSumislawski/pulumi-aws | 260 | 85590 | <filename>sdk/python/pulumi_aws/secretsmanager/outputs.py<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 ty... |
braintree/exceptions/http/connection_error.py | futureironman/braintree_python | 182 | 85618 | from braintree.exceptions.unexpected_error import UnexpectedError
class ConnectionError(UnexpectedError):
pass
|
third_party/typ/typ/pool.py | tingshao/catapult | 2,151 | 85619 | <filename>third_party/typ/typ/pool.py<gh_stars>1000+
# Copyright 2014 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/LI... |
tensorflow_graphics/projects/points_to_3Dobjects/utils/image.py | Liang813/graphics | 2,759 | 85633 | <gh_stars>1000+
# Copyright 2020 The TensorFlow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
explainers.py | marcotcr/lime-kdd | 267 | 85643 | from abc import ABCMeta, abstractmethod
import numpy as np
import scipy as sp
from sklearn import linear_model
import sklearn.metrics.pairwise
###############################
## Random Explainer
###############################
class RandomExplainer:
def __init__(self):
pass
def reset(self):
pass
def e... |
pennylane/transforms/adjoint_metric_tensor.py | therooler/pennylane | 539 | 85652 | # Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... |
rx/concurrency/mainloopscheduler/wxscheduler.py | yutiansut/RxPY | 733 | 85657 | <gh_stars>100-1000
import logging
from rx.core import Disposable
from rx.disposables import SingleAssignmentDisposable, CompositeDisposable
from rx.concurrency.schedulerbase import SchedulerBase
log = logging.getLogger("Rx")
class WxScheduler(SchedulerBase):
"""A scheduler for a wxPython event loop."""
de... |
example/dashboard.py | hzhangse/codis | 9,866 | 85698 | <reponame>hzhangse/codis
#!/usr/bin/env python3
from utils import *
import atexit
import json
import datetime
class CodisDashboard(Process):
def __init__(self, admin_port, product_name, product_auth=None):
self.config = self._open_config(admin_port, product_name, product_auth)
self.admin_port =... |
pywsd/semeval.py | goodmami/pywsd | 581 | 85730 | #!/usr/bin/env python -*- coding: utf-8 -*-
#
# Python Word Sense Disambiguation (pyWSD): SemEval REader API
#
# Copyright (C) 2014-2020 alvations
# URL:
# For license information, see LICENSE.md
import os, io
from collections import namedtuple
from BeautifulSoup import BeautifulSoup as bsoup
from pywsd.utils import ... |
tests/st/pynative/test_pynative_hook.py | Greatpanc/mindspore_zhb | 3,200 | 85745 | <reponame>Greatpanc/mindspore_zhb
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
tests/sharepoint/test_field.py | rikeshtailor/Office365-REST-Python-Client | 544 | 85753 | <reponame>rikeshtailor/Office365-REST-Python-Client<filename>tests/sharepoint/test_field.py<gh_stars>100-1000
import uuid
from tests.sharepoint.sharepoint_case import SPTestCase
from office365.sharepoint.fields.field import Field
from office365.sharepoint.fields.field_creation_information import FieldCreationInformat... |
DML/losses.py | yuichikano/Fashion-Image-Retrieval-System | 551 | 85777 | # Copyright 2019 <NAME> and <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
tests/pipes/test_sents.py | hp0404/spikex | 339 | 85786 | from spikex.defaults import spacy_version
from spikex.pipes import SentX
SENTS = [
"This is a bullet list that we want to be a unique sentence:\n"
"\ta) the first bullet;\n"
"\tb) the second bullet;\n"
"\tc) a bullet with nested bullets:\n"
"\t\t1) first nested bullet;"
"\t\t2) second nested bu... |
src/sims4communitylib/_vanilla_fixes/_sim_full_name.py | velocist/TS4CheatsInfo | 118 | 85788 | """
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
# The purpose of this file is to fix the fact that when try... |
braindecode/experiments/__init__.py | TonioBall/braindecode | 260 | 85806 | """
Convenience classes for experiments, including monitoring and stop criteria.
"""
|
tools/prepare_data_subset.py | xiaoMrzhang/Pytorch_Generalized_3D_Lane_Detection | 186 | 85822 | """
This code conduct:
1. exclude a subset of data related to a certain illumination condition from an existing training set
2. keep a subset of data related to the same illumination condition from an existing test set
ATTENTION: this code require to run prepare_data_split.py first
Author: <NAME> (<EMAIL>)
Date: Marc... |
example/producer.py | Semo/kq | 582 | 85839 | from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers="127.0.0.1:9092")
for _ in range(10000):
producer.send("my_topic", b"message")
# producer.flush()
|
pyfr/backends/hip/packing.py | rishit2307/PyFR | 185 | 85850 | # -*- coding: utf-8 -*-
from pyfr.backends.base import NullKernel
from pyfr.backends.hip.provider import (HIPKernel, HIPKernelProvider,
get_grid_for_block)
class HIPPackingKernels(HIPKernelProvider):
def pack(self, mv):
hip = self.backend.hip
# An exchange... |
tests/test_auto_sharding_bert.py | alpa-projects/alpa | 114 | 85856 | <filename>tests/test_auto_sharding_bert.py
"""Test auto sharding on transformer layers and bert models."""
import unittest
import jax
import jax.numpy as jnp
import numpy as np
from flax import optim, linen as nn
from alpa import parallelize, ShardParallel, LocalPhysicalDeviceMesh, AutoShardingOption
from alpa.model... |
sunpy/visualization/visualization.py | LaudateCorpus1/sunpy | 628 | 85866 | <reponame>LaudateCorpus1/sunpy<filename>sunpy/visualization/visualization.py<gh_stars>100-1000
"""
This module provides plotting support in iPython.
"""
from functools import wraps
import matplotlib.pyplot as plt
__all__ = ['peek_show', "axis_labels_from_ctype"]
def peek_show(func):
"""
A decorator to place... |
tests/pytests/functional/modules/test_aptpkg.py | tomdoherty/salt | 9,425 | 85875 | <reponame>tomdoherty/salt<filename>tests/pytests/functional/modules/test_aptpkg.py
import pathlib
import shutil
import pytest
import salt.exceptions
import salt.modules.aptpkg as aptpkg
import salt.modules.cmdmod as cmd
import salt.modules.file as file
import salt.utils.files
import salt.utils.stringutils
from tests.s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.