max_stars_repo_path stringlengths 3 269 | max_stars_repo_name stringlengths 4 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.05M | score float64 0.23 5.13 | int_score int64 0 5 |
|---|---|---|---|---|---|---|
ultra_config_tests/unit_tests/test_ultra_config.py | timmartin19/ultra-config | 1 | 21800 | <gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import unittest
from ultra_config import simple_config, load_json_file_settings, \
load_configparser_settings, load_python_object_settings, ... | 2.3125 | 2 |
leetcode/87. Scramble String.py | CSU-FulChou/IOS_er | 2 | 21801 | <filename>leetcode/87. Scramble String.py
# 2021.04.16 hard:
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
'''
dp 问题:
1. 子字符串应该一样长. 很简单已经保证了
子字符串一样,那么久直接返回 True
2. 子字符串中 存在的字母应该一样, 同一个字母的数量应该一样多 Count()
两种分割方式,交换 或者 不交换不断的迭代下去:
分割的两种方式要写对!... | 3.34375 | 3 |
packaging/setup/plugins/ovirt-engine-setup/all-in-one/super_user.py | SunOfShine/ovirt-engine | 1 | 21802 | <gh_stars>1-10
#
# ovirt-engine-setup -- ovirt engine setup
# Copyright (C) 2013 Red Hat, 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... | 1.945313 | 2 |
deploy/deploy.py | ColdStack-Network/blockchain | 0 | 21803 | <gh_stars>0
#!/usr/bin/env python3
import argparse
import subprocess
import json
parser = argparse.ArgumentParser(description='Deploy blockchain')
parser.add_argument('--validator-node',
help='validator node ssh address. First node becomes boot node and active validator.',
nargs='+'
)
parser.add_argument('--api... | 2.484375 | 2 |
4_neural_networks.py | scientificprogrammer123/Udacity_Machine-Learning | 0 | 21804 | # lesson 1: neural networks
# cell body, neuron, axon, synapse
# spike trains travel down the axon, and causes excitation to occur at other axons.
# a computation unit.
#
# x1 -> w1 ->
# x2 -> w2 -> theta -> y
# x3 -> w3 ->
#
# sum_{=1}^{k} xi*wi, activation
# >=theta, firing threshold
#
# For percept... | 3.734375 | 4 |
gitprivacy/dateredacter/__init__.py | fapdash/git-privacy | 7 | 21805 | import abc
from datetime import datetime
class DateRedacter(abc.ABC):
"""Abstract timestamp redater."""
@abc.abstractmethod
def redact(self, timestamp: datetime) -> datetime:
"""Redact timestamp."""
from .reduce import ResolutionDateRedacter
| 2.859375 | 3 |
functions/cm_plotter.py | evanmy/keymorph | 0 | 21806 | import torch
from skimage.filters import gaussian
def blur_cm_plot(Cm_plot, sigma):
"""
Blur the keypoints/center-of-masses for better visualiztion
Arguments
---------
Cm_plot : tensor with the center-of-masses
sigma : how much to blur
Return
------
out : blurred points... | 2.703125 | 3 |
examples/cooperative_work_examples.py | hfs/maproulette-python-client | 0 | 21807 | <gh_stars>0
import maproulette
import json
import base64
# Create a configuration object for MapRoulette using your API key:
config = maproulette.Configuration(api_key="API_KEY")
# Create an API objects with the above config object:
api = maproulette.Task(config)
# Setting a challenge ID in which we'll place our coo... | 2.375 | 2 |
src/biopsykit/sleep/sleep_wake_detection/algorithms/_base.py | Zwitscherle/BioPsyKit | 10 | 21808 | """Module for sleep/wake detection base class."""
from biopsykit.utils._types import arr_t
from biopsykit.utils.datatype_helper import SleepWakeDataFrame
class _SleepWakeBase:
"""Base class for sleep/wake detection algorithms."""
def __init__(self, **kwargs):
pass
def fit(self, data: arr_t, **kw... | 2.8125 | 3 |
FluentPython/ch02/cartesian.py | eroicaleo/LearningPython | 1 | 21809 | <reponame>eroicaleo/LearningPython
#!/usr/bin/env python
colors = ['white', 'black']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for size in sizes
for color in colors ]
print(tshirts)
tshirts = [(color, size) for color in colors
for size in sizes ]
print(tshirts... | 3.671875 | 4 |
create.py | devanshsharma22/ONE | 0 | 21810 | <reponame>devanshsharma22/ONE
from flask import Flask
from models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
db.init_app(app)
def main():
db.create_all()
if __name__ == "__main__":
with app.app_... | 1.921875 | 2 |
jmetex/main.py | innovocloud/jmetex | 2 | 21811 | <reponame>innovocloud/jmetex
import sys
import time
import argparse
from prometheus_client import start_http_server, Metric, REGISTRY, Summary
from .interfacecollector import InterfaceCollector
from .opticalcollector import OpticalCollector
def main():
parser = argparse.ArgumentParser(description='JunOS API to Pr... | 2.578125 | 3 |
vispp/io.py | c-cameron/vispp | 0 | 21812 | <gh_stars>0
from matplotlib.backends.backend_pdf import PdfPages
def better_savefig(fig, figfile, format="pdf", **kwargs):
"""To be used instead of .savefig
This function saves pdfs without creation date. So subsequent
overwrites of pdf files does not cause e.g. git modified.
"""
if format == "pd... | 2.5625 | 3 |
mappings.py | timeseries-ru/EL | 0 | 21813 | <gh_stars>0
import sklearn.decomposition as decomposition
import sklearn.preprocessing as preprocessing
import sklearn.linear_model as linear_model
import sklearn.ensemble as ensemble
import sklearn.cluster as cluster
import sklearn.neighbors as neighbors
import sklearn.neural_network as neural_network
class Mapper:
... | 2.53125 | 3 |
Find_the_Runner_Up_Score_.py | KrShivanshu/264136_Python_Daily | 0 | 21814 | <reponame>KrShivanshu/264136_Python_Daily
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
max = -9999999
max2 = -9999999
for i in arr:
if(i>max):
max2=max
max=i
elif i>max2 and max>i:
max2=i
print(max2) | 2.890625 | 3 |
tests/__init__.py | doublechiang/qsmcmd | 1 | 21815 | import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__),'../src'))
| 1.5625 | 2 |
mindspore/python/mindspore/rewrite/namer.py | httpsgithu/mindspore | 1 | 21816 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | 2.84375 | 3 |
tests/test_autopilot.py | aidanmelen/bobcat_miner | 6 | 21817 | <filename>tests/test_autopilot.py<gh_stars>1-10
from unittest.mock import patch, call, PropertyMock, AsyncMock, MagicMock, mock_open
import unittest
from bobcat_miner import BobcatAutopilot, Bobcat, OnlineStatusCheck
import mock_endpoints
class TestAutopilot(unittest.TestCase):
"""Test BobcatAutopilot."""
... | 2.546875 | 3 |
fig/project.py | kazoup/fig | 0 | 21818 | <filename>fig/project.py<gh_stars>0
from __future__ import unicode_literals
from __future__ import absolute_import
import logging
from .service import Service
log = logging.getLogger(__name__)
def sort_service_dicts(services):
# Topological sort (Cormen/Tarjan algorithm).
unmarked = services[:]
temporary... | 2.5 | 2 |
input/utils/chi-squared-contingency-tests.py | g-p-m/GPM | 0 | 21819 | <filename>input/utils/chi-squared-contingency-tests.py
import numpy, scipy.stats
T1 = numpy.asarray([
[ 316, 378, 393, 355, 391, 371, 400, 397, 385, 371, 382, 371, ],
[ 336, 339, 322, 341, 314, 311, 339, 310, 331, 355, 316, 306, ],
[ 375, 364, 375, 381, 381, 401, 374, 396, 422, 417, 372, 435, ],
[ 238, 231, 263, 268, 2... | 2.46875 | 2 |
inference_speed.py | guillesanbri/DPT | 0 | 21820 | import os
import wandb
import torch
import warnings
import numpy as np
import torchvision.transforms
from fvcore.nn import FlopCountAnalysis
from dpt.models import DPTDepthModel
def get_flops(model, x, unit="G", quiet=True):
_prefix = {'k': 1e3, # kilo
'M': 1e6, # mega
'G': 1e9, ... | 2.109375 | 2 |
cybox/common/tools.py | siemens/python-cybox | 0 | 21821 | <reponame>siemens/python-cybox
# Copyright (c) 2014, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox
import cybox.bindings.cybox_common as common_binding
from cybox.common import HashList, StructuredText, VocabString
class ToolType(VocabString):
_XSI_TYPE = 'cyboxVo... | 1.914063 | 2 |
python/ray/rllib/models/tf/tf_modelv2.py | alex-petrenko/ray | 1 | 21822 | <gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.utils import try_import_tf
tf = try_import_tf()
class TFModelV2(ModelV2):
"""TF version of ModelV2."""
def __init__(self, o... | 1.914063 | 2 |
EventManager/Home/models.py | 201901407/woc3.0-eventmanager-DarshilParikh | 1 | 21823 | from django.db import models
import uuid, datetime
from django.utils import timezone
# Create your models here.
class User(models.Model):
user_id = models.CharField(max_length=100,default=uuid.uuid4)
email = models.EmailField(max_length=100)
name = models.CharField(max_length=100)
password = models.Ch... | 2.390625 | 2 |
zulip_bots/zulip_bots/terminal.py | maanuanubhav999/python-zulip-api | 1 | 21824 | #!/usr/bin/env python3
import os
import sys
import argparse
from zulip_bots.finder import import_module_from_source, resolve_bot_path
from zulip_bots.simple_lib import TerminalBotHandler
current_dir = os.path.dirname(os.path.abspath(__file__))
def parse_args():
description = '''
This tool allows you to t... | 2.46875 | 2 |
tesHistMatch.py | cliffeby/Duckpin2 | 0 | 21825 | <reponame>cliffeby/Duckpin2
# import the necessary packages
import io
import time
import cropdata1024, cropdata1440
import numpy as np
import threading
import cv2
mask_crop_ranges = cropdata1440.ballCrops
crop_ranges = cropdata1024.pin_crop_ranges
arm_crop_ranges = cropdata1440.resetArmCrops
scrop_ranges = cropdata102... | 2.1875 | 2 |
authlib/integrations/flask_client/remote_app.py | bobh66/authlib | 1 | 21826 | from flask import redirect
from flask import request as flask_req
from flask import _app_ctx_stack
from ..base_client import RemoteApp
class FlaskRemoteApp(RemoteApp):
"""Flask integrated RemoteApp of :class:`~authlib.client.OAuthClient`.
It has built-in hooks for OAuthClient. The only required configuration
... | 2.765625 | 3 |
models/cnn_stft.py | gumpy-hybridBCI/GUMPY- | 27 | 21827 | from .model import KerasModel
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.layers import BatchNormalization, Dropout, Conv2D, MaxPooling2D
import kapre
from kapre.utils import Normalization2D
from kapre.time_frequency import Spectrogram
class CNN_STF... | 2.984375 | 3 |
test/test_http.py | tylerlong/ringcentral-python | 3 | 21828 | from .test_base import BaseTestCase
class HttpTestCase(BaseTestCase):
def test_get(self):
r = self.rc.get('/restapi/v1.0/account/~/extension/~')
self.assertEqual(200, r.status_code)
def test_post(self):
r = self.rc.post('/restapi/v1.0/account/~/extension/~/sms', {
'to': [{'... | 2.453125 | 2 |
src/scaffold/models/abstract/meta.py | Su-yj/django-scaffold-tools | 2 | 21829 | from datetime import datetime
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from scaffold.exceptions.exceptions import AppError
# def patch_methods(model_class):
# def do_patch(cls):
# for k in cls.__dict__:
# obj ... | 2.3125 | 2 |
tests/unit/client/resources/box/test_box.py | etingof/softboxen | 2 | 21830 | #
# This file is part of softboxen software.
#
# Copyright (c) 2020, <NAME> <<EMAIL>>
# License: https://github.com/etingof/softboxen/LICENSE.rst
#
import json
import sys
import unittest
from unittest import mock
from softboxen.client.resources.box import box
from softboxen.client.resources.box import credentials
fro... | 2.140625 | 2 |
photoseleven/db.py | photoseleven/photoseleven-backend | 0 | 21831 | import click
from flask import current_app, g
from flask.cli import with_appcontext
from flask_pymongo import PyMongo
from werkzeug.security import check_password_hash, generate_password_hash
def get_db():
if 'db' not in g:
mongo = PyMongo(current_app)
g.db = mongo.db
g.db_client = mongo.c... | 2.234375 | 2 |
DataStructures/Stacks/Stack.py | hhimmmmii/Data_Structures_and_Algorithms | 0 | 21832 | <reponame>hhimmmmii/Data_Structures_and_Algorithms
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return Fals... | 4.15625 | 4 |
c1_tools/c1_Preferences.py | jacobmartinez3d/c1_tools | 0 | 21833 | # preferences panel to allow inputting cutom parameters for the structure of a project and its
# naming conventions.
# --------------------------------------------------------------------------------------------------
import hashlib
import nuke
from nukescripts.panels import PythonPanel
import fileinput
import os
impor... | 2.328125 | 2 |
src/proto/runtime_pb2_grpc.py | layotto/python-sdk | 0 | 21834 | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
import runtime_pb2 as runtime__pb2
class RuntimeStub(object):
"""Missing associ... | 1.921875 | 2 |
forecast_box/validate.py | kyleclo/forecast-box | 1 | 21835 | <filename>forecast_box/validate.py
"""
Validation
"""
import numpy as np
import pandas as pd
from model import Model
# TODO: different versions with resampling or subsampling
# TODO: return DataFrame of forecasted_values along with metric?
def validate_model(name, params, time_series, metric_fun):
"""Evaluate... | 3.40625 | 3 |
config/api_router.py | summerthe/django_api_starter | 0 | 21836 | <gh_stars>0
from django.conf import settings
from django.urls.conf import include, path
from rest_framework.routers import DefaultRouter, SimpleRouter
if settings.DEBUG:
router = DefaultRouter()
else:
router = SimpleRouter()
app_name = "api"
urlpatterns = [
path("", include("summers_api.users.api.urls")),... | 1.757813 | 2 |
backstack/__init__.py | pixlie/platform | 2 | 21837 | <reponame>pixlie/platform
from .models import SystemModel, BaseModel
from .errors import ServerError, Errors
from .config import settings
from .db import db, Base
from .commands import Commands
name = "platform"
__all__ = [
"name",
"SystemModel",
"BaseModel",
"ServerError",
"Errors",
"settin... | 1.59375 | 2 |
samples/archive/stream/stream.py | zzzDavid/heterocl | 236 | 21838 | import heterocl as hcl
hcl.init()
target = hcl.Platform.xilinx_zc706
initiation_interval = 4
a = hcl.placeholder((10, 20), name="a")
b = hcl.placeholder((10, 20), name="b")
c = hcl.placeholder((10, 20), name="c")
d = hcl.placeholder((10, 20), name="d")
e = hcl.placeholder((10, 20), name="e")
def add_mul(a, b, c, d,... | 2.171875 | 2 |
setup.py | eminaktas/k8s-workload-scaler | 3 | 21839 | import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as readme_file:
README = readme_file.read()
setup(
name='k8s-workload-scaler',
version='0.0.2',
packages=['k8s_workload_scaler'],
url='github.com/eminaktas/k8s-workl... | 1.34375 | 1 |
results/kata_result.py | tamasmagyar/egyeni_vallalkozo_kalkulator | 0 | 21840 |
class KataResult:
def __init__(self, revenue, ipa, cost_of_kata, net_income, cost_of_goods, kata_penalty):
self.revenue = revenue
self.ipa = ipa
self.cost_of_kata = cost_of_kata
self.net_income = net_income
self.cost_of_goods = cost_of_goods
self.kata_penalty = kata... | 2.578125 | 3 |
ros/dynamic_reconfigure/src/dynamic_reconfigure/client.py | numberen/apollo-platform | 2 | 21841 | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyri... | 1.328125 | 1 |
l0bnb/relaxation/core.py | jonathan-taylor/l0bnb | 25 | 21842 | <filename>l0bnb/relaxation/core.py
import copy
from time import time
from collections import namedtuple
import numpy as np
from numba.typed import List
from numba import njit
from ._coordinate_descent import cd_loop, cd
from ._cost import get_primal_cost, get_dual_cost
from ._utils import get_ratio_threshold, get_act... | 1.679688 | 2 |
uroboros-diversification/src/diversification/bb_branchfunc_diversify.py | whj0401/RLOBF | 3 | 21843 | from analysis.visit import *
from disasm.Types import *
from utils.ail_utils import *
from utils.pp_print import *
from junkcodes import get_junk_codes
obfs_proportion = 0.015
class bb_branchfunc_diversify(ailVisitor):
def __init__(self, funcs, fb_tbl, cfg_tbl):
ailVisitor.__init__(self)
self.fu... | 2.109375 | 2 |
dsfaker/generators/str.py | pajachiet/dsfaker | 3 | 21844 | from random import Random
from rstr import Rstr
from . import Generator
class Regex(Generator):
def __init__(self, regex, seed=None):
self.gen = Rstr(Random(seed))
self.regex = regex
def get_single(self):
return self.gen.xeger(self.regex)
| 3.140625 | 3 |
main1.py | dubblin27/bible-of-algo | 0 | 21845 | su = 0
a = [3,5,6,2,7,1]
print(sum(a))
x, y = input("Enter a two value: ").split()
x = int(x)
y = int(y)
su = a[y] + sum(a[:y])
print(su) | 3.578125 | 4 |
reagent/test/training/test_qrdqn.py | dmitryvinn/ReAgent | 1,156 | 21846 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import unittest
import torch
from reagent.core.parameters import EvaluationParameters, RLParameters
from reagent.core.types import FeatureData, DiscreteDqnInput, ExtraData
from reagent.evaluation.evaluator import get_metric... | 2.03125 | 2 |
highway_env/__init__.py | songanz/highway-env | 1 | 21847 | from gym.envs.registration import register
register(
id='highway-v0',
entry_point='highway_env.envs:HighwayEnv',
)
register(
id='highway-continuous-v0',
entry_point='highway_env.envs:HighwayEnvCon',
)
register(
id='highway-continuous-intrinsic-rew-v0',
entry_point='highway_env.envs:HighwayEnv... | 1.5625 | 2 |
twitcaspy/auth/app.py | Alma-field/twitcaspy | 0 | 21848 | <gh_stars>0
# Twitcaspy
# Copyright 2021 Alma-field
# See LICENSE for details.
#
# based on tweepy(https://github.com/tweepy/tweepy)
# Copyright (c) 2009-2021 <NAME>
from .auth import AuthHandler
from .oauth import OAuth2Basic
class AppAuthHandler(AuthHandler):
"""
Application-only authentication handler
... | 2.28125 | 2 |
tests/test_topic_matching.py | InfraPixels/powerlibs-aws-sqs-dequeue_to_api | 0 | 21849 | def test_topic_regexp_matching(dequeuer):
msg = {'company_name': 'test_company'}
actions_1 = tuple(dequeuer.get_actions_for_topic('object__created', msg))
actions_2 = tuple(dequeuer.get_actions_for_topic('object__deleted', msg))
actions_3 = tuple(dequeuer.get_actions_for_topic('otherthing__created', msg... | 2.359375 | 2 |
src/baskerville/models/model_interface.py | deflect-ca/baskerville | 2 | 21850 | <filename>src/baskerville/models/model_interface.py
# Copyright (c) 2020, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import inspect
import logging
class ModelInterface(object):
def __i... | 2.09375 | 2 |
setup_win(MPL2).py | iefan/army_holiday | 0 | 21851 | <filename>setup_win(MPL2).py
# Used successfully in Python2.5 with matplotlib 0.91.2 and PyQt4 (and Qt 4.3.3)
from distutils.core import setup
import py2exe
import sys
# no arguments
if len(sys.argv) == 1:
sys.argv.append("py2exe")
# We need to import the glob module to search for all files.
import glob
# We ne... | 1.890625 | 2 |
GeeksForGeeks/Sudo Placement 2019/Find the closest number.py | nayanapardhekar/Python | 37 | 21852 | # Find the closest number
# Difficulty: Basic Marks: 1
'''
Given an array of sorted integers. The task is to find the closest value to the given number in array. Array may contain duplicate values.
Note: If the difference is same for two values print the value which is greater than the given number.
Input:
The firs... | 3.8125 | 4 |
qcodes/tests/test_sweep_values.py | riju-pal/QCoDeS_riju | 223 | 21853 | <filename>qcodes/tests/test_sweep_values.py
import pytest
from qcodes.instrument.parameter import Parameter
from qcodes.instrument.sweep_values import SweepValues
from qcodes.utils.validators import Numbers
@pytest.fixture(name='c0')
def _make_c0():
c0 = Parameter('c0', vals=Numbers(-10, 10), get_cmd=None, set... | 2.375 | 2 |
src/django_powerdns_api/urls.py | andrzej-jankowski/django-powerdns-api | 0 | 21854 | # -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from django_powerdns_api.routers import router
urlpatterns = patterns(
'',
url(r... | 1.382813 | 1 |
tools/SDKTool/src/WrappedDeviceAPI/deviceAPI/mobileDevice/android/plugin/Platform_plugin/PlatformWeTest/__init__.py | Passer-D/GameAISDK | 1,210 | 21855 | <reponame>Passer-D/GameAISDK<filename>tools/SDKTool/src/WrappedDeviceAPI/deviceAPI/mobileDevice/android/plugin/Platform_plugin/PlatformWeTest/__init__.py
# -*- 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 Ge... | 1.710938 | 2 |
python/codingbat/src/sum_double.py | christopher-burke/warmups | 0 | 21856 | #!/usr/bin/env python3
"""sum_double
Given two int values, return their sum.
Unless the two values are the same, then return double their sum.
sum_double(1, 2) → 3
sum_double(3, 2) → 5
sum_double(2, 2) → 8
source: https://codingbat.com/prob/p141905
"""
def sum_double(a: int, b: int) -> int:
"""Sum Double.
... | 4.28125 | 4 |
database_email_backend/__init__.py | enderlabs/django-database-email-backend | 1 | 21857 | # -*- coding: utf-8 -*-
VERSION = (1, 0, 4)
__version__ = "1.0.4"
__authors__ = ["<NAME> <<EMAIL>>", ]
| 1 | 1 |
src/draw.py | mattdesl/inkyphat-mods | 7 | 21858 | #!/usr/bin/env python
import argparse
from PIL import Image
from inky import InkyPHAT
print("""Inky pHAT/wHAT: Logo
Displays the Inky pHAT/wHAT logo.
""")
type = "phat"
colour = "black"
inky_display = InkyPHAT(colour)
inky_display.set_border(inky_display.BLACK)
img = Image.open("assets/InkypHAT-212x104-bw.png")
i... | 2.78125 | 3 |
newsapp/tests.py | Esther-Anyona/four-one-one | 0 | 21859 | from django.test import TestCase
from .models import *
from django.contrib.auth.models import User
# Create your tests here.
user = User.objects.get(id=1)
profile = Profile.objects.get(id=1)
neighbourhood = Neighbourhood.objects.get(id=1)
class TestBusiness(TestCase):
def setUp(self):
self.business=Busin... | 2.59375 | 3 |
ssdlite/load_caffe_weights.py | kkrpawkal/MobileNetv2-SSDLite | 0 | 21860 | <filename>ssdlite/load_caffe_weights.py
import numpy as np
import sys,os
caffe_root = '/home/yaochuanqi/work/ssd/caffe/'
sys.path.insert(0, caffe_root + 'python')
import caffe
deploy_proto = 'deploy.prototxt'
save_model = 'deploy.caffemodel'
weights_dir = 'output'
box_layers = ['conv_13/expand', 'Conv_1', '... | 2.375 | 2 |
qa327/frontend/exceptions.py | rickyzhangca/CISC-327 | 0 | 21861 | <reponame>rickyzhangca/CISC-327<gh_stars>0
'''
This is the exceptions module:
'''
'''
Exception of when user do not have the access to certain pages.
'''
class CannotAccessPageException(Exception):
pass
'''
Exception of the first password and the second password does not match during registration.
'''
class Pass... | 2.796875 | 3 |
dags/minimal_dag.py | MarcusJones/kaggle_petfinder_adoption | 1 | 21862 | <filename>dags/minimal_dag.py
import airflow as af
from airflow.operators.dummy_operator import DummyOperator
from datetime import datetime
with af.DAG('minimal_dag', start_date=datetime(2016, 1, 1)) as dag:
op = DummyOperator(task_id='op')
op.dag is dag # True
| 2.1875 | 2 |
app.py | paulinaacostac/GPT2 | 2 | 21863 | # -*- coding: utf-8 -*-
import json
import os
import numpy as np
import tensorflow.compat.v1 as tf
from src import model, sample, encoder
from flask import Flask
from flask import request, jsonify
import time
######model
def interact_model(
model_name='run1',
seed=None,
nsamples=1,
batch_size=1,
... | 2.21875 | 2 |
t/unit/utils/test_div.py | kaiix/kombu | 1,920 | 21864 | <reponame>kaiix/kombu<gh_stars>1000+
import pickle
from io import BytesIO, StringIO
from kombu.utils.div import emergency_dump_state
class MyStringIO(StringIO):
def close(self):
pass
class MyBytesIO(BytesIO):
def close(self):
pass
class test_emergency_dump_state:
def test_dump(self... | 2.203125 | 2 |
intents/oversights/more_than_just_topk.py | googleinterns/debaised-analysis | 1 | 21865 | """
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 agreed to in writing, software
distrib... | 2.609375 | 3 |
release/stubs.min/System/Net/__init___parts/TransportContext.py | htlcnn/ironpython-stubs | 182 | 21866 | <filename>release/stubs.min/System/Net/__init___parts/TransportContext.py<gh_stars>100-1000
class TransportContext(object):
""" The System.Net.TransportContext class provides additional context about the underlying transport layer. """
def GetChannelBinding(self,kind):
"""
GetChannelBinding(self: TransportCon... | 1.9375 | 2 |
zkpytb/json.py | zertrin/zkpytb | 2 | 21867 | """
Helper functions related to json
Author: <NAME>
"""
import datetime
import decimal
import json
import uuid
import pathlib
class JSONEncoder(json.JSONEncoder):
"""
A custom JSONEncoder that can handle a bit more data types than the one from stdlib.
"""
def default(self, o):
# early passt... | 3.15625 | 3 |
back_end/consts.py | DoctorChe/crash_map | 1 | 21868 | # encoding: utf-8
# input data constants
MARI_EL = 'Республика Марий Эл'
YOSHKAR_OLA = 'Республика Марий Эл, Йошкар-Ола'
VOLZHSK = 'Республика Марий Эл, Волжск'
VOLZHSK_ADM = 'Республика Марий Эл, Волжский район'
MOUNTIN = 'Республика Марий Эл, Горномарийский район'
ZVENIGOVO = 'Республика Марий Эл, Звениговский райо... | 1.59375 | 2 |
tests/unit/modules/win_iis_test.py | matt-malarkey/salt | 1 | 21869 | # -*- coding: utf-8 -*-
'''
:synopsis: Unit Tests for Windows IIS Module 'module.win_iis'
:platform: Windows
:maturity: develop
versionadded:: Carbon
'''
# Import Python Libs
from __future__ import absolute_import
import json
# Import Salt Libs
from salt.exceptions import SaltInvocationError
from salt... | 2.171875 | 2 |
scripts/loader_to_sharepoint.py | lawrkelly/python-useful-scripts | 0 | 21870 | #!/usr/bin/env python
# coding: utf-8
# Loader_to_sharepoint.py
#
#
from pathlib import Path
import os.path
import requests,json,urllib
import pandas as pd
import collections
from collections import defaultdict
import xmltodict
import getpass
from shareplum import Office365
from shareplum.site import Version
from sha... | 2.515625 | 3 |
tests/test_tunnels_released.py | jhaapako/tcf | 24 | 21871 | <reponame>jhaapako/tcf<filename>tests/test_tunnels_released.py
#! /usr/bin/python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
# pylint: disable = missing-docstring
import os
import socket
import commonl.testing
import tcfl
import tcfl.tc
srcdir = os.path.dirname(__file__)
ttbd... | 2.15625 | 2 |
template.py | deepak7376/design_pattern | 0 | 21872 | from abc import ABC, abstractmethod
class AverageCalculator(ABC):
def average(self):
try:
num_items = 0
total_sum = 0
while self.has_next():
total_sum += self.next_item()
num_items += 1
if num_items == 0:
ra... | 3.90625 | 4 |
conanfile.py | helmesjo/conan-lua | 0 | 21873 | from conans import ConanFile, CMake, tools
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
class LuaConan(ConanFile):
name = "Lua"
version = "5.3.5"
description = "Lua is a powerful, fast, lightweight, embeddable scripting language."
# topics can get used for searches, GitHub topics, ... | 1.96875 | 2 |
train.py | mcao610/My_BART | 0 | 21874 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import torch
import logging
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import Dataset, DataLoader, BatchSampler
from torch.utils.data.distributed import DistributedSampler
from fairseq.tasks.translation ... | 1.96875 | 2 |
yaml-to-md.py | phlummox/pptx-to-md | 2 | 21875 | #!/usr/bin/env python3
"""
intermediate yaml to markdown conversion
"""
import sys
import yaml
def yaml_to_markdown(yaml, outfile):
"""Given a list of dicts representing PowerPoint slides
-- presumably loaded from a YAML file -- convert to
markdown and print the result on the file-like
object 'outfile'.
""... | 3.578125 | 4 |
library/real/display_real.py | console-beaver/MIT-Racecar-cbeast | 0 | 21876 | """
Copyright <NAME> College
MIT License
Spring 2020
Contains the Display module of the racecar_core library
"""
import cv2 as cv
import os
from nptyping import NDArray
from display import Display
class DisplayReal(Display):
__WINDOW_NAME: str = "RACECAR display window"
__DISPLAY: str = ":1"
def __init... | 2.828125 | 3 |
DominantSparseEigenAD/tests/demos/2ndderivative.py | buwantaiji/DominantSparseEigenAD | 23 | 21877 | <filename>DominantSparseEigenAD/tests/demos/2ndderivative.py<gh_stars>10-100
"""
A small toy example demonstrating how the process of computing 1st
derivative can be added to the original computation graph to produce an enlarged
graph whose back-propagation yields the 2nd derivative.
"""
import torch
x = torch.ran... | 3.109375 | 3 |
test_default.py | dukedhx/tokenflex-reporting-python-script | 4 | 21878 | <filename>test_default.py
#####################################################################
## Copyright (c) Autodesk, Inc. All rights reserved
## Written by Forge Partner Development
##
## Permission to use, copy, modify, and distribute this software in
## object code form for any purpose and without fee is hereby... | 1.960938 | 2 |
HyperAPI/hdp_api/routes/nitro.py | RomainGeffraye/HyperAPI | 0 | 21879 | <filename>HyperAPI/hdp_api/routes/nitro.py
from HyperAPI.hdp_api.routes import Resource, Route
from HyperAPI.hdp_api.routes.base.version_management import available_since
class Nitro(Resource):
name = "nitro"
class _getForecasts(Route):
name = "getForecasts"
httpMethod = Route.POST
pa... | 2.046875 | 2 |
third_party/pyth/p2w_autoattest.py | dendisuhubdy/wormhole | 695 | 21880 | <reponame>dendisuhubdy/wormhole
#!/usr/bin/env python3
# This script sets up a simple loop for periodical attestation of Pyth data
from pyth_utils import *
from http.client import HTTPConnection
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import os
import re
import subprocess
import time
i... | 2.359375 | 2 |
hands-on_introduction/3 - model_validation.py | varunpandey0502/skyfi_labs_ml_workshop | 0 | 21881 | import pandas as pd
melbourne_file_path = './melbourne_housing_data.csv'
melbourne_data = pd.read_csv(melbourne_file_path)
melbourne_data.dropna(axis=0)
y = melbourne_data.Price
melbourne_features = ['Rooms','Bathroom','Landsize','Lattitude','Longtitude']
X = melbourne_data[melbourne_features]
X.describe()
X.he... | 3.765625 | 4 |
src/npu/comprehension.py | feagi/feagi | 1 | 21882 | <reponame>feagi/feagi
# Copyright 2016-2022 The FEAGI 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
#
# Unl... | 2.359375 | 2 |
policyhandler/onap/process_info.py | alex-sh2020/dcaegen2-platform-policy-handler | 2 | 21883 | <gh_stars>1-10
# ================================================================================
# Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# y... | 1.882813 | 2 |
10-19/14. normalize_sentences/test_normalize_sentences.py | dcragusa/PythonMorsels | 1 | 21884 | import unittest
from textwrap import dedent
from normalize_sentences import normalize_sentences
class NormalizeSentencesTests(unittest.TestCase):
"""Tests for normalize_sentences."""
maxDiff = 1000
def test_no_sentences(self):
sentence = "This isn't a sentence"
self.assertEqual(normali... | 3.84375 | 4 |
graph/renkolib.py | kUNWAR-DIVYANSHU/stockui | 2 | 21885 | import atrlib
import pandas as pd
# module for calculation of data for renko graph
def renko(df):
d , l , h ,lbo ,lbc,vol=[],[],[],[],[],[]
brick_size = atrlib.brick_size(df)
volume = 0.0
for i in range(0,len(df)):
if i==0:
if(df['close'][i]>df['open'][i]):
d.append(... | 2.71875 | 3 |
utils/utils.py | SoliareofAstora/Metagenomic-DeepFRI | 0 | 21886 | import os
import pathlib
import requests
import shutil
import subprocess
import time
ENV_PATHS = set()
def add_path_to_env(path):
ENV_PATHS.add(path)
def run_command(command, timeout=-1):
if type(command) == str:
command = str.split(command, ' ')
my_env = os.environ.copy()
my_env["PATH"] +... | 2.71875 | 3 |
fuzzinator/tracker/github_tracker.py | akosthekiss/fuzzinator | 0 | 21887 | <reponame>akosthekiss/fuzzinator
# Copyright (c) 2016-2022 <NAME>, <NAME>.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
try:
# FIXME: very nasty, but a recent P... | 1.9375 | 2 |
qmdz_const.py | cygnushan/measurement | 1 | 21888 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import sys
import os
from init_op import read_config
# ROOT_PATH = os.path.split(os.path.realpath(__file__))[0]
if getattr(sys, 'frozen', None):
ROOT_DIR = os.path.dirname(sys.executable)
else:
ROOT_DIR = os.path.dirname(__file__)
VI_CONF_PATH = ROOT_DIR + "\conf\VI_CO... | 1.828125 | 2 |
lattedb/linksmear/apps.py | callat-qcd/lattedb | 1 | 21889 | from django.apps import AppConfig
class LinkSmearConfig(AppConfig):
name = "linksmear"
| 1.03125 | 1 |
project/repository/user.py | tobiasaditya/fastapi-blog | 0 | 21890 | from typing import List
from fastapi import APIRouter
from fastapi.params import Depends
from fastapi import HTTPException, status
from sqlalchemy.orm.session import Session
from project import schema, models, database, hashing
router = APIRouter(
prefix="/user",
tags=['Users']
)
@router.post('/new')
def crea... | 2.578125 | 3 |
milking_cowmask/data_sources/imagenet_data_source.py | deepneuralmachine/google-research | 23,901 | 21891 | <reponame>deepneuralmachine/google-research<gh_stars>1000+
# 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.apac... | 2.390625 | 2 |
utils/image.py | ariel415el/Efficient-GPNN | 7 | 21892 | import os
import cv2
import torch
from torch.nn import functional as F
from torchvision import transforms
import torchvision.utils
def save_image(img, path):
os.makedirs(os.path.dirname(path), exist_ok=True)
torchvision.utils.save_image(torch.clip(img, -1, 1), path, normalize=True)
def cv2pt(img):
img =... | 2.5625 | 3 |
Exercism/triangle/triangle.py | adityaarakeri/Interview-solved | 46 | 21893 | <filename>Exercism/triangle/triangle.py
def is_triangle(func):
def wrapped(sides):
if any(i <= 0 for i in sides):
return False
sum_ = sum(sides)
if any(sides[i] > sum_ - sides[i] for i in range(3)):
return False
return func(sides)
return wrapped
@is_tria... | 3.984375 | 4 |
docs/user/visualization/matplotlib/pythonstyle.py | joelfrederico/mytools | 1 | 21894 | <filename>docs/user/visualization/matplotlib/pythonstyle.py
#!/usr/bin/env python3
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
# Create data to plot
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create a grid
gs = gridspec.GridSpec(1, 2)
# Create a figure
f... | 3.359375 | 3 |
StockAnalysisSystem/ui/Extension/recycled/announcement_downloader.py | SleepySoft/StockAnalysisSystem | 138 | 21895 | <reponame>SleepySoft/StockAnalysisSystem<filename>StockAnalysisSystem/ui/Extension/recycled/announcement_downloader.py<gh_stars>100-1000
import time
import urllib
import random
import logging
import requests
import datetime
from os import sys, path, makedirs
from PyQt5.QtCore import Qt, QTimer, QDateTime
from PyQt5.Qt... | 1.867188 | 2 |
tests/routes/generators/test_random.py | pedrofreitascampospro/locintel | 0 | 21896 | import random
import shapely.geometry as sg
from locintel.quality.generators.random import RandomRoutePlanGenerator, polygons
random.seed(10)
class TestRandomRoutePlanGenerator(object):
def test_random_route_plan_generator(self):
polygon = polygons["berlin"]
generator = RandomRoutePlanGenerator(... | 3.125 | 3 |
curtin-rci/local_utils.py | Curtin-Open-Knowledge-Initiative/mag_coverage_report | 0 | 21897 | <reponame>Curtin-Open-Knowledge-Initiative/mag_coverage_report
import pandas as pd
import plotly.graph_objects as go
from typing import Union, Optional
from pathlib import Path
def collate_time(df: pd.DataFrame,
columns: Union[str, list[str]],
year_range: Union[list, tuple]):
if ... | 2.359375 | 2 |
scripts/pa-loaddata.py | kbase/probabilistic_annotation | 0 | 21898 | <filename>scripts/pa-loaddata.py<gh_stars>0
#! /usr/bin/python
import argparse
import os
from biokbase.probabilistic_annotation.DataParser import DataParser
from biokbase.probabilistic_annotation.Helpers import get_config
from biokbase import log
desc1 = '''
NAME
pa-loaddata -- load static database of gene anno... | 2.375 | 2 |
pippin.py | harlowja/pippin | 0 | 21899 | <filename>pippin.py
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Yahoo! 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.or... | 1.992188 | 2 |