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 |
|---|---|---|---|---|---|---|
gpypi/__init__.py | tastuteche/g-pypi-py3 | 1 | 12798951 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pkg_resources
__version__ = pkg_resources.get_distribution('g-pypi').version.replace('dev', '')
| 1.382813 | 1 |
Codes/optimization/src/preprocess/calibration.py | dychen24/magx | 7 | 12798952 | <reponame>dychen24/magx
import numpy as np
from .data_reader import read_data
def calibrate(path):
data = read_data(path)
# cut = int(data.shape[0]/10)
# data = data[cut: -cut]
nsensor = int(data.shape[1] / 3)
offX = np.zeros(nsensor)
offY = np.zeros(nsensor)
offZ = np.zeros(nsensor)
s... | 2.34375 | 2 |
my_test/calc.py | irux/test-bump | 0 | 12798953 | def summcalc(a,b):
return a+b | 1.601563 | 2 |
setup.py | PontusHultkrantz/tcapy | 0 | 12798954 | <filename>setup.py
from setuptools import setup, find_packages
long_description = """tcapy is a transaction cost analysis library for determining calculating your trading costs"""
setup(name='tcapy',
version='0.1.0',
description='Tranasction cost analysis library',
author='<NAME>',
author_emai... | 1.398438 | 1 |
gitScrabber/scrabTasks/report/easeOfUseEstimation.py | Eyenseo/gitScrabber | 0 | 12798955 | <reponame>Eyenseo/gitScrabber<filename>gitScrabber/scrabTasks/report/easeOfUseEstimation.py
"""
The MIT License (MIT)
Copyright (c) 2017 <NAME>
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 wit... | 1.5625 | 2 |
neuro_evolutional_net/genetic_algorithm.py | DominikSpiljak/Fuzzy-Evolutionary-and-Neuro-computing | 0 | 12798956 | from individual import Individual
class GeneticAlgorithm:
def __init__(self, population_generation, num_iter, selection, combination, mutation, solution, goal_error):
self.population_generation = population_generation
self.num_iter = num_iter
self.selection = selection
self.combin... | 3.171875 | 3 |
pyanimate/__init__.py | martinmcbride/sympl | 0 | 12798957 | name = "pyanimate"
| 1.0625 | 1 |
server/app/api/lib/notify.py | Lazarus118/virtual-queue | 0 | 12798958 | import twilio
import twilio.rest
class Notify(object):
def __init__(self, account_sid, auth_token, phone_number):
self.account_sid = account_sid
self.auth_token = auth_token
self.phone_number = phone_number
def _request(self, to_number, message):
try:
client = twil... | 2.53125 | 3 |
custom_components/fritzbox_tools/binary_sensor.py | jloehr/ha-fritzbox-tools | 0 | 12798959 | <reponame>jloehr/ha-fritzbox-tools
"""AVM Fritz!Box connectivitiy sensor"""
import logging
from collections import defaultdict
import datetime
try:
from homeassistant.components.binary_sensor import ENTITY_ID_FORMAT, BinarySensorEntity
except ImportError:
from homeassistant.components.binary_sensor import ENTI... | 2.046875 | 2 |
solutions/python3/667.py | sm2774us/amazon_interview_prep_2021 | 42 | 12798960 | class Solution:
def constructArray(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
left, right, res = 0, n+1, [None]*n
for i in range(n):
if k == 1:
if i%2 == 0:
while i<n: res[i], right, i = rig... | 2.96875 | 3 |
mozi/layers/normalization.py | hycis/Mozi | 122 | 12798961 | <gh_stars>100-1000
from mozi.layers.template import Template
from mozi.utils.theano_utils import shared_zeros, sharedX, shared_ones
from mozi.weight_init import UniformWeight
import theano.tensor as T
import theano
class BatchNormalization(Template):
def __init__(self, dim, layer_type, gamma_init=UniformWeight()... | 2.6875 | 3 |
task1/learning.py | EgorOrachyov/MachineLearning | 0 | 12798962 | from csv import reader
from sklearn import preprocessing
from plotly import graph_objects
def import_data(path):
return [[float(f) for f in r] for r in reader(open(path, "r"))]
def normalize_data(dataset):
scaler = preprocessing.MinMaxScaler(feature_range=(0,1))
normalized = scaler.fit_transform(dataset... | 2.90625 | 3 |
Week 02/summationerror_BSW.py | bswood9321/PHYS-3210 | 0 | 12798963 | <reponame>bswood9321/PHYS-3210
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import matplotlib.pyplot as plt
N = int(input("Pick a number: "))
n, a, sum1, m, b, sum2 = 1, 0, 0, N, 0, 0
while (n<=N):
a = 1/n
sum1+=a
n = n+1
while (m>=1):
b =... | 3.453125 | 3 |
imix/models/vqa_models/lxmert/lxmert_task.py | linxi1158/iMIX | 0 | 12798964 | <gh_stars>0
from imix.models.builder import VQA_MODELS
import torch
import copy
'''
from transformers.modeling_bert import (
BertConfig,
BertEmbeddings,
BertEncoder,
# BertLayerNorm,
BertPreTrainedModel,
)
'''
from .lxmert import LXMERTForPretraining
from imix.models.vqa_models.base_model import Bas... | 2.171875 | 2 |
srun.py | qaqcxh/lectureHack | 0 | 12798965 | #!/bin/python3
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
import sys,os
options = webdriver.ChromeOptio... | 2.609375 | 3 |
users/migrations/0005_auto_20190911_2212.py | nhy17-thu/ImageProcessingWebsite | 1 | 12798966 | # Generated by Django 2.2.4 on 2019-09-11 14:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20190907_1334'),
]
operations = [
migrations.AddField(
model_name='pic',
name='classification152'... | 1.515625 | 2 |
project_2/scripts/graph.py | jsbruglie/adrc | 0 | 12798967 | <gh_stars>0
import prio_dict
class Graph:
def __init__(self):
self.vertices = {}
def __str__(self):
return str([key for key in self.vertices.keys()])
def __iter__(self):
return iter(self.vertices.values())
def add_vertex(self, node):
self.vertices[node] = {}
def... | 3.015625 | 3 |
algorithms/289. Game of Life.py | woozway/py3-leetcode | 1 | 12798968 | <reponame>woozway/py3-leetcode<gh_stars>1-10
"""
1. Clarification
2. Possible solutions
- Simulation v1
- Simulation optimised v2
3. Coding
4. Tests
"""
# T=O(m*n), S=O(m*n)
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
neighbors = [(1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (... | 3.1875 | 3 |
src/dbxdeploy/package/PackageDependencyLoader.py | Kukuksumusu/dbx-deploy | 2 | 12798969 | <reponame>Kukuksumusu/dbx-deploy
import tomlkit
from tomlkit.items import Table
from typing import List
from pathlib import Path
from dbxdeploy.package.Dependency import Dependency
from dbxdeploy.package.RequirementsLineConverter import RequirementsLineConverter
from dbxdeploy.package.RequirementsGenerator import Requi... | 1.945313 | 2 |
open_spiel/python/mfg/algorithms/EGTA/egta.py | wyz2368/open_spiel | 0 | 12798970 | # Copyright 2019 DeepMind Technologies Ltd. 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 appl... | 2.3125 | 2 |
OpenGLCffi/GLX/EXT/SGI/swap_control.py | cydenix/OpenGLCffi | 0 | 12798971 | <reponame>cydenix/OpenGLCffi<filename>OpenGLCffi/GLX/EXT/SGI/swap_control.py
from OpenGLCffi.GLX import params
@params(api='glx', prms=['interval'])
def glXSwapIntervalSGI(interval):
pass
| 1.609375 | 2 |
snsim/io_utils.py | bcarreres/snsim | 5 | 12798972 | <reponame>bcarreres/snsim
"""This module contains io stuff."""
import os
import warnings
import pickle
import pandas as pd
import numpy as np
try:
import json
import pyarrow as pa
import pyarrow.parquet as pq
json_pyarrow = True
except ImportError:
json_pyarrow = False
from . import salt_utils as s... | 2.15625 | 2 |
submission_json.py | selva604/DA_TBN | 1 | 12798973 | <filename>submission_json.py
import json
from pathlib import Path
import numpy as np
import pandas as pd
from epic_kitchens.meta import training_labels, test_timestamps
def softmax(x):
'''
>>> res = softmax(np.array([0, 200, 10]))
>>> np.sum(res)
1.0
>>> np.all(np.abs(res - np.array([0, 1, 0])) <... | 2.484375 | 2 |
AWS_Services/showPlacementCompany.py | demirkirans/PlaDat-BLG411E | 0 | 12798974 | <gh_stars>0
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key,Attr
from botocore.exceptions import ClientError
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
# wanted a simple yield str(o) in the next ... | 2.203125 | 2 |
BackEnd/FaceDetector/FaceExt.py | RickyYXY/The-Mask | 2 | 12798975 | # encoding:utf-8
import os, sys
basepath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(basepath, 'FaceDetector'))
import requests
import base64
import cv2
import numpy as np
import urllib.request
import base64
def fetchImageFromHttp(image_url, timeout_s=1):
# 该函数是读取url... | 2.578125 | 3 |
courses/bxx-python/b01/s08-compound-interest.py | vinaynk/nooromtech_tutorials | 0 | 12798976 | #
# compound interest
#
# P - principal
# r - annual rate (%)
# n - compounding frequency
# y - number of years
#
# Py = P0 (1 + r/n) ** (ny)
#
P = 1000
r = 2.5 # %
n = 4 # quarterly
y = 5
amount = P
print('Amount (Starting):', amount)
for year in range(1, y+1):
for period in range(1, n+1):
amount *= (... | 3.53125 | 4 |
ecomstore/caching.py | Pythonian/ecomstore | 0 | 12798977 | <filename>ecomstore/caching.py
from django.core.cache import cache
from .settings import CACHE_TIMEOUT
def cache_update(sender, **kwargs):
""" signal for updating a model instance in the cache;
any Model class using this signal must
have a uniquely identifying 'cache_key' property.
"""
item = kw... | 2.359375 | 2 |
openmaptiles/pgutils.py | ldgeo/openmaptiles-tools | 0 | 12798978 | <reponame>ldgeo/openmaptiles-tools<filename>openmaptiles/pgutils.py
import re
from typing import Tuple, Dict
from asyncpg import UndefinedFunctionError, UndefinedObjectError, Connection
from openmaptiles.perfutils import COLOR
async def show_settings(conn: Connection) -> Tuple[Dict[str, str], bool]:
postgis_ver... | 1.96875 | 2 |
bluesky_widgets/models/_tests/test_image.py | bsobhani/bluesky-widgets | 0 | 12798979 | <gh_stars>0
from bluesky_live.run_builder import build_simple_run
import numpy
from ..plot_builders import Images
from ..plot_specs import AxesSpec, FigureSpec
from ...headless.figures import HeadlessFigure
def test_image():
"Test Images with a 2D array."
run = build_simple_run({"ccd": numpy.random.random((1... | 2.234375 | 2 |
hw3/Fast_Map.py | tian-yu/INF552 | 0 | 12798980 | #
# INF 552 Homework 3
# Part 2: Fast Map
# Group Members: <NAME> (zhan198), <NAME> (minyihua), <NAME> (jeffyjac)
# Date: 2/27/2018
# Programming Language: Python 3.6
#
import numpy as np
import matplotlib.pyplot as plt
DIMENSION = 2
DATA_SIZE = 10
# WORDS = ["acting", "activist", "compute", "coward","forward","in... | 3.40625 | 3 |
waves/WAVtoMIF.py | willzhang05/fpga-synthesizer | 3 | 12798981 | <filename>waves/WAVtoMIF.py<gh_stars>1-10
#!/usr/bin/python
import wave, sys
if len(sys.argv) < 2:
print("Missing args.")
print("Expected: input")
waveReader = wave.open(sys.argv[1], 'rb')
depth = waveReader.getnframes()
width = 16 # wav is 16 bits
radix = "HEX" # address and data in hex
print("DEPTH =", st... | 3.125 | 3 |
algorithms/python/leetcode/UniquePaths.py | ytjia/coding-pratice | 0 | 12798982 | <filename>algorithms/python/leetcode/UniquePaths.py
# -*- coding: utf-8 -*-
# Authors: <NAME> <<EMAIL>>
"""
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach
the bottom-right... | 3.84375 | 4 |
datascience/sympy/evaluating2.py | janbodnar/Python-Course | 13 | 12798983 | <reponame>janbodnar/Python-Course
#!/usr/bin/python
import numpy
from sympy import Symbol, lambdify, sin, pprint
a = numpy.arange(10)
x = Symbol('x')
expr = sin(x)
f = lambdify(x, expr, "numpy")
pprint(f(a))
| 3.09375 | 3 |
app/backend-test/core_datasets/run05_test_directory_size_calculation.py | SummaLabs/DLS | 32 | 12798984 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import os
import glob
from app.backend.core.utils import getDirectorySizeInBytes, humanReadableSize
if __name__ == '__main__':
path='../../../data/datasets'
for ii,pp in enumerate(glob.glob('%s/*' % path)):
tbn=os.path.basename(pp)
ts... | 2.34375 | 2 |
tests/cli/_trivial.py | pcarranzav2/pyuavcan | 0 | 12798985 | #
# Copyright (c) 2019 UAVCAN Development Team
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
#
import pytest
import subprocess
from ._subprocess import run_cli_tool
def _unittest_trivial() -> None:
run_cli_tool('show-transport', timeout=2.0)
with pytest.raises... | 1.867188 | 2 |
insomnia/agents/d4pg_learner.py | takeru1205/Insomnia | 0 | 12798986 | import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import queue
from insomnia.utils import empty_torch_queue
from insomnia.explores.gaussian_noise import GaussianActionNoise
from insomnia.numeric_models import d4pg
from insomnia.numeric_models.misc import l2_projection
cla... | 2.0625 | 2 |
OPCDataTransfer/OPC/OPC.py | Shanginre/OPCDataTransfer | 1 | 12798987 | <reponame>Shanginre/OPCDataTransfer<filename>OPCDataTransfer/OPC/OPC.py
#!/usr/bin/env python3.6
# -*- coding: UTF-8 -*-
import OpenOPC
import pywintypes
import datetime
from builtins import print
import json
import copy
import logging
import os
class ConnectionOPC:
def __init__(self, conf_settings):
se... | 2.09375 | 2 |
test/test_si7021.py | arkjedrz/si7021 | 0 | 12798988 | <gh_stars>0
import unittest
import si7021
class Si7021SensorTests(unittest.TestCase):
def setUp(self):
# TODO: checks for Windows, but should check for embedded platform
import os
if os.name == 'Windows':
raise OSError
self._sensor = si7021.Si7021Sensor()
def _... | 3.09375 | 3 |
dlcli/api/user.py | outlyerapp/dlcli | 1 | 12798989 | import logging
from wrapper import *
logger = logging.getLogger(__name__)
# noinspection PyUnusedLocal
def get_user(url='', key='', timeout=60, **kwargs):
return get(url + '/user', headers={'Authorization': "Bearer " + key}, timeout=timeout).json()
# noinspection PyUnusedLocal
def get_user_tokens(url='', key='... | 2.484375 | 2 |
galaxy/objectstore/lwr.py | jmchilton/lwr | 1 | 12798990 | from __future__ import absolute_import # Need to import lwr_client absolutely.
from ..objectstore import ObjectStore
try:
from galaxy.jobs.runners.lwr_client.manager import ObjectStoreClientManager
except ImportError:
from lwr.lwr_client.manager import ObjectStoreClientManager
class LwrObjectStore(ObjectStor... | 2.359375 | 2 |
Algorithm/String/242. Valid Anagram.py | smsubham/Data-Structure-Algorithms-Questions | 0 | 12798991 | #https://leetcode.com/problems/valid-anagram/
#https://leetcode.com/problems/valid-anagram/discuss/66499/Python-solutions-(sort-and-dictionary).
def isAnagram1(self, s, t):
dic1, dic2 = {}, {}
for item in s:
dic1[item] = dic1.get(item, 0) + 1
for item in t:
dic2[item] = dic2.get(item, 0) + ... | 3.90625 | 4 |
pyshtools/constant/Mars.py | dilkins/SHTOOLS | 1 | 12798992 | <filename>pyshtools/constant/Mars.py
"""
pyshtools constants for the planet Mars.
Each object is an astropy Constant that possesses the attributes name, value,
unit, uncertainty, and reference.
"""
from __future__ import absolute_import as _absolute_import
from __future__ import division as _division
from __future__ ... | 2.40625 | 2 |
hard-gists/3791168/snippet.py | jjhenkel/dockerizeme | 21 | 12798993 | """
Demo of json_required decorator for API input validation/error handling
"""
import inspect
import functools
import json
from traceback import format_exception
from flask import jsonify, request
import sys
from flask.exceptions import JSONBadRequest
from flask import Flask
import re
app = Flask(__name__)
def... | 3.453125 | 3 |
ACME/render/camera_extrinsics.py | mauriziokovacic/ACME | 3 | 12798994 | import torch
from ..math.cross import *
from ..math.normvec import *
class CameraExtrinsic(object):
"""
A class representing the camera extrinsic properties
Attributes
----------
position : Tensor
the camera position
target : Tensor
the camera target
up_vector : Tensor
... | 3.125 | 3 |
jupyter_d3/scatter_plot.py | nicolemoiseyev/jupyter-d3 | 1 | 12798995 | import uuid
from textwrap import dedent
from IPython.core.display import display, HTML
from string import Template
import numpy as np
# function to initialize a scatter plot
def init_chart(data,features):
chart_id = 'mychart-' + str(uuid.uuid4())
feature_types = {} # map each feature to type
num_feature_ra... | 2.59375 | 3 |
methods/methods.py | ZhangShuang92/csslab | 7 | 12798996 | # -*- coding:utf-8 -*-
'''
目的:提供一些文件操作 和 数据处理的方法
方法:
# 功能 # - # 方法 #
* 读取文件较大的csv - read_csv
* 获取当前目录下所有子目录 - get_subdirs
* 获取当前目录下所有该类型的文件名 - get_files
* 获取当前目录和所有子目录下所有该类型的文件名 - get_files_all
* ... | 2.765625 | 3 |
yardstick/benchmark/scenarios/lib/create_image.py | upfront710/yardstick | 28 | 12798997 | ##############################################################################
# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, ... | 1.859375 | 2 |
tests/blueprints/test_network.py | tssujt/remote | 67 | 12798998 | <reponame>tssujt/remote
from unittest.mock import patch
import pyipip
from dns.exception import DNSException
from remote.blueprints.network import IPRecord
from tests.test_app import TestBase
class TestNetwork(TestBase):
_test_domain = "example.com"
_test_ip = "127.0.0.1"
def test_ip(self):
res... | 2.546875 | 3 |
api/Mongo/abc_dbops.py | AutoCoinDCF/NEW_API | 0 | 12798999 | <filename>api/Mongo/abc_dbops.py<gh_stars>0
'''AbstractDbOps: 数据库操作接口抽象类
@author: <EMAIL>
@last_modified: 2019.6.20
'''
from abc import ABC, abstractmethod
class AbstractDbOps(ABC):
@abstractmethod
def __init__(self):
'''初始化
eg: Initialize db instance
'''
rai... | 2.234375 | 2 |
card.py | akaeme/BlackJackBot | 0 | 12799000 | #encoding: utf8
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__license__ = "GPL"
__version__ = "0.1"
import random
class Card(object):
suit_names = ["♠️", "♣️", "♦️", "♥️"]
rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
def __init__(self, suit=0, rank=1)... | 3.890625 | 4 |
Aula04/Exemplo_Arquivos.py | MateusPeschke/CursoPython | 0 | 12799001 | <reponame>MateusPeschke/CursoPython
# "r" read - abre o arquivo
# "w" write - cria ou substitui um arquivo
# "a" append - adiciona novas informações
import matplotlib.pyplot as plt
import numpy as np
arquivo = open(r"C:\Users\67184\Documents\Desenvolvimento_Agil_em_Python_1_2020\aula4\exemplos\cadastro.txt","r")
li... | 3.296875 | 3 |
models.py | foamliu/i-Cloud | 1 | 12799002 | <filename>models.py
import math
import torch
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch import nn
from torch.nn import Parameter
from config import device, num_classes
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls =... | 2.484375 | 2 |
src/test/data_pipe_test/basic_index_test.py | random-python/data_pipe | 14 | 12799003 | """
"""
from data_pipe.basic_index import *
from data_pipe_test.verify_index import *
def test_log2():
print()
assert integer_log2(1) == 0
assert integer_log2(2) == 1
assert integer_log2(4) == 2
assert integer_log2(8) == 3
def test_index_store():
index_store = BasicIndex()
verify_index(... | 1.984375 | 2 |
mopidy_radioworld/radioworld.py | anabolyc/Mopidy-RadioWorld | 0 | 12799004 | <filename>mopidy_radioworld/radioworld.py
import requests
from time import sleep
from contextlib import closing
import logging
logger = logging.getLogger(__name__)
class RadioWorld(object):
def __init__(self):
self._base_uri = 'https://radioworld-api-prod.azurewebsites.net/%s'
#self._base_uri = 'h... | 2.59375 | 3 |
pingsweeper.py | allanvictor/pingsweeper | 0 | 12799005 | <filename>pingsweeper.py
#!/usr/bin/python
import logging
logging.getLogger('scapy.runtime').setLevel(logging.ERROR)
from scapy.all import *
from netaddr import *
import socket
import sys, getopt
def getlive():
for i in live:
print('live {0}'.format(i[0].dst))
def getdead():
for j in dead:
pri... | 2.53125 | 3 |
build.py | Lzhiyong/android-sdk-tools | 22 | 12799006 | #!/usr/bin/env python
#
# Copyright © 2022 Github Lzhiyong
#
# 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 applicabl... | 2.234375 | 2 |
airflow_ml_dags/dags/model_train.py | made-ml-in-prod-2021/liliyamakhmutova- | 0 | 12799007 | import pathlib
from datetime import timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import Stan... | 2.5 | 2 |
core/utils.py | mannyfin/aioget | 1 | 12799008 | <gh_stars>1-10
import os
from pathlib import Path
import shutil
import json
import asyncio
import concurrent.futures
from functools import partial
from datetime import datetime, timedelta
from typing import Union, List, Coroutine, Callable, Tuple, Optional
from multiprocessing import cpu_count
import pickle
from depre... | 2.203125 | 2 |
qaboard/runners/celery_app.py | Samsung/qaboard | 51 | 12799009 | <reponame>Samsung/qaboard
import os
import subprocess
from celery import Celery
app = Celery('celery_app')
app.conf.update(
broker_url=os.environ.get('CELERY_BROKER_URL', 'pyamqp://guest@localhost//'),
result_backend=os.environ.get('CELERY_RESULT_BACKEND', 'rpc://'),
task_serializer='pickle',
accept_c... | 2.140625 | 2 |
src/tf_frodo/__init__.py | xarion/tf_frodo | 1 | 12799010 | from .frodo import FRODO
| 1.046875 | 1 |
day10/python/subesokun/main.py | matason/aoc-2018 | 17 | 12799011 | <gh_stars>10-100
INPUT_FILE_NAME = 'input.txt'
def parseSpotInput(text):
tmp_split = text.split('>')
pos_str, velo_str = tmp_split[0], tmp_split[1]
pos = tuple([int(coord) for coord in pos_str.replace(' ', '').split('<')[1].split(',')])
velo = tuple([int(velo) for velo in velo_str.replace(' ', '').spli... | 3.09375 | 3 |
register_api/views.py | BrenonOrtega/bug_catcher | 0 | 12799012 | <filename>register_api/views.py
from django.conf import settings
from django.contrib.auth.models import User
from django.http.response import Http404
from django.contrib.auth import get_user
from django.shortcuts import render
from rest_framework import status, mixins
from rest_framework.response import Response
from ... | 2.21875 | 2 |
resources/tools/presentation/pal.py | nidhyanandhan/csit | 0 | 12799013 | <gh_stars>0
# Copyright (c) 2019 Cisco and/or its affiliates.
# 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 applicab... | 2.078125 | 2 |
machine_learning/classification.py | soikkea/python-algorithms | 0 | 12799014 | """Classification methods."""
import numpy as np
from machine_learning.constants import N_CLASSES, FOLDS, MAX_K, RANDOM_SEED
from machine_learning.utilities import k_fold_split_indexes, get_k_nn
def classification(method, error_func, train, test, **kwargs):
"""Perform classification for data and return error.
... | 3.65625 | 4 |
test/unit/test_providers_raw_master_key_config.py | farleyb-amazon/aws-encryption-sdk-python | 95 | 12799015 | <filename>test/unit/test_providers_raw_master_key_config.py<gh_stars>10-100
# Copyright 2017 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 ... | 2.015625 | 2 |
spatiotemporal/db/functions.py | ResonantGeoData/django-image-annotations | 0 | 12799016 | """Django database functions.
This module supplements Django's own coverage of Postgres
and PostGIS functions.
https://docs.djangoproject.com/en/4.0/ref/models/expressions/#func-expressions-1
"""
from django.contrib.gis.db.models import GeometryField, LineStringField, PointField
from django.db.models import FloatFi... | 2.75 | 3 |
reskit/util/leap_day.py | OfficialCodexplosive/RESKit | 16 | 12799017 | import numpy as np
import pandas as pd
from . import ResError
def remove_leap_day(timeseries):
"""Removes leap days from a given timeseries
Parameters
----------
timeseries : array_like
The time series data to remove leap days from
* If something array_like is given, the length mus... | 3.96875 | 4 |
accounts/migrations/0002_auto_20190727_1159.py | Alwin1847207/Hackathon | 0 | 12799018 | # Generated by Django 2.2.3 on 2019-07-27 06:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id',... | 1.867188 | 2 |
pipekit/__init__.py | DrDub/pipekit | 3 | 12799019 | <reponame>DrDub/pipekit
#!/usr/bin/env python3
from .pipe import NullPipe # noqa: W0611
| 1.039063 | 1 |
djforms/alumni/urls.py | carthagecollege/django-djforms | 1 | 12799020 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from django.urls import path
from django.views.generic import TemplateView
from djforms.alumni.classnotes import views as classnotes
from djforms.alumni.distinguished import views as distinguished
from djforms.alumni.memory import views as memory
urlpatterns = [
... | 1.859375 | 2 |
utils/messages/create-welsh-translations.py | hmrc/cds-reimbursement-claim-frontend | 1 | 12799021 | import csv
import sys
def write_welsh_translations(csv_file_name, output_file_name):
with open(csv_file_name, newline='') as csv_file:
messages = csv.reader(csv_file, delimiter=',')
output_file = open(output_file_name, 'w+')
# skip headers
for i in range(2):
next(messag... | 3.390625 | 3 |
dtu-api/dtu_api/model/database.py | demitri/DtU_api | 1 | 12799022 | <reponame>demitri/DtU_api
#!/usr/bin/python
''' This file handles a database connection. It can simply be deleted if not needed.
The example given is for a PostgreSQL database, but can be modified for any other.
'''
import psycopg2
from ..config import AppConfig
from ..designpatterns import singleton
config = Ap... | 2.53125 | 3 |
polarization/profiles.py | woutergins/polarization | 0 | 12799023 | <reponame>woutergins/polarization<filename>polarization/profiles.py
"""
.. module:: profiles
:platform: Windows
:synopsis: Implementation of classes for different lineshapes,
creating callables for easy and intuitive calculations.
.. moduleauthor:: <NAME> <<EMAIL>>
.. moduleauthor:: <NAME> <<EMAIL>>
"""
i... | 2.78125 | 3 |
blueprints/tdmaps/tdmaps.py | filipecosta90/im2modelpy_api | 0 | 12799024 | from flask import Flask, render_template, request, redirect, Blueprint
from flask_jsonpify import jsonpify
from werkzeug import secure_filename
import urllib.request
import urllib.error
import urllib.parse
import os
import json
import sys
import ase.io.cif
from ase import Atoms
import zlib
import sqlite3
import ntpath... | 2.234375 | 2 |
src/localmodule.py | lostanlen/ismir2018-lbd | 6 | 12799025 | from joblib import Memory
import math
import music21 as m21
import numpy as np
import os
from scipy.fftpack import fft, ifft
def get_composers():
return ["Haydn", "Mozart"]
def get_data_dir():
return "/scratch/vl1019/nemisig2018_data"
def get_dataset_name():
return "nemisig2018"
def concatenate_layer... | 2.28125 | 2 |
tests/test_web.py | natumbri/mopidy-bandcamp | 16 | 12799026 | <filename>tests/test_web.py
from unittest import mock
import tornado.testing
import tornado.web
import tornado.websocket
import mopidy.config as config
from mopidy_bandcamp import Extension
class BaseTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
extension = Extension()
self.config ... | 2.296875 | 2 |
nodes/1.x/python/Material.Properties.py | jdehotin/Clockworkfordynamo | 147 | 12799027 | <gh_stars>100-1000
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
mats = UnwrapElement(IN[0])
colorlist = list()
glowlist = list()
classlist = list()
shinylist = list()
smoothlist = list()
translist = list()
for mat in mats:
colorlist.append(mat.Color)
if mat.Glow:
glowlist.append(True)
... | 2.0625 | 2 |
meta_tagger/cms_sitemap.py | dreipol/meta-tagger | 3 | 12799028 | from cms.sitemaps import CMSSitemap
class MetaTagRobotsSiteMap(CMSSitemap):
def items(self):
return super(MetaTagRobotsSiteMap, self).items().exclude(page__metatagpageextension__robots_indexing=False)
| 1.507813 | 2 |
project2/api/simulator.py | fabiorodp/IN_STK5000_Adaptive_methods_for_data_based_decision_making | 0 | 12799029 | ## Comborbidities:
## Comborbidities:
## Asthma, Obesity, Smoking, Diabetes, Heart diseae, Hypertension
## Symptom list: Covid-Recovered, Covid-Positive, Taste, Fever, Headache,
# Pneumonia, Stomach, Myocarditis, Blood-Clots, Death
## Mild symptoms: Taste, Fever, Headache, Stomach
## Critical symptoms: Pneumonia, Myoc... | 2.546875 | 3 |
code_samples/vec2d_use.py | xanewton/PygameCreepsGame | 1 | 12799030 | <reponame>xanewton/PygameCreepsGame
#! /usr/bin/env python
import sys
sys.path.append('..')
from vec2d import vec2d
v = vec2d(-1, 1)
print (v.angle)
| 2.25 | 2 |
tarakania_rpg/db/redis.py | tarakania/discord-bot | 1 | 12799031 | from typing import Any, Dict
from asyncio import sleep
from logging import getLogger
import aioredis
log = getLogger(__name__)
class _ConnectionsPool(aioredis.ConnectionsPool):
def __init__(
self, *args: Any, retry_count: int = 5, retry_interval: int = 2, **kwargs: Any
) -> None:
super().__i... | 2.34375 | 2 |
train.py | AlexMetsai/pytorch-time-series-autoencoder | 0 | 12799032 | # <NAME>
# <EMAIL>
# MIT License
# As-simple-as-possible training loop for an autoencoder.
import torch
import numpy as np
import torch.optim as optim
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from model.shallow_autoencoder import ConvAutoencoder
# load model definition
model = Co... | 3.109375 | 3 |
regtests/bench/copy_list-typed-stack.py | secureosv/pythia | 17 | 12799033 | <reponame>secureosv/pythia<filename>regtests/bench/copy_list-typed-stack.py
'''copy list micro benchmark'''
from time import clock
from runtime import *
with stack:
def copy_list( a:[]int, n ) -> [][]int:
x = [][]int()
for i in range(n):
b = a[:]
for j in range(10):
b.push_back( j )
x.push_back( b )
... | 2.453125 | 2 |
examples/expander.py | furimu1234/discord-ext-utils | 1 | 12799034 | <reponame>furimu1234/discord-ext-utils
from discord.ext.utils import MinimalExpander
from discord.ext import commands
bot = commands.Bot(command_prefix=commands.when_mentioned)
# Expand simple.
bot.load_extension("discord.ext.utils.cogs.minimal_expander")
# Expand all.
# self.load_extension("discord.ext... | 2.234375 | 2 |
apps/quotes/quote_fetcher/quote_fetcher.py | Ev1dentSnow/ArtemisAPI_django | 0 | 12799035 | <gh_stars>0
import json
import requests
from apps.quotes import models
def fetch_quote():
pass
| 1.140625 | 1 |
standalone.py | askehill/covis2 | 0 | 12799036 | <reponame>askehill/covis2
#! /usr/bin/python3
import seeed_mlx9064x
import time,board,busio
import numpy as np
import adafruit_mlx90640
import matplotlib.pyplot as plt
from scipy import ndimage
import argparse
parser = argparse.ArgumentParser(description='Thermal Camera Program')
parser.add_argument('--mirror', dest='... | 2.171875 | 2 |
tloen/domain/transports.py | josiah-wolf-oberholtzer/tloen | 3 | 12799037 | import asyncio
import dataclasses
import enum
from typing import Dict, Optional, Set, Tuple
from supriya.clocks import AsyncTempoClock, Moment
from ..bases import Event
from .bases import ApplicationObject
from .parameters import ParameterGroup, ParameterObject
class Transport(ApplicationObject):
### CLASS VAR... | 2.09375 | 2 |
django/app/hivernants/admin.py | jeanpommier/ker51 | 0 | 12799038 | <gh_stars>0
from django.contrib.gis import admin
from .models import Hivernant, Phone, Email
class PhoneInline(admin.TabularInline):
model = Phone
extra = 1
class EmailInline(admin.TabularInline):
model = Email
extra = 1
class HivernantAdmin(admin.OSMGeoAdmin):
default_lon = 300000
default_l... | 1.796875 | 2 |
sagas/ofbiz/rpc_artifacts.py | samlet/stack | 3 | 12799039 | <reponame>samlet/stack
from concurrent import futures
import time
import grpc
import requests
import json
import blueprints_pb2_grpc
import blueprints_pb2
from sagas.ofbiz.blackboard import Blackboard, BlackboardReceiver
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
"""
$ start as
# or: python -m sagas.ofbiz.rpc_artifacts
"""... | 2.203125 | 2 |
1 - Beginner/1789.py | andrematte/uri-submissions | 1 | 12799040 | <filename>1 - Beginner/1789.py
# URI Online Judge 1789
while True:
try:
N = int(input())
entrada = [int(i) for i in input().split()]
if max(entrada) < 10:
print(1)
elif max(entrada) >= 10 and max(entrada) < 20:
print(2)
elif max(entrada) >= 2... | 3.6875 | 4 |
database/postgresql.py | andreformento/querido-diario-data-processing | 3 | 12799041 | <filename>database/postgresql.py
from typing import Generator
import os
import logging
import psycopg2
from tasks import DatabaseInterface
def get_database_name():
return os.environ["POSTGRES_DB"]
def get_database_user():
return os.environ["POSTGRES_USER"]
def get_database_password():
return os.envi... | 2.828125 | 3 |
hard-gists/df9ad5ef01d16c02d68d9a8c17c75b73/snippet.py | jjhenkel/dockerizeme | 21 | 12799042 |
#
# twitter csv process
# write by @jiyang_viz
#
# require:
# https://github.com/edburnett/twitter-text-python
#
# download csv file from:
# https://github.com/bpb27/political_twitter_archive/tree/master/realdonaldtrump
#
import json
import csv
from ttp import ttp
from dateutil import parser as date_parser
# read cs... | 3.234375 | 3 |
thebotplatform.py | TheBotPlatform/POCInteractionEndPoint | 0 | 12799043 | <filename>thebotplatform.py
import requests
import json
from decouple import config
import time
#Creating and getting my bearer token
LastToken = False
LastTokenTime = False
TokenLifespan = 58 * 60
def BearerTokenGrab():
global LastToken
global LastTokenTime
now = time.time()
if LastToken and LastT... | 3.078125 | 3 |
freeCodeCamp/01-scientific-computing-with-python/src/02-functions.py | aysedemirel/python-journey | 1 | 12799044 | <gh_stars>1-10
def sum(a,b):
return a+b
a = input("Enter first number: ")
b = input("Enter first number: ")
sum_numbers = sum(int(a),int(b))
print("Sum: ", sum_numbers) | 3.6875 | 4 |
batch_generator.py | mr4msm/cramer_gan_chainer | 3 | 12799045 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""Batch generator definition."""
import cv2
import numpy as np
class ImageBatchGenerator(object):
"""Batch generator for training on general images."""
def __init__(self, input_files, batch_size, height, width, channel=3,
shuffle=False, flip_h=False):... | 3.015625 | 3 |
libraries/graphite2-1.3.12/tests/corrupt.py | myzhang1029/zmymingw | 0 | 12799046 | #!/usr/bin/env python
import optparse
import os
import shutil
import sys
def revert(path):
bkup = path + os.path.extsep + options.backup_suffix
if os.access(bkup, os.R_OK):
shutil.copy2(bkup, path)
os.remove(bkup)
def corrupt(path, offset, value):
if options.backup:
shutil.copy2(... | 2.921875 | 3 |
parser.py | veer66/vtimeline | 0 | 12799047 | <reponame>veer66/vtimeline
#-*- coding: UTF-8 -*-
#
# Copyright 2009 <NAME>
#
# 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 without
# restriction, including without limitation the rights t... | 2.453125 | 2 |
tests/telnet.py | cmu-sei/usersim | 10 | 12799048 | # Copyright 2017 <NAME>. See LICENSE.md file for terms.
import socket
import threading
import api
import usersim
TCP_IP = 'localhost'
TCP_PORT = 5005
def run_test():
telnet_config = {'type': 'telnet',
'config': {'host': TCP_IP,
'username': 'admin',
... | 2.453125 | 2 |
polichart/api/views.py | cjmabry/PoliChart | 0 | 12799049 | <filename>polichart/api/views.py
# -*- coding: utf-8 -*-
from flask import Blueprint, current_app, request, jsonify
from flask.ext.login import login_user, current_user, logout_user
from ..extensions import db
from polichart import models
api = Blueprint('api', __name__, url_prefix='/api')
| 1.601563 | 2 |
guillotina/contrib/swagger/services.py | Qiwn/guillotina | 0 | 12799050 | import copy
import json
import os
from urllib.parse import urlparse
import pkg_resources
from guillotina import app_settings
from guillotina import configure
from guillotina.api.service import Service
from guillotina.component import getMultiAdapter
from guillotina.interfaces import IAbsoluteURL
from guillotina.utils... | 2.046875 | 2 |