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 |
|---|---|---|---|---|---|---|
pytype/tests/py3/test_pickle.py | adamcataldo/pytype | 2 | 12778651 | """Tests for loading and saving pickled files."""
from pytype import file_utils
from pytype.tests import test_base
class PickleTest(test_base.TargetPython3BasicTest):
"""Tests for loading and saving pickled files."""
def testContainer(self):
pickled = self.Infer("""
import collections, json
def ... | 2.640625 | 3 |
search.py | nik-sm/gan-compression | 2 | 12778652 | import argparse
from datetime import datetime
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from torch_model import SizedGenerator
import os
from tqdm import trange
from torchvision.utils import save_image, make_grid
import params as P
from utils impo... | 2.359375 | 2 |
app/utils/kafka.py | junpengxu/MyFlask | 0 | 12778653 | # -*- coding: utf-8 -*-
# @Time : 2021/11/13 1:47 下午
# @Author : xujunpeng
from app import app
from confluent_kafka import Producer
KafkaProducer = Producer({'bootstrap.servers': app.config["KAFKA_SERVERS"]})
| 1.328125 | 1 |
django/pokemongo/migrations/0033_auto_20200829_1259.py | TrainerDex/trainerdex.co.uk | 1 | 12778654 | import django.core.validators
from django.db import migrations, models
def clear_gen8(apps, schema_editor):
Update = apps.get_model("pokemongo", "Update")
Update.objects.update(badge_pokedex_entries_gen8=None)
class Migration(migrations.Migration):
dependencies = [
("pokemongo", "0032_remove_tr... | 1.789063 | 2 |
tests/test_platforms_apscheduler.py | collectiveacuity/labPack | 2 | 12778655 | __author__ = 'rcj1492'
__created__ = '2016.11'
__license__ = 'MIT'
from labpack.platforms.apscheduler import apschedulerClient
if __name__ == '__main__':
from labpack.records.settings import load_settings
system_config = load_settings('../../cred/system.yaml')
scheduler_url = 'http://%s:%s' % (sy... | 2.0625 | 2 |
tests/django/test_django.py | ecarrara/connexion-faker | 2 | 12778656 | <gh_stars>1-10
import pytest
def test_settings(settings):
assert settings.ROOT_URLCONF == "tests.django.testapp.urls"
assert settings.INSTALLED_APPS == ['tests.django.testapp']
def test_hello_name(client):
resp = client.get("/hello")
assert resp.status_code == 200
assert resp.json() == {"name": an... | 2.5 | 2 |
altymeter/api/exchange.py | juharris/altymeter | 0 | 12778657 | <reponame>juharris/altymeter<filename>altymeter/api/exchange.py
from abc import ABCMeta, abstractmethod
from collections import namedtuple
from typing import List, Optional
class ExchangeOpenOrder(namedtuple('Order', [
'name',
'exchange',
'price',
'volume',
'order_type',
])):
"""
An open o... | 2.96875 | 3 |
py/segment.py | weiwang2330/MultiGraph_MultiLabel_Learning | 11 | 12778658 | <filename>py/segment.py
"""
Segment image
usage: segment.py [-h] -i IMAGE -n NODE [-o OUTPUT]
optional arguments:
-h, --help show this help message and exit
-i IMAGE, --image IMAGE
(Required) Image file path
-n NODE, --node NODE (Required) Number of nodes which each image wil... | 2.9375 | 3 |
restaurant/admin.py | shankarj67/Django-RESTAPI | 0 | 12778659 | <filename>restaurant/admin.py<gh_stars>0
from django.contrib import admin
from .models import FoodDetail, OrderDetail
from import_export.admin import ImportExportActionModelAdmin
@admin.register(FoodDetail)
class StartupAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
@admin.register(OrderDeta... | 1.664063 | 2 |
mbdata/api/data.py | markweaversonos/mbdata | 51 | 12778660 | from sqlalchemy import sql
from sqlalchemy.orm import joinedload, subqueryload
from sqlalchemy.inspection import inspect
from mbdata.utils.models import get_entity_type_model, get_link_model, ENTITY_TYPES
from mbdata.models import (
Area,
Artist,
Label,
Link,
LinkAreaArea,
LinkType,
Place,
... | 2.265625 | 2 |
scripts/doubletiny_umap_visualize.py | langmead-lab/reference_flow-experiments | 0 | 12778661 | <reponame>langmead-lab/reference_flow-experiments
import seaborn as sns
import pandas as pd
import json
import glob, os, sys, subprocess
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets im... | 2.234375 | 2 |
contrib/tests/runtests.py | ryr/django-social-auth | 1 | 12778662 | <reponame>ryr/django-social-auth
#!/usr/bin/env python
import os, sys
from os.path import dirname, abspath
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_settings'
parent = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0, parent)
from django.test.simple import DjangoTestSuiteRunner
if __name__ == '__... | 1.492188 | 1 |
services/_api_service_template/src/main.py | amthorn/qutex | 0 | 12778663 | <gh_stars>0
import flask
import os
import json
import marshmallow
import pprint
import requests
import werkzeug
import traceback
from app import app
from typing import Union
from bson.objectid import ObjectId
app.config['SERVICE_PREFIX'] = os.environ.get('SERVICE_PREFIX')
app.config['AUTH_SERVICE_TOKEN_CHECK_ROUTE'] =... | 1.960938 | 2 |
examples/resnest50.py | NodLabs/SHARK-Samples | 11 | 12778664 | import torch
import numpy as np
import os
import sys
from shark_runner import shark_inference
class ResNest50(torch.nn.Module):
def __init__(self):
super().__init__()
self.model = torch.hub.load(
"zhanghang1989/ResNeSt", "resnest50", pretrained=True
)
self.train(False)
... | 2.671875 | 3 |
As_util.py | a2gs/AsWallet | 1 | 12778665 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# <NAME> (https://sites.google.com/view/a2gs/)
VERSION = float(0.1)
BTCLIB_DB_PATH = str('')
HOME_DIR = str('')
SCREENBAR = str('')
MSGBAR = str('')
| 1.640625 | 2 |
travel/docs/Amadeus-master/pactravel-master/swagger_client/models/car_reservation.py | shopglobal/api | 0 | 12778666 | <filename>travel/docs/Amadeus-master/pactravel-master/swagger_client/models/car_reservation.py
# coding: utf-8
"""
Amadeus Travel Innovation Sandbox
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.2
Generated by: https... | 1.953125 | 2 |
nesdis_aws/nesdis_aws.py | hagne/nesdis_aws | 0 | 12778667 | # -*- coding: utf-8 -*-
import pathlib as _pl
import pandas as _pd
import s3fs as _s3fs
# import urllib as _urllib
# import html2text as _html2text
import psutil as _psutil
import numpy as _np
# import xarray as _xr
def readme():
url = 'https://docs.opendata.aws/noaa-goes16/cics-readme.html'
# html = _urllib.r... | 2.609375 | 3 |
src/datalayer/snapshotcreator.py | Dabble-of-DevOps-Bio/ella | 0 | 12778668 | from typing import Sequence, Dict, Union
import itertools
from vardb.datamodel import workflow, assessment, annotation
class SnapshotCreator(object):
EXCLUDED_FLAG = {
"classification": "CLASSIFICATION",
"frequency": "FREQUENCY",
"region": "REGION",
"ppy": "POLYPYRIMIDINE",
... | 2.296875 | 2 |
face_detection.py | gnublet/portfolio | 0 | 12778669 | <reponame>gnublet/portfolio
import cv2
import numpy as np
# Load the face, eye, nose, cascade file
face_cascade = cv2.CascadeClassifier('cascade_files/haarcascade_frontalface_alt.xml')
eye_cascade = cv2.CascadeClassifier('cascade_files/haarcascade_eye.xml')
nose_cascade = cv2.CascadeClassifier('cascade_files/haarcasca... | 2.59375 | 3 |
obj.py | mretolaza/flatShader | 0 | 12778670 | import struct
def color(r, g, b):
return bytes([b, g, r])
def try_int(s, base=10, val=None):
try:
return int(s, base)
except ValueError:
return val
class Obj(object):
def __init__(self, filename, fileMaterial=None):
with open(filename) as f:
self.lines = f.read().splitlines()
... | 2.9375 | 3 |
docs/examples/cpu_temperature_bar_graph.py | NotBobTheBuilder/gpiozero | 743 | 12778671 | <reponame>NotBobTheBuilder/gpiozero<filename>docs/examples/cpu_temperature_bar_graph.py
from gpiozero import LEDBarGraph, CPUTemperature
from signal import pause
cpu = CPUTemperature(min_temp=50, max_temp=90)
leds = LEDBarGraph(2, 3, 4, 5, 6, 7, 8, pwm=True)
leds.source = cpu
pause()
| 2.59375 | 3 |
nion/ui/CanvasItem.py | icbicket/nionui | 3 | 12778672 | """
CanvasItem module contains classes related to canvas items.
"""
from __future__ import annotations
# standard libraries
import collections
import concurrent.futures
import contextlib
import copy
import datetime
import enum
import functools
import imageio
import logging
import operator
import sys
import threadi... | 2.171875 | 2 |
test/module/rule/test_rule.py | amabowilli/cfn-python-lint | 0 | 12778673 | """
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 to ... | 2.0625 | 2 |
pyqt_auto_search_bar/__init__.py | yjg30737/pyqt-auto-search-bar | 0 | 12778674 | from .autoSearchBar import AutoSearchBar | 1.117188 | 1 |
unibit_api_v2/crypto.py | liuzulin/python-unibit | 31 | 12778675 | from .unibit import UniBit as ub
class CryptoPrice(ub):
def getHistoricalCryptoPrice(self, ticker, startDate, endDate, size=None, selectedFields=None, datatype="json"):
if isinstance(ticker, list):
ticker = ",".join(ticker)
else:
raise TypeError('ticker input should be a ... | 2.71875 | 3 |
Classification/Perceptron/perceptron.py | pvlawhatre/MachinePy | 2 | 12778676 | <reponame>pvlawhatre/MachinePy
import numpy as np
def perceptron(X_train,y_train,X_test,**kwargs):
n_train,dim=np.shape(X_train)
W=np.random.rand(dim,1)
b=np.random.rand()
old_W=np.random.rand(dim,1)
old_b=np.random.rand()
flag=0
try:
trshld=kwargs['eps']
except:
... | 2.640625 | 3 |
test/argparser_test.py | makzyt4/discogs-tagger | 2 | 12778677 | <reponame>makzyt4/discogs-tagger<gh_stars>1-10
import unittest
from discogstagger.argparser import ArgumentParser
class ValidURLTest(unittest.TestCase):
def test(self):
url = 'https://www.discogs.com/Radiohead-The-Bends/release/368116'
args = ['-u', url, 'abc']
parser = ArgumentParser(arg... | 2.921875 | 3 |
main.py | H3xadecimal/Nest | 10 | 12778678 | <reponame>H3xadecimal/Nest<gh_stars>1-10
#!/usr/bin/env python3
"""
Load and start the Nest client.
"""
import os
import logging
import yaml
from nest import client, helpers, exceptions
DEFAULTS = {
"prefix": "nest!",
"locale": "en_US",
}
def main():
"""
Parse config from file or environment and ... | 2.265625 | 2 |
tests/2019/test_12_the_n_body_problem.py | wimglenn/advent-of-code-wim | 20 | 12778679 | from aoc_wim.aoc2019 import q12
test10 = """\
<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>"""
test100 = """\
<x=-8, y=-10, z=0>
<x=5, y=5, z=10>
<x=2, y=-7, z=3>
<x=9, y=-8, z=-3>"""
def test_total_energy_after_10_steps():
assert q12.simulate(test10, n=10) == 179
def test_total_energ... | 2.078125 | 2 |
contrastive_highlights/Interfaces/abstract_interface.py | yotamitai/Contrastive_Highlights | 0 | 12778680 | <reponame>yotamitai/Contrastive_Highlights
class AbstractInterface(object):
def __init__(self, config, output_dir):
self.output_dir = output_dir
self.config = config
def initiate(self):
return
def get_state_action_values(self, agent, state):
return
def get_state_from... | 2.1875 | 2 |
Day_005/day-5-1-exercise.py | masedos/100DaysOfCodePython | 0 | 12778681 | #!/usr/bin/env python
__version__ = '0.0.1'
__author__ = '<NAME>'
__email__ = '<EMAIL>'
# 🚨 Don't change the code below 👇
#student_heights = [180, 124, 165, 173, 189, 169, 146]
student_heights = input("Input a list of student heights ").split()
sum = 0
count = 0
for n in range(0, len(student_heights)):
student_h... | 3.96875 | 4 |
track-amazon-prices.py | thijsBoet/small-python-projects | 0 | 12778682 | import requests
import smtplib
import time
from bs4 import BeautifulSoup
URL = 'https://www.amazon.de/PowerColor-Radeon-5700-8192MB-PCI/dp/B07WT15P2P/ref=sr_1_8?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&keywords=PowerColor+Radeon+RX+5700+Red+Dragon+8GB&qid=1582975984&sr=8-8#customerReviews'
def send_mail():
serv... | 2.890625 | 3 |
gym_ur5/envs/ur5_env.py | pnnayyeri/gym-ur5 | 1 | 12778683 | <reponame>pnnayyeri/gym-ur5
import sim
import numpy as np
import time
import matplotlib.pyplot as plt
import gym
from gym import error, spaces
class UR5Env(gym.Env):
def __init__(self): # n_actions:3 (target pos), n_states:6 (3pos+3force)
self.metadata = {'render.modes': ['human']}
super().__ini... | 2.390625 | 2 |
src/text_mining.py | desiguel/asx-announce-analysis | 6 | 12778684 | from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.decomposition import PCA, IncrementalPCA
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.gri... | 2.8125 | 3 |
discursus_core/discursus_repo.py | discursus-io/dio_data_stack | 6 | 12778685 | from dagster import repository
from pipelines import mine_gdelt_data
from pipelines import build_data_warehouse
from schedules import mine_gdelt_data_schedule, build_data_warehouse_schedule
@repository
def discursus_repository():
pipelines = [
mine_gdelt_data,
build_data_warehouse
]
sche... | 1.828125 | 2 |
scripts/main.py | michaellyoungg/DeerVision | 1 | 12778686 | <filename>scripts/main.py
# {tkinter}
from tkinter import *
from tkinter import filedialog, Button, messagebox
# {playback}
from playbackController import PlayBack
# {thermography}
from thermography import Thermography
# {WebODM}
from webodmAPI import WebODMAPI
# {Python}
import time
import os
from PIL import Image... | 2.6875 | 3 |
leetcode/sort/heap.py | deevarvar/myLab | 0 | 12778687 | #! /usr/bin/python
def heapify(array):
# first non-leaf node
nlnode = (len(array) - 1)/2
for i in reversed(range(nlnode)):
siftdown(array, i, len(array) - 1)
print "index {} {}".format(i, array)
def siftdown(array, start, end):
root = start
while (2*root + 1) <= end: # at lease on... | 4.0625 | 4 |
Dummy_code/dummy1.py | garima-softuvo/Flask_practice | 0 | 12778688 | <gh_stars>0
from flask import Flask, request, jsonify
import json
import os
import sqlite3
app = Flask(__name__)
path = r"/home/softuvo/Garima/Flask Practice/Flask_practice/files"
files = os.listdir(path)
for f in files:
filename=os.path.join(path, f)
def convertToBinaryData(filename):
# Convert digit... | 3.3125 | 3 |
trolly/label.py | WoLpH/Trolly | 1 | 12778689 | from . import trelloobject
class Label(trelloobject.TrelloObject):
'''
Class representing a Trello Label
'''
def __init__(self, trello_client, label_id, name=''):
super(Label, self).__init__(trello_client)
self.id = label_id
self.name = name
self.base_uri = '/labels... | 3.109375 | 3 |
tda-api_test.py | kspringfield13/MoneyTree | 0 | 12778690 | <reponame>kspringfield13/MoneyTree<filename>tda-api_test.py
from tda import auth, client
from tda.orders.common import OrderType, Duration, Session
from tda.orders.generic import OrderBuilder
from tda.orders.equities import equity_buy_limit
import json, config
try:
c = auth.client_from_token_file(config.tda_token_... | 2.125 | 2 |
lilu/data_layer/__init__.py | xyla-io/lambda_lilu | 0 | 12778691 | <reponame>xyla-io/lambda_lilu
from .base import get_connection, run_query
from .query import Query, UnloadQuery
from .locator import ResourceLocator, locator_factory
from .encryptor import Encryptor, Decryptor | 1.242188 | 1 |
funowl/terminals/Terminals.py | clin113jhu/funowl | 23 | 12778692 |
# String pattern matches used in Functional Owl
# The following productions are taken from ShExJ.py from the ShExJSG project
from typing import Union, Any
from funowl.terminals.Patterns import String, Pattern
class HEX(String):
pattern = Pattern(r'[0-9]|[A-F]|[a-f]')
python_type = Union[int, str]
class UC... | 2.9375 | 3 |
scripts/generate_html.py | biancaitian/gurobi-official-examples | 4 | 12778693 | <reponame>biancaitian/gurobi-official-examples
import os
path = '../documents'
output = '../dist'
for root, dirs, files in os.walk(path):
for file in files:
# print(os.path.join(root,file))
if file.endswith(".ipynb"):
# 过滤掉 check point 的 ipynb
if file.find('-checkpoint') < 0... | 2.75 | 3 |
DelibeRating/DelibeRating/deliberating-env/Lib/site-packages/etc/admin/__init__.py | Severose/DelibeRating | 25 | 12778694 | <reponame>Severose/DelibeRating<filename>DelibeRating/DelibeRating/deliberating-env/Lib/site-packages/etc/admin/__init__.py
from .admins import ReadonlyAdmin
from .models import CustomModelPage
| 1.054688 | 1 |
src/parse.py | Arsh25/Oracl | 0 | 12778695 | import pcapkit
import json
from pymongofunct import insert_data
def pcaptojson(file) -> dict:
return(pcapkit.extract(fin=file, nofile=True, format='json', auto=False,
engine='deafult', extension=False, layer='Transport', tcp=True, ip=True,strict=True, store=False))
def pcapparse(obj) -> dict:
ma... | 2.671875 | 3 |
torchwi/loss/FreqLoss.py | pkgpl/TorchWI | 5 | 12778696 | import torch
import numpy as np
from torchwi.utils.ctensor import ca2rt, rt2ca
class FreqL2Loss(torch.autograd.Function):
@staticmethod
def forward(ctx, frd, true):
# resid: (nrhs, 2*nx) 2 for real and imaginary
resid = frd - true
resid_c = rt2ca(resid)
l2 = np.real(0.5*np.sum(... | 2.359375 | 2 |
venv/lib/python3.9/site-packages/setupcfg/options/__init__.py | xanderstevenson/devnet-support-helper | 2 | 12778697 | <filename>venv/lib/python3.9/site-packages/setupcfg/options/__init__.py
#!/usr/bin/env pythons
"""
http://setuptools.readthedocs.io/en/latest/setuptools.html#options
"""
KEYS = [
"zip_safe",
"setup_requires",
"install_requires",
"extras_require",
"python_requires",
"entry_points",
"use_2to... | 1.359375 | 1 |
main/aio/multi.py | chaosannals/trial-python | 0 | 12778698 | from asyncio import sleep, wait, get_event_loop, ensure_future
async def work(t):
await sleep(t)
print('time {}'.format(t))
return t
def on_done(t):
print(t.result())
async def main():
# 协程
coroutines = []
for i in range(2):
c = work(i)
print(type(c))
coroutines.ap... | 3.3125 | 3 |
main.py | arrickx/DateNotification | 0 | 12778699 | import csv
from datetime import datetime
aday,bday=[],[]
today = datetime.today().strftime('%m/%d')
with open('data.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if today in row['Birthday']:
bday.append([row['Name'], row['E-Mail'],row['Birthday']])
if today in row[... | 3.453125 | 3 |
data/preprocessed/extract-data.py | janfreyberg/healthy-brain-eeg | 1 | 12778700 | <filename>data/preprocessed/extract-data.py
from pathlib import Path
import os
import shutil
import sys
import platform
# where the compressed data is stored
datadir = Path('D:\\') / 'cmi-hbn'
# where 7zip is stored
if platform.system() == 'Windows':
zipcommand = '7z'
# find the compressed Files
tarfiles = datadi... | 2.796875 | 3 |
tests/ea/mutation/mutator/conftest.py | stevenbennett96/stk | 21 | 12778701 | import pytest
from pytest_lazyfixture import lazy_fixture
# Fixtures must be visible for lazy_fixture() calls.
from .fixtures import * # noqa
@pytest.fixture(
params=(
lazy_fixture('random_building_block'),
lazy_fixture('random_topology_graph'),
lazy_fixture('similar_building_block'),
... | 1.898438 | 2 |
setup.py | eduardogpg/pybose | 3 | 12778702 | <reponame>eduardogpg/pybose
from setuptools import setup, find_packages
from pathlib import Path
this_directory = Path(__file__).parent
# long_description = (this_directory / "README.md").read_text()
with open(this_directory / "README.md", encoding="utf8") as file:
long_description = file.read()
VERSION = '0.1... | 1.671875 | 2 |
ffptutils/scripts/__init__.py | sekineh/ffptutils-py | 0 | 12778703 | __all__ = ['csv2ffpt', 'ffpt2csv'] | 1.070313 | 1 |
src/opendr/perception/activity_recognition/x3d/algorithm/x3d.py | makistsantekidis/opendr | 217 | 12778704 | <gh_stars>100-1000
""" Adapted from: https://github.com/facebookresearch/SlowFast
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from .head_helper import X3DHead
from .resnet_helper import ResStage
from .stem_helper import VideoModelStem
import pytorch_light... | 1.984375 | 2 |
test.py | mitmedialab/MediaCloud-WordEmbeddingsServer | 0 | 12778705 | import unittest
import sys
import os
import logging
from dotenv import load_dotenv
# load env-vars from .env file if there is one
basedir = os.path.abspath(os.path.dirname(__file__))
test_env = os.path.join(basedir, '.env')
if os.path.isfile(test_env):
load_dotenv(dotenv_path=os.path.join(basedir, '.env'), verbose... | 2.515625 | 3 |
app/settings/arq.py | leosussan/fastapi-gino-arq-postgres | 289 | 12778706 | <filename>app/settings/arq.py
from arq.connections import RedisSettings
from .globals import REDIS_IP, REDIS_PORT
settings = RedisSettings(host=REDIS_IP, port=REDIS_PORT)
| 1.46875 | 1 |
src/blrequests/authentication.py | circius/bl-requests | 0 | 12778707 | # -*- coding: utf-8 -*-
"""Encapsulates functions which handle credentials.
"""
from blrequests.data_definitions import Credentials
import subprocess
import configparser
import os.path
CONFIG_FILE = ".blrequestsrc"
CONFIG_FILE_EXISTS = os.path.exists(CONFIG_FILE)
def fetch_credentials() -> Credentials:
"""Produ... | 3.3125 | 3 |
server/manager/dataManager.py | pengzhuo/gameServer | 0 | 12778708 | # coding: utf-8
import redis
from models.singleton import Singleton
from common.config import *
class DataManager:
__metaclass__ = Singleton
redis_instance = None # redis实例
def __init__(self):
self.redis_instance = redis.StrictRedis(REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD)
def sa... | 2.484375 | 2 |
lfs/criteria/models/criteria.py | naro/django-lfs | 0 | 12778709 | <gh_stars>0
# django imports
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.db import models
from django.utils.translation import ugettext_lazy as _, ugettext
from django.template import RequestContext
from django.template.loader ... | 2.0625 | 2 |
engram/result.py | rgrannell1/engram.py | 0 | 12778710 | <filename>engram/result.py
#!/usr/bin/env python3
import traceback
import logging
logger = logging.getLogger(__name__)
class Result(object):
def __init__(self, value):
self.value = value.value if isinstance(value, Result) else value
@staticmethod
def of(fn):
"""Create a Result from the return result of... | 2.8125 | 3 |
src/preprocess.py | mjpekala/faster-membranes | 0 | 12778711 | """ Preprocess the ISBI data set.
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2015, JHU/APL"
__license__ = "Apache 2.0"
import argparse, os.path
import numpy as np
from scipy.stats.mstats import mquantiles
import scipy.io
import emlib
def get_args():
"""Command line parameters for the 'deploy' proc... | 2.3125 | 2 |
config/config.py | KingsleyXie/Yatpd | 1 | 12778712 | import yaml
def get(filename='config/config.yaml'):
with open(filename, 'r') as stream:
data = yaml.safe_load(stream)
return data
if __name__ == '__main__':
print(get())
| 2.4375 | 2 |
django_double_accounting/blackbook/charts.py | bsiebens/django-double-accounting | 0 | 12778713 | <gh_stars>0
from datetime import timedelta, date
from .models import CurrencyConversion
import json
def get_color_code(i):
color_codes = ["98, 181, 229", "134, 188, 37", "152, 38, 73", "124, 132, 131", "213, 216, 135", "247, 174, 248"]
color = (i - 1) % len(color_codes)
return color_codes[color]
clas... | 2.375 | 2 |
map_test.py | CrazyJ36/python | 0 | 12778714 | <reponame>CrazyJ36/python
#!/usr/bin/env python3
# The library module function 'map' takes A function and
# an iterable as arguments, returns A new iterable with
# the function applied to each argument.
nums = [2, 5, 1]
# the function adds one to any arg.
def add_one(x):
return x + 1
# map function taking add_on... | 4.59375 | 5 |
calpy/rqa/rqa.py | robert-cochran/Calpy | 6 | 12778715 | import numpy
import math
#from .. import utilities
class phase_space(object):
"""Phase space class.
"""
def __init__(self, xs, tau=1, m=2, eps=.001):
self.tau, self.m, self.eps = tau, m, eps
N = int(len(xs)-m*tau+tau)
self.matrix = numpy.empty([N,m],dtype=float)
fo... | 3.328125 | 3 |
04-perfectionnez-vous/coffee.py | gruiick/openclassrooms-py | 0 | 12778716 | #!/usr/bin/env python3
# coding: utf-8
#
# $Id: coffee.py 1.1 $
# SPDX-License-Identifier: BSD-2-Clause
def name(func):
def inner(*args, **kwargs):
print('Running this method:', func.__name__)
return func(*args, **kwargs)
return inner
class CoffeeMachine():
water_level = 100
@name
... | 3.375 | 3 |
paper/plot_cert2016.py | lunpin1101/acobe | 1 | 12778717 | <filename>paper/plot_cert2016.py
#!/usr/bin/python3
import csv, gzip, json, matplotlib, numpy, os, random
matplotlib.use ('Agg')
import matplotlib.pyplot
exp = 'expbeh'
votes = 3
r1 = '/home/lunpin/anom/cert2016/r6.1/' + exp
r2 = '/home/lunpin/anom/cert2016/r6.2/' + exp
r1 = '/media/lunpin/ext-drive/bizon/anom/cert20... | 2.46875 | 2 |
aot/meta_triggers/metatrigger.py | jaycheungchunman/age-of-triggers | 8 | 12778718 | <reponame>jaycheungchunman/age-of-triggers
from abc import ABC, abstractmethod
class MetaTrigger(ABC):
pass
@abstractmethod
def setup(self, scenario):
pass
def triggers_to_activate(self):
return []
class EffectGenerator(ABC):
@abstractmethod
def generate(self, player_id, ... | 2.4375 | 2 |
deepstochlog/network.py | ML-KULeuven/deepstochlog | 10 | 12778719 | <filename>deepstochlog/network.py
from typing import List
import torch.nn as nn
from deepstochlog.term import Term
class Network(object):
def __init__(
self,
name: str,
neural_model: nn.Module,
index_list: List[Term],
concat_tensor_input=True,
):
self.name = n... | 2.6875 | 3 |
bot/sticker/error.py | TinderBrazil/sticker-thief | 0 | 12778720 | <filename>bot/sticker/error.py
class StickerError(Exception):
def __init__(self, message):
super(StickerError, self).__init__()
self.message = message
def __str__(self):
return '{}'.format(self.message)
class NameAlreadyOccupied(StickerError):
pass
class PackInvalid(StickerErro... | 2.484375 | 2 |
src/jackdaw/RuntimeChecks/__init__.py | miicck/jackdaw | 0 | 12778721 | import traceback
class CallStructureException(Exception):
pass
def must_be_called_from(method):
for frame in traceback.extract_stack():
if frame.name == method.__name__ and frame.filename == method.__globals__['__file__']:
return
raise CallStructureException("Method called incorrect... | 2.8125 | 3 |
Python_Crash_Courses_V2/O_Name.py | obareau/python_travaux_pratiques | 1 | 12778722 | # Return name with each words capitalized
name = "<NAME>"
print(name.title())
# Ada Lovelace
# Some useful methods
name2 = "<NAME>"
print(name2.upper())
print(name2.lower())
# ADA LOVELACE
# ada lovelace
# Using Variables in Strings
gender = "miss"
first_name = "ada"
last_name = "lovelace"
# f is for f-strings
full_... | 4.1875 | 4 |
exact_solvers/shallow_water.py | haraldschilly/riemann_book | 0 | 12778723 | <reponame>haraldschilly/riemann_book<filename>exact_solvers/shallow_water.py
import sys, os
import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
import warnings
from ipywidgets import interact
from ipywidgets import widgets, Checkbox, fixed
from utils import riemann_tools
from collection... | 2.71875 | 3 |
tournamentcontrol/competition/migrations/0006_sportingpulse_import_fields.py | goodtune/vitriolic | 0 | 12778724 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('competition', '0005_alter_club_facebook_youtube_position'),
]
operations = [
migrations.AddField(
model_name='di... | 1.695313 | 2 |
doc/source/examples/transform.py | WhiteSheet/pcsg | 0 | 12778725 | import math
import pcsg
from exampleimg import runtime
from exampleimg import conf
def _setAttributes2D (attributes):
return attributes.override ({
'camera.view': (0, 0, 0, 0, 0, 0, 8)
})
def _setAttributes (attributes):
return attributes.override ({
'camera.view': (0, 0, 0, 70, 0, 3... | 2.6875 | 3 |
main.py | aiziXx/WechatHelper | 3 | 12778726 | <gh_stars>1-10
'''
Function:
微信小助手主函数
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import os
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Wechat helper(微信小助手), Author: Charles, WeChat Official Accounts: Charles_pikachu(微信公众号: Charles的皮卡丘), Version: V0.1.0")
parser.add_argume... | 3.140625 | 3 |
source/socket-client.py | Chu3an/rpi-iot-lesson | 0 | 12778727 | import socket
HOST, PORT = '127.0.0.1', 8000
clientMessage = 'Hello!'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
client.connect((HOST, PORT))
client.sendall(clientMessage.encode())
serverMessage = str(client.recv(1024), encoding='utf-8')
print('Server:', serverMessage)
| 2.734375 | 3 |
conanfile.py | mmha/conan-opencl-icd-loader | 0 | 12778728 | <filename>conanfile.py
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
class KhronosOpenCLICDLoaderConan(ConanFile):
name = "khronos-opencl-icd-loader"
version = "20190412"
description = "The OpenCL ICD Loader"
topics = ("conan", "opencl", "opencl-icd-loader", "build-syst... | 1.976563 | 2 |
mkdocs.py | dsbowen/flask-download-btn | 1 | 12778729 | <filename>mkdocs.py
from docstr_md.python import PySoup, compile_md
from docstr_md.src_href import Github
src_href = Github('https://github.com/dsbowen/flask-download-btn/blob/master')
path = 'flask_download_btn/__init__.py'
soup = PySoup(path=path, parser='sklearn', src_href=src_href)
compile_md(soup, compiler='skle... | 2.28125 | 2 |
pecan/lang/optimizer/arithmetic.py | ondrik-misc-code/Pecan | 0 | 12778730 | #!/usr/bin/env python3.6
# -*- coding=utf-8 -*-
from pecan.lang.ir_transformer import IRTransformer
from pecan.lang.optimizer.basic_optimizer import BasicOptimizer
from pecan.lang.ir import *
class ArithmeticOptimizer(BasicOptimizer):
def constant_eq(self, node, val):
return type(node) is IntConst and no... | 2.78125 | 3 |
notes/2017-10-10-voxel-reconstruction/figures/my_draw_scene.py | talonchandler/dipsim | 0 | 12778731 | <reponame>talonchandler/dipsim<gh_stars>0
import numpy as np
import subprocess
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def draw_scene(scene_string, filename='out.png', my_ax=None, dpi=500,
save_file=False, chop=True):
asy_string = """
... | 2.4375 | 2 |
zinnia/migrations/__init__.py | Boondockers-Welcome/django-blog-zinnia | 1,522 | 12778732 | """Migrations for Zinnia"""
| 1.09375 | 1 |
utils/tools.py | yshen47/iq | 59 | 12778733 | <reponame>yshen47/iq
"""Contains a set of helper functions.
"""
class Dict2Obj(dict):
"""Converts dicts to objects.
"""
def __getattr__(self, name):
if name in self:
return self[name]
else:
raise AttributeError("No such attribute: " + name)
def __setattr__(sel... | 3.0625 | 3 |
tests/test_suite.py | ikethecoder/sae-postgres | 1 | 12778734 | <gh_stars>1-10
import sys, os
import logging
from unittest import TestCase
from client.cli import CLI
from tests.expect import Expect
log = logging.getLogger(__name__)
logging.basicConfig(level=os.environ['LOG_LEVEL'],
format='%(asctime)s - %(levelname)s - %(message)s')
creds = {
"PGHOST" : ... | 2.40625 | 2 |
tests/demo/stocklab_demo/nodes/Price.py | hchsiao/stocklab | 1 | 12778735 | <gh_stars>1-10
from stocklab.node import *
from stocklab.core.runtime import FooCrawler
class Price(DataNode):
crawler_entry = FooCrawler.bar
args = Args(
date_idx = Arg(type=int),
stock = Arg(),
)
schema = Schema(
stock = {'key': True},
date = {'... | 2.65625 | 3 |
demos/zipoisson.py | mbannick/CorrelatedCounts | 3 | 12778736 | <reponame>mbannick/CorrelatedCounts
# -*- coding: utf-8 -*-
"""
Zero-Inflated Poisson Demo
~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from ccount.simulate import ZIPoissonSimulation
from ccount.models import ZeroInflatedPoisson
import numpy as np
zip_p_error = []
zip_beta_error = []
i = 0
while i < 100:
# set up the ... | 2.265625 | 2 |
2015/day_03/3_2.py | sunjerry019/adventOfCode18 | 0 | 12778737 | <gh_stars>0
#!/usr/bin/env python3
import numpy as np
inputFile = open("3.in",'r')
inputContents = inputFile.readlines()[0].strip()
visited = {(0, 0)}
currPerson = 0
currPositions = [np.array([0, 0], dtype=int), np.array([0, 0], dtype=int)] # x, y
ordnung = {
'^' : np.array([ 0, 1], dtype=int),
'>' : np.arr... | 3.125 | 3 |
T567_CheckInclusion.py | zoubohao/LeetCodes | 0 | 12778738 | <reponame>zoubohao/LeetCodes<gh_stars>0
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
s1Size = len(s1)
s2Size = len(s2)
if s2Size < s1Size:
return False
left = 0
right = s1Size
valid = 0
need = {}
windo... | 3.171875 | 3 |
tests/test_fil2h5.py | lacker/blimpy | 1 | 12778739 | <filename>tests/test_fil2h5.py
"""
# test_fil2h5
"""
import pytest
import os
import blimpy as bl
from tests.data import voyager_fil
def test_fil2h5_conversion():
""" Tests the conversion of fil files into h5 in both light and heavy modes.
"""
# Creating test file.
bl.fil2h5.make_h5_file(voyager_fil... | 2.5625 | 3 |
Statistics/main_numpy.py | hui-shao/python-toolk | 3 | 12778740 | <reponame>hui-shao/python-toolk
#简单现行回归:只有一个自变量 y=k*x+b 预测使 (y-y*)^2 最小
import numpy as np
def fitSLR(x,y):
n=len(x) #获取x的长度,x是list
dinominator = 0#初始化分母
numerator=0 #初始化分子
for i in range(0,n): #求b1
numerator += (x[i]-np.mean(x))*(y[i]-np.mean(y))
dinominator += (x[i]-np.mean... | 3.609375 | 4 |
occult/horoscopes.py | CelinaWalkowicz/Discord-Bots | 0 | 12778741 | '''
Horoscope Attributes of the Occult Bot
'''
# Imports
import requests, json
# Variables
# Emojis
aries_emoji = '\N{ARIES}'
taurus_emoji = '\N{TAURUS}'
gemini_emoji = '\N{GEMINI}'
cancer_emoji = '\N{CANCER}'
leo_emoji = '\N{LEO}'
virgo_emoji = '\N{VIRGO}'
libra_emoji = '\N{LIBRA}'
scorpio_emoji = '\N{SCORPIUS}'
sa... | 3.703125 | 4 |
cielo/api/funcao.py | CharlesTenorio/strive_api | 0 | 12778742 | <reponame>CharlesTenorio/strive_api<gh_stars>0
import json
import logging
from cieloApi3 import Environment
from cieloApi3 import Merchant
from cieloApi3 import Sale
from cieloApi3 import Customer
from cieloApi3 import CreditCard
from cieloApi3 import CieloEcommerce
from cieloApi3 import Payment
from decouple import co... | 2.171875 | 2 |
tests/test_standard_templates.py | TopOfMinds/dw-generator | 5 | 12778743 | import sqlite3
import unittest
from collections import namedtuple
from datetime import datetime
from dwgenerator.dbobjects import Schema, Table, Column, create_typed_table, Hub, Link, Satellite, MetaDataError, MetaDataWarning
from dwgenerator.mappings import TableMappings, ColumnMappings, Mappings
from dwgenerator.tem... | 2.453125 | 2 |
xl_tensorflow/models/vision/detection/loss/yolo_loss.py | Lannister-Xiaolin/xl_tensorflow | 0 | 12778744 | <reponame>Lannister-Xiaolin/xl_tensorflow
#!usr/bin/env python3
# -*- coding: UTF-8 -*-
import tensorflow as tf
from xl_tensorflow.models.vision.detection.dataloader.utils.anchors_yolo import YOLOV3_ANCHORS
import tensorflow.keras.backend as K
from ..body.yolo import yolo_head, box_iou
class YoloLoss(tf.keras.losses.... | 2.203125 | 2 |
tests/test_response.py | therefromhere/webtest | 0 | 12778745 | #coding: utf-8
from __future__ import unicode_literals
import sys
import webtest
from webtest.debugapp import debug_app
from webob import Request
from webob.response import gzip_app_iter
from webtest.compat import PY3
from tests.compat import unittest
import webbrowser
def links_app(environ, start_response):
... | 2.546875 | 3 |
publications/models.py | tarsisferreira/personalsite | 0 | 12778746 | <reponame>tarsisferreira/personalsite
from django.db import models
class Journal(models.Model):
"""
A journal
"""
journal = models.CharField(max_length=500)
def __unicode__(self):
return self.journal
class Author(models.Model):
"""
A single author
"""
first_name = models.Ch... | 2.59375 | 3 |
sabi/sync.py | sabi-ai/sabi | 0 | 12778747 | from sabi.api_client import ApiClient
class Sync(ApiClient):
headers = None
def __init__(self, api_key, host = None):
version = 'v1'
base = f'{version}/sync'
super().__init__(api_key, base, host)
def save_individuals(self, individuals):
"""
Example for valid payloa... | 2.421875 | 2 |
tests/test_accumulators.py | YiqingZhouKelly/pyqmc | 0 | 12778748 | import numpy as np
from pyqmc.energy import energy
from pyqmc.accumulators import LinearTransform
def test_transform():
""" Just prints things out;
TODO: figure out a thing to test.
"""
from pyscf import gto, scf
import pyqmc
r = 1.54 / 0.529177
mol = gto.M(
atom="H 0. 0. 0.; H 0... | 2.21875 | 2 |
src/mlscratch/measurer/probs_measurer.py | aicroe/mlscratch | 0 | 12778749 | """ProbsMeasurer's module."""
import numpy as np
from mlscratch.tensor import Tensor
from .measurer import Measurer
class ProbsMeasurer(Measurer[float]):
"""Computes how many samples were evaluated correctly by
getting the most probable label/index in the probability array."""
def measure(
se... | 2.5625 | 3 |
cbe/cbe/physical_object/views.py | cdaf/cbe | 3 | 12778750 | from rest_framework import permissions, renderers, viewsets
from cbe.physical_object.models import Structure, Vehicle, Device, Owner
from cbe.physical_object.serializers import StructureSerializer, VehicleSerializer, DeviceSerializer
class StructureViewSet(viewsets.ModelViewSet):
queryset = Structure.objects.all... | 2.140625 | 2 |