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 |
|---|---|---|---|---|---|---|
project1/budget/migrations/0005_delete_hiddenstatus_budget.py | sujeethiremath/Project-1 | 0 | 5000 | # Generated by Django 2.2.5 on 2020-04-08 00:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('budget', '0004_auto_20200407_2356'),
]
operations = [
migrations.DeleteModel(
name='HiddenStatus_Budget',
),
]
| 1.140625 | 1 |
tutorial/43.py | mssung94/daishin-trading-system | 2 | 5001 | # 대신증권 API
# 데이터 요청 방법 2가지 BlockRequest 와 Request 방식 비교 예제
# 플러스 API 에서 데이터를 요청하는 방법은 크게 2가지가 있습니다
#
# BlockRequest 방식 - 가장 간단하게 데이터 요청해서 수신 가능
# Request 호출 후 Received 이벤트로 수신 받기
#
# 아래는 위 2가지를 비교할 수 있도록 만든 예제 코드입니다
# 일반적인 데이터 요청에는 BlockRequest 방식이 가장 간단합니다
# 다만, BlockRequest 함수 내에서도 동일 하게 메시지펌핑을 하고 있어 해당 ... | 2.21875 | 2 |
ADPTC_LIB/DPTree_ST.py | SuilandCoder/ADPTC_LIB | 0 | 5002 | <filename>ADPTC_LIB/DPTree_ST.py<gh_stars>0
#%%
import numpy as np
import copy
import matplotlib.pyplot as plt
import time
def split_cluster_new(tree,local_density,dc_eps,closest_denser_nodes_id,mixin_near_matrix):
'''
dc_eps: density_connectivity 阈值
使用父子节点的直接距离,与子节点与兄弟节点的连通距离进行聚簇划分;
使用平均密... | 2.375 | 2 |
datasets/tao/tao.py | Nik-V9/AirObject | 9 | 5003 | <reponame>Nik-V9/AirObject
from __future__ import print_function
import sys
sys.path.append('.')
import os
from typing import Optional, Union
import cv2
import numpy as np
import PIL.Image as Image
import pickle
import torch
from torch.utils import data
__all__ = ["TAO"]
class TAO(data.Dataset):
r"""A torch Dat... | 2.609375 | 3 |
Platforms/Web/Processing/Api/Discord/Configs/Quotedisabledchannels/errors.py | The-CJ/Phaazebot | 2 | 5004 | from typing import TYPE_CHECKING
if TYPE_CHECKING:
from Platforms.Web.main_web import PhaazebotWeb
import json
from aiohttp.web import Response
from Utils.Classes.extendedrequest import ExtendedRequest
async def apiDiscordConfigsQuoteDisabledChannelExists(cls:"PhaazebotWeb", WebRequest:ExtendedRequest, **kwargs) -> ... | 2.4375 | 2 |
augmentation/ISDA.py | RichardScottOZ/sota-data-augmentation-and-optimizers | 31 | 5005 | import torch
import torch.nn as nn
class EstimatorCV():
def __init__(self, feature_num, class_num):
super(EstimatorCV, self).__init__()
self.class_num = class_num
self.CoVariance = torch.zeros(class_num, feature_num, feature_num)#.cuda()
self.Ave = torch.zeros(class_num, feature_nu... | 2.390625 | 2 |
netpyne/plotting/plotter.py | sanjayankur31/netpyne | 0 | 5006 | """
Module for plotting analyses
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from copy import deepcopy
import pickle, json
import os
from matplotlib.offsetbox import AnchoredOffsetbox
try:
basestring
except NameError:
basestring = str
colorList = [[0.42, 0.67, 0.84], [0.... | 2.203125 | 2 |
examples/simpleWiki.py | klahnakoski/mo-parsing | 1 | 5007 | from mo_parsing.helpers import QuotedString
wikiInput = """
Here is a simple Wiki input:
*This is in italics.*
**This is in bold!**
***This is in bold italics!***
Here's a URL to {{Pyparsing's Wiki Page->https://site-closed.wikispaces.com}}
"""
def convertToHTML(opening, closing):
def convers... | 3.125 | 3 |
tests/test_app_settings_dict.py | wheelercj/app_settings | 0 | 5008 | <filename>tests/test_app_settings_dict.py<gh_stars>0
import pytest
import re
from typing import Any, Tuple
from dataclasses import dataclass
from app_settings_dict import Settings
def test_simple_settings() -> None:
settings = Settings(
settings_file_path="C:/Users/chris/Documents/sample_settings_file_nam... | 2.40625 | 2 |
demo/demo_FSANET_ssd.py | jacke121/FSA-Net | 0 | 5009 | import os
import time
import cv2
import sys
sys.path.append('..')
import numpy as np
from math import cos, sin
from lib.FSANET_model import *
import numpy as np
from keras.layers import Average
def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 50):
print(yaw,roll,pitch)
pitch = pitch * np.pi /... | 2.71875 | 3 |
examples/app_commands/slash_autocomplete.py | Mihitoko/pycord | 0 | 5010 | import discord
from discord.commands import option
bot = discord.Bot(debug_guilds=[...])
COLORS = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
LOTS_OF_COLORS = [
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"blueviolet",
"brown... | 2.671875 | 3 |
tools/Networking/sybil_block_no_ban.py | simewu/bitcoin_researcher | 1 | 5011 | from _thread import start_new_thread
from bitcoin.messages import *
from bitcoin.net import CAddress
from bitcoin.core import CBlock
from io import BytesIO as _BytesIO
import atexit
import bitcoin
import fcntl
import hashlib
import json
import os
import random
import re
import socket
import struct
import sys
import tim... | 2.25 | 2 |
spider/db.py | aloneZERO/douban-movie-visualization | 0 | 5012 | <reponame>aloneZERO/douban-movie-visualization
#!python3
'''
数据库操作类
author: justZero
email: <EMAIL>
date: 2017-8-6
'''
import time
import pandas as pd
import numpy as np
import pymysql
import pymysql.cursors
import pprint
class MySQLdb(object):
def __init__(self):
self.conn = pymysql.connect(
... | 3.03125 | 3 |
examples/rxff-serial/run.py | sctiwari/EZFF_ASE | 3 | 5013 | <reponame>sctiwari/EZFF_ASE<filename>examples/rxff-serial/run.py
import ezff
from ezff.interfaces import gulp, qchem
# Define ground truths
gt_gs = qchem.read_structure('ground_truths/optCHOSx.out')
gt_gs_energy = qchem.read_energy('ground_truths/optCHOSx.out')
gt_scan = qchem.read_structure('ground_truths/scanCHOSx.o... | 2.078125 | 2 |
dev_files/utils.py | dylanwal/unit_parse | 1 | 5014 | import logging
from testing_func import testing_func, test_logger
from unit_parse import logger, Unit, Q
from unit_parse.utils import *
test_logger.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
test_split_list = [
# positive control (changes)
[["fish","pig", "cow"], ["f", "is", "h", "pig", "cow"], ... | 2.53125 | 3 |
genlicense.py | d53dave/python-crypto-licensecheck | 0 | 5015 | <reponame>d53dave/python-crypto-licensecheck
import sys
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
def sign_data(key, data, output_file):
with open(key, 'r', encoding='utf-8') as keyFile:
rsakey = RSA.importKey(keyFile.read())
signer = pkc... | 2.5625 | 3 |
freqtrade/strategy/informative_decorator.py | Fractate/freqbot | 1 | 5016 | <reponame>Fractate/freqbot
from typing import Any, Callable, NamedTuple, Optional, Union
from pandas import DataFrame
from freqtrade.exceptions import OperationalException
from freqtrade.strategy.strategy_helper import merge_informative_pair
PopulateIndicators = Callable[[Any, DataFrame, dict], DataFrame]
class I... | 2.640625 | 3 |
codigo_das_aulas/aula_09/aula_09_03.py | VeirichR/curso-python-selenium | 234 | 5017 | from functools import partial
from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import (
WebDriverWait
)
def esperar_elemento(elemento, webdriver):
print(f'Tentando encontrar "{elemento}"')
if webdriver.find_elements_by_css_selector(elemento):
return True
return False
... | 2.90625 | 3 |
prae/losses.py | irom-lab/RL_Generalization | 24 | 5018 | <gh_stars>10-100
import torch
from torch import nn
from prae.distances import square_dist, HingedSquaredEuclidean
class Loss(nn.Module):
"""
"""
def __init__(self, hinge, neg=True, rew=True):
"""
"""
super().__init__()
self.reward_loss = square_dist
# If False, no n... | 2.1875 | 2 |
orion/modules/active/wolfram.py | isathish/ai_opesource | 0 | 5019 | <reponame>isathish/ai_opesource
"""
Handles most general questions (including math!)
Requires:
- WolframAlpha API key
Usage Examples:
- "How tall is Mount Everest?"
- "What is the derivative of y = 2x?"
"""
import wolframalpha
from orion.classes.module import Module
from orion.classes.task... | 2.65625 | 3 |
polymatch/matchers/standard.py | linuxdaemon/poly-match | 0 | 5020 | <reponame>linuxdaemon/poly-match
from polymatch import PolymorphicMatcher
class ExactMatcher(PolymorphicMatcher):
def compile_pattern(self, raw_pattern):
return raw_pattern
def compile_pattern_cs(self, raw_pattern):
return raw_pattern
def compile_pattern_ci(self, raw_pattern):
re... | 2.90625 | 3 |
djcorsche/settings_default.py | carthage-college/django-djcorsche | 0 | 5021 | <reponame>carthage-college/django-djcorsche
"""
Django settings for project.
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
# Debug
#DEBUG = False
DEBUG = True
TEMPLATE_DEBUG = DEBUG
INFORMIX_DEBUG = "debug"
ADMINS = (
('', ''),
)
MANAGERS = ADMINS
SECRET_KEY = ''
ALLOWED_H... | 2.046875 | 2 |
records/12-09/ffff.py | AaronYang2333/CSCI_570 | 36 | 5022 | <filename>records/12-09/ffff.py<gh_stars>10-100
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__date__ = '12/9/2020 4:18 PM'
from abc import abstractmethod
class Product(object):
@abstractmethod
def setMsg(self, msg="default info"):
self.msg = msg
@abstractmethod
def info(self):
print... | 3.40625 | 3 |
tests/test_users.py | fastapi-users/fastapi-users-db-sqlmodel | 18 | 5023 | <gh_stars>10-100
import uuid
from typing import AsyncGenerator
import pytest
from sqlalchemy import exc
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session, SQLModel, create_engine
from fastapi_users_db_sqlmodel import (
NotSetO... | 2.125 | 2 |
copy_reg.py | rtbo/vkdgen | 2 | 5024 | <filename>copy_reg.py
#! /usr/bin/env python3
import os
from os import path
root_dir = path.dirname(path.realpath(__file__))
local_reg_dir = path.join(root_dir, 'registry')
os.makedirs(local_reg_dir, exist_ok=True)
def copy_reg(reg_dir, files):
import shutil
for f in files:
file_path = path.join(reg_... | 2.6875 | 3 |
utils.py | atward424/ASCVD_ML | 1 | 5025 | <gh_stars>1-10
import numpy as np
import pandas as pd
import scipy.stats as st
#from medical_ML import Experiment
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.dummy import DummyClassifier
from sklearn.tree import Deci... | 2.6875 | 3 |
cloud/caasp-admin-setup/lib/caaspadminsetup/utils.py | hwoarang/caasp-container-manifests | 5 | 5026 | <gh_stars>1-10
import json
import logging
import re
import susepubliccloudinfoclient.infoserverrequests as ifsrequest
import yaml
import sys
RELEASE_DATE = re.compile('^.*-v(\d{8})-*.*')
def get_caasp_release_version():
"""Return the version from os-release"""
os_release = open('/etc/os-release', 'r').readli... | 2.359375 | 2 |
tools/Bitcoin Parser/blockchain_parser/tests/test_block.py | simewu/bitcoin_researcher | 1 | 5027 | <filename>tools/Bitcoin Parser/blockchain_parser/tests/test_block.py
# Copyright (C) 2015-2016 The bitcoin-blockchain-parser developers
#
# This file is part of bitcoin-blockchain-parser.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of b... | 2.25 | 2 |
genegenie/admin/__init__.py | genegeniebio/genegenie-admin | 0 | 5028 | '''
DNA++ (c) DNA++ 2017
All rights reserved.
@author: neilswainston
'''
| 1.085938 | 1 |
tests/conftest.py | pkavousi/similar-users | 0 | 5029 | import os
import pandas as pd
import pytest
from user_similarity_model.config.core import DATASET_DIR, config
@pytest.fixture()
def sample_local_data():
"""AI is creating summary for sample_local_data
Returns:
[Dict]: This function returns a dictionary with CSV files which
in dataset folder... | 2.421875 | 2 |
weather/apps.py | chrisjen83/rfb_weather_obs | 1 | 5030 | from django.apps import AppConfig
import logging
logger = logging.getLogger(__name__)
class WeatherConfig(AppConfig):
name = 'weather'
def ready(self):
from forecastUpdater import updater
updater.start()
| 1.976563 | 2 |
projects/django-filer/test.py | fleimgruber/python | 25 | 5031 | import filer
import tests
| 1.039063 | 1 |
examples/plots/plot_pass_network.py | DymondFormation/mplsoccer | 0 | 5032 | <reponame>DymondFormation/mplsoccer<filename>examples/plots/plot_pass_network.py
"""
============
Pass Network
============
This example shows how to plot passes between players in a set formation.
"""
import pandas as pd
from mplsoccer.pitch import Pitch
from matplotlib.colors import to_rgba
import numpy as np
from ... | 3.078125 | 3 |
jsfiddle_factory/__init__.py | andrewp-as-is/jsfiddle-factory.py | 0 | 5033 | <filename>jsfiddle_factory/__init__.py
__all__ = ['Factory']
import jsfiddle_build
import jsfiddle_github
import jsfiddle_generator
import jsfiddle_readme_generator
import getdirs
import getfiles
import os
import popd
import yaml
@popd.popd
def _build(path):
os.chdir(path)
jsfiddle_build.Build().save("build... | 2.34375 | 2 |
spellnn/train.py | MartinXPN/SpellNN | 0 | 5034 | import logging
import os
from datetime import datetime
from inspect import signature, Parameter
from pathlib import Path
from pprint import pprint
from textwrap import dedent
from typing import Optional, Union
import fire
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, Te... | 2.15625 | 2 |
flax/core/frozen_dict.py | juliuskunze/flax | 0 | 5035 | <filename>flax/core/frozen_dict.py
# Copyright 2020 The Flax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 2.421875 | 2 |
pybb/middleware.py | grigi/pybbm | 0 | 5036 | <reponame>grigi/pybbm
# -*- coding: utf-8 -*-
from django.utils import translation
from django.db.models import ObjectDoesNotExist
from pybb import util
from pybb.signals import user_saved
class PybbMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
t... | 2.15625 | 2 |
streetlite/common/constants.py | s0h3ck/streetlite | 0 | 5037 | from enum import Enum
class CustomEnum(Enum):
@classmethod
def has_value(cls, value):
return any(value == item.value for item in cls)
@classmethod
def from_value(cls, value):
found_element = None
if cls.has_value(value):
found_element = cls(value)
retu... | 3.328125 | 3 |
day5.py | achien/advent-of-code-2021 | 0 | 5038 | import fileinput
counts = {}
for line in fileinput.input():
line = line.strip()
p1, p2 = line.split('>')
p1 = p1[:-2]
x1, y1 = p1.split(',')
x1 = int(x1)
y1 = int(y1)
p2 = p2[1:]
x2, y2 = p2.split(',')
x2 = int(x2)
y2 = int(y2)
if x1 == x2:
dx = 0
elif x1 > x2:... | 3.140625 | 3 |
meditation_example.py | sodapopinsky/dfk | 90 | 5039 | import logging
from web3 import Web3
import sys
import time
import meditation.meditation as meditation
if __name__ == "__main__":
log_format = '%(asctime)s|%(name)s|%(levelname)s: %(message)s'
logger = logging.getLogger("DFK-meditation")
logger.setLevel(logging.DEBUG)
logging.basicConfig(level=loggin... | 2.03125 | 2 |
python/johnstarich/interval.py | JohnStarich/dotfiles | 3 | 5040 | <reponame>JohnStarich/dotfiles
import time
class Interval(object):
def __init__(self, delay_time: int):
self.delay_time = delay_time
self.current_time = 0
@staticmethod
def now():
return time.gmtime().tm_sec
def should_run(self) -> bool:
if self.current_time == 0:
... | 3.125 | 3 |
servers/python/coweb/bot/wrapper/object.py | opencoweb/coweb | 83 | 5041 | <filename>servers/python/coweb/bot/wrapper/object.py
'''
Copyright (c) The Dojo Foundation 2011. All Rights Reserved.
Copyright (c) IBM Corporation 2008, 2011. All Rights Reserved.
'''
# tornado
import tornado.ioloop
# std lib
import logging
import time
import weakref
import functools
# coweb
from .base import BotWrapp... | 1.648438 | 2 |
battle_tut5.py | lankotiAditya/RPG_battle_main | 22 | 5042 | import pygame
import random
pygame.init()
clock = pygame.time.Clock()
fps = 60
#game window
bottom_panel = 150
screen_width = 800
screen_height = 400 + bottom_panel
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Battle')
#define game variables
current_fighter = 1
total... | 3.265625 | 3 |
curso_em_video/0087a.py | marinaoliveira96/python-exercises | 0 | 5043 | <reponame>marinaoliveira96/python-exercises
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
soma = col3 = maior = 0
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c] = int(input(f'[{l}][{c}]: '))
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matriz[l][c]:^5}]', end='')
if matri... | 4.09375 | 4 |
custom_components/tapo_control/utils.py | david-kalbermatten/HomeAssistant-Tapo-Control | 0 | 5044 | <gh_stars>0
import onvif
import os
import asyncio
import urllib.parse
from onvif import ONVIFCamera
from pytapo import Tapo
from .const import ENABLE_MOTION_SENSOR, DOMAIN, LOGGER, CLOUD_PASSWORD
from homeassistant.const import CONF_IP_ADDRESS, CONF_USERNAME, CONF_PASSWORD
from homeassistant.components.onvif.event impo... | 2.203125 | 2 |
camd3/infrastructure/component/tests/test_uidattr.py | mamrhein/CAmD3 | 0 | 5045 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Name: test_uidattr
# Purpose: Test driver for module 'uidattr'
#
# Author: <NAME> (<EMAIL>)
#
# Copyright: (c) 2018 <NAME>
# -------------------------------------------------... | 2.234375 | 2 |
s.py | tn012604409/HW3_chatRobot | 0 | 5046 | <gh_stars>0
import requests
import time
from bs4 import BeautifulSoup
def get_web_page(url):
resp = requests.get(
url=url,
)
if resp.status_code != 200:
print('Invalid url:', resp.url)
return None
else:
return resp.text
def get_articles(dom):
soup = BeautifulSoup(... | 2.921875 | 3 |
awstin/dynamodb/orm.py | k2bd/awstin | 1 | 5047 | <reponame>k2bd/awstin
import uuid
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import Union
from boto3.dynamodb.conditions import Attr as BotoAttr
from boto3.dynamodb.conditions import Key as BotoKey
from awstin.dynamodb.utils import from_decimal, to_decimal
class NotSet:
... | 2.421875 | 2 |
Losses/__init__.py | SimonTheVillain/ActiveStereoNet | 17 | 5048 | from .supervise import *
def get_losses(name, **kwargs):
name = name.lower()
if name == 'rhloss':
loss = RHLoss(**kwargs)
elif name == 'xtloss':
loss = XTLoss(**kwargs)
else:
raise NotImplementedError('Loss [{:s}] is not supported.'.format(name))
return loss
| 2.171875 | 2 |
model/src/recurrent.py | qkaren/converse_reading_cmr | 87 | 5049 | <filename>model/src/recurrent.py
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from torch.nn.utils.rnn import pack_padded_sequence as pack
from .my_optim import weight_norm as WN
# TODO: use system func to bind ~
RNN_MAP... | 2.453125 | 2 |
kmcsim/sim/events_old.py | vlcekl/kmcpy | 0 | 5050 | #!//anaconda/envs/py36/bin/python
#
# File name: kmc_pld.py
# Date: 2018/08/03 09:07
# Author: <NAME>
#
# Description:
#
import numpy as np
from collections import Counter
class EventTree:
"""
Class maintaining a binary tree for random event type lookup
and arrays for choosing specific even... | 2.875 | 3 |
env/lib/python3.6/site-packages/odf/meta.py | anthowen/duplify | 5,079 | 5051 | # -*- coding: utf-8 -*-
# Copyright (C) 2006-2007 <NAME>, European Environment Agency
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your op... | 1.929688 | 2 |
scripts/my_inference.py | Mr-TalhaIlyas/Scaled-YOLOv4 | 0 | 5052 | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
import torch
torch.rand(10)
import torch.nn as nn
import torch.nn.functional as F
import glob
from tqdm import tqdm, trange
print(torch.cuda.is_available())
print(torch.cuda.get_device_name())
print(torch.cuda.current_device())
device = torch.device('cuda' if torch.cu... | 2.140625 | 2 |
src/tests/unit/fixtures/endpoint_standard/mock_recommendation.py | fslds/carbon-black-cloud-sdk-python | 24 | 5053 | <reponame>fslds/carbon-black-cloud-sdk-python<filename>src/tests/unit/fixtures/endpoint_standard/mock_recommendation.py<gh_stars>10-100
"""Mock responses for recommendations."""
SEARCH_REQ = {
"criteria": {
"policy_type": ['reputation_override'],
"status": ['NEW', 'REJECTED', 'ACCEPTED'],
"... | 1.5625 | 2 |
monasca/microservice/notification_engine.py | TeamZenith/python-monasca | 0 | 5054 | # Copyright 2015 Carnegie Mellon University
#
# Author: <NAME> <<EMAIL>>
#
# 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 require... | 1.789063 | 2 |
dhf_wrapper/base_client.py | Enflow-io/dhf-pay-python | 0 | 5055 | <gh_stars>0
from typing import Optional, Callable
import requests
from requests.auth import AuthBase
from requests.exceptions import RequestException
class BearerAuth(AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['Authorization'] = f'Bearer {self.t... | 2.921875 | 3 |
flametree/utils.py | Edinburgh-Genome-Foundry/Flametree | 165 | 5056 | <gh_stars>100-1000
import os
import shutil
from .ZipFileManager import ZipFileManager
from .DiskFileManager import DiskFileManager
from .Directory import Directory
import string
printable = set(string.printable) - set("\x0b\x0c")
def is_hex(s):
return any(c not in printable for c in s)
def file_tree(target, ... | 3.390625 | 3 |
audio/audio_client.py | artigianitecnologici/marrtino_apps | 0 | 5057 | <reponame>artigianitecnologici/marrtino_apps
import sys
import socket
import time
ip = '127.0.0.1'
port = 9001
if (len(sys.argv)>1):
ip = sys.argv[1]
if (len(sys.argv)>2):
port = int(sys.argv[2])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip,port))
sock.send('bip\n\r')
data = s... | 2.5 | 2 |
qmotor/message/matcher.py | yulinfeng000/qmotor | 0 | 5058 | <filename>qmotor/message/matcher.py
from abc import ABC, abstractmethod
from typing import List
from .common import (
AtCell,
BasicMessage,
GroupMessage,
FriendMessage,
MsgCellType,
MessageType,
PlainCell,
)
from ..utils import is_str_blank, str_contains
class MsgMatcher(ABC):
def msg_... | 2.421875 | 2 |
invert-binary-tree/invert-binary-tree.py | Atri10/Leet-code---Atri_Patel | 1 | 5059 | class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root:
root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
return root
return None | 3.515625 | 4 |
main/admin.py | sinahmr/childf | 0 | 5060 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.contrib.auth.models import Group
from django.utils.translation import ugettext_lazy as _
from main.models import UserInfo, User, Child, Volunteer, Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed, ... | 1.9375 | 2 |
hunting/display/render.py | MoyTW/RL_Arena_Experiment | 0 | 5061 | import tdl
import time
import hunting.constants as c
class Renderer:
def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT):
if main_console is None:
self.main_console = tdl.init(level_display_width, level_display_height, 'From Renderer ... | 2.484375 | 2 |
ideas/models.py | neosergio/hackatrix-api | 1 | 5062 | <gh_stars>1-10
from django.db import models
class Idea(models.Model):
title = models.CharField(max_length=255, unique=True)
description = models.TextField()
author = models.OneToOneField('events.Registrant',
related_name='author_idea',
on... | 2.09375 | 2 |
section2/out/src/data_prep/SlicesDataset.py | ssheikh85/AIHCND_c3_3d_imaging | 0 | 5063 | <reponame>ssheikh85/AIHCND_c3_3d_imaging
"""
Module for Pytorch dataset representations
"""
import torch
from torch.utils.data import Dataset
class SlicesDataset(Dataset):
"""
This class represents an indexable Torch dataset
which could be consumed by the PyTorch DataLoader class
"""
def __init__(... | 3.5 | 4 |
zenslackchat/zendesk_webhooks.py | uktrade/zenslackchat | 2 | 5064 | from zenslackchat.zendesk_base_webhook import BaseWebHook
from zenslackchat.zendesk_email_to_slack import email_from_zendesk
from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk
class CommentsWebHook(BaseWebHook):
"""Handle Zendesk Comment Events.
"""
def handle_event(self, event, slac... | 2.125 | 2 |
Examples/PagesOperations/MovePage.py | groupdocs-merger-cloud/groupdocs-merger-cloud-python-samples | 0 | 5065 | <reponame>groupdocs-merger-cloud/groupdocs-merger-cloud-python-samples
# Import modules
import groupdocs_merger_cloud
from Common import Common
# This example demonstrates how to move document page to a new position
class MovePage:
@classmethod
def Run(cls):
pagesApi = groupdocs_merger_cloud.PagesApi... | 2.5 | 2 |
src/models/predict_model.py | joseluistello/Regression-Analysis-Apple-Data | 0 | 5066 | y_pred=ml.predict(x_test)
print(y_pred)
from sklearn.metrics import r2_score
r2_score(y_test,y_pred)
pred_y_df=pd.DataFrame({'Actual Value':y_test,'Predicted Value':y_pred, 'Difference': y_test-y_pred})
pred_y_df[0:20] | 2.796875 | 3 |
src/models/utils_func.py | Soufiane-Fartit/cars-prices | 0 | 5067 | <reponame>Soufiane-Fartit/cars-prices<filename>src/models/utils_func.py
# -*- coding: utf-8 -*-
""" This module offers util functions to be called and used
in other modules
"""
from datetime import datetime
import os
import json
import pickle
import string
import random
import numpy as np
import pandas as pd
from... | 2.78125 | 3 |
modules/finance.py | KpaBap/palbot | 0 | 5068 | import asyncio
import discord
from discord.ext import commands
import re
import sqlite3
from urllib.parse import quote as uriquote
import html
CURR = ["AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR",
"GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN",
"MYR", "NOK", "NZD", "P... | 2.984375 | 3 |
SG_GetDataForClassifier.py | shubha1593/MovieReviewAnalysis | 7 | 5069 | <reponame>shubha1593/MovieReviewAnalysis<filename>SG_GetDataForClassifier.py<gh_stars>1-10
from SG_GetFeatureMatrix import *
from SG_VectorY import *
featureMatrix = featureMatrixFromReviews()
Y = getYVector()
def getDataForClassifier() :
return featureMatrix, Y | 1.953125 | 2 |
greenbounty/bounties/migrations/0001_initial.py | Carnales/green-bounty | 1 | 5070 | <gh_stars>1-10
# Generated by Django 3.1.4 on 2021-01-17 19:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),... | 1.742188 | 2 |
nova/tests/virt/docker/test_driver.py | osrg/nova | 0 | 5071 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2013 dotCloud, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache... | 1.796875 | 2 |
pyx/tests/test_http.py | l04m33/pyx | 2 | 5072 | import unittest
import unittest.mock as mock
import asyncio
import pyx.http as http
def create_dummy_message():
msg = http.HttpMessage(None)
msg.headers = [
http.HttpHeader('Server', 'Pyx'),
http.HttpHeader('Cookie', 'a'),
http.HttpHeader('Cookie', 'b'),
]
return msg
def crea... | 2.5625 | 3 |
tests/test_webdriver_chrome.py | kidosoft/splinter | 1 | 5073 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import os
import unittest
from splinter import Browser
from .fake_webapp import EXAMPLE_APP
from .base import WebDriverT... | 2.328125 | 2 |
main.py | DuskXi/ArkX | 2 | 5074 | <filename>main.py
import os
import json
from File.file import File
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def fileRead(fileName, encoding='utf-8'):
with open(fileName, encoding=encoding) as f:
return f.read()
def main():
from Automation.distributor import Distributor
from Performance import... | 2.296875 | 2 |
tests/test_simple.py | cprogrammer1994/miniglm | 4 | 5075 | <reponame>cprogrammer1994/miniglm<filename>tests/test_simple.py<gh_stars>1-10
import struct
import numpy as np
import pytest
import miniglm
def test_add_vec_vec():
res = miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8, 1.2))
np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2))
assert type(res) is tuple
def tes... | 2.171875 | 2 |
flaskbb/plugins/news/views.py | konstantin1985/forum | 0 | 5076 | <filename>flaskbb/plugins/news/views.py<gh_stars>0
# -*- coding: utf-8 -*-
from flask import Blueprint, redirect
from flaskbb.utils.helpers import render_template
from .forms import AddForm, DeleteForm
from .models import MyPost
from flaskbb.extensions import db
news = Blueprint("news", __name__, template_folder="tem... | 2.234375 | 2 |
stix_shifter_modules/aws_athena/tests/stix_translation/test_aws_athena_json_to_stix.py | nkhetia31/stix-shifter | 33 | 5077 | from stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator
from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers
from stix_shifter_modules.aws_athena.entry_point import EntryPoint
import unittest
MODULE = "aws_athena"
entry_point = EntryPoint(... | 2.1875 | 2 |
Python Spider/xpath/03 login.py | CodingGorit/Coding-with-Python | 1 | 5078 | <filename>Python Spider/xpath/03 login.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#file: 03 login.py
#@author: Gorit
#@contact: <EMAIL>
#@time: 2020/1/20 12:44
import requests
from lxml import etree
# 封装类,进行学习猿地的登录和订单的获取
class lMonKey():
# 登录请求地址
loginUrl = "https://www.lmonkey.com/login"
# 账户中心地址
o... | 2.96875 | 3 |
src/gui/MultiplayerPlayerInfo.py | fireclawthefox/AnkandoraLight | 3 | 5079 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file was created using the DirectGUI Designer
from direct.gui import DirectGuiGlobals as DGG
from direct.gui.DirectFrame import DirectFrame
from direct.gui.DirectLabel import DirectLabel
from direct.gui.DirectButton import DirectButton
from direct.gui.DirectOptionMenu... | 1.9375 | 2 |
publications/time_mag.py | mkoo21/rss-review-scraper | 0 | 5080 | from . import FROM_FEED_PUBLISHED_TODAY, STRINGIFY
def filter_by_tag(tag, entries):
matches = list(filter(
lambda x: any(list(map(
lambda y: y.term == tag,
x.tags
))),
entries
))
if len(matches) == 0:
return ""
return "<h2>TIME {} - {} result... | 2.78125 | 3 |
2020/21/code.py | irobin591/advent-of-code-2019 | 0 | 5081 | # Advent of Code 2020
# Day 21
# Author: irobin591
import os
import doctest
import re
re_entry = re.compile(r'^([a-z ]+) \(contains ([a-z, ]*)\)$')
with open(os.path.join(os.path.dirname(__file__), "input.txt"), 'r') as input_file:
input_data = input_file.read().strip().split('\n')
def part1(input_data):
"... | 3.515625 | 4 |
tests/test_html_escaping.py | copart/pandoc-mustache | 43 | 5082 | """
Test that escaping characters for HTML is disabled.
"""
import os, subprocess
def test_escape_singlequote(tmpdir):
# Define empty dictionaries
doc = {}
template = {}
# Prepare file names
doc['path'] = tmpdir.join("document.md")
template['path'] = tmpdir.join("template.yaml")
# Prepar... | 2.734375 | 3 |
app.py | iandees/microdata2osm | 1 | 5083 | from flask import Flask, jsonify, request
from w3lib.html import get_base_url
import extruct
import requests
app = Flask(__name__)
def extract_osm_tags(data):
tags = {}
schema_org_type = data.get('@type')
if schema_org_type == 'Restaurant':
tags['amenity'] = 'restaurant'
serves_cuisine... | 2.609375 | 3 |
dags/simple_python_taskflow_api.py | davemasino/airflow101 | 0 | 5084 | """
A simple Python DAG using the Taskflow API.
"""
import logging
import time
from datetime import datetime
from airflow import DAG
from airflow.decorators import task
log = logging.getLogger(__name__)
with DAG(
dag_id='simple_python_taskflow_api',
schedule_interval=None,
start_date=datetime(2021, 1, 1)... | 3.046875 | 3 |
pyunmarked/roylenichols.py | kenkellner/pyunmarked | 0 | 5085 | from . import model
import numpy as np
from scipy import special, stats
class RoyleNicholsModel(model.UnmarkedModel):
def __init__(self, det_formula, abun_formula, data):
self.response = model.Response(data.y)
abun = model.Submodel("Abundance", "abun", abun_formula, np.exp, data.site_covs)
... | 2.296875 | 2 |
proc_chords_xarray.py | pgriewank/ASR_tools | 0 | 5086 | #Contains the functions needed to process both chords and regularized beards
# proc_chords is used for chords
#proc_beard_regularize for generating beards
#proc_pdf saves pdfs of a variable below cloud base
#Both have a large overlap, but I split them in two to keep the one script from getting to confusing.
import nu... | 2.265625 | 2 |
expression-atlas-wf/scripts/dmel_tau_housekeeping.py | jfear/larval_gonad | 1 | 5087 | """D. mel housekeeping genes based on tau.
Uses the intersection of w1118 and orgR to create a list of
D. mel housekeeping genes.
"""
import os
from functools import partial
import pandas as pd
from larval_gonad.io import pickle_load, pickle_dump
def main():
# Load mapping of YOgn to FBgn
annot = pickle_loa... | 2.4375 | 2 |
api-server/server/core/key.py | TK-IBM-Call-for-Code-Challange-2021/call-for-code-challenge-2021 | 75 | 5088 | <filename>api-server/server/core/key.py
"""
Api Key validation
"""
from typing import Optional
from fastapi.security.api_key import APIKeyHeader
from fastapi import HTTPException, Security, Depends
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN
from server.core.security i... | 2.453125 | 2 |
scripts/kconfig-split.py | Osirium/linuxkit | 7,798 | 5089 | <reponame>Osirium/linuxkit<gh_stars>1000+
#!/usr/bin/env python
# This is a slightly modified version of ChromiumOS' splitconfig
# https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig
"""See this page for more details:
http://dev.chromium.org/ch... | 2.40625 | 2 |
src/synapse/azext_synapse/vendored_sdks/azure_synapse/models/livy_statement_output.py | Mannan2812/azure-cli-extensions | 2 | 5090 | <gh_stars>1-10
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Genera... | 2.03125 | 2 |
src/main.py | mafshar/sub-puppo | 1 | 5091 | <reponame>mafshar/sub-puppo<filename>src/main.py
#!/usr/bin/env python
'''
Notes:
- Weak implies weakly supervised learning (4 classes)
- Strong implies strongly (fully) superversied learning (10 classes)
- frame number is set to 22ms (default); that is the "sweet spot" based on dsp literature
- sampli... | 2.109375 | 2 |
plugins/Operations/Crypto/blowfish_encrypt_dialog.py | nmantani/FileInsight-plugins | 120 | 5092 | <filename>plugins/Operations/Crypto/blowfish_encrypt_dialog.py
#
# Blowfish encrypt - Encrypt selected region with Blowfish
#
# Copyright (c) 2019, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condit... | 1.632813 | 2 |
dns/rdtypes/IN/IPSECKEY.py | preo/dnspython | 0 | 5093 | <filename>dns/rdtypes/IN/IPSECKEY.py
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all ... | 2.140625 | 2 |
multistream_select/__init__.py | Projjol/py-multistream-select | 0 | 5094 | __version = '0.1.0'
__all__ = ['MultiStreamSelect', 'hexify']
__author__ = '<NAME> (<EMAIL>)'
__name__ = 'multistream'
from .multistream import MultiStreamSelect
from .utils import hexify
| 1.21875 | 1 |
python/input_reader.py | dagesundholm/DAGE | 3 | 5095 | <gh_stars>1-10
"""---------------------------------------------------------------------------------*
* Copyright (c) 2010-2018 <NAME>, <NAME>, <NAME>, *
* <NAME>, <NAME>, <NAME> *
* *
* ... | 1.375 | 1 |
tests/test_mate_hashes_methods.py | MacHu-GWU/pathlib_mate-project | 9 | 5096 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import pytest
from pathlib_mate.pathlib2 import Path
class TestHashesMethods(object):
def test(self):
p = Path(__file__)
assert len({
p.md5, p.get_partial_md5(nbytes=1 << 20),
p.sha256, p.get_partial_sha256(nbytes=1 << 20),
... | 2.328125 | 2 |
tools/lib/auth.py | shoes22/openpilot | 121 | 5097 | #!/usr/bin/env python3
"""
Usage::
usage: auth.py [-h] [{google,apple,github,jwt}] [jwt]
Login to your comma account
positional arguments:
{google,apple,github,jwt}
jwt
optional arguments:
-h, --help show this help message and exit
Examples::
./auth.py # Log in with google accou... | 2.53125 | 3 |
datedfolder.py | IgorRidanovic/flapi | 3 | 5098 | <gh_stars>1-10
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Create a Baselight folder with current date and time stamp.
You must refresh the Job Manager after running the script.
Copyright (c) 2020 <NAME>, Igor [at] hdhead.com, www.metafide.com
'''
import flapi
from getflapi import getflapi
from datetime import... | 2.703125 | 3 |
elastica/wrappers/callbacks.py | zhidou2/PyElastica | 71 | 5099 | <reponame>zhidou2/PyElastica<gh_stars>10-100
__doc__ = """
CallBacks
-----------
Provides the callBack interface to collect data over time (see `callback_functions.py`).
"""
from elastica.callback_functions import CallBackBaseClass
class CallBacks:
"""
CallBacks class is a wrapper for calling callback funct... | 2.703125 | 3 |