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 |
|---|---|---|---|---|
cupyx/scipy/sparse/linalg/_norm.py | Onkar627/cupy | 6,180 | 12648260 | import numpy
import cupy
import cupyx.scipy.sparse
def _sparse_frobenius_norm(x):
if cupy.issubdtype(x.dtype, cupy.complexfloating):
sqnorm = abs(x).power(2).sum()
else:
sqnorm = x.power(2).sum()
return cupy.sqrt(sqnorm)
def norm(x, ord=None, axis=None):
"""Norm of a cupy.scipy.spma... |
pyjswidgets/pyjamas/Canvas/CanvasGradientImplIE6.py | takipsizad/pyjs | 739 | 12648266 | """
* Copyright 2008 Google Inc.
* Copyright 2011 <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... |
mmd_tools/properties/material.py | lsr123/PX4-loacl_code | 822 | 12648274 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import bpy
from bpy.types import PropertyGroup
from bpy.props import BoolProperty, EnumProperty, FloatProperty, FloatVectorProperty, IntProperty, StringProperty
from mmd_tools.core import material
#===========================================
# Property classes
#============... |
tests/test_toggle_setting.py | steveklabnik/sublime-rust | 480 | 12648324 | <gh_stars>100-1000
"""Tests for toggle command."""
from rust_test_common import *
class TestToggle(TestBase):
def test_toggle(self):
window = sublime.active_window()
self.assertEqual(
util.get_setting('rust_syntax_checking', True),
True)
window.run_command('toggl... |
Python/tower_of_hanoi.py | MjCode01/DS-Algo-Point | 1,148 | 12648332 | def TowerOfHanoi(n , first, last, mid):
if n == 1:
print ("Move disk 1 from rod",first,"to rod",last)
return
TowerOfHanoi(n-1, first, mid, last)
print ("Move disk",n,"from rod",first,"to rod",last )
TowerOfHanoi(n-1, mid, last, first)
n=int(input())
TowerOfHanoi(n, 'F', 'M', 'L') ... |
recipes/Python/496905_ActiveRecord_like_ORM_object_relatimapper_200/recipe-496905.py | tdiprima/code | 2,023 | 12648334 | # this is storm.py
import string, new, MySQLdb
from types import *
from MySQLdb.cursors import DictCursor
bag_belongs_to, bag_has_many = [],[]
def belongs_to(what): bag_belongs_to.append(what)
def has_many(what): bag_has_many.append(what)
class Mysqlwrapper:
def __init__(self,**kwds):
self.con... |
examples/advanced/compute_render_to_texture.py | minuJeong/moderngl-window | 142 | 12648336 | import moderngl as mgl
from pathlib import Path
import moderngl_window as mglw
from moderngl_window import geometry
class ComputeRenderToTexture(mglw.WindowConfig):
"""Simple example rendering to a texture with a compute shader"""
title = "Render Texture Using Compute Shader"
resource_dir = (Path(__file__... |
updater_enc.py | takerum/neural-collage | 580 | 12648337 | <reponame>takerum/neural-collage<gh_stars>100-1000
import numpy as np
import chainer
import chainer.functions as F
from chainer import Variable
import chainercv
def reconstruction_loss(dis, recon, gt):
with chainer.using_config('train', False):
v1 = dis.feature_vector(recon)
v2 = dis.feature_vect... |
utils/track_seq.py | yiling-chen/MBMD | 220 | 12648342 | import tensorflow as tf
import numpy as np
from google.protobuf import text_format
from object_detection.protos import pipeline_pb2
from core.model_builder import build_man_model
from object_detection.core import box_list
from object_detection.core import box_list_ops
from PIL import Image
import scipy.io as sio
import... |
netbox/ipam/migrations/0050_iprange.py | TheFlyingCorpse/netbox | 4,994 | 12648393 | <reponame>TheFlyingCorpse/netbox<gh_stars>1000+
# Generated by Django 3.2.5 on 2021-07-16 14:15
import django.core.serializers.json
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.expressions
import ipam.fields
import taggit.managers
class Migration(migrations.Migrat... |
src/radish/parser/transformer.py | radish-bdd/radish2 | 182 | 12648401 | """
radish
~~~~~~
the root from red to green. BDD tooling for Python.
:copyright: (c) 2019 by <NAME> <<EMAIL>>
:license: MIT, see LICENSE for more details.
"""
import itertools
import textwrap
from pathlib import Path
from lark import Transformer
from radish.models import (
Background,
ConstantTag,
De... |
downloads-generation/models_class1_pan_variants/exclude_data_from_training.py | ignatovmg/mhcflurry | 113 | 12648406 | """
Extract allele/peptide pairs to exclude from training data.
"""
import sys
import os
import argparse
import pandas
from mhcflurry.common import normalize_allele_name
def normalize_allele_name_or_return_unknown(s):
return normalize_allele_name(
s, raise_on_error=False, default_value="UNKNOWN")
pars... |
templates/create_formula/languages/python2/src/main.py | antoniofilhozup/ritchie-formulas | 107 | 12648424 | <reponame>antoniofilhozup/ritchie-formulas
#!/usr/bin/python2
import os
from formula import formula
input1 = os.environ.get("RIT_INPUT_TEXT")
input2 = os.environ.get("RIT_INPUT_BOOLEAN")
input3 = os.environ.get("RIT_INPUT_LIST")
input4 = os.environ.get("RIT_INPUT_PASSWORD")
formula.Run(input1, input2, input3, input4)
|
boto3_type_annotations/boto3_type_annotations/amplify/client.py | cowboygneox/boto3_type_annotations | 119 | 12648495 | <gh_stars>100-1000
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from typing import Union
from botocore.paginate import Paginator
from datetime import datetime
from botocore.waiter import Waiter
from typing import List
class Client(BaseClient):
def can_paginate(self, o... |
deeppy/expr/nnet/dropout.py | purushothamgowthu/deeppy | 1,170 | 12648560 | import cudarray as ca
from ...base import PhaseMixin
from ..base import UnaryElementWise
class Dropout(UnaryElementWise, PhaseMixin):
def __init__(self, dropout=0.5):
self.dropout = dropout
self._tmp_mask = None
self.phase = 'train'
def __call__(self, x):
if self.dropout == 0.... |
test/test_jit_cuda_fuser_profiling.py | jsun94/nimble | 206 | 12648583 | <gh_stars>100-1000
import sys
sys.argv.append("--ge_config=profiling")
import os
os.environ['PYTORCH_CUDA_FUSER_DISABLE_FALLBACK'] = '1'
os.environ['PYTORCH_CUDA_FUSER_DISABLE_FMA'] = '1'
os.environ['PYTORCH_CUDA_FUSER_JIT_OPT_LEVEL'] = '0'
from test_jit_cuda_fuser import *
if __name__ == '__main__':
run_tests()... |
tests/flow/test_keyspace_accesses.py | 10088/RedisGraph | 313 | 12648616 | from common import *
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../..')
from demo import QueryInfo
graph = None
redis_con = None
GRAPH_ID = "G"
NEW_GRAPH_ID = "G2"
class testKeyspaceAccesses(FlowTestsBase):
def __init__(self):
self.env = Env(decodeResponses=True)
global graph... |
examples/plots/plot_camera_projection.py | alek5k/pytransform3d | 304 | 12648628 | <reponame>alek5k/pytransform3d
"""
=================
Camera Projection
=================
We can see the camera coordinate frame and a grid of points in the camera
coordinate system which will be projected on the sensor. From the coordinates
on the sensor we can compute the corresponding pixels.
"""
print(__doc__)
im... |
opendatatools/aqi/aqi_agent.py | solider245/OpenData | 1,179 | 12648648 | <filename>opendatatools/aqi/aqi_agent.py
# encoding: UTF-8
from opendatatools.common import get_current_day
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from opendatatools.common import RestAgent
from opendatatools.aqi.constant import city_code_map
class AQIAgent(RestAgent):
def __init__(... |
python/runtime/local/submitter.py | hebafer/sqlflow | 4,742 | 12648650 | <filename>python/runtime/local/submitter.py
# Copyright 2020 The SQLFlow 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... |
indy_node/test/state_proof/test_state_proof_for_missing_data.py | Rob-S/indy-node | 627 | 12648697 | import pytest
from indy_common.constants import GET_ATTR, GET_NYM, GET_SCHEMA, GET_CLAIM_DEF, CLAIM_DEF_FROM, CLAIM_DEF_SCHEMA_REF, \
CLAIM_DEF_SIGNATURE_TYPE, SCHEMA_NAME, SCHEMA_VERSION, SCHEMA_ATTR_NAMES, JSON_LD_CONTEXT, RICH_SCHEMA, \
RICH_SCHEMA_ENCODING, RICH_SCHEMA_MAPPING, RICH_SCHEMA_CRED_DEF, RS_CRE... |
Scripts/sims4communitylib/utils/objects/common_object_ownership_utils.py | ColonolNutty/Sims4CommunityLibrary | 118 | 12648711 | <filename>Scripts/sims4communitylib/utils/objects/common_object_ownership_utils.py
"""
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
Copyrig... |
zippy/benchmarks/src/micro/list-indexing.py | lucapele/pele-c | 319 | 12648828 | <gh_stars>100-1000
# zwei 12/03/13
# subscribe list by index
import time
def index_list(ll, num):
ll_len = len(ll)
item = 0
for t in range(num):
for i in range(ll_len):
item = (item + ll[i]) % 7
return item
def measure():
print("Start timing...")
start = time.time()
ll = [x*2 for x in range(1000)]
la... |
ISMLnextGen/postTest.py | Ravenclaw-OIer/ISML_auto_voter | 128 | 12648841 | from requests import post
headers={'ipNum':'5'}
payload={'0':'1.1.1.1:8080',
'1':'2.2.2.2:8080',
'2':'2.2.2.2:8080',
'3':'2.2.2.2:8080',
'4':'2.2.2.2:8080',}
response=post(url='http://127.0.0.1:8999/main',headers=headers,json=payload)
pass |
sleekxmpp/plugins/xep_0059/__init__.py | E-Tahta/sleekxmpp | 499 | 12648848 | <gh_stars>100-1000
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2010 <NAME>, <NAME>
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.plugins.base import register_plugin
from sleekxmpp.plugins.xep_0059.stanza import Set
from sleekxmpp.plugins.xep_0... |
tests/test_expression.py | talhaHavadar/dissect.cstruct | 227 | 12648896 | <reponame>talhaHavadar/dissect.cstruct
import pytest
from dissect.cstruct.expression import Expression
testdata = [
('1 * 0', 0),
('1 * 1', 1),
('7 * 8', 56),
('7*8', 56),
('7 *8', 56),
(' 7 * 8 ', 56),
('0 / 1', 0),
('1 / 1', 1),
('2 / 2', 1),
('3 / 2', 1),
('4 / ... |
algorithms/utils/spaces/discretized.py | magicly/sample-factory | 320 | 12648991 | <filename>algorithms/utils/spaces/discretized.py
from gym.spaces import Discrete
class Discretized(Discrete):
def __init__(self, n, min_action, max_action):
super().__init__(n)
self.min_action = min_action
self.max_action = max_action
def to_continuous(self, discrete_action):
... |
src/settings_csv.py | hodgerpodger/staketaxcsv | 140 | 12649019 | import os
# Environment variables (required for each respective report)
ALGO_HIST_INDEXER_NODE = os.environ.get("ALGO_HIST_INDEXER_NODE", "https://indexer.algoexplorerapi.io")
ALGO_INDEXER_NODE = os.environ.get("ALGO_INDEXER_NODE", "https://algoindexer.algoexplorerapi.io")
ALGO_NFDOMAINS = os.environ.get("ALGO_NFDOMA... |
KG/DuEE_baseline/bin/finetune/sequence_label.py | pkulzb/Research | 1,319 | 12649043 | <reponame>pkulzb/Research
# coding: utf-8
# Copyright (c) 2019 PaddlePaddle 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/licen... |
iot_hunter/dynamic_analysis/DynamicAnalyzer.py | byamao1/HaboMalHunter | 727 | 12649049 | <filename>iot_hunter/dynamic_analysis/DynamicAnalyzer.py
# Tencent is pleased to support the open source community by making IoTHunter available.
# Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except in
# compl... |
plugin/ERCC_Analysis/code/ercc_seq_utils.py | konradotto/TS | 125 | 12649053 | <filename>plugin/ERCC_Analysis/code/ercc_seq_utils.py
# Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved
# Sequence and read streaming utilities
import sys
import time
import pysam
# decorators section
def _use_and_del(d, k, v):
"""
Use a values from a dict and remove it.
"""
if k in d:
v... |
dl_lib/modeling/meta_arch/__init__.py | AndysonYs/DynamicRouting | 122 | 12649093 | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# import all the meta_arch, so they will be registered
from .semantic_seg import SemanticSegmentor
from .dynamic4seg import DynamicNet4Seg |
nativedroid/nativedroid/analyses/annotation_based_analysis.py | CherishAZ/Argus-SAF | 152 | 12649141 | import copy
from cStringIO import StringIO
from nativedroid.analyses.resolver.annotation import *
from nativedroid.analyses.resolver.armel_resolver import ArmelResolver
from nativedroid.analyses.resolver.jni.jni_helper import *
from nativedroid.analyses.resolver.model.__android_log_print import *
from nativedroid.prot... |
whatsapp-bot-venv/Lib/site-packages/twilio/rest/preview/deployed_devices/__init__.py | RedaMastouri/ConversationalPythonicChatBot | 1,362 | 12649152 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base.version import Version
from twilio.rest.preview.deployed_devices.fleet import FleetList
class DeployedDevices(Version):
def __init__(self, domain):
"""
Initial... |
scale.app/scripts/lizard_metrics.py | f4rsh/SCALe | 239 | 12649153 | #!/usr/bin/env python
# Copyright (c) 2007-2018 Carnegie Mellon University.
# All Rights Reserved. See COPYRIGHT file for details.
import lizard
import scale
import argparse
import os
import sys
# Get path arg from cmd line
def getArgs():
parser = argparse.ArgumentParser(description="Gathers metrics via Lizard")... |
libcity/pipeline/__init__.py | moghadas76/test_bigcity | 221 | 12649217 | from libcity.pipeline.pipeline import run_model, hyper_parameter, objective_function
__all__ = [
"run_model",
"hyper_parameter",
"objective_function"
]
|
third_party/infra_libs/time_functions/zulu.py | webrtc-lizp/infra-luci-client-py | 2,151 | 12649221 | # Copyright 2015 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.
"""Provides functions for parsing and outputting Zulu time."""
import datetime
import pytz
from infra_libs.time_functions import timestamp
def parse_zul... |
hydra-configs-torchvision/hydra_configs/torchvision/__init__.py | LaudateCorpus1/hydra-torch | 149 | 12649232 | <filename>hydra-configs-torchvision/hydra_configs/torchvision/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
#
# Generated by configen, do not edit.
# See https://github.com/facebookresearch/hydra/tree/main/tools/configen
# fmt: off
# isort:skip_file
# flake8: noqa
from packaging im... |
var/spack/repos/builtin/packages/librmm/package.py | kkauder/spack | 2,360 | 12649236 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Librmm(CMakePackage):
"""RMM: RAPIDS Memory Manager. Achieving optimal
performance in ... |
selim_sef/dataset/dense_transform.py | ktncktnc/SpaceNet_Off_Nadir_Solutions | 164 | 12649239 | <filename>selim_sef/dataset/dense_transform.py
import math
import random
import cv2
cv2.setNumThreads(0)
import numpy as np
import torch
from numpy.core.multiarray import ndarray
_DEFAULT_ALPHASTD = 0.1
_DEFAULT_EIGVAL = torch.Tensor([0.2175, 0.0188, 0.0045])
_DEFAULT_EIGVEC = torch.Tensor([[-0.5675, 0.7192, 0.4009... |
cadence/tests/test_query_workflow.py | simkimsia/temporal-python-sdk | 141 | 12649247 | import time
import pytest
from cadence.exceptions import QueryFailureException
from cadence.workerfactory import WorkerFactory
from cadence.workflow import workflow_method, signal_method, Workflow, WorkflowClient, query_method
TASK_LIST = "TestQueryWorkflow"
DOMAIN = "sample"
class GreetingException(Exception):
... |
tests/test_robots.py | PLPeeters/reppy | 137 | 12649252 | <filename>tests/test_robots.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
'''These are unit tests that are derived from the rfc at
http://www.robotstxt.org/norobots-rfc.txt'''
import codecs
import unittest
import mock
from requests.exceptions import SSLError
from reppy imp... |
osbrain/tests/conftest.py | RezaBehzadpour/osbrain | 176 | 12649253 | <gh_stars>100-1000
import pytest
from osbrain import run_agent
from osbrain import run_logger
from osbrain import run_nameserver
from osbrain.helper import sync_agent_logger
@pytest.fixture(scope='function')
def nsproxy(request):
ns = run_nameserver()
yield ns
ns.shutdown()
@pytest.fixture(scope='funct... |
python/helpers/pydev/pydev_tests_python/resources/_debugger_case_frame_eval.py | tgodzik/intellij-community | 695 | 12649261 | '''
Things this test checks:
- frame.f_trace is None when there are only regular breakpoints.
- The no-op tracing function is set by default (otherwise when set tracing functions have no effect).
- When stepping in, frame.f_trace must be set by the frame eval.
- When stepping over/return, the frame.f_trace must not... |
ecp5/trellis_import.py | antmicro/nextpnr | 865 | 12649273 | #!/usr/bin/env python3
import argparse
import json
import sys
from os import path
location_types = dict()
type_at_location = dict()
tiletype_names = dict()
gfx_wire_ids = dict()
gfx_wire_names = list()
parser = argparse.ArgumentParser(description="import ECP5 routing and bels from Project Trellis")
parser.add_argumen... |
datasets/movielens_pinterest_NCF/get_train_data.py | ziyoujiyi/PaddleRec | 2,739 | 12649280 | # Copyright (c) 2021 PaddlePaddle 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 appli... |
trailscraper/record_sources/__init__.py | ocefpaf/trailscraper | 497 | 12649284 | """Package containing classes that represent a source of CloudTrail records, e.g. from an API or disk storage"""
|
awswrangler/quicksight/_delete.py | isichei/aws-data-wrangler | 2,695 | 12649333 | <filename>awswrangler/quicksight/_delete.py
"""Amazon QuickSight Delete Module."""
import logging
from typing import Any, Callable, Dict, Optional
import boto3
from awswrangler import _utils, exceptions, sts
from awswrangler.quicksight._get_list import (
get_dashboard_id,
get_data_source_id,
get_dataset_... |
leaf/api/settings.py | guiqiqi/leaf | 119 | 12649360 | <filename>leaf/api/settings.py<gh_stars>100-1000
"""API 接口的设置文件"""
from typing import Optional
from flask import abort
from ..core import error
class Authorization:
"""权限验证中的设置"""
ExecuteAPMissing = True # 在未找到接入点信息时是否允许
@staticmethod
def UnAuthorized(_reason: error.Error):
"""
验证失... |
dataflows/base/datastream.py | cschloer/dataflows | 160 | 12649362 | from datapackage import Package
class DataStream:
def __init__(self, dp=None, res_iter=None, stats=None):
self.dp = dp if dp is not None else Package()
self.res_iter = res_iter if res_iter is not None else []
self.stats = stats if stats is not None else []
def merge_stats(self):
... |
common/concertina_lib.py | RAbraham/logica | 1,434 | 12649381 | <filename>common/concertina_lib.py
"""Concertina: small Python Workflow execution handler."""
import datetime
import graphviz
from IPython.display import display
from IPython.display import update_display
class ConcertinaQueryEngine(object):
def __init__(self, final_predicates, sql_runner):
self.final_predicat... |
Spyder/DecryptLogin_note/DecryptLogin_modules/core/sohu.py | Lightblues/10-playground | 2,268 | 12649393 | '''
Function:
搜狐模拟登录
Author:
Charles
微信公众号:
Charles的皮卡丘
更新日期:
2020-10-29
'''
import time
import requests
from hashlib import md5
'''PC端登录搜狐'''
class sohuPC():
is_callable = False
def __init__(self, **kwargs):
for key, value in kwargs.items(): setattr(self, key, value)
self.info... |
Trakttv.bundle/Contents/Libraries/Shared/plugin/core/libraries/tests/core/base.py | disrupted/Trakttv.bundle | 1,346 | 12649405 | from plugin.core.helpers.variable import merge
from subprocess import Popen
import json
import logging
import os
import subprocess
import sys
CURRENT_PATH = os.path.abspath(__file__)
HOST_PATH = os.path.join(os.path.dirname(CURRENT_PATH), 'host.py')
log = logging.getLogger(__name__)
class BaseTest(object):
nam... |
pygmt/tests/test_logo.py | daroari/pygmt | 326 | 12649417 | """
Tests for fig.logo.
"""
import pytest
from pygmt import Figure
@pytest.mark.mpl_image_compare
def test_logo():
"""
Plot the GMT logo as a stand-alone plot.
"""
fig = Figure()
fig.logo()
return fig
@pytest.mark.mpl_image_compare
def test_logo_on_a_map():
"""
Plot the GMT logo at t... |
mlmodel/docs/preprocess.py | LaudateCorpus1/coremltools | 11,356 | 12649441 | import os
import re
from itertools import izip
import inflection
def preprocess():
"splits _sources/reference.rst into separate files"
text = open("./_sources/reference.rst", "r").read()
os.remove("./_sources/reference.rst")
if not os.path.exists("./_sources/reference"):
os.makedirs("./_sour... |
mamba/cli.py | kfischer-okarin/mamba | 462 | 12649445 | # -*- coding: utf-8 -*-
import sys
import argparse
from mamba import application_factory, __version__
def main():
arguments = _parse_arguments()
if arguments.version:
print(__version__)
return
factory = application_factory.ApplicationFactory(arguments)
runner = factory.runner()
... |
utils/llvm-build/llvmbuild/util.py | clayne/DirectXShaderCompiler | 4,812 | 12649447 | import os
import sys
def _write_message(kind, message):
program = os.path.basename(sys.argv[0])
sys.stderr.write('%s: %s: %s\n' % (program, kind, message))
note = lambda message: _write_message('note', message)
warning = lambda message: _write_message('warning', message)
error = lambda message: _write_message... |
iota/commands/core/check_consistency.py | EasonC13/iota.py | 347 | 12649460 | <gh_stars>100-1000
import filters as f
from iota import TransactionHash
from iota.commands import FilterCommand, RequestFilter
from iota.filters import Trytes
__all__ = [
'CheckConsistencyCommand',
]
class CheckConsistencyCommand(FilterCommand):
"""
Executes ``checkConsistency`` extended API command.
... |
examples/graphsage/train.py | zbmain/PGL | 1,389 | 12649468 | # Copyright (c) 2020 PaddlePaddle 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 appli... |
gateway/sensorsdb.py | QuPengfei/Smart-City-Sample | 126 | 12649472 | <filename>gateway/sensorsdb.py<gh_stars>100-1000
#!/usr/bin/python3
from urllib.parse import unquote
from tornado import web,gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from db_query import DBQuery
from db_ingest import DBIngest
from language import encode
from ... |
ray-rllib/multi-armed-bandits/market_bandit.py | aksakalli/academy | 342 | 12649498 | <gh_stars>100-1000
import gym
from gym.spaces import Discrete, Box
from gym.utils import seeding
import numpy as np
import random
class MarketBandit (gym.Env):
def __init__ (self, config={}):
self.max_inflation = config.get('max-inflation', DEFAULT_MAX_INFLATION)
self.tickers = config.get('tickers... |
pyblur/RandomizedBlur.py | lospooky/pyblur | 102 | 12649532 | import numpy as np
from BoxBlur import BoxBlur_random
from DefocusBlur import DefocusBlur_random
from GaussianBlur import GaussianBlur_random
from LinearMotionBlur import LinearMotionBlur_random
from PsfBlur import PsfBlur_random
blurFunctions = {"0": BoxBlur_random, "1": DefocusBlur_random, "2": GaussianBlur_random,... |
program/request-tvm-nnvm-inference/mali_imagenet_bench.py | ctuning/ck-request-asplos18-mobilenets-tvm | 174 | 12649550 | """
Benchmark inference speed on ImageNet
Example (run on Firefly RK3399):
python mali_imagenet_bench.py --target-host 'llvm -target=aarch64-linux-gnu' --host 192.168.0.100 --port 9090 --model mobilenet
"""
import time
import argparse
import numpy as np
import tvm
import nnvm.compiler
import nnvm.testing
from tvm.cont... |
onnx2pytorch/constants.py | Robust-Robots/onnx2pytorch | 147 | 12649552 | <filename>onnx2pytorch/constants.py
from torch import nn
from torch.nn.modules.conv import _ConvNd
from torch.nn.modules.pooling import _MaxPoolNd
from onnx2pytorch.operations import (
BatchNormWrapper,
InstanceNormWrapper,
Loop,
LSTMWrapper,
Split,
TopK,
)
COMPOSITE_LAYERS = (nn.Sequential,)
... |
cmd_ir/instructions/events.py | Commodoreprime/Command-Block-Assembly | 223 | 12649553 | """Events"""
from ._core import PreambleInsn, ConstructorInsn, SingleCommandInsn
from ..core_types import (VirtualString,
AdvEventRef,
TagEventRef,
EventRef,
Selector,
SelectorType,
... |
DSA 450 GFG/PrintAnagrams.py | siddhi-244/CompetitiveProgrammingQuestionBank | 931 | 12649575 |
# Problem : https://practice.geeksforgeeks.org/problems/print-anagrams-together/1
# Input:
# N = 5
# words[] = {act,god,cat,dog,tac}
# Output:
# god dog
# act cat tac
# Explanation:
# There are 2 groups of
# anagrams "god", "dog" make group 1.
# "act", "cat", "tac" make group 2.
from collections import defaultdict... |
emukit/examples/fabolas/fabolas_model.py | ndalchau/emukit | 152 | 12649583 | from copy import deepcopy
from typing import Tuple
import GPy
import numpy as np
from emukit.model_wrappers.gpy_model_wrappers import GPyModelWrapper
class FabolasKernel(GPy.kern.Kern):
def __init__(self, input_dim, basis_func, a=1., b=1., active_dims=None):
super(FabolasKernel, self).__init__(input_d... |
navec/tar.py | FreedomSlow/navec | 115 | 12649603 |
import tarfile
from io import BytesIO
from .record import Record
class Tar(Record):
__attributes__ = ['path']
mode = 'r'
def __init__(self, path):
self.path = path
def __enter__(self):
self.tar = tarfile.open(self.path, self.mode)
return self
def __exit__(self, *args)... |
test/hummingbot/strategy/perpetual_market_making/test_perpetual_market_making_start.py | BGTCapital/hummingbot | 3,027 | 12649604 | from decimal import Decimal
import unittest.mock
import hummingbot.strategy.perpetual_market_making.start as strategy_start
from hummingbot.connector.exchange_base import ExchangeBase
from hummingbot.strategy.perpetual_market_making.perpetual_market_making_config_map import (
perpetual_market_making_config_map as c... |
tests/batchnorm.py | kihyuks/objax | 715 | 12649618 | <gh_stars>100-1000
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
tests/python3_f_strings/f_strings.py | hixio-mh/plugin-python | 362 | 12649651 | width = 10
precision = 4
value = decimal.Decimal("12.34567")
f"result: {value:{width}.{precision}}"
rf"result: {value:{width}.{precision}}"
foo(f'this SHOULD be a multi-line string because it is '
f'very long and does not fit on one line. And {value} is the value.')
foo('this SHOULD be a multi-line string, but no... |
extensions/python/src/main/resources/jet_to_python_grpc_server.py | software-is-art/hazelcast | 4,283 | 12649653 | <reponame>software-is-art/hazelcast
import grpc
import sys
import os
import socket
import logging
import importlib
from concurrent import futures
import jet_to_python_pb2
import jet_to_python_pb2_grpc
logger = logging.getLogger('Python PID %d' % os.getpid())
class JetToPythonServicer(jet_to_python_pb2_grpc.JetToPyth... |
nodes/1.x/python/Group.Ungroup.py | jdehotin/Clockworkfordynamo | 147 | 12649684 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from System.Collections.Generic import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.Current... |
src/genie/libs/parser/iosxe/tests/ShowStandbyAll/cli/equal/golden_output4_expected.py | balmasea/genieparser | 204 | 12649701 | <gh_stars>100-1000
expected_output = {
"BDI3147": {
"interface": "BDI3147",
"redirects_disable": False,
"address_family": {
"ipv4": {
"version": {
1: {
"groups": {
31: {
... |
flask_admin/tests/test_tools.py | caffeinatedMike/flask-admin | 4,440 | 12649723 | <reponame>caffeinatedMike/flask-admin
from flask_admin import tools
def test_encode_decode():
assert tools.iterdecode(tools.iterencode([1, 2, 3])) == (u'1', u'2', u'3')
assert tools.iterdecode(tools.iterencode([',', ',', ','])) == (u',', u',', u',')
assert tools.iterdecode(tools.iterencode(['.hello.,', ... |
Multitasking_with_CircuitPython/code_buttons_without_sleep/code.py | gamblor21/Adafruit_Learning_System_Guides | 665 | 12649750 | <gh_stars>100-1000
"""
This example script shows how to read button state with
debouncing that does not rely on time.sleep().
"""
import board
from digitalio import DigitalInOut, Direction, Pull
btn = DigitalInOut(board.SWITCH)
btn.direction = Direction.INPUT
btn.pull = Pull.UP
prev_state = btn.value
while True:
... |
src/map_renderer/glow.py | XiaoJake/range-mcl | 141 | 12649821 | <reponame>XiaoJake/range-mcl<filename>src/map_renderer/glow.py
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
# Brief: OpenGL Object Wrapper (GLOW) in python.
# Some convenience classes to simplify resource management.
import re
from typing import Any, Union
from OpenGL... |
regtests/c++/array_sized.py | ahakingdom/Rusthon | 622 | 12649830 | <reponame>ahakingdom/Rusthon
'''
array with default size
'''
class A:
pass
def somefunc():
a = [5]int(1,2,3,4,5)
print('len a:', len(a))
a.pop()
print('len a:', len(a))
print(a[0])
print(a[1])
b = [10]int()
print('len b:', len(b))
print b[0]
print b[1]
c = [10]f64( 1.1, 2.2, 3.3 )
print c[0]
print c[1... |
nndet/inference/detection/__init__.py | joeranbosma/nnDetection | 242 | 12649834 | from nndet.inference.detection.wbc import batched_wbc, wbc
from nndet.inference.detection.model import batched_nms_model
from nndet.inference.detection.ensemble import batched_wbc_ensemble, batched_nms_ensemble, \
wbc_nms_no_label_ensemble
|
tests/sectools/test_domain_utils.py | kubajir/msticpy | 820 | 12649837 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""domain_... |
ggplot/geoms/__init__.py | themiwi/ggplot | 1,133 | 12649844 | from .geom_abline import geom_abline
from .geom_area import geom_area
from .geom_bar import geom_bar
from .geom_bin2d import geom_bin2d
from .geom_blank import geom_blank
from .geom_boxplot import geom_boxplot
from .geom_density import geom_density
from .geom_errorbar import geom_errorbar
from .geom_histogram import ge... |
mzutils/json_misc.py | Mohan-Zhang-u/mzutils | 132 | 12649846 | <gh_stars>100-1000
import codecs
import json
def dump_json(dictionary, file_path):
"""
:param dict:
:param file_path:
:return:
"""
with codecs.open(file_path, 'w+', encoding='utf-8') as fp:
json.dump(dictionary, fp)
def load_json(file_path):
"""
:param file_path:
:r... |
modules/unicode.py | nikolas/jenni | 133 | 12649870 | #!/usr/bin/env python
"""
unicode.py - jenni Unicode Module
Copyright 2010-2013, yano (yanovich.net)
Licensed under the Eiffel Forum License 2.
More info:
* jenni: https://github.com/myano/jenni/
* Phenny: http://inamidst.com/phenny/
"""
import re
import unicodedata
import urlparse
control_chars = ''.join(map(unic... |
yyets/BagAndDrag/zimuxia/convert_db.py | kuyacai/YYeTsBot | 9,250 | 12649874 | #!/usr/local/bin/python3
# coding: utf-8
# YYeTsBot - convert_db.py
# 2/5/21 13:46
#
__author__ = "Benny <<EMAIL>>"
# convert to mongodb and con_sqlite
import pymongo
import pymysql
import tqdm
import json
from typing import List
con_mysql = pymysql.Connect(host="127.0.0.1", user="root", password="<PASSWORD>", ch... |
tests/test_buildoptionsparser.py | druttka/iotedgedev | 111 | 12649924 | import pytest
from iotedgedev.buildoptionsparser import BuildOptionsParser
pytestmark = pytest.mark.unit
def test_filter_build_options():
build_options = [
"--rm",
"-f test",
"--file test",
"-t image",
"--tag image"
]
build_options_parser = BuildOptionsParser(build... |
examples/slow_task.py | avivazran/UnrealEnginePython | 2,350 | 12649931 | from unreal_engine import FSlowTask
import time
# Create an FSlowTask object, defining the amount of work that
# will be done, and the initial message.
t = FSlowTask(10, "Doing Something")
t.initialize()
# Make the dialog, and include a Cancel button (default is not to
# allow a cancel button).
t.make_dialog(True)
t... |
tools/harness/tests/multihoptests.py | lambdaxymox/barrelfish | 111 | 12649972 | <gh_stars>100-1000
##########################################################################
# Copyright (c) 2009, 2010, ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, ... |
rqalpha/model/__init__.py | LawrentChen/rqalpha | 5,263 | 12650035 | # -*- coding: utf-8 -*-
# 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”)
#
# 除非遵守当前许可,否则不得使用本软件。
#
# * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件):
# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。
# 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”... |
docs/build.py | TimoRoth/ghp-import | 313 | 12650046 | <gh_stars>100-1000
#!/usr/bin/env python
import io
import os
from markdown import markdown
def main():
base = os.path.abspath(os.path.dirname(__file__))
readme_path = os.path.join(os.path.dirname(base), "README.md")
with io.open(readme_path, encoding="utf-8") as fobj:
readme = fobj.read()
... |
tests/management/commands/test_drop_test_database.py | dankgen-tobias/django-extensions | 4,057 | 12650047 | <filename>tests/management/commands/test_drop_test_database.py
# -*- coding: utf-8 -*-
from io import StringIO
from unittest.mock import MagicMock, Mock, PropertyMock, call, patch
from django.core.management import CommandError, call_command
from django.test import TestCase
from django.test.utils import override_setti... |
backend/auth_api/migrations/0004_extra_github_details.py | NeilsC/prestige | 314 | 12650057 | # Generated by Django 3.2.5 on 2021-09-04 14:30
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auth_api', '0003_githubidentity'),
]
operations = [
migrations.AlterModelO... |
examples/slack/botapp/mypythonbot/code.py | patgoley/gordon | 2,204 | 12650085 | import json
from urlparse import parse_qs
def handler(event, context):
with open('.context', 'r') as f:
gordon_context = json.loads(f.read())
expected_token = gordon_context['token']
req_body = event['body']
params = parse_qs(req_body)
# Check if the token is the correct one
token ... |
at_learner_core/at_learner_core/models/model.py | hieuvecto/CASIA-SURF_CeFA | 133 | 12650110 | <reponame>hieuvecto/CASIA-SURF_CeFA
'''
TODO:
def get_wrapper
def get_optimizer
''' |
kratos/python_scripts/timer_process.py | lkusch/Kratos | 778 | 12650122 | # Importing the Kratos Library
import KratosMultiphysics
def Factory(settings, Model):
if not isinstance(settings, KratosMultiphysics.Parameters):
raise Exception("expected input shall be a Parameters object, encapsulating a json string")
return TimerProcess(Model, settings["Parameters"])
# All the pr... |
keras_squeezenet/__init__.py | zr71516/squeezeNet | 430 | 12650128 | from keras_squeezenet.squeezenet import SqueezeNet
from keras_squeezenet.version import __version__
|
openstackclient/tests/unit/api/test_compute_v2.py | cloudification-io/python-openstackclient | 262 | 12650133 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... |
migrations/versions/ad23a56abf25_.py | boladmin/security_monkey | 4,258 | 12650149 | <reponame>boladmin/security_monkey<gh_stars>1000+
"""Ability to link issues to other tech type items
Revision ID: <KEY>
Revises: 67ea2aac5ea0
Create Date: 2016-02-23 18:52:45.024716
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa... |
recipes/Python/415983_Simple_XML_serlializerdeserializer_using/recipe-415983.py | tdiprima/code | 2,023 | 12650197 | """Simple XML marshaling (serializing) and
unmarshaling(de-serializing) module using Python
dictionaries and the marshal module.
"""
from xml.sax.handler import ContentHandler
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import XMLReader
from xml.sax import make_parser
import marshal
import os,... |
nuplan/planning/simulation/controller/tracker/abstract_tracker.py | motional/nuplan-devkit | 128 | 12650207 | <reponame>motional/nuplan-devkit
import abc
from nuplan.common.actor_state.dynamic_car_state import DynamicCarState
from nuplan.common.actor_state.ego_state import EgoState
from nuplan.planning.simulation.simulation_time_controller.simulation_iteration import SimulationIteration
from nuplan.planning.simulation.traject... |
applications/fixImageXml.py | vincentschut/isce2 | 1,133 | 12650231 | <filename>applications/fixImageXml.py<gh_stars>1000+
#!/usr/bin/env python3
import os
import argparse
import isce
import isceobj
from isceobj.Util.ImageUtil import ImageLib as IML
def cmdLineParse():
'''
Command line parser.
'''
parser = argparse.ArgumentParser(description='Fixes pathnames in ISCE ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.