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 |
|---|---|---|---|---|---|---|
tests/base.py | Suhail6inkling/bot | 1 | 21400 | <reponame>Suhail6inkling/bot
import logging
import unittest
from contextlib import contextmanager
class _CaptureLogHandler(logging.Handler):
"""
A logging handler capturing all (raw and formatted) logging output.
"""
def __init__(self):
super().__init__()
self.records = []
def em... | 2.875 | 3 |
blog/app/admin/views.py | web-user/flask-blog | 0 | 21401 | from flask import Flask, render_template, session, redirect, url_for, request, flash, abort, current_app, make_response
from flask_login import login_user, logout_user, login_required, current_user
from . import admin
from .. import db
from ..models import User, Post
from ..form import PostForm
from functools import wr... | 2.625 | 3 |
examples/get-set-params/robot.py | Tyler-Duckworth/robotpy-rev | 1 | 21402 | <gh_stars>1-10
# ----------------------------------------------------------------------------
# Copyright (c) 2017-2018 FIRST. All Rights Reserved.
# Open Source Software - may be modified and shared by FRC teams. The code
# must be accompanied by the FIRST BSD license file in the root directory of
# the project.
# ---... | 2.53125 | 3 |
pyclustering/nnet/som.py | JosephChataignon/pyclustering | 1,013 | 21403 | """!
@brief Neural Network: Self-Organized Feature Map
@details Implementation based on paper @cite article::nnet::som::1, @cite article::nnet::som::2.
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
import math
import random
import matplotlib.pyplot as plt
import pyclusterin... | 3.265625 | 3 |
ros/src/tl_detector/light_classification/tl_classifier.py | trajkd/Programming-a-Real-Self-Driving-Car | 1 | 21404 | import rospy
from styx_msgs.msg import TrafficLight
import numpy as np
from keras.models import Model
from keras import applications
from keras.models import load_model
from keras.preprocessing import image as img_preprocessing
import cv2
# load the trained model
from keras.utils.generic_utils import CustomObjectScop... | 2.765625 | 3 |
sktime/clustering/evaluation/_plot_clustering.py | marcio55afr/sktime | 5,349 | 21405 | # -*- coding: utf-8 -*-
"""Cluster plotting tools"""
__author__ = ["<NAME>", "<NAME>"]
__all__ = ["plot_cluster_algorithm"]
import pandas as pd
from sktime.clustering.base._typing import NumpyOrDF
from sktime.clustering.base.base import BaseClusterer
from sktime.clustering.partitioning._lloyds_partitioning import (
... | 3.03125 | 3 |
src/tests/crud/test_user.py | Behnam-sn/neat-backend | 1 | 21406 | from sqlalchemy.orm import Session
from src import crud
from src.core.security import verify_password
from src.schemas.user import UserCreate, UserUpdate
from src.tests.utils.user import create_random_user_by_api
from src.tests.utils.utils import random_lower_string
def test_create_user(db: Session):
username = ... | 2.78125 | 3 |
src/transductor/tests/test_forms.py | fga-gpp-mds/2016.2-Time07 | 0 | 21407 | from django.test import TestCase
from transductor.forms import EnergyForm
from transductor.models import TransductorModel
class EnergyTransductorForm(TestCase):
def setUp(self):
t_model = TransductorModel()
t_model.name = "TR 4020"
t_model.transport_protocol = "UDP"
t_model.serial_... | 2.578125 | 3 |
src/models/base.py | zhengzangw/pytorch-classification | 0 | 21408 | from typing import Any, List, Optional
import hydra
import torch
import torchmetrics
from omegaconf import DictConfig
from pytorch_lightning import LightningModule
from ..optimizer.scheduler import create_scheduler
from ..utils import utils
from ..utils.misc import mixup_data
log = utils.get_logger(__name__)
class... | 2.09375 | 2 |
tea/balance.py | pcubillos/TEA | 25 | 21409 | <filename>tea/balance.py<gh_stars>10-100
#! /usr/bin/env python
############################# BEGIN FRONTMATTER ################################
# #
# TEA - calculates Thermochemical Equilibrium Abundances of chemical species #
# ... | 2.03125 | 2 |
sims/s251/calc-err.py | ammarhakim/ammar-simjournal | 1 | 21410 | from pylab import *
import tables
def exactSol(X, Y, t):
return exp(-2*t)*sin(X)*cos(Y)
fh = tables.openFile("s251-dg-diffuse-2d_q_1.h5")
q = fh.root.StructGridField
nx, ny, nc = q.shape
dx = 2*pi/nx
Xf = linspace(0, 2*pi-dx, nx)
dy = 2*pi/ny
Yf = linspace(0, 2*pi-dy, ny)
XX, YY = meshgrid(Xf, Yf)
Xhr = linspace... | 2.046875 | 2 |
PyCharm/Exercicios/Aula12/ex041.py | fabiodarice/Python | 0 | 21411 | <filename>PyCharm/Exercicios/Aula12/ex041.py<gh_stars>0
# Importação de bibliotecas
from datetime import date
# Título do programa
print('\033[1;34;40mCLASSIFICAÇÃO DE CATEGORIAS PARA NATAÇÃO\033[m')
# Objetos
nascimento = int(input('\033[30mDigite o ano do seu nascimento:\033[m '))
idade = date.today().year - nascim... | 3.484375 | 3 |
github-bot/harvester_github_bot/config.py | futuretea/bot | 0 | 21412 | from everett.component import RequiredConfigMixin, ConfigOptions
from everett.manager import ConfigManager, ConfigOSEnv
class BotConfig(RequiredConfigMixin):
required_config = ConfigOptions()
required_config.add_option('flask_loglevel', parser=str, default='info', doc='Set the log level for Flask.')
requi... | 1.984375 | 2 |
scripts/MCA/1combine.py | jumphone/scRef | 10 | 21413 | import sys
output=sys.argv[1]
input_list=(sys.argv[2:])
EXP={}
header=[]
for input_file in input_list:
fi=open(input_file)
header=header+fi.readline().replace('"','').rstrip().split()
for line in fi:
seq=line.replace('"','').rstrip().split()
if seq[0] in EXP:
EXP[s... | 2.625 | 3 |
apps/portalbase/macros/wiki/graph/1_main.py | jumpscale7/jumpscale_portal | 2 | 21414 | <gh_stars>1-10
def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
tags = params.tags
out = ""
cmdstr = params.macrostr.split(":", 1)[1].replace("}}", "").strip()
md5 = j.base.byteprocessor.hashMd5(cmdstr)
j.system.fs.createDir(j.system.fs.joinPaths(j.core.portal... | 2.15625 | 2 |
pyramda/logic/any_pass.py | sergiors/pyramda | 124 | 21415 | <filename>pyramda/logic/any_pass.py
from pyramda.function.curry import curry
from pyramda.function.always import always
from pyramda.iterable.reduce import reduce
from .either import either
@curry
def any_pass(ps, v):
return reduce(either, always(False), ps)(v)
| 1.703125 | 2 |
bio/scheduler/views.py | ZuluPro/bio-directory | 0 | 21416 | <reponame>ZuluPro/bio-directory
from django.shortcuts import render, get_object_or_404
from django.utils.timezone import now
from schedule.models import Calendar
from schedule.periods import Day
from bio.scheduler import models
def actions(request):
actions = models.Action.objects.order_by('-created_on')
peri... | 1.992188 | 2 |
src/undefined/1/try.py | ytyaru0/Python.Sqlite.framework.think.20180305101210 | 0 | 21417 | try:
import MyTable
except NameError as e:
print(e)
import importlib
importlib.import_module('Constraints')
# 現在 locals() にある module に Constraints.py モジュールを加える。
# (MyTableにConstraintsを加える。`from Constraints import PK,UK,FK,NN,D,C`する)
# トレースバックで例外発生モジュールを補足
import sys, traceback
exc_t... | 2.578125 | 3 |
trac/wiki/tests/admin.py | rjollos/trac | 0 | 21418 | <gh_stars>0
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2020 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://trac.edgewall.org/wiki/TracLicense.
#
# This s... | 1.953125 | 2 |
cli/cli.py | kandrio/toy-chord | 0 | 21419 | import click, requests, sys
bootstrap_ip = '192.168.0.2'
bootstrap_port = '8000'
base_url = 'http://' + bootstrap_ip + ':' + bootstrap_port
@click.group()
def toychord():
"""CLI client for toy-chord."""
pass
@toychord.command()
@click.option('--key', required=True, type=str)
@click.option('--value', requir... | 3.046875 | 3 |
sportstrackeranalyzer/plugin_handler/__init__.py | XeBoris/SportsTrackerAnalyzer | 1 | 21420 | <gh_stars>1-10
from sportstrackeranalyzer.plugins.plugin_simple_distances import Plugin_SimpleDistance | 1.179688 | 1 |
migrations/versions/a12e86de073c_.py | ravenscroftj/harri_gttool | 0 | 21421 | <filename>migrations/versions/a12e86de073c_.py<gh_stars>0
"""Initial creation of schema
Revision ID: a12e86de073c
Revises:
Create Date: 2018-01-05 13:42:18.768932
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a12e86de073c'
down_revision = None
branch_labels... | 1.703125 | 2 |
takedown/__init__.py | zsxing99/Takedown-script | 1 | 21422 | """
TakeDown v0.0.1
===============
author: <NAME>
email: <EMAIL>
This Python project is to help people search on some client hosting contents that potential violate the their copyright.
"""
VERSION = "0.1.0"
DESCRIPTION = "A python script that allows users to search potential copyright violated information on GitHub... | 2.90625 | 3 |
test/test_data.py | xoriath/py-cab | 0 | 21423 |
import os.path
CABEXTRACT_TEST_DIR = os.path.join(os.path.dirname(__file__), 'test-data', 'cabextract', 'cabs')
CABEXTRACT_BUGS_DIR = os.path.join(os.path.dirname(__file__), 'test-data', 'cabextract', 'bugs')
LIBMSPACK_TEST_DIR = os.path.join(os.path.dirname(__file__), 'test-data', 'libmspack')
def read_cabextract_... | 2.609375 | 3 |
utils/exception.py | Lolik-Bolik/Hashing_Algorithms | 2 | 21424 | <gh_stars>1-10
"""
Exceptions module
"""
class CuckooHashMapFullException(Exception):
"""
Exception raised when filter is full.
"""
pass
| 1.6875 | 2 |
finetwork/plotter/_centrality_metrics.py | annakuchko/FinNetwork | 5 | 21425 | import networkx as nx
class _CentralityMetrics:
def __init__(self, G, metrics):
self.G = G
self.metrics = metrics
def _compute_metrics(self):
metrics = self.metrics
if metrics == 'degree_centrality':
c = self.degree_centrality()
elif... | 2.859375 | 3 |
filters/incoming_filters.py | juhokokkala/podoco_juhokokkala | 0 | 21426 | ###############################################################################
# Copyright (C) 2016 <NAME>
# This is part of <NAME>'s PoDoCo project.
#
# This file is licensed under the MIT License.
###############################################################################
"""
Particle filters for tracking the in... | 2.53125 | 3 |
model/semantic_gcn.py | AndersonStra/Mucko | 2 | 21427 | <filename>model/semantic_gcn.py<gh_stars>1-10
import torch
import torch.nn.functional as F
from torch import nn
import dgl
import networkx as nx
class SemanticGCN(nn.Module):
def __init__(self, config, in_dim, out_dim, rel_dim):
super(SemanticGCN, self).__init__()
self.config = config
sel... | 2.28125 | 2 |
negentropy/scriptparser.py | shewitt-au/negentropy | 4 | 21428 | from inspect import cleandoc
from textwrap import indent
from lark import Lark, Transformer
from lark.exceptions import LarkError
from .interval import Interval
from . import errors
def parse(ctx, fname):
with open(fname, "r") as f:
t = f.read()
try:
l = Lark(open(ctx.implfile("s... | 2.4375 | 2 |
Ex25.py | CarlosDouradoPGR/PythonBR-EstruturasDecs | 0 | 21429 | print('Interrogando um suspeito: ')
pg1 = str(input("Telefonou para a vítma?(S/N)\n").upper().strip())
pg2 = str(input('Esteve no local do crime?(S/N)\n').upper().strip())
pg3 = str(input('Mora perto da vítma?(S/N)\n').upper().strip())
pg4 = str(input('Devia para a vítma?(S/N)\n').upper().strip())
pg5 = str(input('Já t... | 3.75 | 4 |
28. Implement strStr()/solution.py | alexwhyy/leetcode | 0 | 21430 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
for i in range(0, len(haystack) - len(needle) + 1):
print(haystack[i : i + len(needle)], needle)
if haystack[i : i + len(needle)] == needle:
return i
... | 3.546875 | 4 |
t/text_test.py | gsnedders/Template-Python | 0 | 21431 | from template import Template
from template.test import TestCase, main
class Stringy:
def __init__(self, text):
self.text = text
def asString(self):
return self.text
__str__ = asString
class TextTest(TestCase):
def testText(self):
tt = (("basic", Template()),
("interp", Template({ "I... | 2.609375 | 3 |
research/destroyer.py | carrino/FrisPy | 0 | 21432 | # Copyright (c) 2021 <NAME>
import math
from pprint import pprint
import matplotlib.pyplot as plt
from frispy import Disc
from frispy import Discs
model = Discs.destroyer
mph_to_mps = 0.44704
v = 70 * mph_to_mps
rot = -v / model.diameter * 1.2
x0 = [6, -3, 25]
a, nose_up, hyzer = x0
disc = Disc(model, {"vx": math.c... | 2.5625 | 3 |
litex/soc/cores/clock/xilinx_common.py | suarezvictor/litex | 1 | 21433 | #
# This file is part of LiteX.
#
# Copyright (c) 2018-2020 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex.build.io import DifferentialInput
from litex.soc.interconnect.csr import *
from litex.soc.cores.clock.common i... | 1.789063 | 2 |
my_des/my_des.py | ipid/my-des | 0 | 21434 | __all__ = (
'des_encrypt',
'des_decrypt',
)
from typing import List, Any
from ._tools import *
from ._constant import *
from rich import print
from rich.text import Text
from rich.panel import Panel
def keygen(key: bytes) -> List[List[int]]:
res = []
key = bytes_to_binlist(key)
key = permute_wit... | 2.421875 | 2 |
Chromebook/setup.py | mahtuag/DistroSetup | 3 | 21435 | <gh_stars>1-10
#!/usr/bin/python3
import subprocess
import apt
import sys
cache = apt.cache.Cache()
cache.update()
cache.open()
packages = [
'git',
'curl',
'wget',
'software-properties-common',
'build-essential',
'automake',
'libtool',
'autoconf',
... | 2.203125 | 2 |
performance_test.py | alan-augustine/python_singly_linkedlist | 0 | 21436 | from time import time
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
from singly_linkedlist.singly_linkedlist import SinglyLinkedList
start = time()
linked_list = SinglyLinkedList()
for i in range(100000):
linked_list.insert_head(111111111111)
end = time()
print("Took {0} sec... | 2.75 | 3 |
python/leetcode/0001.py | bluewaitor/playground | 0 | 21437 | <filename>python/leetcode/0001.py
# 1. 两数之和
from typing import List, Optional
class Solution:
def twoSum(self, nums: List[int], target: int) -> Optional[List[int]]:
index_map = {}
for index, value in enumerate(nums):
index_map[value] = index
for index, value in enumerate(nums):... | 3.515625 | 4 |
dataprocess/print_msg.py | lifelong-robotic-vision/openloris-scene-tools | 13 | 21438 | <reponame>lifelong-robotic-vision/openloris-scene-tools<filename>dataprocess/print_msg.py
#!/usr/bin/env python2
import rosbag
import sys
filename = sys.argv[1]
topics = sys.argv[2:]
with rosbag.Bag(filename) as bag:
for topic, msg, t in bag.read_messages(topics):
print('%s @%.7f --------------------------... | 2.3125 | 2 |
alegra/resources/invoice.py | okchaty/alegra | 1 | 21439 | <filename>alegra/resources/invoice.py<gh_stars>1-10
from alegra.api_requestor import APIRequestor
from alegra.resources.abstract import CreateableAPIResource
from alegra.resources.abstract import EmailableAPIResource
from alegra.resources.abstract import ListableAPIResource
from alegra.resources.abstract import Update... | 2.546875 | 3 |
dask_ml/model_selection.py | lesteve/dask-ml | 1 | 21440 | """Utilities for hyperparameter optimization.
These estimators will operate in parallel. Their scalability depends
on the underlying estimators being used.
"""
from dask_searchcv.model_selection import GridSearchCV, RandomizedSearchCV # noqa
| 1.21875 | 1 |
code/sample_2-1-9.py | KoyanagiHitoshi/AtCoder-Python-Introduction | 1 | 21441 | <filename>code/sample_2-1-9.py
x = 5
y = 6
print(x*y)
| 1.992188 | 2 |
whatrecord/tests/test_stcmd.py | ZLLentz/whatrecord | 2 | 21442 | import pytest
from ..iocsh import IocshRedirect, IocshSplit, split_words
@pytest.mark.parametrize(
"line, expected",
[
pytest.param(
"""dbLoadRecords(a, "b", "c")""",
["dbLoadRecords", "a", "b", "c"],
id="basic_paren"
),
pytest.param(
"... | 2.34375 | 2 |
code/generateElevationFile.py | etcluvic/sme.altm | 0 | 21443 | <gh_stars>0
from bs4 import BeautifulSoup
from datetime import datetime
from lxml import etree
import time
import codecs
import pickle
import os
def printSeparator(character, times):
print(character * times)
if __name__ == '__main__':
doiPrefix = '10.7202' #erudit's doi prefix
myTime = datetime.now().strftim... | 2.8125 | 3 |
MilightWifiBridge/MilightWifiBridge.py | K-Stefan/Milight-Wifi-Bridge-3.0-Python-Library | 0 | 21444 | <filename>MilightWifiBridge/MilightWifiBridge.py<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Milight 3.0 (LimitlessLED Wifi Bridge v6.0) library: Control wireless lights (Milight 3.0) with Wifi
Note that this library was tested with Milight Wifi iBox v1 and RGBW lights. It should work with any ot... | 2.28125 | 2 |
Homework/HW5/Test.py | zhufyaxel/ML_SaltyFish | 0 | 21445 | import os
import numpy as np
import pandas as pd
from Base import Train, Predict
def getTest(boolNormalize, boolDeep, boolBias, strProjectFolder):
if boolNormalize:
if boolDeep:
strOutputPath = "02-Output/" + "Deep" + "Normal"
else:
if boolBias:
strOutputPa... | 2.625 | 3 |
auxilium/__init__.py | sonntagsgesicht/auxilium | 0 | 21446 | <filename>auxilium/__init__.py
# -*- coding: utf-8 -*-
# auxilium
# --------
# Python project for an automated test and deploy toolkit.
#
# Author: sonntagsgesicht
# Version: 0.2.8, copyright Friday, 14 January 2022
# Website: https://github.com/sonntagsgesicht/auxilium
# License: Apache License 2.0 (see LICENSE ... | 1.625 | 2 |
importtime_output_wrapper.py | Victor333Huesca/importtime-output-wrapper | 1 | 21447 | import re
import subprocess
import shutil
import sys
import json
import argparse
from typing import List, NamedTuple, Optional, Sequence
PATTERN_IMPORT_TIME = re.compile(r"^import time:\s+(\d+) \|\s+(\d+) \|(\s+.*)")
class InvalidInput(Exception):
pass
class Import(dict):
def __init__(self, name: str, t_s... | 2.671875 | 3 |
test/unit/test_params.py | davvil/sockeye | 1,117 | 21448 | <reponame>davvil/sockeye<gh_stars>1000+
# Copyright 2017--2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.c... | 1.9375 | 2 |
code/utils/data_preparation.py | cltl/positive-interpretations | 0 | 21449 | import csv
import collections
import pandas as pd
from random import shuffle
from tqdm import tqdm
def get_all_tokens_conll(conll_file):
"""
Reads a CoNLL-2011 file and returns all tokens with their annotations in a dataframe including the original
sentence identifiers from OntoNotes
"""
all_toke... | 3.046875 | 3 |
{{ cookiecutter.project_name }}/setup.py | wlongxiang/cookiecutter-data-science | 0 | 21450 | from setuptools import find_packages, setup
import re
VERSIONFILE = "{{ cookiecutter.project_name }}/__init__.py"
with open(VERSIONFILE, "rt") as versionfle:
verstrline = versionfle.read()
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(version_re, verstrline, re.M)
if mo:
ver_str = mo.group(... | 1.882813 | 2 |
square/api/cards_api.py | codertjay/square-python-sdk | 1 | 21451 | <reponame>codertjay/square-python-sdk
# -*- coding: utf-8 -*-
from square.api_helper import APIHelper
from square.http.api_response import ApiResponse
from square.api.base_api import BaseApi
class CardsApi(BaseApi):
"""A Controller to access Endpoints in the square API."""
def __init__(self, config, auth_ma... | 2.828125 | 3 |
setup.py | nilp0inter/threadedprocess | 9 | 21452 | import os
from setuptools import setup
try:
import concurrent.futures
except ImportError:
CONCURRENT_FUTURES_PRESENT = False
else:
CONCURRENT_FUTURES_PRESENT = True
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="threadedprocess",
version="0.... | 2.078125 | 2 |
coremltools/converters/mil/mil/passes/const_elimination.py | VadimLevin/coremltools | 3 | 21453 | # -*- coding: utf-8 -*-
# Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import numpy as np
from coremltools.converters.mil.mil import Builder as mb... | 1.796875 | 2 |
matching/retrieval.py | Macielyoung/sentence_representation_matching | 22 | 21454 | from simcse import SimCSE
from esimcse import ESimCSE
from promptbert import PromptBERT
from sbert import SBERT
from cosent import CoSent
from config import Params
from log import logger
import torch
from transformers import AutoTokenizer
class SimCSERetrieval(object):
def __init__(self, pretrained_model_path, si... | 2.21875 | 2 |
Backend/src/awattprice/notifications.py | a8/AWattPrice | 0 | 21455 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Check which users apply to receive certain notifications.
Send notifications via APNs to those users.
"""
import asyncio
import json
from datetime import datetime
from math import floor
from pathlib import Path
from typing import List, Optional, Tuple
import arrow # type: ... | 2.609375 | 3 |
examples/charts/horizon.py | timelyportfolio/bokeh | 1 | 21456 | from collections import OrderedDict
import pandas as pd
from bokeh.charts import Horizon, output_file, show
# read in some stock data from the Yahoo Finance API
AAPL = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2010",
parse_dates=['Date'])
MSFT = pd.read_csv(
"http://... | 3.015625 | 3 |
backend.py | CameronStollery/road-trip-planner | 1 | 21457 | # from __future__ import print_function
import pymzn
import time
from pprint import pprint
from collections import OrderedDict
import openrouteservice
from openrouteservice.geocode import pelias_search
from openrouteservice.distance_matrix import distance_matrix
client = openrouteservice.Client(key='')
# routes = cli... | 2.4375 | 2 |
examples/python/django/load-generator.py | ScriptBox99/pyroscope | 5,751 | 21458 | import random
import requests
import time
HOSTS = [
'us-east-1',
'us-west-1',
'eu-west-1',
]
VEHICLES = [
'bike',
'scooter',
'car',
]
if __name__ == "__main__":
print(f"starting load generator")
time.sleep(15)
print('done sleeping')
while True:
host = HOSTS[random.rand... | 2.78125 | 3 |
python/Multi-Service/content_moderator_cs.py | kyichii/cognitive-services-quickstart-code | 2 | 21459 | <filename>python/Multi-Service/content_moderator_cs.py
import os
from pprint import pprint
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.contentmoderator import ContentModeratorClient
from azure.cognitiveservices.vision.contentmoderator.models import ( Evaluate, OCR... | 2.4375 | 2 |
usda_nutrition/admin.py | danielnaab/django-usda-nutrition | 11 | 21460 | from django.contrib import admin
from . import models
class ReadOnlyAdminMixin():
def get_readonly_fields(self, request, obj=None):
return list(set(
[field.name for field in self.opts.local_fields] +
[field.name for field in self.opts.local_many_to_many]
))
class ReadOnl... | 1.976563 | 2 |
FisherExactTest/FisherExactTest.py | Ae-Mc/Fisher | 0 | 21461 | from decimal import Decimal
def Binominal(n: int, k: int) -> int:
if k > n:
return 0
result = 1
if k > n - k:
k = n - k
i = 1
while i <= k:
result *= n
result //= i
n -= 1
i += 1
return result
def pvalue(a: int, b: int,
c: int, d: in... | 3.8125 | 4 |
Signature Detection and Analysis/signprocessing.py | andrevks/Document-Forgery-Detection | 0 | 21462 | <filename>Signature Detection and Analysis/signprocessing.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 31 04:01:49 2018
@author: abhilasha
"""
#Team: GuardiansOfGalaxy
from PIL import Image, ImageEnhance
def enhance_signature(img):
bw = ImageEnhance.Color(img).enhance(0.0)
bright = Im... | 3 | 3 |
crowdsource/views.py | Code-and-Response/ISAC-SIMO-Repo-2 | 5 | 21463 | <filename>crowdsource/views.py
from main.customdecorators import check_honeypot_conditional
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.http.response import HttpResponseRedirect, JsonResponse
from rest_framework.decorators import action
from api.models import ObjectType
from django.core.... | 1.851563 | 2 |
epochCiCdApi/ita/viewsOperations.py | matsumoto-epoch/epoch | 0 | 21464 | # Copyright 2019 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | 1.820313 | 2 |
tests/test_init.py | keisuke-umezawa/chutil | 1 | 21465 | <reponame>keisuke-umezawa/chutil
import chutil as module
def test_versions():
pass
| 0.992188 | 1 |
src/service/uri_generator.py | HalbardHobby/git-LFS-for-Lambda | 0 | 21466 | <filename>src/service/uri_generator.py
"""Generates pre-signed uri's for blob handling."""
from boto3 import client
import os
s3_client = client('s3')
def create_uri(repo_name, resource_oid, upload=False, expires_in=300):
"""Create a download uri for the given oid and repo."""
action = 'get_object'
if u... | 2.671875 | 3 |
rnn/chatbot/chatbot.py | llichengtong/yx4 | 128 | 21467 | # coding=utf8
import logging
import os
import random
import re
import numpy as np
import tensorflow as tf
from seq2seq_conversation_model import seq2seq_model
from seq2seq_conversation_model import data_utils
from seq2seq_conversation_model import tokenizer
from seq2seq_conversation_model.seq2seq_conversation_model imp... | 2.390625 | 2 |
chip8_pygame_integration/config_test.py | Artoooooor/chip8 | 0 | 21468 | import unittest
import pygame
from chip8_pygame_integration.config import get_config, KeyBind, to_text
DEFAULT = [KeyBind(pygame.K_o, pygame.KMOD_CTRL, 'some_command')]
class ConfigLoadTest(unittest.TestCase):
def setUp(self):
self.default = None
def test_empty_pattern_returns_empty_array(self):
... | 2.734375 | 3 |
Trees/Binary Trees/Preorder_Binary_Tree.py | jarvis-1805/DSAwithPYTHON | 1 | 21469 | '''
Preorder Binary Tree
For a given Binary Tree of integers, print the pre-order traversal.
Input Format:
The first and the only line of input will contain the nodes data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of t... | 3.84375 | 4 |
test/pages/base_pages.py | gordonnguyen/10fastfingers-auto-type | 0 | 21470 | <filename>test/pages/base_pages.py
'''
Super classes for Page object
Serve as a base template for page
automating functions with selenium
'''
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from utils.best_buy.locators import Locator... | 3.015625 | 3 |
Form-Filler.py | Zaidtech/AUTOMATION-SCRIPTS | 4 | 21471 | #!/usr/bin/env python3
"""
This script has been tested on various custom google forms and other various forms with
few alteratios ..
Google forms which does include the input type "token" attribute are found
to be safer than those who don't.
Any form contains various fields.
1. input text fields
2. radio
3. checkb... | 2.984375 | 3 |
lektor_root_relative_path.py | a2csuga/lektor-root-relative-path | 2 | 21472 | <reponame>a2csuga/lektor-root-relative-path<gh_stars>1-10
# -*- coding: utf-8 -*-
try:
# py3
from urllib.parse import urljoin, quote
except ImportError:
# py2
from urlparse import urljoin
from urllib import quote
from lektor.pluginsystem import Plugin
from furl import furl
class RootRelativePath... | 2.203125 | 2 |
controllers/main.py | dduarte-odoogap/odoo_jenkins | 5 | 21473 | # -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
import jenkins
class JenkinsController(http.Controller):
@http.route('/web/jenkins/jobs', type='json', auth='user')
def jenkins_get_jobs(self, **kw):
params = request.env['ir.config_parameter']
jenkins_url = params.... | 2.375 | 2 |
attendance.py | mykbgwl/Students-Attendance | 0 | 21474 | <reponame>mykbgwl/Students-Attendance
import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar
import sys
import time
import pybase64
# Starting the webcam
capt = cv2.VideoCapture(0)
names = []
# Creating Attendees file
fob = open('attendees.txt', 'a+')
def enterData(z):
if z in names:... | 3.015625 | 3 |
net.py | rishabnayak/SegAN | 0 | 21475 | <filename>net.py
import torch.nn as nn
import torch.nn.functional as F
import torch
from numpy.random import normal
from math import sqrt
import argparse
channel_dim = 3
ndf = 64
class GlobalConvBlock(nn.Module):
def __init__(self, in_dim, out_dim, kernel_size):
super(GlobalConvBlock, self).__init__()
... | 2.390625 | 2 |
karmagrambot/__init__.py | caiopo/karmagrambot | 0 | 21476 | import dataset
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from .config import TOKEN, DB_URI
from .commands import HANDLERS
logging.basicConfig()
def save_message(message, db):
replied = None
if message.reply_to_message is not None:
replied = message.rep... | 2.28125 | 2 |
app/services/articles.py | StanislavRud/api-realword-app-test | 1,875 | 21477 | <filename>app/services/articles.py<gh_stars>1000+
from slugify import slugify
from app.db.errors import EntityDoesNotExist
from app.db.repositories.articles import ArticlesRepository
from app.models.domain.articles import Article
from app.models.domain.users import User
async def check_article_exists(articles_repo: ... | 2.28125 | 2 |
tests/test_decoder.py | carlosmouracorreia/python_mp3_decoder | 23 | 21478 | from pymp3decoder import Decoder
import contextlib
import os
import math
import pyaudio
CHUNK_SIZE = 4096
def take_chunk(content):
""" Split a buffer of data into chunks """
num_blocks = int(math.ceil(1.0*len(content)/CHUNK_SIZE))
for start in range(num_blocks):
yield content[CHUNK_SIZE*start:... | 3.03125 | 3 |
bot.py | Euphorichuman/StarConstellationBot-TelgramBot- | 0 | 21479 | import telegram.ext
import messsages as msg
import functions as f
import matplotlib.pyplot as plt
import traceback
import os
import os.path
from os import path
def start(update, context):
nombre = update.message.chat.first_name
mensaje = "Bienvenido {}, para conocer lo que puedo hacer utiliza el comando /Help... | 2.5 | 2 |
tests/unit/states/test_slack.py | amaclean199/salt | 12 | 21480 | <filename>tests/unit/states/test_slack.py
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`<NAME> <<EMAIL>>`
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit im... | 2.265625 | 2 |
lintcode/499.py | jianershi/algorithm | 1 | 21481 | <gh_stars>1-10
"""
499. Word Count (Map Reduce)
https://www.lintcode.com/problem/word-count-map-reduce/description
"""
class WordCount:
# @param {str} line a text, for example "Bye Bye see you next"
def mapper(self, _, line):
# Write your code here
# Please use 'yield key, value'
word_l... | 2.953125 | 3 |
dataframe/statistic.py | kuangtu/pandas_exec | 0 | 21482 | # -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
def countnum():
dates = pd.date_range(start="2019-01-01", end="2019-05-31", freq='M')
# print(dates)
# print(dates[0])
# print(type(dates[0]))
col1 = [i for i in range(1, len(dates) + 1)]
# print(col1)
col2 = [i + 1 for i in ra... | 3.078125 | 3 |
asv/results.py | pitrou/asv | 0 | 21483 | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import base64
import os
import zlib
from .environment import get_environment
from . import util
def iter_results_paths... | 2.390625 | 2 |
core/secretfinder/utils.py | MakoSec/pacu | 26 | 21484 | <gh_stars>10-100
import math
import json
import re
import os
class Color:
GREEN = '\033[92m'
BLUE = '\033[94m'
RED = '\033[91m'
# noinspection SpellCheckingInspection
ENDC = '\033[0m'
@staticmethod
def print(color, text):
print('{}{}{}'.format(color, text, Color.ENDC))
def shanno... | 2.859375 | 3 |
validation/step_03_-_predict_state/step_03_-_plot_results.py | martin0004/drone_perception_system | 1 | 21485 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from typing import Tuple
def clean_df_headers(df: pd.DataFrame) -> pd.DataFrame:
"""Remove leading and trailing spaces in DataFrame headers."""
headers = pd.Series(df.columns)
new_headers = [header.strip() for header in headers]
... | 3.140625 | 3 |
lvsr/dependency/datasets.py | mzapotoczny/dependency-parser | 3 | 21486 | <reponame>mzapotoczny/dependency-parser
'''
Created on Mar 20, 2016
'''
import numpy
import numbers
from fuel.datasets.hdf5 import H5PYDataset
from fuel.utils import Subset
class VMap(object):
def __init__(self, vmap_dset):
dtype = vmap_dset.dtype
dtype_unicode = [('key', 'U%d' % (dtype[0].itemsiz... | 1.710938 | 2 |
setup.py | LandRegistry/govuk-frontend-wtf | 10 | 21487 | <filename>setup.py
import glob
import os
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
templates = []
directories = glob.glob("govuk_frontend_wtf/templates/*.html")
for directory in directories:
templates.append(os.path.relpath(os.path.dirname(directory), "govuk_frontend_w... | 1.671875 | 2 |
project/experiments/exp_003_best_Walker2D/src/4.plot_1.py | liusida/thesis-bodies | 0 | 21488 | import os
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from common.tflogs2pandas import tflog2pandas, many_logs2pandas
from common.gym_interface import template
bodies = [300]
all_seeds = list(range(20))
all_stackframe = [0,4]
cache_filename = "output_data/tmp/plot0"
try:
df = pd.rea... | 2.171875 | 2 |
wsgi.py | emilan21/macvert | 0 | 21489 | <reponame>emilan21/macvert
#!/usr/bin/python
# mac_convertor.py - Converts mac address from various formats to other formats
from macvert.web import app
if __name__ == '__main__':
app.run()
| 2.078125 | 2 |
config/dotenv.py | CharuchithRanjit/open-pos | 0 | 21490 | """
Loads dotenv variables
Classes:
None
Functions:
None
Misc variables:
DATABASE_KEY (str) -- The key for the database
DATABASE_PASSWORD (str) -- The password for the database
DATABASE_URL (str) -- The url for the database
"""
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
DATABA... | 2.734375 | 3 |
617. Merge Two Binary Trees/solution1.py | zhoudaxia233/LeetCode | 3 | 21491 | <reponame>zhoudaxia233/LeetCode
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
# This method changes the existing tree instead of returning a new one
if t1 and t2:
t1.val += t2.val
... | 4.03125 | 4 |
tests/zero_model_test.py | shatadru99/archai | 1 | 21492 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
from archai.nas.model import Model
from archai.nas.macro_builder import MacroBuilder
from archai.common.common import common_init
def test_darts_zero_model():
conf = common_init(config_filepath='confs/algos/darts.yaml')... | 2 | 2 |
reports/dataset.py | TexasDigitalLibrary/dataverse-reports | 5 | 21493 | import logging
import datetime
class DatasetReports(object):
def __init__(self, dataverse_api=None, dataverse_database=None, config=None):
if dataverse_api is None:
print('Dataverse API required to create dataset reports.')
return
if dataverse_database is None:
p... | 2.640625 | 3 |
classifier.py | hemu243/focus-web-crawler | 2 | 21494 | <reponame>hemu243/focus-web-crawler
#
from abc import ABCMeta
import metapy
class WebClassifier(object):
"""
This module is abstract module which needs to be called by
inherit
"""
__metaclass__ = ABCMeta
def __init__(self, configFile):
"""
Initialized basic of classifier like fwd index, index
:param con... | 2.765625 | 3 |
backend/tests/access/test_access_event_publish.py | fjacob21/mididecweb | 0 | 21495 | <reponame>fjacob21/mididecweb
from src.access import EventPublishAccess
from generate_access_data import generate_access_data
def test_publish_event_access():
sessions = generate_access_data()
event = sessions['user'].events.get('test')
useraccess = EventPublishAccess(sessions['user'], event)
managera... | 1.984375 | 2 |
aiorabbitmq_admin/base.py | miili/aiorabbitmq-admin | 0 | 21496 | import json
import aiohttp
from copy import deepcopy
class Resource(object):
"""
A base class for API resources
"""
# """List of allowed methods, allowed values are
# ```['GET', 'PUT', 'POST', 'DELETE']``"""
# ALLOWED_METHODS = []
def __init__(self, url, auth):
"""
:param... | 2.96875 | 3 |
from_3b1b/old/highD.py | tigerking/manim2 | 0 | 21497 | <reponame>tigerking/manim2
from manim2.imports import *
##########
#force_skipping
#revert_to_original_skipping_status
##########
class Slider(NumberLine):
CONFIG = {
"color" : WHITE,
"x_min" : -1,
"x_max" : 1,
"unit_size" : 2,
"center_value" : 0,
"number_scale_val... | 2.25 | 2 |
start_palpeo.py | RealDebian/Palpeo | 0 | 21498 | from link_extractor import run_enumeration
from colorama import Fore
from utils.headers import HEADERS
from time import sleep
import requests
import database
import re
import json
from bs4 import BeautifulSoup
import colorama
print(Fore.GREEN + '-----------------------------------' + Fore.RESET, Fore.RED)
print('尸闩㇄尸㠪... | 2.75 | 3 |
tests/test_scores_das_01.py | wavestoweather/enstools | 5 | 21499 | <reponame>wavestoweather/enstools
import xarray
import numpy
from enstools.scores import DisplacementAmplitudeScore
def test_embed_image():
"""
test of embed_image from match_pyramide_ic
"""
# create test image
test_im = xarray.DataArray(numpy.random.randn(5, 3))
# new array should have shape... | 2.71875 | 3 |