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 |
|---|---|---|---|---|---|---|
python/paddle/tensor/attribute.py | douch/Paddle | 1 | 2600 | # 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 app... | 2.046875 | 2 |
ocdsmerge/exceptions.py | open-contracting/ocds-merge | 4 | 2601 | <reponame>open-contracting/ocds-merge
class OCDSMergeError(Exception):
"""Base class for exceptions from within this package"""
class MissingDateKeyError(OCDSMergeError, KeyError):
"""Raised when a release is missing a 'date' key"""
def __init__(self, key, message):
self.key = key
self.me... | 2.46875 | 2 |
appcodec.py | guardhunt/TelemterRC | 0 | 2602 | <filename>appcodec.py
import evdev
import time
import struct
class appcodec():
def __init__(self):
self.device = evdev.InputDevice("/dev/input/event2")
self.capabilities = self.device.capabilities(verbose=True)
self.capaRAW = self.device.capabilities(absinfo=False)
self.config = {}
... | 2.828125 | 3 |
scripts/examples/OpenMV/16-Codes/find_barcodes.py | jiskra/openmv | 1,761 | 2603 | # Barcode Example
#
# This example shows off how easy it is to detect bar codes using the
# OpenMV Cam M7. Barcode detection does not work on the M4 Camera.
import sensor, image, time, math
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.VGA) # High Res!
sensor.set_windowing((640, 80... | 3.265625 | 3 |
Python/factorial.py | devaslooper/Code-Overflow | 0 | 2604 | <reponame>devaslooper/Code-Overflow
n=int(input("Enter number "))
fact=1
for i in range(1,n+1):
fact=fact*i
print("Factorial is ",fact)
| 3.796875 | 4 |
mundo 3/099.py | thiagofreitascarneiro/Curso-de-Python---Curso-em-Video | 1 | 2605 | <reponame>thiagofreitascarneiro/Curso-de-Python---Curso-em-Video
import time
# O * é para desempacotar o paramêtro. Permite atribuir inumeros parametros.
def maior(* num):
contador = maior = 0
print('Analisando os valores passados...')
for v in num:
contador = contador + 1
print(f'{v} ', end... | 3.734375 | 4 |
tests/test_packed_to_padded.py | theycallmepeter/pytorch3d_PBR | 0 | 2606 | <gh_stars>0
# Copyright (c) Facebook, Inc. and its affiliates.
# 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 unittest
import torch
from common_testing import TestCaseMixin, get_random_cuda_devi... | 2.21875 | 2 |
easyric/tests/test_io_geotiff.py | HowcanoeWang/EasyRIC | 12 | 2607 | <filename>easyric/tests/test_io_geotiff.py
import pyproj
import pytest
import numpy as np
from easyric.io import geotiff, shp
from skimage.io import imread
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
def test_prase_header_string_width():
out_dict = geotiff._prase_header_string("* 256 image_w... | 2.234375 | 2 |
src/ebay_rest/api/buy_marketplace_insights/models/item_location.py | matecsaj/ebay_rest | 3 | 2608 | # coding: utf-8
"""
Marketplace Insights API
<a href=\"https://developer.ebay.com/api-docs/static/versioning.html#limited\" target=\"_blank\"> <img src=\"/cms/img/docs/partners-api.svg\" class=\"legend-icon partners-icon\" title=\"Limited Release\" alt=\"Limited Release\" />(Limited Release)</a> The Marketpl... | 2.171875 | 2 |
fractionalKnapsack.py | aadishgoel2013/Algos-with-Python | 6 | 2609 | <filename>fractionalKnapsack.py
# Fractional Knapsack
wt = [40,50,30,10,10,40,30]
pro = [30,20,20,25,5,35,15]
n = len(wt)
data = [ (i,pro[i],wt[i]) for i in range(n) ]
bag = 100
data.sort(key=lambda x: x[1]/x[2], reverse=True)
profit=0
ans=[]
i=0
while i<n:
if data[i][2]<=bag:
bag-=data[... | 2.859375 | 3 |
pysrc/classifier.py | CrackerCat/xed | 1,261 | 2610 | #!/usr/bin/env python
# -*- python -*-
#BEGIN_LEGAL
#
#Copyright (c) 2019 Intel 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-... | 1.914063 | 2 |
tests/integration/api/test_target_groups.py | lanz/Tenable.io-SDK-for-Python | 90 | 2611 | <reponame>lanz/Tenable.io-SDK-for-Python<gh_stars>10-100
import pytest
from tenable_io.api.target_groups import TargetListEditRequest
from tenable_io.api.models import TargetGroup, TargetGroupList
@pytest.mark.vcr()
def test_target_groups_create(new_target_group):
assert isinstance(new_target_group, TargetGroup)... | 2.1875 | 2 |
Installation/nnAudio/Spectrogram.py | tasercake/nnAudio | 0 | 2612 | """
Module containing all the spectrogram classes
"""
# 0.2.0
import torch
import torch.nn as nn
from torch.nn.functional import conv1d, conv2d, fold
import numpy as np
from time import time
from nnAudio.librosa_functions import *
from nnAudio.utils import *
sz_float = 4 # size of a float
epsilon = 10e-8 # fudg... | 2.609375 | 3 |
train.py | hui-won/KoBART_Project | 13 | 2613 | <gh_stars>10-100
import argparse
import logging
import os
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
from pytorch_lightning import loggers as pl_loggers
from torch.utils.data import DataLoader, Dataset
from dataset import KoBARTSummaryDataset
from transformers import BartForCondi... | 1.976563 | 2 |
homeassistant/components/shelly/sensor.py | RavensburgOP/core | 1 | 2614 | <reponame>RavensburgOP/core
"""Sensor for Shelly."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Final, cast
import aioshelly
from homeassistant.components import sensor
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries ... | 1.851563 | 2 |
tests/web/config.py | zcqian/biothings.api | 0 | 2615 | <filename>tests/web/config.py
"""
Web settings to override for testing.
"""
import os
from biothings.web.settings.default import QUERY_KWARGS
# *****************************************************************************
# Elasticsearch Variables
# ****************************************************************... | 1.539063 | 2 |
InvenTree/InvenTree/management/commands/rebuild_thumbnails.py | rocheparadox/InvenTree | 656 | 2616 | """
Custom management command to rebuild thumbnail images
- May be required after importing a new dataset, for example
"""
import os
import logging
from PIL import UnidentifiedImageError
from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import OperationalError... | 2.421875 | 2 |
cogs/carbon.py | Baracchino-Della-Scuola/Bot | 6 | 2617 | <gh_stars>1-10
import discord
from discord.ext import commands
import urllib.parse
from .constants import themes, controls, languages, fonts, escales
import os
from pathlib import Path
from typing import Any
# from pyppeteer import launch
from io import *
import requests
def encode_url(text: str) -> str:
first_e... | 2.671875 | 3 |
examples/show_artist.py | jimcortez/spotipy_twisted | 0 | 2618 | <gh_stars>0
# shows artist info for a URN or URL
import spotipy_twisted
import sys
import pprint
if len(sys.argv) > 1:
urn = sys.argv[1]
else:
urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu'
sp = spotipy_twisted.Spotify()
artist = sp.artist(urn)
pprint.pprint(artist)
| 2.53125 | 3 |
examples/mcp3xxx_mcp3002_single_ended_simpletest.py | sommersoft/Adafruit_CircuitPython_MCP3xxx | 0 | 2619 | <filename>examples/mcp3xxx_mcp3002_single_ended_simpletest.py
import busio
import digitalio
import board
import adafruit_mcp3xxx.mcp3002 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
# create the spi bus
spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
# create the cs (chip select)
cs = dig... | 3.125 | 3 |
glue/core/data_factories/tables.py | rosteen/glue | 550 | 2620 | from glue.core.data_factories.helpers import has_extension
from glue.config import data_factory
__all__ = ['tabular_data']
@data_factory(label="ASCII Table",
identifier=has_extension('csv txt tsv tbl dat '
'csv.gz txt.gz tbl.bz '
... | 2.640625 | 3 |
code_doc/views/author_views.py | coordt/code_doc | 0 | 2621 | <filename>code_doc/views/author_views.py
from django.shortcuts import render
from django.http import Http404
from django.views.generic.edit import UpdateView
from django.views.generic import ListView, View
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django... | 2.359375 | 2 |
d00dfeed/analyses/print_sloc_per_soc.py | rehosting/rehosting_sok | 4 | 2622 | # External deps
import os, sys, json
from pathlib import Path
from typing import Dict, List
# Internal deps
os.chdir(sys.path[0])
sys.path.append("..")
import df_common as dfc
import analyses_common as ac
# Generated files directory
GEN_FILE_DIR = str(Path(__file__).resolve().parent.parent) + os.sep + "generated_file... | 2.296875 | 2 |
mingpt/lr_decay.py | asigalov61/minGPT | 18 | 2623 | import math
import pytorch_lightning as pl
class LearningRateDecayCallback(pl.Callback):
def __init__(self, learning_rate, warmup_tokens=<PASSWORD>, final_tokens=<PASSWORD>, lr_decay=True):
super().__init__()
self.learning_rate = learning_rate
self.tokens = 0
self.final_tokens = f... | 2.421875 | 2 |
apprise/config/ConfigBase.py | calvinbui/apprise | 0 | 2624 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2020 <NAME> <<EMAIL>>
# 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 documentation files(the "Software"), to deal
# in the Software withou... | 1.375 | 1 |
ffmpeg_util.py | manuel-fischer/ScrollRec | 0 | 2625 | import sys
import subprocess
from subprocess import Popen, PIPE
AV_LOG_QUIET = "quiet"
AV_LOG_PANIC = "panic"
AV_LOG_FATAL = "fatal"
AV_LOG_ERROR = "error"
AV_LOG_WARNING = "warning"
AV_LOG_INFO = "info"
AV_LOG_VERBOSE = "verbose"
AV_LOG_DEBUG = "debug"
ffmpeg_loglevel = AV_LOG_ERROR
IS_WIN32 = 'win32' ... | 2.515625 | 3 |
setup.py | rizar/CLOSURE | 14 | 2626 | from setuptools import setup
setup(
name="nmn-iwp",
version="0.1",
keywords="",
packages=["vr", "vr.models"]
)
| 1 | 1 |
analysis_tools/PYTHON_RICARDO/output_ingress_egress/scripts/uniform_grid.py | lefevre-fraser/openmeta-mms | 0 | 2627 | """ Represent a triangulated surface using a 3D boolean grid"""
import logging
import numpy as np
from rpl.tools.ray_tracing.bsp_tree_poly import BSP_Element
from rpl.tools.geometry import geom_utils
import data_io
class BSP_Grid(object):
def __init__(self, node_array, tris, allocate_step=100000):
... | 3.078125 | 3 |
silver_bullet/crypto.py | Hojung-Jeong/Silver-Bullet-Encryption-Tool | 0 | 2628 | '''
>List of functions
1. encrypt(user_input,passphrase) - Encrypt the given string with the given passphrase. Returns cipher text and locked pad.
2. decrypt(cipher_text,locked_pad,passphrase) - Decrypt the cipher text encrypted with SBET. It requires cipher text, locked pad, and passphrase.
'''
# CODE ============... | 3.953125 | 4 |
pyfire/errors.py | RavidLevi98/pyfire | 0 | 2629 | <reponame>RavidLevi98/pyfire
# -*- coding: utf-8 -*-
"""
pyfire.errors
~~~~~~~~~~~~~~~~~~~~~~
Holds the global used base errors
:copyright: 2011 by the pyfire Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import xml.etree.ElementTree as ET
class XMPPProtoc... | 1.710938 | 2 |
app/nextMoveLogic.py | thekitbag/starter-snake-python | 0 | 2630 | import random
class Status(object):
def getHeadPosition(gamedata):
me = gamedata['you']
my_position = me['body']
head = my_position[0]
return head
def getMyLength(gamedata):
me = gamedata['you']
my_position = me['body']
if my_position[0] == my_position[1] == my_position[2]:
return 1
elif my_... | 3.1875 | 3 |
generator/util.py | gbtami/lichess-puzzler | 1 | 2631 | from dataclasses import dataclass
import math
import chess
import chess.engine
from model import EngineMove, NextMovePair
from chess import Color, Board
from chess.pgn import GameNode
from chess.engine import SimpleEngine, Score
nps = []
def material_count(board: Board, side: Color) -> int:
values = { chess.PAWN:... | 2.8125 | 3 |
sleep.py | SkylerHoward/O | 0 | 2632 | import time, morning
from datetime import datetime
def main():
while True:
a = time.mktime(datetime.now().timetuple())
n = datetime.now()
if n.hour == 6 and (n.minute-(n.minute%5)) == 15:
return morning.main()
time.sleep(300 - (time.mktime(datetime.now().timetuple())-a)) | 3.546875 | 4 |
tests/unit/commands/local/start_lambda/test_cli.py | ourobouros/aws-sam-cli | 2 | 2633 | <reponame>ourobouros/aws-sam-cli
from unittest import TestCase
from mock import patch, Mock
from samcli.commands.local.start_lambda.cli import do_cli as start_lambda_cli
from samcli.commands.local.cli_common.user_exceptions import UserException
from samcli.commands.validate.lib.exceptions import InvalidSamDocumentExce... | 2.140625 | 2 |
restapi/services/Utils/test_getters.py | Varun487/CapstoneProject_TradingSystem | 3 | 2634 | <gh_stars>1-10
from django.test import TestCase
import pandas as pd
from .getters import Getter
from .converter import Converter
from strategies.models import Company
from strategies.models import IndicatorType
class GetDataTestCase(TestCase):
def setUp(self) -> None:
# Dummy company data
Comp... | 2.578125 | 3 |
pytorch_toolkit/ote/ote/modules/trainers/mmdetection.py | abhatikar/training_extensions | 2 | 2635 | <filename>pytorch_toolkit/ote/ote/modules/trainers/mmdetection.py
"""
Copyright (c) 2020 Intel 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/L... | 1.664063 | 2 |
svn-go-stats/transform.py | BT-OpenSource/bt-betalab | 1 | 2636 | import sys
import json
import subprocess
import re
import statistics
def get_complexity():
# Load the cyclomatic complexity info
cyclostats = subprocess.check_output(['./gocyclo', 'repo']).decode("utf-8")
results = re.findall('([0-9]+)\s([^\s]+)\s([^\s]+)\s([^:]+):([0-9]+):([0-9]+)', cyclostats)
# S... | 2.890625 | 3 |
test/test_python_errors.py | yangyangxcf/parso | 0 | 2637 | """
Testing if parso finds syntax errors and indentation errors.
"""
import sys
import warnings
import pytest
import parso
from parso._compatibility import is_pypy
from .failing_examples import FAILING_EXAMPLES, indent, build_nested
if is_pypy:
# The errors in PyPy might be different. Just skip the module for n... | 2.6875 | 3 |
shogitk/usikif.py | koji-hirono/pytk-shogi-replayer | 0 | 2638 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from shogitk.shogi import Coords, Move, BLACK, WHITE, DROP, PROMOTE
RANKNUM = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7,
'h': 8,
'i': 9
}
def decoder(f):
color = ... | 2.59375 | 3 |
etherbank_cli/oracles.py | ideal-money/etherbank-cli | 1 | 2639 | <reponame>ideal-money/etherbank-cli
import click
from . import utils
@click.group()
def main():
"Simple CLI for oracles to work with Ether dollar"
pass
@main.command()
@click.option('--ether-price', type=float, help="The ether price in ether dollar")
@click.option('--collateral-ratio', type=float, help="The... | 2.484375 | 2 |
src/grader/machine.py | MrKaStep/csc230-grader | 0 | 2640 | import getpass
from plumbum import local
from plumbum.machines.paramiko_machine import ParamikoMachine
from plumbum.path.utils import copy
def _once(f):
res = None
def wrapped(*args, **kwargs):
nonlocal res
if res is None:
res = f(*args, **kwargs)
return res
return wrapp... | 2.390625 | 2 |
Mundo 1/Ex33.py | legna7/Python | 0 | 2641 | <reponame>legna7/Python<gh_stars>0
salario = float(input('digite o seu salario: '))
aumento = (salario + (salario * 15)/100 if salario <= 1250 else salario + (salario * 10)/100)
print(aumento) | 3.8125 | 4 |
tests/test_tree.py | andreax79/airflow-code-editor | 194 | 2642 | <gh_stars>100-1000
#!/usr/bin/env python
import os
import os.path
import airflow
import airflow.plugins_manager
from airflow import configuration
from flask import Flask
from unittest import TestCase, main
from airflow_code_editor.commons import PLUGIN_NAME
from airflow_code_editor.tree import (
get_tree,
)
asser... | 2.25 | 2 |
examples/token_freshness.py | greenape/flask-jwt-extended | 2 | 2643 | from quart import Quart, jsonify, request
from quart_jwt_extended import (
JWTManager,
jwt_required,
create_access_token,
jwt_refresh_token_required,
create_refresh_token,
get_jwt_identity,
fresh_jwt_required,
)
app = Quart(__name__)
app.config["JWT_SECRET_KEY"] = "super-secret" # Change ... | 2.734375 | 3 |
env/lib/python3.7/site-packages/tinvest/typedefs.py | umchemurziev/Practics | 1 | 2644 | from datetime import datetime
from typing import Any, Dict, Union
__all__ = 'AnyDict'
AnyDict = Dict[str, Any] # pragma: no mutate
datetime_or_str = Union[datetime, str] # pragma: no mutate
| 2.625 | 3 |
keras/linear/model/pipeline_train.py | PipelineAI/models | 44 | 2645 | <gh_stars>10-100
import os
os.environ['KERAS_BACKEND'] = 'theano'
os.environ['THEANO_FLAGS'] = 'floatX=float32,device=cpu'
import cloudpickle as pickle
import pipeline_invoke
import pandas as pd
import numpy as np
import keras
from keras.layers import Input, Dense
from keras.models import Model
from keras.models impor... | 2.25 | 2 |
tests/effects/test_cheerlights.py | RatJuggler/led-shim-effects | 1 | 2646 | from unittest import TestCase
from unittest.mock import Mock, patch
import sys
sys.modules['smbus'] = Mock() # Mock the hardware layer to avoid errors.
from ledshimdemo.canvas import Canvas
from ledshimdemo.effects.cheerlights import CheerLightsEffect
class TestCheerLights(TestCase):
TEST_CANVAS_SIZE = 3 # t... | 2.796875 | 3 |
figures/Figure_7/02_generate_images.py | Jhsmit/ColiCoords-Paper | 2 | 2647 | from colicoords.synthetic_data import add_readout_noise, draw_poisson
from colicoords import load
import numpy as np
import mahotas as mh
from tqdm import tqdm
import os
import tifffile
def chunk_list(l, sizes):
prev = 0
for s in sizes:
result = l[prev:prev+s]
prev += s
yield result
... | 2.328125 | 2 |
epiphancloud/models/settings.py | epiphan-video/epiphancloud_api | 0 | 2648 | <filename>epiphancloud/models/settings.py
class DeviceSettings:
def __init__(self, settings):
self._id = settings["id"]
self._title = settings["title"]
self._type = settings["type"]["name"]
self._value = settings["value"]
@property
def id(self):
return self._id
... | 2.296875 | 2 |
dictionary.py | SchmitzAndrew/OSS-101-example | 0 | 2649 | <filename>dictionary.py
word = input("Enter a word: ")
if word == "a":
print("one; any")
elif word == "apple":
print("familiar, round fleshy fruit")
elif word == "rhinoceros":
print("large thick-skinned animal with one or two horns on its nose")
else:
print("That word must not exist. This dictionary is... | 4.03125 | 4 |
solved_bronze/num11720.py | ilmntr/white_study | 0 | 2650 | <gh_stars>0
cnt = int(input())
num = list(map(int, input()))
sum = 0
for i in range(len(num)):
sum = sum + num[i]
print(sum) | 3.21875 | 3 |
setup.py | sdnhub/kube-navi | 0 | 2651 | <gh_stars>0
from distutils.core import setup
setup(
name = 'kube_navi',
packages = ['kube_navi'], # this must be the same as the name above
version = '0.1',
description = 'Kubernetes resource discovery toolkit',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'https://github.com/sdnhub/kube-navi', # us... | 1.515625 | 2 |
flink-ai-flow/ai_flow/metric/utils.py | MarvinMiao/flink-ai-extended | 1 | 2652 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | 1.507813 | 2 |
src/moduels/gui/Tab_Help.py | HaujetZhao/Caps_Writer | 234 | 2653 | <reponame>HaujetZhao/Caps_Writer<filename>src/moduels/gui/Tab_Help.py
# -*- coding: UTF-8 -*-
from PySide2.QtWidgets import QWidget, QPushButton, QVBoxLayout
from PySide2.QtCore import Signal
from moduels.component.NormalValue import 常量
from moduels.component.SponsorDialog import SponsorDialog
import os, webbrowser
... | 2.15625 | 2 |
app/routes/register.py | AuFeld/COAG | 1 | 2654 | <gh_stars>1-10
from typing import Callable, Optional, Type, cast
from fastapi import APIRouter, HTTPException, Request, status
from app.models import users
from app.common.user import ErrorCode, run_handler
from app.users.user import (
CreateUserProtocol,
InvalidPasswordException,
UserAlreadyExists,
V... | 2.609375 | 3 |
utils/visual.py | xizaoqu/Panoptic-PolarNet | 90 | 2655 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import numpy as np
def flow_to_img(flow, normalize=True):
"""Convert flow to viewable image, using color hue to encode flow vector orientation, and color saturation to
encode vector length. This is similar to the OpenCV tutorial on dense optical flow, e... | 3.875 | 4 |
DistributedRL/Gateway/build/Code/sim/Parser/LAI/GreenIndex.py | zhkmxx9302013/SoftwarePilot | 4 | 2656 | <filename>DistributedRL/Gateway/build/Code/sim/Parser/LAI/GreenIndex.py<gh_stars>1-10
import argparse
from PIL import Image, ImageStat
import math
parser = argparse.ArgumentParser()
parser.add_argument('fname')
parser.add_argument('pref', default="", nargs="?")
args = parser.parse_args()
im = Image.open(args.fname)
R... | 2.4375 | 2 |
reports/heliosV1/python/heliosStorageStats/heliosStorageStats.py | ped998/scripts | 0 | 2657 | <gh_stars>0
#!/usr/bin/env python
"""cluster storage stats for python"""
# import pyhesity wrapper module
from pyhesity import *
from datetime import datetime
import codecs
# command line arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--vip', type=str, default='helios.cohesity... | 2.40625 | 2 |
src/advanceoperate/malimgthread.py | zengrx/S.M.A.R.T | 10 | 2658 | <reponame>zengrx/S.M.A.R.T<filename>src/advanceoperate/malimgthread.py<gh_stars>1-10
#coding=utf-8
from PyQt4 import QtCore
import os, glob, numpy, sys
from PIL import Image
from sklearn.cross_validation import StratifiedKFold
from sklearn.metrics import confusion_matrix
from sklearn.neighbors import KNeighborsClassif... | 2.140625 | 2 |
tests/unittests/command_parse/test_stream.py | itamarhaber/iredis | 1,857 | 2659 | def test_xrange(judge_command):
judge_command(
"XRANGE somestream - +",
{"command": "XRANGE", "key": "somestream", "stream_id": ["-", "+"]},
)
judge_command(
"XRANGE somestream 1526985054069 1526985055069",
{
"command": "XRANGE",
"key": "somestream",
... | 1.898438 | 2 |
tests/test_find_forks/test_find_forks.py | ivan2kh/find_forks | 41 | 2660 | <filename>tests/test_find_forks/test_find_forks.py
# coding: utf-8
"""test_find_fork."""
# pylint: disable=no-self-use
from __future__ import absolute_import, division, print_function, unicode_literals
from os import path
import unittest
from six import PY3
from find_forks.__init__ import CONFIG
from find_forks.find... | 2.3125 | 2 |
neutron/agent/l3/dvr_router.py | insequent/neutron | 0 | 2661 | # Copyright (c) 2015 Openstack Foundation
#
# 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 ... | 1.734375 | 2 |
sider/warnings.py | PCManticore/sider | 19 | 2662 | <reponame>PCManticore/sider
""":mod:`sider.warnings` --- Warning categories
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module defines several custom warning category classes.
"""
class SiderWarning(Warning):
"""All warning classes used by Sider extend this base class."""
class PerformanceWarning(Sid... | 1.859375 | 2 |
kadal/query.py | Bucolo/Kadal | 1 | 2663 | MEDIA_SEARCH = """
query ($search: String, $type: MediaType, $exclude: MediaFormat, $isAdult: Boolean) {
Media(search: $search, type: $type, format_not: $exclude, isAdult: $isAdult) {
id
type
format
title {
english
romaji
native
}
synonyms
status
description
start... | 1.273438 | 1 |
sandbox/test/testChainop.py | turkeydonkey/nzmath3 | 1 | 2664 | <reponame>turkeydonkey/nzmath3<filename>sandbox/test/testChainop.py
import unittest
import operator
import sandbox.chainop as chainop
class BasicChainTest (unittest.TestCase):
def testBasicChain(self):
double = lambda x: x * 2
self.assertEqual(62, chainop.basic_chain((operator.add, double), 2, 31)... | 3.015625 | 3 |
labs_final/lab5/experiments/run_trpo_pendulum.py | mrmotallebi/berkeley-deeprl-bootcamp | 3 | 2665 | #!/usr/bin/env python
import chainer
from algs import trpo
from env_makers import EnvMaker
from models import GaussianMLPPolicy, MLPBaseline
from utils import SnapshotSaver
import numpy as np
import os
import logger
log_dir = "data/local/trpo-pendulum"
np.random.seed(42)
# Clean up existing logs
os.system("rm -rf {... | 1.96875 | 2 |
jtyoui/regular/regexengine.py | yy1244/Jtyoui | 1 | 2666 | #!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2019/12/2 10:17
# @Author: <EMAIL>
"""
正则解析器
"""
try:
import xml.etree.cElementTree as et
except ModuleNotFoundError:
import xml.etree.ElementTree as et
import re
class RegexEngine:
def __init__(self, xml, str_):
"""加载正则表。正则表为xml
:pa... | 2.78125 | 3 |
proglearn/transformers.py | rflperry/ProgLearn | 0 | 2667 | <gh_stars>0
"""
Main Author: <NAME>
Corresponding Email: <EMAIL>
"""
import keras
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.utils.validation import check_array, check_is_fitted, check_X_y
from .base import BaseTransformer
class NeuralClassificationTransformer(BaseTransformer):
... | 2.765625 | 3 |
morphelia/external/saphire.py | marx-alex/Morphelia | 0 | 2668 | import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.collections as mcoll
from matplotlib.ticker import MaxNLocator
plt.style.use('seaborn-darkgrid')
class BaseTraj:
def __init__(self, model, X):
self.model = model
assert len(X.shape) == 2, f"X should be 2... | 2.515625 | 3 |
account/views.py | Stfuncode/food-beverage-investigator | 0 | 2669 | import imp
from venv import create
from django.shortcuts import render, redirect
from django.views import View
from django.views.generic import (
ListView,
)
from account.models import *
from account.forms import *
from data.models import *
from django.contrib.auth import login as auth_login
from django.contrib.a... | 2.21875 | 2 |
fpds/client.py | mgradowski/aiproject | 0 | 2670 | <filename>fpds/client.py<gh_stars>0
import cv2
import aiohttp
import asyncio
import concurrent.futures
import argparse
import numpy as np
async def camera_source(ws: aiohttp.ClientWebSocketResponse, threadpool: concurrent.futures.ThreadPoolExecutor, src_id: int=0):
loop = asyncio.get_running_loop()
try:
... | 2.484375 | 2 |
Giveme5W1H/extractor/tools/key_value_cache.py | bkrrr/Giveme5W | 410 | 2671 | import logging
import os
import pickle
import sys
import threading
import time
from typing import List
from Giveme5W1H.extractor.root import path
from Giveme5W1H.extractor.tools.util import bytes_2_human_readable
class KeyValueCache(object):
def __init__(self, cache_path):
"""
:param cache_path: ... | 2.328125 | 2 |
nsst_translate_corpus.py | AlexanderJenke/nsst | 0 | 2672 | from argparse import ArgumentParser
from tqdm import tqdm
import NSST
from nsst_translate import best_transition_sequence
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("--nsst_file", default="output/nsst_tss20_th4_nSt100_Q0.pkl", help="nsst file")
parser.add_argument("--src_lan... | 2.546875 | 3 |
10 Days of Statistics/Day 1/Standard Deviation.py | dhyanpatel110/HACKERRANK | 0 | 2673 | # Import library
import math
# Define functionts
def mean(data):
return sum(data) / len(data)
def stddev(data, size):
sum = 0
for i in range(size):
sum = sum + (data[i] - mean(data)) ** 2
return math.sqrt(sum / size)
# Set data
size = int(input())
numbers = list(map(int, input().split()))
# ... | 3.796875 | 4 |
Homework/Hw4/Solution/problem5a.py | jmsevillam/Herramientas-Computacionales-UniAndes | 0 | 2674 | <reponame>jmsevillam/Herramientas-Computacionales-UniAndes
def decode(word1,word2,code):
if len(word1)==1:
code+=word1+word2
return code
else:
code+=word1[0]+word2[0]
return decode(word1[1:],word2[1:],code)
Alice='Ti rga eoe esg o h ore"ermetsCmuainls'
Bob='hspormdcdsamsaefrte<... | 3.359375 | 3 |
pychron/lasers/power/composite_calibration_manager.py | ASUPychron/pychron | 31 | 2675 | <reponame>ASUPychron/pychron
# ===============================================================================
# Copyright 2012 <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
#
# ht... | 1.445313 | 1 |
ttt_package/libs/best_move.py | Ipgnosis/tic_tac_toe | 0 | 2676 | <gh_stars>0
# refactored from make_play to simplify
# by Russell on 3/5/21
#from ttt_package.libs.move_utils import get_open_cells
from ttt_package.libs.compare import get_transposed_games, reorient_games
from ttt_package.libs.calc_game_bound import calc_game_bound
from ttt_package.libs.maxi_min import maximin
# find... | 2.71875 | 3 |
yard/skills/66-python/cookbook/yvhai/demo/mt/raw_thread.py | paser4se/bbxyard | 1 | 2677 | #!/usr/bin/env python3
# python 线程测试
import _thread
import time
from yvhai.demo.base import YHDemo
def print_time(thread_name, interval, times):
for cnt in range(times):
time.sleep(interval)
print(" -- %s: %s" % (thread_name, time.ctime(time.time())))
class RawThreadDemo(YHDemo):
def __in... | 3.5625 | 4 |
rasa/utils/tensorflow/constants.py | praneethgb/rasa | 8 | 2678 | # constants for configuration parameters of our tensorflow models
LABEL = "label"
IDS = "ids"
# LABEL_PAD_ID is used to pad multi-label training examples.
# It should be < 0 to avoid index out of bounds errors by tf.one_hot.
LABEL_PAD_ID = -1
HIDDEN_LAYERS_SIZES = "hidden_layers_sizes"
SHARE_HIDDEN_LAYERS = "share_hid... | 1.882813 | 2 |
client/canyons-of-mars/maze.py | GamesCreatorsClub/GCC-Rover | 3 | 2679 | <reponame>GamesCreatorsClub/GCC-Rover
#
# Copyright 2016-2019 Games Creators Club
#
# MIT License
#
import math
import pyroslib
import pyroslib.logging
import time
from pyroslib.logging import log, LOG_LEVEL_ALWAYS, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG
from rover import WheelOdos, WHEEL_NAMES
from rover import normaiseAn... | 2.734375 | 3 |
src/spaceone/monitoring/conf/proto_conf.py | jean1042/monitoring | 5 | 2680 | PROTO = {
'spaceone.monitoring.interface.grpc.v1.data_source': ['DataSource'],
'spaceone.monitoring.interface.grpc.v1.metric': ['Metric'],
'spaceone.monitoring.interface.grpc.v1.project_alert_config': ['ProjectAlertConfig'],
'spaceone.monitoring.interface.grpc.v1.escalation_policy': ['EscalationPolicy']... | 1.0625 | 1 |
tests/delete_regress/models.py | PirosB3/django | 2 | 2681 | <gh_stars>1-10
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Award(models.Model):
name = models.CharField(max_length=25)
object_id = models.PositiveIntegerField()
conte... | 2.09375 | 2 |
All_Program.py | TheoSaify/Yolo-Detector | 0 | 2682 | import cv2
from cv2 import *
import numpy as np
from matplotlib import pyplot as plt
###############################SIFT MATCH Function#################################
def SIFTMATCH(img1,img2):
# Initiate SIFT detector
sift = cv2.xfeatures2d.SIFT_create()
# find the keypoints and descri... | 2.78125 | 3 |
apps/UI_phone_mcdm.py | industrial-optimization-group/researchers-night | 0 | 2683 | import dash
from dash.exceptions import PreventUpdate
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import dash_table
import plotly.express as ex
import plotly.graph_objects as go
import pandas as pd
imp... | 2.4375 | 2 |
pyxon/utils.py | k-j-m/Pyxon | 0 | 2684 | <reponame>k-j-m/Pyxon<filename>pyxon/utils.py<gh_stars>0
import pyxon.decode as pd
def unobjectify(obj):
"""
Turns a python object (must be a class instance)
into the corresponding JSON data.
Example:
>>> @sprop.a # sprop annotations are needed to tell the
>>> @sprop.b # unobjectify function ... | 2.90625 | 3 |
AxonDeepSeg/segment.py | sophie685/newfileplzworklord | 0 | 2685 | # Segmentation script
# -------------------
# This script lets the user segment automatically one or many images based on the default segmentation models: SEM or
# TEM.
#
# <NAME> - 2017-08-30
# Imports
import sys
from pathlib import Path
import json
import argparse
from argparse import RawTextHelpFormatter
from tqd... | 3.03125 | 3 |
tests/test_hedges.py | aplested/DC_Pyps | 1 | 2686 | from dcstats.hedges import Hedges_d
from dcstats.statistics_EJ import simple_stats as mean_SD
import random
import math
def generate_sample (length, mean, sigma):
#generate a list of normal distributed samples
sample = []
for n in range(length):
sample.append(random.gauss(mean, sigma))
return ... | 2.796875 | 3 |
src/FYP/fifaRecords/urls.py | MustafaAbbas110/FinalProject | 0 | 2687 | from django.urls import path
from . import views
urlpatterns = [
path('', views.Records, name ="fRec"),
] | 1.523438 | 2 |
spacy_transformers/tests/regression/test_spacy_issue6401.py | KennethEnevoldsen/spacy-transformers | 0 | 2688 | import pytest
from spacy.training.example import Example
from spacy.util import make_tempdir
from spacy import util
from thinc.api import Config
TRAIN_DATA = [
("I'm so happy.", {"cats": {"POSITIVE": 1.0, "NEGATIVE": 0.0}}),
("I'm so angry", {"cats": {"POSITIVE": 0.0, "NEGATIVE": 1.0}}),
]
cfg_string = """
... | 2.40625 | 2 |
hydra/client/repl.py | rpacholek/hydra | 0 | 2689 | import asyncio
from ..core.common.io import input
from .action_creator import ActionCreator
class REPL:
def __init__(self, action_queue, config, *args, **kwargs):
self.action_queue = action_queue
self.config = config
async def run(self):
await asyncio.sleep(1)
print("Insert c... | 2.78125 | 3 |
train_dv3.py | drat/Neural-Voice-Cloning-With-Few-Samples | 361 | 2690 | <reponame>drat/Neural-Voice-Cloning-With-Few-Samples
"""Trainining script for seq2seq text-to-speech synthesis model.
usage: train.py [options]
options:
--data-root=<dir> Directory contains preprocessed features.
--checkpoint-dir=<dir> Directory where to save model checkpoints [default: check... | 2.359375 | 2 |
magic_mirror.py | alcinnz/Historical-Twin | 1 | 2691 | #! /usr/bin/python2
import time
start = time.time()
import pygame, numpy
import pygame.camera
# Init display
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("Magic Mirror")
#pygame.mouse.set_visible(False)
# Init font
pygame.font.init()
font_colour = 16, 117, 186
fonts = {40: p... | 2.671875 | 3 |
resolwe/__init__.py | plojyon/resolwe | 27 | 2692 | <reponame>plojyon/resolwe<gh_stars>10-100
""".. Ignore pydocstyle D400.
=======
Resolwe
=======
Open source enterprise dataflow engine in Django.
"""
from resolwe.__about__ import ( # noqa: F401
__author__,
__copyright__,
__email__,
__license__,
__summary__,
__title__,
__url__,
__ver... | 1.21875 | 1 |
audio_som64_u_grupo1.py | andremsouza/swine_sound_analysis | 0 | 2693 | # %% [markdown]
# # Testing python-som with audio dataset
# %% [markdown]
# # Imports
# %%
import matplotlib.pyplot as plt
# import librosa as lr
# import librosa.display as lrdisp
import numpy as np
import pandas as pd
import pickle
import seaborn as sns
import sklearn.preprocessing
from python_som import SOM
FILE... | 2.640625 | 3 |
footy/engine/UpdateEngine.py | dallinb/footy | 2 | 2694 | """Prediction Engine - Update the data model with the most resent fixtures and results."""
from footy.domain import Competition
class UpdateEngine:
"""Prediction Engine - Update the data model with the most resent fixtures and results."""
def __init__(self):
"""Construct a UpdateEngine object."""
... | 3.078125 | 3 |
bindings/pydeck/docs/scripts/embed_examples.py | marsupialmarcos/deck.gl | 2 | 2695 | """Script to embed pydeck examples into .rst pages with code
These populate the files you see once you click into a grid cell
on the pydeck gallery page
"""
from multiprocessing import Pool
import os
import subprocess
import sys
from const import DECKGL_URL_BASE, EXAMPLE_GLOB, GALLERY_DIR, HTML_DIR, HOSTED_STATIC_PAT... | 2.765625 | 3 |
symbolicR/python/forward_kin.py | mharding01/augmented-neuromuscular-RT-running | 0 | 2696 | <filename>symbolicR/python/forward_kin.py
import numpy as np
import sympy as sp
import re
import os
######################
# #
# 17 16 21 #
# 18 15 22 #
# 19 14 23 #
# 20 01 24 #
# 02 08 #
# 03 09 #
# 04 10 #
# 05 ... | 2.515625 | 3 |
examples/last.py | 0xiso/PyMISP | 5 | 2697 | <reponame>0xiso/PyMISP
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import misp_url, misp_key, misp_verifycert
import argparse
import os
import json
# Usage for pipe masters: ./last.py -l 5h | jq .
def init(url, key):
return PyMISP(url, key, misp_verifycert, 'json')
def d... | 2.609375 | 3 |
saleor/dashboard/urls.py | Chaoslecion123/Diver | 0 | 2698 | from django.conf.urls import include, url
from django.views.generic.base import TemplateView
from . import views as core_views
from .category.urls import urlpatterns as category_urls
from .collection.urls import urlpatterns as collection_urls
from .customer.urls import urlpatterns as customer_urls
from .discount.urls ... | 1.601563 | 2 |
experiments/CUB_fewshot_raw/FRN/ResNet-12/train.py | Jf-Chen/FRN-main | 43 | 2699 | import os
import sys
import torch
import yaml
from functools import partial
sys.path.append('../../../../')
from trainers import trainer, frn_train
from datasets import dataloaders
from models.FRN import FRN
args = trainer.train_parser()
with open('../../../../config.yml', 'r') as f:
temp = yaml.safe_load(f)
data... | 2.109375 | 2 |