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 |
|---|---|---|---|---|---|---|
spaces/utils.py | jgillick/Spaces | 1 | 27000 | <filename>spaces/utils.py
import re
import os
import uuid
from datetime import date
from django.conf import settings
def normalize_path(path):
"""
Normalizes a path:
* Removes extra and trailing slashes
* Converts special characters to underscore
"""
if path is None:
return ""
... | 2.796875 | 3 |
babyname_parser.py | jongtaeklho/swpp-hw1-jongtaeklho | 0 | 27001 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Modified by <NAME> at SNU Software Platform Lab for
# SWPP fall 2020 lecture.
import sys
i... | 3.71875 | 4 |
tests/test_position_stk_short.py | nwillemse/nctrader | 1 | 27002 | <reponame>nwillemse/nctrader
import unittest
from datetime import datetime
from nctrader.position2 import Position
from nctrader.price_parser import PriceParser
class TestShortRoundTripSPYPosition(unittest.TestCase):
"""
Test a round-trip trade in SPY ETF where the initial
trade is a buy/long of 100 shar... | 3.109375 | 3 |
app/services/bgm_tv/bgm_tv.py | renovate-tests/pol | 5 | 27003 | from typing import Optional
import requests
from app.core import config
from app.services.bgm_tv.model import UserInfo, SubjectWithEps
class BgmApi:
def __init__(self, mirror=False):
self.session = requests.Session()
if mirror:
self.host = "mirror.api.bgm.rin.cat"
self.se... | 2.25 | 2 |
backend_thread.py | HusseinLezzaik/Stock-Market-Prediction | 0 | 27004 | <filename>backend_thread.py
import time
import numpy as np
import yahoo_fin.stock_info as si
from PyQt5.QtCore import QThread, pyqtSignal
from data_processing.download_data import download_data
class GetLivePrice(QThread):
# 产生信号, 用于传输数据和通知UI进行更改
update_data = pyqtSignal(list)
# 从本地读取etf名称
# Haifei: ... | 2.65625 | 3 |
csp_observer/settings.py | flxn/django-csp-observer | 1 | 27005 | <reponame>flxn/django-csp-observer<filename>csp_observer/settings.py<gh_stars>1-10
from django.conf import settings
from .models import StoredConfig
NAMESPACE = getattr(settings, 'CSP_OBSERVER_NAMESPACE' , 'CSPO')
def ns_getattr(object, name, default=None):
return getattr(settings, '_'.join([NAMESPACE, name]), def... | 1.945313 | 2 |
examples/gemini examples/basic_private_api_usage.py | wiqram/robin_stocks | 0 | 27006 | ''' The most basic way to use the Private API. I recommend renaming the file .env
to .env and filling out the gemini api key information. The dotenv package loads the .env (or .env)
file and the os.environ() function reads the values from the file.ß
'''
import os
import robin_stocks.gemini as g
from dotenv import load... | 2.421875 | 2 |
cozens_circles_beams.py | hattfe/Math | 0 | 27007 | <reponame>hattfe/Math<filename>cozens_circles_beams.py
import turtle
t = turtle.Pen()
t.speed(10)
x1 = []
y1 = []
for i in range(0, 36):
t.circle(200,10)
x, y =(t.pos())
x1.append(int(x))
y1.append(int(y))
print(x1, y1)
x11 = x1[0]
y11 = y1[0]
def basagit(node, adım):
t.penup()
t.goto(x... | 3.28125 | 3 |
mysite/stocktrader/models.py | bennett39/stocktrader | 1 | 27008 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator
# Create your models here.
class Profile(models.Model):
""" Extend built-in Django User model with cash v... | 2.59375 | 3 |
sql/mysql_demo.py | garyhu1/first-python | 1 | 27009 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'Mysql 连接数据库'
__author__ = 'garyhu'
import mysql.connector;
# 数据库连接
conn = mysql.connector.connect(user='root',password='****',database='websites');
s = conn.cursor();
s.execute('select * from users where id = %s',(7,))
value = s.fetchall();
print(value);
s.close();... | 2.875 | 3 |
plugins/remind/plugin.py | CrushAndRun/Automata | 0 | 27010 | <gh_stars>0
from twisted.internet import reactor
class RemindPlugin(object):
def remind(self, cardinal, user, channel, msg):
message = msg.split(None, 2)
if len(message) < 3:
cardinal.sendMsg(channel, "Syntax: .remind <minutes> <message>")
return
try:
... | 2.625 | 3 |
kkutil/loader/loader.py | kaka19ace/kkutils | 1 | 27011 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import threading
import logging
class Loader(object):
_config = NotImplemented
_config_cache_map = {}
_lock = threading.RLock()
@classmethod
def set_config(cls, config):
"""
:param config: kkutils.config.Config instan... | 2.328125 | 2 |
bdt2cpp/XGBoostParser.py | bixel/bdt2cpp | 3 | 27012 | import re
from .Node import Node
class XGBoostNode(Node):
FLOAT_REGEX = '[+-]?\d+(\.\d+)?([eE][+-]?\d+)?'
BRANCH_REGEX = re.compile(f'(?P<branch>\d+):\[(?P<feature>\w+)(?P<comp><)(?P<value>{FLOAT_REGEX})\]')
LEAF_REGEX = re.compile(f'(?P<leaf>\d+):leaf=(?P<value>{FLOAT_REGEX})')
FEATURE_REGEX = re.c... | 2.71875 | 3 |
Backend/ChatBot/model.py | paucutrina/RareHacks_Chatbot | 0 | 27013 | <filename>Backend/ChatBot/model.py
import pickle
import json
import random
# NLP stuff
import nltk
# nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
# TensorFlow stuff
import numpy as np
import tflearn
import tensorflow as tf
import os
import time
stemmer = LancasterStemmer()
intents_dict ... | 2.5625 | 3 |
.tmpl/python_scripts/batch_cmd_py/batch_cmd.py | githeim/wh_tmpl | 3 | 27014 | <filename>.tmpl/python_scripts/batch_cmd_py/batch_cmd.py
#!/usr/bin/python3
import subprocess
import os
import sys
import unittest
import enum
import datetime
def Get_Parent_Dir():
return os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
def Get_Current_Dir():
return os.path.abspath(os.path.dirname(__fil... | 2.359375 | 2 |
{{cookiecutter.repo_name}}/src/evaluate.py | nussl/cookiecutter | 0 | 27015 | <filename>{{cookiecutter.repo_name}}/src/evaluate.py
import nussl
import os
import json
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import tqdm
import gin
from .helpers import build_dataset
import logging
@gin.configurable
def evaluate(output_folder, separation_algorithm, eval_class,
... | 2.265625 | 2 |
ballpark/cashflows/admin.py | keyvanm/ballpark | 0 | 27016 | <gh_stars>0
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(GenericOnetimeIncome)
admin.site.register(GenericRecurringIncome)
admin.site.register(GenericOnetimeExpense)
admin.site.register(GenericRecurringExpense)
| 1.34375 | 1 |
client/examples/cycle-cards.py | spoore1/smart-card-removinator | 26 | 27017 | <reponame>spoore1/smart-card-removinator<gh_stars>10-100
#!/usr/bin/env python
from removinator import removinator
import subprocess
# This example cycles through each card slot in the Removinator. Any
# slots that have a card present will then have the certificates on the
# card printed out using the pkcs15-tool ut... | 2.9375 | 3 |
PDFParser/Client.py | NekuHarp/TPScrum1 | 2 | 27018 | <filename>PDFParser/Client.py
# -*- coding: utf-8 -*-
from . import Defs as _D
from .Parser import Parser as _P
class Client:
def __init__(self):
self.id = 4
self.p = _P()
pass
def doXML(self, folder):
_EOUT = 'xml'
print(_EOUT, folder)
def doTXT(self, folder):
... | 2.9375 | 3 |
tree/binary/02.py | zlikun-lang/python-data-structure-and-algorithm | 0 | 27019 | <reponame>zlikun-lang/python-data-structure-and-algorithm
class BinaryTree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert_left(self, data):
if self.left is None:
self.left = BinaryTree(data)
... | 3.9375 | 4 |
tmp/keyword_get.py | mingyuexc/huluxia_woman_meitui | 3 | 27020 | <reponame>mingyuexc/huluxia_woman_meitui<filename>tmp/keyword_get.py
#!/usr/bin/python3
# coding = utf-8
"""
@author:m1n9yu3
@file:keyword_get.py
@time:2021/01/13
"""
from get_data import *
import threading
from urllib import parse
def multi_thread(idlist, path):
"""线程控制 , 一次跑 1000 个线程"""
# for i in range(st... | 2.671875 | 3 |
Proctor_Brad/Assignments/bubble sort.py | webguru001/Python-Django-Web | 5 | 27021 | import random
import time
b = []
for x in range(0,100):
b.append(int(random.random()*10000))
maximum = len(b) - 1
start_time = time.time()
for i in range(0,maximum):
for j in range(0,maximum):
if(b[j] > b[j+1]):
temp = b[j]
b[j] = b[j+1]
b[j+1] = temp
maximum -= ... | 2.984375 | 3 |
app/morocco/authentication.py | troydai/Morocco | 0 | 27022 | import flask_login
from .application import app
from .models import DbUser
login_manager = flask_login.LoginManager() # pylint: disable=invalid-name
login_manager.init_app(app)
login_manager.user_loader(lambda user_id: DbUser.query.filter_by(id=user_id).first())
login_required = flask_login.login_required
@login_ma... | 2.328125 | 2 |
src/pynwb/ndx_icephys_meta/io/icephys.py | oruebel/ndx-icephys-meta | 6 | 27023 | <reponame>oruebel/ndx-icephys-meta
"""
Module with ObjectMapper classes for the icephys-meta Container classes/neurodata_types
"""
from pynwb import register_map
from pynwb.io.file import NWBFileMap
from hdmf.common.io.table import DynamicTableMap
from ndx_icephys_meta.icephys import ICEphysFile, AlignedDynamicTable
... | 1.835938 | 2 |
plugin/AssemblerSPAdes/bin/RunAssembler.py | konradotto/TS | 125 | 27024 | #!/usr/bin/env python
import json
import os
import subprocess
import sys
def fileExistsAndNonEmpty(filename):
if not os.path.exists(filename):
return False
return os.stat(filename).st_size > 0
class AssemblerRunner(object):
def __init__(self, sample_id, sample_seq, bam_file):
with open("st... | 2.296875 | 2 |
log_utils.py | zheng-yanan/hierarchical-deep-generative-models | 1 | 27025 | # -*- coding:utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import logging
def logger_fn(name, filepath, level = logging.DEBUG):
""" Function for creating log manager
Args:
name: name for log manager
filepath: file ... | 2.5625 | 3 |
api/types.py | ElPapi42/test-api | 0 | 27026 | <reponame>ElPapi42/test-api
from bson.objectid import ObjectId, InvalidId
class PydanticObjectId(str):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls, v):
try:
ObjectId(str(v))
except InvalidId:
raise TypeErro... | 2.59375 | 3 |
phr/insteducativa/api/serializers.py | richardqa/django-ex | 0 | 27027 | from drf_extra_fields.geo_fields import PointField
from rest_framework import serializers
from phr.insteducativa.models import InstitucionEducativa
from phr.ubigeo.models import UbigeoDepartamento, UbigeoDistrito, UbigeoProvincia
class InstEducativaSerializer(serializers.ModelSerializer):
ubicacion = PointField(... | 1.96875 | 2 |
python/review_02_list.py | dayoungMM/TIL | 0 | 27028 | ## list
array = [1,2,3,"four","five","six",True]
print(array[:3])
dust = {
'영등포구': 50,
'강남구' : 40
}
## Dictionary
print(dust['영등포구'])
dust2 = dict(abc=50)
print(dust2)
## 랜덤으로 coffee메뉴 3개 뽑기
import random
coffee = ['아아','뜨아','라떼','믹스','핫초코']
coffee_fav=coffee[1:4] #내가 좋아하는 메뉴 일부 출력
print(coffee_fav)
ls... | 3.484375 | 3 |
DetectAESECB.py | styojm/CryptoPal-Challenges | 0 | 27029 | '''
Detect AES in ECB mode
In this file are a bunch of hex-encoded ciphertexts.
One of them has been encrypted with ECB.
Detect it.
Remember that the problem with ECB is that it is stateless and deterministic; the same 16 byte plaintext block will always produce the same 16 byte ciphertext.
Strategy is to separate ... | 3.53125 | 4 |
uam_simulator/orca.py | colineRamee/UAM_simulator_scitech2021 | 1 | 27030 | <filename>uam_simulator/orca.py
import numpy as np
import math
""" Implementation of the ORCA algorithm
Resources: <NAME>, Reciprocal n-body Collision Avoidance,
RVO2 library (C++) https://github.com/snape/RVO2/blob/master/src/Agent.cpp
Pyorca library to see another python implemen... | 3.109375 | 3 |
lib/heuristic_methods/greedy_packing/largest_heat_match_greedy.py | cog-imperial/min_matches_heuristics | 4 | 27031 | <gh_stars>1-10
from time import time
from ...problem_classes.heat_exchange import Heat_Exchange
def largest_heat_match_greedy(inst):
# Initialization of a local copy of the instance
n = inst.n
m = inst.m
k = inst.k
QH = list(inst.QH)
QC = list(inst.QC)
R = list(inst.R)
# Initialization of variables for sto... | 2.90625 | 3 |
cosifer/utils/stats.py | C-nit/cosifer | 7 | 27032 | <gh_stars>1-10
"""Statistics utils."""
import numpy as np
import pandas as pd
from statsmodels.stats import multitest as mt
from .data import scale_graph
def bonferroni_correction(p_values, q_star):
"""
Return indices of pValues that make reject null hypothesis
at given significance level with a Bonferron... | 2.84375 | 3 |
src/dmglib.py | rickmark/dmglib | 0 | 27033 | <reponame>rickmark/dmglib
"""
dmglib is a basic ``hdiutil`` wrapper that simplifies working with dmg images from Python.
The module can be used to attach and detach disk images, to check a disk image's
validity and to query whether disk images are password protected or have a license
agreement included.
"""
import pl... | 2.625 | 3 |
example_app/sqlalchemy/models.py | aalamdev/py-angular-testapp | 0 | 27034 | <filename>example_app/sqlalchemy/models.py
import sqlalchemy as sqa
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
db_name = "aalam_pyangtestapp"
class Owners(Base):
__tablename__ = "owners"
__table_args__ = {'schema': db_name}
id = sqa.Column(sqa.Integer, primary_key=... | 2.828125 | 3 |
UMSLHackRestAPI/api/serializeres.py | trujivan/climate-impact-changes | 1 | 27035 | <filename>UMSLHackRestAPI/api/serializeres.py
from rest_framework import serializers
from .utils import get_ml_predictions
from .models import MLRequest, Prediction
class PredictionSerializer(serializers.ModelSerializer):
class Meta:
model = Prediction
fields = ['year', 'pollution',]
class MLReq... | 2.453125 | 2 |
info/modules/passport/__init__.py | xnzgt/git_flask_news | 0 | 27036 | <reponame>xnzgt/git_flask_news<gh_stars>0
# 创建蓝图接收前端发送数据
from flask import Blueprint
# 设置url_prefix用于与其他蓝图进行区分
passport_blu = Blueprint("passport",__name__,url_prefix="/passport")
from .views import *
| 1.429688 | 1 |
sequential_bake_main.py | Mateusz-Grzelinski/cycles-bake-workaround | 1 | 27037 | <reponame>Mateusz-Grzelinski/cycles-bake-workaround
#!/usr/bin/python
import sys
import argparse
import os
import tempfile
def parse():
parser = argparse.ArgumentParser()
parser.add_argument("file",
help="Path to blend file. File should be previously prepared for baking")
return ... | 2.53125 | 3 |
serve.py | uwmisl/purpledrop-driver | 0 | 27038 |
from gevent import monkey
monkey.patch_all()
import sys
import purpledrop.server as server
from purpledrop.purpledrop import list_purpledrop_devices, PurpleDropDevice, PurpleDropController
devices = list_purpledrop_devices()
if(len(devices) == 0):
print("No PurpleDrop USB device found")
sys.exit(1)
elif len(d... | 3.03125 | 3 |
freiner/storage/redis_cluster.py | djmattyg007/freiner | 0 | 27039 | from typing import Any
from urllib.parse import urlparse
from rediscluster import RedisCluster
from .redis import RedisStorage
class RedisClusterStorage(RedisStorage):
"""
Rate limit storage with redis cluster as backend.
Depends on `redis-py-cluster` library.
"""
@classmethod
def from_uri... | 2.78125 | 3 |
test4/alien_dict_coderpad.py | MrCsabaToth/IK | 0 | 27040 | def alien_order(words):
# Underspecified input 0
if not words:
return []
# Underspecified input 1
if len(words) == 1:
return "".join(sorted(set(list(words[0]))))
nodes = []
adj_list = []
chars = set()
# 1. Take each word pair
for i, word1 in enumerate(words[:-1]):
... | 3.5625 | 4 |
KAMA1ShortOnly/custom_indicators/__init__.py | ysdede/jesse_strategies | 38 | 27041 | <filename>KAMA1ShortOnly/custom_indicators/__init__.py
from .ott import ott
from .var import var
from .rma import rma
| 1.171875 | 1 |
tests/test_invoke.py | avara1986/ardy | 3 | 27042 | <gh_stars>1-10
# coding=utf-8
# python imports
from __future__ import unicode_literals, print_function, absolute_import
import os
import unittest
from ardy.core.invoke import Invoke
TESTS_PATH = os.path.dirname(os.path.abspath(__file__))
class InvokeTest(unittest.TestCase):
EXAMPLE_PROJECT = "myexamplelambdapro... | 2.21875 | 2 |
pysparkbasics/L02_DataFrame/S01_DataStructures/01_RowClassExp.py | pengfei99/PySparkCommonFunc | 0 | 27043 | from pyspark import Row
from pyspark.sql import SparkSession
"""
Row class introduction:
Row class extends the tuple hence it takes variable number of arguments, Row() is used to create the row object.
Once the row object created, we can retrieve the data from Row using index similar to tuple.
Key Points of Row Cla... | 4.25 | 4 |
icon_prometheus_exporter/config.py | ghalwash/icon-prometheus-exporter | 0 | 27044 |
discovery_node_rpc_url='https://ctz.solidwallet.io/api/v3'
request_data = {
"jsonrpc": "2.0",
"id": 1234,
"method": "icx_call",
"params": {
"to": "cx0000000000000000000000000000000000000000",
"dataType": "call",
"data": {
... | 1.367188 | 1 |
web/models.py | rkhozinov/dicease-area | 0 | 27045 | # models.py
from sys import path
from os.path import dirname as dir
path.append(dir(path[0]))
from app import db
class District(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), unique=True)
coordinates = db.Column(db.String(120), nullable=True)
def __init__(s... | 2.75 | 3 |
PJ-X-ACT/train.py | Seth-Park/MultimodalExplanations | 39 | 27046 | <reponame>Seth-Park/MultimodalExplanations<filename>PJ-X-ACT/train.py
import matplotlib
matplotlib.use('Agg')
import os
import sys
import numpy as np
import json
import matplotlib.pyplot as plt
import caffe
from caffe import layers as L
from caffe import params as P
from activity_data_provider_layer import ActivityDa... | 2 | 2 |
disBatch.py | flatironinstitute/disBatch | 21 | 27047 | #!/usr/bin/env python3
import os, sys
dr = os.getenv('DISBATCH_ROOT')
if dr and dr not in sys.path:
sys.path.append(dr)
try:
import disbatch
except:
print(f'disBatch environment is incomplete. Check:\n\tDISBATCH_ROOT {dr!r}.', file=sys.stderr)
sys.exit(1)
dbExec = os.path.join(os.path.dirnam... | 1.859375 | 2 |
cloudflare_exporter/handlers.py | cpaillet/cloudflare-exporter | 0 | 27048 | from aiohttp import web
from prometheus_client import generate_latest
from prometheus_client.core import REGISTRY
def metric_to_text():
return generate_latest(REGISTRY).decode('utf-8')
async def handle_metrics(_request):
return web.Response(text=metric_to_text())
async def handle_health(_request):
he... | 2.34375 | 2 |
Step4/04_reversing_bis.py | Aterwyn/SSTIC2019 | 0 | 27049 | <filename>Step4/04_reversing_bis.py<gh_stars>0
from SM4 import SM4
input_data = "<KEY>"
input_data = "<KEY>"
#input_data = "0000000000000000000000000000000000000000000000000000000000000000"
global input_list
input_list = bytearray.fromhex(input_data)
global data
data = [0]*16
#plain data, written in littl... | 2.515625 | 3 |
util/list_store.py | natduca/ndbg | 5 | 27050 | <gh_stars>1-10
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | 2.203125 | 2 |
blogs/views/feed.py | daaawx/bearblog | 657 | 27051 | from django.http.response import Http404
from django.http import HttpResponse
from blogs.helpers import unmark, clean_text
from blogs.views.blog import resolve_address
from feedgen.feed import FeedGenerator
import mistune
def feed(request):
blog = resolve_address(request)
if not blog:
raise Http404... | 2.15625 | 2 |
src/data_hub/lcd/migrations/0053_alter_collectionfootprint_the_geom.py | TNRIS/api.tnris.org | 6 | 27052 | <reponame>TNRIS/api.tnris.org
# Generated by Django 3.2.5 on 2021-08-10 20:12
import django.contrib.gis.db.models.fields
import django.contrib.gis.geos.collections
import django.contrib.gis.geos.polygon
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('lcd', '005... | 1.539063 | 2 |
utility/timer.py | xlnwel/g2rl | 1 | 27053 | from time import strftime, gmtime, time
from collections import defaultdict
import tensorflow as tf
from utility.aggregator import Aggregator
from utility.display import pwc
def timeit(func, *args, name=None, to_print=True,
return_duration=False, **kwargs):
start_time = gmtime()
start = time()
r... | 2.53125 | 3 |
tests/functional/test_tagged_unions_unknown.py | karim7262/botocore | 1,063 | 27054 | <gh_stars>1000+
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "licen... | 2.234375 | 2 |
pytest_profiler/pytest_profiler.py | emilberwald/pytest_profiler | 0 | 27055 | import io
import multiprocessing
import pathlib
from urllib.parse import quote_plus
import pytest
import yappi
semaphore = multiprocessing.Semaphore(1)
class PytestProfiler:
def __init__(self, outdir):
self.func_stats_summary = io.StringIO()
self.outdir = pathlib.Path(outdir)
def pytest_ses... | 2.15625 | 2 |
codewars/difficulty_level_6kyu/football_yellow_and_red_cards/test_solution_football_yellow_and_red_cards.py | aleattene/python-codewars-challenges | 1 | 27056 | <gh_stars>1-10
""" To start the tests, type from CLI: python test_solution_sum_of_missing_numbers.py """
import unittest
from solution_football_yellow_and_red_cards import men_still_standing
class TestSolution(unittest.TestCase):
def test_simple_cases(self):
self.assertEqual(men_still_standing([]), (11... | 2.96875 | 3 |
iCount/tests/test_externals.py | zhouyu/iCount | 0 | 27057 | <filename>iCount/tests/test_externals.py
# pylint: disable=missing-docstring, protected-access
import warnings
import unittest
import iCount.externals.cutadapt as cutadapt
import iCount.externals.star as star
from iCount.tests.utils import make_fasta_file, make_fastq_file, get_temp_dir, \
get_temp_file_name, mak... | 1.9375 | 2 |
source/auxiliary/other_utilities.py | JoZimmer/ParOptBeam | 1 | 27058 | <filename>source/auxiliary/other_utilities.py
from os.path import sep as os_sep
def get_adjusted_path_string(path_string):
for separator in ['\\\\', '\\', '/', '//']:
path_string = path_string.replace(separator, os_sep)
return path_string[:]
| 2.1875 | 2 |
modules/04/examples/dollar.py | edsu/inst126 | 2 | 27059 | # jaylin
hours = float(input("Enter hours worked: "))
rate = float(input("Enter hourly rate: "))
if (rate >= 15):
pay=(hours* rate)
print("Pay: $", pay)
else:
print("I'm sorry " + str(rate) + " is lower than the minimum wage!")
| 4 | 4 |
Week 1/id_545/LeetCode_26_545.py | theshaodi/algorithm004-05 | 1 | 27060 | <gh_stars>1-10
## 删除排序数组中的重复项
# 方法: 快慢指针 时间:O(n) 空间:O(1)
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
s = 0
for f in range(0, len(nums)):
if nums[f] != nums[s]:
s += 1
nums[s] = nums[f]
return s + 1 | 3.046875 | 3 |
tests/diag/test_ccsd.py | fevangelista/pyWicked | 0 | 27061 | <filename>tests/diag/test_ccsd.py
import wicked as w
def print_comparison(val, val2):
print(f"Result: {val}")
print(f"Test: {val2}")
def compare_expressions(test, ref):
test_expr = w.Expression()
ref_expr = w.Expression()
for s in ref:
ref_expr += w.string_to_expr(s)
for eq in test... | 2.234375 | 2 |
notes/publish.py | simonrus/about | 0 | 27062 | #/bin/python3
## Step1 scan recursively over all files
import os
import re
import pdb
import datetime
path = "./notes"
dest = "_posts"
magic_prefix = "Active-"
def extractModifiedDate(string):
regexp = r"\d+-\d+-\d+T\d+:\d+:\d+.\d+Z"
date_strings_all = re.findall(regexp,string)
date = None
if (len(da... | 2.796875 | 3 |
unittest/test_unittest_runner.py | asisudai/practical_pipeline | 3 | 27063 | #!/usr/bin/env python
import unittest
# import your test modules
import test_unittest_01
import test_unittest_02
import test_unittest_03
import test_unittest_04
if __name__ == '__main__':
# initialize the test suite
loader = unittest.TestLoader()
suite = unittest.TestSuite()
# add tests to the test... | 2.046875 | 2 |
secret_msg(tk).py | weijun-github/some-python-codes | 0 | 27064 | <reponame>weijun-github/some-python-codes
from tkinter import messagebox, simpledialog, Tk
def is_even(number):
return number % 2 == 0
def get_even_letters(message):
even_letters = []
for counter in range(0, len(message)):
if is_even(counter):
even_letters.append(message[counter])
... | 3.8125 | 4 |
class1/backpropagation.py | janewen134/tensorflow_self_improment | 0 | 27065 | <filename>class1/backpropagation.py
import tensorflow as tf
w = tf.Variable(tf.constant(5, dtype=tf.float32)) # set random initial value 5, and make it trainable
lr = 0.2 # learning rate
epoch = 40
for epoch in range(epoch):
with tf.GradientTape() as tape: # "with expression as variable"
loss = tf... | 3.6875 | 4 |
rorow/feusers/apps.py | derhelge/rorow | 0 | 27066 | from django.apps import AppConfig
class FeusersConfig(AppConfig):
name = 'feusers'
| 1.070313 | 1 |
buck/__init__.py | bukzor/buck.pprint | 4 | 27067 | # This is a namespace package. See also:
# http://pythonhosted.org/distribute/setuptools.html#namespace-packages
# http://osdir.com/ml/python.distutils.devel/2006-08/msg00029.html
__import__('pkg_resources').declare_namespace(__name__)
| 1.179688 | 1 |
Python/Difference of times/main.py | drtierney/hyperskill-problems | 5 | 27068 | # put your python code here
def event_time(hours, minutes, seconds):
return (hours * 3600) + (minutes * 60) + seconds
def time_difference(a, b):
return abs(a - b)
hours_1 = int(input())
minutes_1 = int(input())
seconds_1 = int(input())
hours_2 = int(input())
minutes_2 = int(input())
seconds_2 = int(input()... | 3.859375 | 4 |
tools/build_defs/detect_root.bzl | slsyy/rules_foreign_cc | 2 | 27069 | <reponame>slsyy/rules_foreign_cc
# buildifier: disable=module-docstring
# buildifier: disable=function-docstring-header
def detect_root(source):
"""Detects the path to the topmost directory of the 'source' outputs.
To be used with external build systems to point to the source code/tools directories.
Args:
... | 2.296875 | 2 |
getcurrentexplorerfile.py | CailleauThierry/MyPython | 0 | 27070 | #!python3
# from https://stackoverflow.com/questions/21241708/python-get-a-list-of-selected-files-in-explorer-windows-7/52959617#52959617
import win32gui, time
from win32con import PAGE_READWRITE, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE, PROCESS_ALL_ACCESS, WM_GETTEXTLENGTH, WM_GETTEXT
from commctrl import LVS_OWNERDATA, ... | 2.21875 | 2 |
cookiecutter-project/pages/views.py | goldhand/cookiecutter-project | 1 | 27071 | from django.shortcuts import render, render_to_response
from django.core.mail import mail_admins
from django.contrib import messages
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.views.generic.base import TemplateView
from .forms import Conta... | 1.96875 | 2 |
ratelimitbackend/middleware.py | Edraak/django-ratelimit-backend | 95 | 27072 | <reponame>Edraak/django-ratelimit-backend<gh_stars>10-100
from django.http import HttpResponseForbidden
from django.utils.deprecation import MiddlewareMixin
from .exceptions import RateLimitException
class RateLimitMiddleware(MiddlewareMixin):
"""
Handles exceptions thrown by rate-limited login attepmts.
... | 2.25 | 2 |
RNN/alternative_configurations.py | oncebasun/seq2seq-theano | 0 | 27073 | def get_config_cs2en():
config = {}
# Settings which should be given at start time, but are not, for convenience
config['the_task'] = 0
# Settings ----------------------------------------------------------------
config['allTagsSplit'] = 'allTagsSplit/' # can be 'allTagsSplit/', 'POSextra/' or ... | 2.328125 | 2 |
setup.py | Shadofer/dogey | 3 | 27074 | from setuptools import setup
with open('README.md', 'r') as f:
long_description = f.read()
setup(
name = 'dogey',
version = '0.1',
description = 'A pythonic dogehouse API.',
long_description = long_description,
long_description_content_type = 'text/markdown',
author = 'Shadofer#7312',
... | 1.265625 | 1 |
settings/testing.py | skylifewww/artdelo | 0 | 27075 | ALLOWED_HOSTS = ['testserver']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOC... | 1.4375 | 1 |
h1/models/billing.py | hyperonecom/h1-client-python | 0 | 27076 | # coding: utf-8
"""
HyperOne
HyperOne API # noqa: E501
The version of the OpenAPI document: 0.1.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from h1.configuration import Configuration
class Billing(object):
"""NOTE: This class is auto ... | 2.046875 | 2 |
docs/names/examples/gethostbyname.py | ndg63276/twisted | 1 | 27077 | #!/usr/bin/env python
# -*- test-case-name: twisted.names.test.test_examples -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Print the IP address for a given hostname. eg
python gethostbyname.py www.google.com
This script does a host lookup using the default Twisted Names
resolver, ... | 3.71875 | 4 |
consumers/venv/lib/python3.7/site-packages/faust/cli/faust.py | spencerpomme/Public-Transit-Status-with-Apache-Kafka | 0 | 27078 | <reponame>spencerpomme/Public-Transit-Status-with-Apache-Kafka
"""Program ``faust`` (umbrella command)."""
# Note: The command options above are defined in .cli.base.builtin_options
from .agents import agents
from .base import call_command, cli
from .clean_versions import clean_versions
from .completion import complet... | 1.484375 | 1 |
generator.py | cenarturkmen/watercolor-CycleGAN | 9 | 27079 | <reponame>cenarturkmen/watercolor-CycleGAN<filename>generator.py
from model_utils import Upsample, Downsample
from torch import nn
class CycleGAN_Unet_Generator(nn.Module):
def __init__(self, filter=64):
super(CycleGAN_Unet_Generator, self).__init__()
self.downsamples = nn.ModuleList([
... | 2.28125 | 2 |
accelerator/models/ethno_racial_identity.py | masschallenge/django-accelerator | 6 | 27080 | import swapper
from accelerator_abstract.models.base_ethno_racial_identity import (
BaseEthnoRacialIdentity,
)
class EthnoRacialIdentity(BaseEthnoRacialIdentity):
class Meta(BaseEthnoRacialIdentity.Meta):
swappable = swapper.swappable_setting(
BaseEthnoRacialIdentity.Meta.app_label, 'Ethno... | 2.21875 | 2 |
setup.py | HaaLeo/vague-requirements-scripts | 0 | 27081 | <filename>setup.py
# ------------------------------------------------------------------------------------------------------
# Copyright (c) <NAME>. All rights reserved.
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
# -------------------------------------------... | 1.625 | 2 |
src/python/WMCore/WMRuntime/Scripts/__init__.py | khurtado/WMCore | 21 | 27082 | #!/usr/bin/env python
"""
_Scripts_
"""
| 1.007813 | 1 |
combine-json.py | efficient/catbench | 10 | 27083 | #!/usr/bin/python
import argparse;
import os;
import sys;
import json;
def setup_optparse():
parser = argparse.ArgumentParser();
parser.add_argument('--input', '-i', dest='file1',
help='json to append to');
parser.add_argument('--append', '-a', nargs='+', dest='files2',
... | 2.703125 | 3 |
following.py | yoshualukash/insta-crawler | 0 | 27084 | <gh_stars>0
# Get instance
import instaloader
import json
L = instaloader.Instaloader(max_connection_attempts=0)
# Login or load session
username = ''
password = ''
L.login(username, password) # (login)
# Obtain profile metadata
instagram_target = ''
profile = instaloader.Profile.from_username(L.... | 2.59375 | 3 |
ihs/collector/tasks.py | la-mar/ihs-deo | 0 | 27085 | from __future__ import annotations
import logging
from datetime import date, datetime, timedelta
from typing import Dict, Generator, List, Optional, Union, Tuple
import pandas as pd
import metrics
from api.models import ( # noqa
ChangeDeleteLog,
County,
ProductionHorizontal,
ProductionMasterHorizont... | 1.84375 | 2 |
hivprotmut/structures/pdbcuration.py | victor-gil-sepulveda/PhD-HIVProteaseMutation | 0 | 27086 | <reponame>victor-gil-sepulveda/PhD-HIVProteaseMutation
"""
Created on 25/8/2014
@author: victor
"""
import prody
import numpy
class CurationSelections():
LIGAND_SELECTION = "hetero not water not ion"
HEAVY_LIGAND_SELECTION = "hetero and not water and not ion and not hydrogen"
PROTEIN_CHAIN_TEMPLATE = "pr... | 2.890625 | 3 |
Session 3/Dictionaries/Accessing, writing & deleting data.py | Tassneem04Hamdy/AUG-Problem-Solving-For-Bioinformatics-Level-1- | 4 | 27087 | <reponame>Tassneem04Hamdy/AUG-Problem-Solving-For-Bioinformatics-Level-1-
my_dictionary = {
'type': 'Fruits',
'name': 'Apple',
'color': 'Green',
'available': True,
'number': 25
}
print(my_dictionary)
print(my_dictionary['name'])
# searching with wrong key
print(my_dictionary['weight'])
###########... | 3.9375 | 4 |
old/data_handler_VALVE.py | dlaredo/NASA_RUL_-CMAPS- | 27 | 27088 | import numpy as np
import random
import pandas as pd
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import select
from sqlalchemy import and_
from sqlalchemy import between
from sqlalchemy.sql import exists
from sqlalchemy import desc
from datetime import datetime, timezone, timedelta
... | 2.234375 | 2 |
Course 01 - Getting Started with Python/Extra Studies/Basics/ex036.py | marcoshsq/python_practical_exercises | 9 | 27089 | <reponame>marcoshsq/python_practical_exercises<gh_stars>1-10
import math
# Extra Exercise 004
"""Write a program that asks for the radius of a circle, calculates and displays its area."""
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius**2
circumference = 2 * math.pi * radius
print(
... | 4.25 | 4 |
bw_tools/modules/bw_framer/bw_framer.py | ben-wilson-github/bw_tools | 4 | 27090 | from __future__ import annotations
import os
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Dict
from PySide2.QtGui import QIcon, QKeySequence
from bw_tools.common.bw_node import BWNode
from bw_tools.modules.bw_settings.bw_settings import BWModuleSettings
from PySide2.QtWidg... | 1.992188 | 2 |
CodePipeline.py | larroy/codebuild_pipeline_skeleton | 0 | 27091 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Github attached AWS Code Pipeline"""
__author__ = '<NAME>'
__version__ = '0.1'
import boto3
import os
import sys
import subprocess
import logging
from troposphere import Parameter, Ref, Template, iam
from troposphere.iam import Role
from troposphere.s3 import Bucket
... | 1.8125 | 2 |
src/huaytools/_demo/argparse_demo.py | imhuay/studies-gitbook | 100 | 27092 | <reponame>imhuay/studies-gitbook<filename>src/huaytools/_demo/argparse_demo.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Time:
2021-01-18 19:20
Author:
huayang
Subject:
argparse usage demo
References:
https://docs.python.org/zh-cn/3/library/argparse.html#the-add-argument-method
"""
imp... | 3.375 | 3 |
src/test.py | qitar888/ga2016_final_project | 0 | 27093 | import cost_function as cf
import pic
target_image = pic.pic2rgb("../data/img03.jpg", 50, 50)
cf.set_target_image(target_image)
s = "(H 0.73 (V 0.451 (H 0.963 (L color)(L color))(V 0.549 (L color)(L color)))(L color))"
matrix = cf.to_array(s, 50, 50, 1)
#print(matrix)
pic.rgb2pic(matrix, 'LAB', "./master_piece.png")
| 2.421875 | 2 |
vkquick/pretty_view.py | lordralinc/vkquick | 47 | 27094 | import json
import pygments.formatters
import pygments.lexers
def pretty_view(mapping: dict, /) -> str:
"""
Args:
mapping:
Returns:
"""
dumped_mapping = json.dumps(mapping, ensure_ascii=False, indent=4)
pretty_mapping = pygments.highlight(
dumped_mapping,
pygments.lex... | 2.640625 | 3 |
firefox/install.py | lfkeitel/dotfiles | 2 | 27095 | from pathlib import Path
from configparser import ConfigParser
from utils.installer import Installer
from utils.chalk import print_header
from utils.utils import link_file
import utils.platform as platform
MOZILLA_DIR = Path.home().joinpath(".mozilla", "firefox")
SCRIPT_DIR = Path(__file__).parent
class Main(Instal... | 2.3125 | 2 |
Example/wangyi.py | Willshon/Python | 0 | 27096 | # 网易云音乐批量下载
# By Tsing
# Python3.4.4
import requests
import urllib
# 榜单歌曲批量下载
# r = requests.get('http://music.163.com/api/playlist/detail?id=2884035') # 网易原创歌曲榜
# r = requests.get('http://music.163.com/api/playlist/detail?id=19723756') # 云音乐飙升榜
# r = requests.get('http://music.163.com/api/playlist/detai... | 3.203125 | 3 |
cloudkittyclient/v1/info.py | mmariani/python-cloudkittyclient | 0 | 27097 | # -*- coding: utf-8 -*-
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 2.109375 | 2 |
PiCN/Layers/PacketEncodingLayer/BasicPacketEncodingLayer.py | NikolaiRutz/PiCN | 0 | 27098 | """ De- and Encoding Layer, using a predefined Encoder """
import multiprocessing
from PiCN.Layers.PacketEncodingLayer.Encoder import BasicEncoder
from PiCN.Processes import LayerProcess
class BasicPacketEncodingLayer(LayerProcess):
""" De- and Encoding Layer, using a predefined Encoder """
def __init__(sel... | 3 | 3 |
bounce2.py | Yokohama-Miyazawa/bounce_games | 4 | 27099 | from tkinter import *
import random
import time
class Widget(object): # 画面上で動く物の基本となるクラス
def __init__(self, window, size, color, pos, speed=[0, 0]):
self.window = window
self.size = size
self.color = color
self.pos = pos
self.speed = speed
def acty(self): # インスタンスを動... | 3.46875 | 3 |