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 |
|---|---|---|---|---|---|---|
fund.py | JS-WangZhu/Fund | 9 | 32600 | <reponame>JS-WangZhu/Fund<filename>fund.py<gh_stars>1-10
import os
import pickle
import requests
from bs4 import BeautifulSoup
import re
import prettytable as pt
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import warnings
from colorama import init, Fore, Back, Style
warnings.fil... | 2.21875 | 2 |
src/streamexecutors/stream.py | pkch/executors | 1 | 32601 | <reponame>pkch/executors
import time
from queue import Queue, Full, Empty
from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
from concurrent.futures.process import _get_chunks, _process_chunk
from functools import partial
import sys
import contextlib
import threading
import itertools
cla... | 3.3125 | 3 |
src/custom_layers.py | fkong7/HeartFFDNet | 12 | 32602 | <reponame>fkong7/HeartFFDNet<filename>src/custom_layers.py
#Copyright (C) 2021 <NAME>, <NAME>, University of California, Berkeley
#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.... | 2.265625 | 2 |
data_spec_validator/spec/actions.py | travisliu/data-spec-validator | 23 | 32603 | from .defines import MsgLv, UnknownFieldValue, ValidateResult, get_msg_level
from .validators import SpecValidator
def _wrap_error_with_field_info(failure):
if get_msg_level() == MsgLv.VAGUE:
return RuntimeError(f'field: {failure.field} not well-formatted')
if isinstance(failure.value, UnknownFieldVal... | 2.34375 | 2 |
hwtypes/compatibility.py | splhack/hwtypes | 167 | 32604 | import sys
__all__ = ['IntegerTypes', 'StringTypes']
if sys.version_info < (3,):
IntegerTypes = (int, long)
StringTypes = (str, unicode)
long = long
import __builtin__ as builtins
else:
IntegerTypes = (int,)
StringTypes = (str,)
long = int
import builtins
| 1.945313 | 2 |
py_tdlib/constructors/secret_chat.py | Mr-TelegramBot/python-tdlib | 24 | 32605 | <gh_stars>10-100
from ..factory import Type
class secretChat(Type):
id = None # type: "int32"
user_id = None # type: "int32"
state = None # type: "SecretChatState"
is_outbound = None # type: "Bool"
ttl = None # type: "int32"
key_hash = None # type: "bytes"
layer = None # type: "int32"
| 1.90625 | 2 |
paraVerComoFuncionaAlgumasCoisas/sqlite3/fazendoTeste/teste.py | jonasht/pythonEstudos | 0 | 32606 | import PegandoVariavel as v
print(v.get_Pessoas())
print()
for d in v.get_Pessoas():
print(d) | 2.15625 | 2 |
main.py | Abrolhus/animeDlCLI | 0 | 32607 | <reponame>Abrolhus/animeDlCLI<gh_stars>0
import click
from Crypto.Cipher import AES
import base64
from hashlib import md5
import warnings
import requests_cache
import requests
import logging
import subprocess
import tempfile
from anime_downloader.sites import get_anime_class
import util
@click.command()
@click.argum... | 2.296875 | 2 |
file_upload/address/models.py | pkscredy/lat_long | 0 | 32608 | <reponame>pkscredy/lat_long
from __future__ import unicode_literals
from django.db import models
class Document(models.Model):
file_name = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str_... | 2.171875 | 2 |
src/messages/results/base.py | rkulyn/telegram-dutch-taxbot | 2 | 32609 | import abc
from collections import OrderedDict
from .constants import RESULT_KEY_MAP
class ResultMessageBase(abc.ABC):
"""
Result message base class.
"""
@abc.abstractmethod
def get_content(self, custom_data=None):
"""
Get message content.
Args:
custom_data ... | 2.78125 | 3 |
extract_wn_synsets.py | napsternxg/WordNetExperiments | 2 | 32610 | # coding: utf-8
from nltk.corpus import wordnet as wn
all_synsets = set()
for word in wn.words():
for synset in wn.synsets(word):
all_synsets.add(synset)
with open("wordnet_synset_definition.txt", "wb+") as fp:
for synset in all_synsets:
print >> fp, "%s\t%s" % (
synset.name()... | 2.875 | 3 |
week01/test_f.py | wasit7/cn350 | 0 | 32611 | <reponame>wasit7/cn350<gh_stars>0
n=1
def f(x):
print(n)
f(0) | 1.507813 | 2 |
otel_billing/otel_billing.py | rnishtala/otel_billing | 0 | 32612 | """Main module."""
from sqlalchemy import create_engine
import pandas as pd
import collections
import logging
import re
from pprint import pprint
from typing import Sequence
from opentelemetry.metrics import Counter, Metric
from opentelemetry.sdk.metrics.export import (
MetricRecord,
MetricsExporter,
Metr... | 2.46875 | 2 |
broker/service/api/v10.py | bigsea-ufcg/bigsea-manager | 3 | 32613 | # Copyright (c) 2017 UFCG-LSD.
#
# 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 to in writing,... | 1.96875 | 2 |
Unit_B/chapter10_Lists/sampleCode/makeList.py | noynaert/csc184Handouts | 2 | 32614 | # creates a list and prints it
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
# traversing without an index
for day in days:
print(day)
# traversing with an index
for i in range(len(days)):
print(f"Day {i} is {days[i]}")
days[1] = "Lunes"
print("Day[1] is now ... | 4.4375 | 4 |
cellacdc/models/YeaZ/__init__.py | SchmollerLab/Cell_ACDC | 29 | 32615 | try:
import tensorflow
except ModuleNotFoundError:
pkg_name = 'tensorflow'
import os
import sys
import subprocess
from cellacdc import myutils
cancel = myutils.install_package_msg(pkg_name)
if cancel:
raise ModuleNotFoundError(
f'User aborted {pkg_name} installation'
... | 2.25 | 2 |
demos/shortify/shortify/utils.py | Ixyk-Wolf/aiohttp-demos | 649 | 32616 | import aioredis
import trafaret as t
import yaml
from aiohttp import web
CONFIG_TRAFARET = t.Dict(
{
t.Key('redis'): t.Dict(
{
'port': t.Int(),
'host': t.String(),
'db': t.Int(),
'minsize': t.Int(),
'maxsize': t.In... | 2.34375 | 2 |
anonymizers/location_anonymizer.py | zacharywilkins/anonymizac | 0 | 32617 | from anonymizers.base_anonymizer import Anonymizer
class LocationAnonymizer(Anonymizer):
anonymization_type = "location"
location_prepositions = ["in", "at"]
def __init__(self):
self.initialize_spacy_model()
def is_location(self, index: int) -> bool:
if self.parsed_user_input[index ... | 3.078125 | 3 |
Chapter05/python/init_data.py | iamssxn/PacktPublishingb | 18 | 32618 | <reponame>iamssxn/PacktPublishingb
from pymongo import MongoClient
import json
class InitData:
def __init__(self):
self.client = MongoClient('localhost', 27017, w='majority')
self.db = self.client.mongo_bank
self.accounts = self.db.accounts
# drop data from accounts collection ever... | 2.828125 | 3 |
067_MiDaS/01_float32/07_float16_quantization.py | IgiArdiyanto/PINTO_model_zoo | 1,529 | 32619 | ### tensorflow==2.3.1
import tensorflow as tf
# Float16 Quantization - Input/Output=float32
height = 384
width = 384
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
tflite_model = converter.c... | 2.765625 | 3 |
experiments/e2_multi_directional_model_comparison/file_naming/rules/single_target_tree_rule_naming.py | joschout/Multi-Directional-Rule-Set-Learning | 3 | 32620 | import os
from experiments.file_naming.single_target_classifier_indicator import SingleTargetClassifierIndicator
from project_info import project_dir
def get_single_target_tree_rule_dir() -> str:
mcars_dir: str = os.path.join(project_dir,
'models',
... | 2.296875 | 2 |
devconf/ast/mixins/expression.py | everclear72216/ucapi | 0 | 32621 | import ast.value
import ast.qualifier
import ast.mixins.node
import ast.mixins.typed
import ast.mixins.qualified
class LValueExpression(ast.mixins.node.Node, ast.mixins.typed.Typed, ast.mixins.qualified.Qualified):
def __init__(self):
super().__init__()
self.__value: ast.value.Value or None = No... | 2.421875 | 2 |
todo/mail/delivery.py | sweetlearn/django-todo | 1 | 32622 | <gh_stars>1-10
import importlib
def _declare_backend(backend_path):
backend_path = backend_path.split('.')
backend_module_name = '.'.join(backend_path[:-1])
class_name = backend_path[-1]
def backend(*args, headers={}, from_address=None, **kwargs):
def _backend():
backend_module = i... | 2.28125 | 2 |
models.py | 12DReflections/cab_trips | 0 | 32623 | from database import Base
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, DateTime, Float
from sqlalchemy.types import DateTime
from flask import Flask, request, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = ... | 2.78125 | 3 |
census_api/census_query.py | chrispyles/census_api | 0 | 32624 | #####################################
##### Class to Query Census API #####
#####################################
import requests
import json
import pandas as pd
import datascience as ds
from .utils import *
class CensusQuery:
"""Object to query US Census API"""
_url_endings = {
"acs5": "acs/acs5",
"acs1": "ac... | 3.390625 | 3 |
tests/utils.py | mihhail-m/avaandmed-py | 0 | 32625 | <reponame>mihhail-m/avaandmed-py
import json
from pathlib import Path
def load_json(path: Path):
data = None
with open(path.absolute(), encoding='utf-8') as f:
data = json.load(f)
return data
def format_mock_url(url: str, mock_value: str):
return f'{url}/{mock_value}'
| 2.1875 | 2 |
setup.py | ammarsys/pyanywhere-wrapper | 5 | 32626 | <gh_stars>1-10
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="pyaww",
version="0.0.3",
author="ammarsys",
author_email="<EMAIL>",
description="A simple API wrapper around the pythonanywhere's API.",
long_descripti... | 1.648438 | 2 |
development/CAMInterp.py | kohanlee1995/MHCfovea | 4 | 32627 | import os, sys, re, json, random, importlib
import numpy as np
import pandas as pd
from collections import OrderedDict
from tqdm import tqdm
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import logomaker as lm
from venn import venn
from venn import generate_petal_labels, draw_venn
from scipy.s... | 1.71875 | 2 |
projects/imsend/imsend.py | ZJM6658/PythonProject | 1 | 32628 | #!usr/bin/python
# -*- coding: utf-8 -*-
' an im_send project '
# __author__ '<NAME>'
import sys
import mysql.connector #python3不支持
import requests
import json
from os import path, access, R_OK # W_OK for write permission.
#python2默认编码ascii 使用此方法改为utf8
reload(sys)
sys.setdefaultencoding('utf8')
# 流程
# 1.检查传入... | 2.109375 | 2 |
manage.py | g90tony/tonys-perspective | 0 | 32629 | from flask_script import Manager, Server
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db
from app.models import User, Article, Category, Comment, Quote
app = create_app('development')
manager = Manager(app)
migrate= Migrate(app, db)
manager.add_command('db', MigrateCommand)
manager... | 2.109375 | 2 |
setup.py | alvations/mindset | 2 | 32630 | <gh_stars>1-10
from distutils.core import setup
import setuptools
setup(
name = 'mindset',
packages = ['mindset'],
version = '0.0.1',
description = 'Mindset',
author = '',
url = 'https://github.com/alvations/mindset',
keywords = [],
classifiers = [
"Programming Language :: Python :: 3",
"Licens... | 1.140625 | 1 |
cir_project/cirp_user/scripts/camera_user.py | sprkrd/UPC-MAI-CIR | 1 | 32631 | #!/usr/bin/env python
import rospy
from std_msgs.msg import String
from peyetribe import EyeTribe
import time
from cir_user.srv import UserAction, UserActionResponse
TH1 = 1280*(1.0/3)
TH2 = 1280*(2.0/3)
IP = "192.168.101.72"
class CameraUserServer:
def __init__(self):
rospy.init_node("talker")
... | 2.390625 | 2 |
captcha_bypass.py | ruroot/captcha_bypass | 0 | 32632 | <gh_stars>0
import requests
cookie = {'_ga':'GA1.2.1373385590.1498799275','_gid':'GA1.2.867459789.1498799275','_gat':'1','PHPSESSID':'1kr76vh1164sbgeflnngimi321'}
url = 'http://captcha.ringzer0team.com:7421'
headers = {'Authorization':'Basic Y2FwdGNoYTpRSmM5VTZ3eEQ0U0ZUMHU='}
for i in range(1000):
# get captacha
r ... | 2.65625 | 3 |
antlr-python/ChatErrorListener.py | evilkirin/antlr-mega-tutorial | 138 | 32633 | import sys
from antlr4 import *
from ChatParser import ChatParser
from ChatListener import ChatListener
from antlr4.error.ErrorListener import *
import io
class ChatErrorListener(ErrorListener):
def __init__(self, output):
self.output = output
self._symbol = ''
def syntaxError(sel... | 2.3125 | 2 |
home/urls.py | auxfuse/ci-hackathon-app | 11 | 32634 | from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home"),
path("faq/", views.faq, name="faq"),
path("plagiarism_policy/", views.plagiarism_policy,
name="plagiarism_policy"),
path("privacy_policy/", views.privacy_policy, name="privacy_policy"),
path... | 1.757813 | 2 |
ogreyMaterialTool.py | opengd/OgreyTool | 0 | 32635 | import wx
from ogreyPopupMenu import *
from ogreyOgreManagers import *
from ogreyTool import *
class Singleton(type):
def __init__(self, *args):
type.__init__(self, *args)
self._instances = {}
def __call__(self, *args):
if not args in self._instances:
self._instan... | 2.078125 | 2 |
utils/nlp.py | dominikmn/one-million-posts | 0 | 32636 | <reponame>dominikmn/one-million-posts<filename>utils/nlp.py
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
stopwords=stopwords.words('german')
nltk.download('punkt')
from nltk.stem.snowball import SnowballStemmer
import spacy
from spacy_iwnlp import spaCyIWNLP
nlp=spacy.load('de') #You need to... | 2.796875 | 3 |
heat/engine/resources/__init__.py | pshchelo/heat | 0 | 32637 | #
# 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 to in writing, software
# ... | 1.875 | 2 |
research/02_TrafficSignClassification/02_CarNDTrafficSignClassifier/source/path/run.py | LewisCollum/frostAV | 5 | 32638 | import os
from datetime import datetime
directory = "../runs"
current = os.path.join(directory, ".current")
class Run:
def __init__(self, runName):
run = os.path.join(directory, runName)
self.model = os.path.join(run, "model.h5")
self.log = os.path.join(run, "log.csv")
self.accurac... | 2.828125 | 3 |
flask_code/day02_request/12xss.py | haitaoss/flask_study | 0 | 32639 | <reponame>haitaoss/flask_study<gh_stars>0
# coding:utf-8
from flask import Flask, render_template, request
# 创建flask应用
app = Flask(__name__)
# 视图函数
@app.route('/xss', methods=['POST', 'GET'])
def xss():
text = ""
if request.method == 'POST':
text = request.form.get('text')
return render_templa... | 2.34375 | 2 |
mk312/constants.py | bkifft/mk312com | 2 | 32640 | # -*- coding: utf-8 -*-
# Memory addresses
ADDRESS_R15 = 0x400f
ADDRESS_ADC_POWER = 0x4062
ADDRESS_ADC_BATTERY = 0x4063
ADDRESS_LEVELA = 0x4064
ADDRESS_LEVELB = 0x4065
ADDRESS_PUSH_BUTTON = 0x4068
ADDRESS_COMMAND_1 = 0x4070
ADDRESS_COMMAND_2 = 0x4071
ADDRESS_MA_MIN_VALUE = 0x4086
ADDRESS_MA_MAX_VALUE = 0x4087
ADDRESS_... | 1.453125 | 1 |
nerlogparser/grammar/bluegenelog.py | studiawan/nerlogparser | 5 | 32641 | <filename>nerlogparser/grammar/bluegenelog.py
import os
import csv
from pyparsing import Word, alphas, Combine, nums, Regex, ParseException
from collections import OrderedDict
class BlueGeneLog(object):
def __init__(self, dataset):
self.dataset = dataset
self.bluegenelog_grammar = self.__get_blueg... | 2.546875 | 3 |
wagtailcomments/views.py | takeflight/wagtailcomments | 7 | 32642 | <gh_stars>1-10
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from wagtailcomments import registry
from wagtailcomme... | 2.03125 | 2 |
open_mafia_engine/built_in/roleblock.py | open-mafia/open_mafia_engine | 9 | 32643 | <filename>open_mafia_engine/built_in/roleblock.py
from typing import List, Optional
from open_mafia_engine.core.all import (
Ability,
Action,
Actor,
ATBase,
CancelAction,
EPreAction,
Game,
GameObject,
handler,
)
from .auxiliary import TempPhaseAux
class RoleBlockerAux(TempPhaseAu... | 2.359375 | 2 |
covid_data/daily_updates/update_outbreak.py | gunnarsundberg/covid-tracker | 0 | 32644 | <reponame>gunnarsundberg/covid-tracker<filename>covid_data/daily_updates/update_outbreak.py
import os
import io
import math
import requests
from datetime import datetime, date, timedelta
import pandas as pd
from covid_data.models import State, County, Outbreak, OutbreakCumulative
from covid_data.utilities import get_da... | 3.21875 | 3 |
books/PythonAutomate/webscrap/using_bs4.py | zeroam/TIL | 0 | 32645 | import bs4
with open("example.html") as f:
# 텍스트 파일로 부터 BeautifulSoup 객체 생성
soup = bs4.BeautifulSoup(f.read(), "lxml")
print(type(soup)) # <class 'bs4.BeautifulSoup'>
# id가 author인 태그 리스트 조회
elems = soup.select("#author")
print(type(elems)) # <class 'list'>
print(type(elems[0])) # <class 'bs4.element.Tag'... | 3.328125 | 3 |
__init__.py | dl-fmi/bottleneck | 0 | 32646 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 13 11:34:33 2019
@author: manninan
""" | 1.203125 | 1 |
pytorchltr/__init__.py | rjagerman/pytorchltr | 37 | 32647 | <gh_stars>10-100
r"""
.. include::../README.md
:start-line: 1
"""
| 1.039063 | 1 |
ImageNet/lib/validation.py | mhilmiasyrofi/AT_HE | 107 | 32648 | from utils import *
import torch
import sys
import numpy as np
import time
import torchvision
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as datasets
def validate_pgd(val_loader, model, criterion, K, step, configs, logger, save_image=False, HE=False):
... | 2.1875 | 2 |
scripts/merge.py | vsui/hypergraph-k-cut | 2 | 32649 | <gh_stars>1-10
#!/usr/bin/env python3
"""This is a script for making graphs of constant rank instances with varying rank
Usage:
<script> <src_dir> <dest_dir>
Where <src_dir> is a directory with subfolders
```
constant02
constant04
...
```
And each subfolder has a file `data.csv` with the CXY run in it.
This combin... | 2.6875 | 3 |
StationeryBG.py | CharlesW1970/Handright | 1 | 32650 | # coding: utf-8
from PIL import Image, ImageFont
from handright import Template, handwrite
text = """
这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是一段自动生成的笔迹。
这是一段自动生成的笔迹,这是一段自动生成的笔迹。这是一段自动生成的笔迹,这是... | 2.625 | 3 |
api/metadata/views.py | cad106uk/market-access-api | 0 | 32651 | <gh_stars>0
from django.conf import settings
from hawkrest import HawkAuthentication
from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .constants import (
BARRIER_PENDING,
BARRIER_SOURCE,
BarrierStatus,
... | 1.804688 | 2 |
test_memory.py | dbstein/python_examples | 0 | 32652 | import numpy as np
from numexpr_kernel import numexpr_kernel
from numba_kernel import numba_kernel
N = 10000
x = np.random.rand(N)
y = np.random.rand(N)
z = np.random.rand(N)
tau = np.random.rand(N)
r1 = numexpr_kernel(x, y, z, tau)
r1 = numexpr_kernel(x, y, z, tau)
r2 = np.zeros(N, dtype=float)
numba_kernel(x, y, z,... | 2.328125 | 2 |
8kyu/grasshopper_combine_strings.py | nhsz/codewars | 1 | 32653 | <filename>8kyu/grasshopper_combine_strings.py
# http://www.codewars.com/kata/55f73f66d160f1f1db000059/
def combine_names(first_name, last_name):
return "{0} {1}".format(first_name, last_name)
| 2.171875 | 2 |
PG/project/myapp/urls.py | vishalimpinge7696/vishal_pg | 0 | 32654 | <filename>PG/project/myapp/urls.py<gh_stars>0
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: ... | 2.75 | 3 |
full_test_data_svm_rbf.py | HarikrishnanNB/occd_experiments | 0 | 32655 | """
This module give the classification results for test data using SVM with RBF
kernel.
Email: <EMAIL>
Dtd: 2 - August - 2020
Parameters
----------
classification_type : string
DESCRIPTION - classification_type == "binary_class" loads binary classification artificial data.
classification_type == "... | 3.484375 | 3 |
sci_analysis/preferences/preferences.py | cmmorrow/sci-analysis | 17 | 32656 |
class DefaultPreferences(type):
"""The type for Default Preferences that cannot be modified"""
def __setattr__(cls, key, value):
if key == "defaults":
raise AttributeError("Cannot override defaults")
else:
return type.__setattr__(cls, key, value)
def __delattr__(c... | 2.59375 | 3 |
cogs/WelcomeCog.py | tandemdude/DevilDonkey | 1 | 32657 | <reponame>tandemdude/DevilDonkey
# User welcome extension coded by github u/tandemdude
# https://github.com/tandemdude
import discord
import json
from discord.ext import commands
class Welcome(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member)... | 2.703125 | 3 |
configurations.py | KumundzhievMaxim/WearingGlassesClassification | 1 | 32658 | # ------------------------------------------
#
# Program created by <NAME>
#
#
# email: <EMAIL>
# github: https://github.com/KumundzhievMaxim
# -------------------------------------------
BATCH_SIZE = 10
IMG_SIZE = (160, 160)
MODEL_PATH = 'checkpoints/model'
| 1.367188 | 1 |
conditional/models/migrate.py | adamhb123/conditional | 2 | 32659 | from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from conditional import db
from conditional.models import models, old_models as zoo
import flask_migrate
# pylint: skip-file
old_engine = None
zoo_session = None
# Takes in param of SqlAlchemy Database Connection String
def... | 2.234375 | 2 |
ch04/cross_entropy_error.py | sankaku/deep-learning-from-scratch-py | 0 | 32660 | <filename>ch04/cross_entropy_error.py<gh_stars>0
import numpy as np
def cross_entropy_error(y, t):
delta = 1e-7 # to avoid log(0)
return - np.sum(t * np.log(y + delta))
if __name__ == '__main__':
t = np.array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
y1 = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0])
y2 = np... | 2.609375 | 3 |
day-02/part-2/david.py | badouralix/adventofcode-2018 | 31 | 32661 | from tool.runners.python import SubmissionPy
class DavidSubmission(SubmissionPy):
def bucket_key(self, w, i):
return w[:i] + w[i+1:]
def run(self, s):
words = s.split("\n")
n = len(words[0])
buckets = [set() for i in range(n)]
for w in words:
for i in range(... | 2.96875 | 3 |
Plug-ins/PlexSportsAgent.bundle/Contents/Code/Teams/NFL/ProFootballReferenceFranchiseAdapter.py | waldosax/PlexSports | 5 | 32662 | # Pro-Football-Reference.com
# TEAMS
import re, os
import uuid
import json
from datetime import datetime, date, time
from bs4 import BeautifulSoup
import bs4
from Constants import *
from PathUtils import *
from PluginSupport import *
from Serialization import *
from StringUtils import *
import ProFoo... | 2.375 | 2 |
KfoldBERT.py | JamesUOA/K-Fold-CrossValidation | 1 | 32663 | import torch
import numpy as np
import time
import datetime
import random
from Kfold import KFold
from split_data import DataManager
from transformers import BertTokenizer
from transformers import BertTokenizer
from torch.utils.data import TensorDataset, random_split
from torch.utils.data import DataLoader, RandomSamp... | 2.328125 | 2 |
kdc/kdc.py | cesium12/webathena | 0 | 32664 | #!/usr/bin/env python
# pylint: disable=invalid-name
""" Web-based proxy to a Kerberos KDC for Webathena. """
import base64
import json
import os
import select
import socket
import dns.resolver
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.codec.der import encoder as der_encoder
from pyasn1.error im... | 2.265625 | 2 |
dedupsqlfs/db/migrations/m20171103001.py | tabulon-ext/dedupsqlfs | 22 | 32665 | # -*- coding: utf8 -*-
#
# DB migration 001 by 2017-11-03
#
# New statistics for subvolume - root diff in blocks / bytes
#
__author__ = 'sergey'
__NUMBER__ = 20171103001
def run(manager):
"""
:param manager: Database manager
:type manager: dedupsqlfs.db.sqlite.manager.DbManager|dedupsqlfs.db.mysql.manage... | 2.21875 | 2 |
tests/test_keywords.py | VeerendraNathLukkani/pytest_test | 51 | 32666 | import pytest
@pytest.mark.parametrize("cli_options", [
('-k', 'notestdeselect',),
])
def test_autoexecute_yml_keywords_skipped(testdir, cli_options):
yml_file = testdir.makefile(".yml", """
---
markers:
- marker1
- marker2
---
- provider: python
type: assert
expression: "1"
""")
assert yml_fi... | 2.078125 | 2 |
python/find_largest_divisor.py | codevscolor/codevscolor | 6 | 32667 | <gh_stars>1-10
#1
num = int(input("Enter a number : "))
largest_divisor = 0
#2
for i in range(2, num):
#3
if num % i == 0:
#4
largest_divisor = i
#5
print("Largest divisor of {} is {}".format(num,largest_divisor))
| 3.90625 | 4 |
lintcode/0008-rotate-string.py | runzezhang/Data-Structure-and-Algorithm-Notebook | 1 | 32668 | <filename>lintcode/0008-rotate-string.py
# Description
# 中文
# English
# Given a string(Given in the way of char array) and an offset, rotate the string by offset in place. (rotate from left to right)
# offset >= 0
# the length of str >= 0
# Have you met this question in a real interview?
# Example
# Example 1:
# I... | 4.28125 | 4 |
CIFAR10/losses.py | ankanbansal/semi-supervised-learning | 0 | 32669 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import ipdb
import time
# Clustering penalties
class ClusterLoss(torch.nn.Module):
"""
Cluster loss comes from the SuBiC paper and consists of two losses. First is the Mean Entropy
Loss which makes the output to be clos... | 3.015625 | 3 |
roles/monitoring/files/cluster_monitoring_library.py | dubalda/sv-manager | 34 | 32670 | import solana_rpc as rpc
def get_apr_from_rewards(rewards_data):
result = []
if rewards_data is not None:
if 'epochRewards' in rewards_data:
epoch_rewards = rewards_data['epochRewards']
for reward in epoch_rewards:
result.append({
'percent_c... | 2.40625 | 2 |
src/ralph_assets/rest/serializers/models_dc_asssets.py | vi4m/ralph_assets | 0 | 32671 | <filename>src/ralph_assets/rest/serializers/models_dc_asssets.py<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from rest_framework impo... | 2.03125 | 2 |
endochrone/ensemble/random_forest.py | nickwood/endochrone | 2 | 32672 | <reponame>nickwood/endochrone
# -*- coding: utf-8 -*-
import numpy as np
import time
from endochrone import Base
from endochrone.classification import BinaryDecisionTree
__author__ = "nickwood"
__copyright__ = "nickwood"
__license__ = "mit"
class RandomForest(Base):
def __init__(self, n_trees, sample_size=None,... | 2.765625 | 3 |
projects/microphysics/scripts/config.py | jacnugent/fv3net | 5 | 32673 | <reponame>jacnugent/fv3net
BUCKET = "vcm-ml-experiments"
PROJECT = "microphysics-emulation"
| 0.824219 | 1 |
seatsio/events/objectProperties.py | nathanielwarner/seatsio-python | 2 | 32674 | class ObjectProperties:
def __init__(self, object_id, extra_data=None, ticket_type=None, quantity=None):
if extra_data:
self.extraData = extra_data
self.objectId = object_id
if ticket_type:
self.ticketType = ticket_type
if quantity:
self.quantity =... | 2.515625 | 3 |
Leetcode/1096. Brace Expansion II/solution1.py | asanoviskhak/Outtalent | 51 | 32675 | import re
class Solution:
def helper(self, expression: str) -> List[str]:
s = re.search("\{([^}{]+)\}", expression)
if not s: return {expression}
g = s.group(1)
result = set()
for c in g.split(','):
result |= self.helper(expression.replace('{' + g + '}', c, ... | 3.5625 | 4 |
3-longest-substring-without-repeating-characters.py | Iciclelz/leetcode | 0 | 32676 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0:
return 0
m = 1
for _ in range(len(s)):
i = 0
S = set()
for x in range(_, len(s)):
if s[x] not in S:
S.add(s... | 3.125 | 3 |
poem_generator/PoemCallback.py | Aaronsom/poem-generation | 0 | 32677 | from tensorflow.keras.callbacks import Callback
from poem_generator.word_generator import generate_poem
class PoemCallback(Callback):
def __init__(self, poems, seed_length, dictionary, single=True):
super(PoemCallback, self).__init__()
self.poems = poems
self.dictionary = dictionary
... | 2.890625 | 3 |
Inprocessing/Thomas/Python/core/optimizers/linear_shatter.py | maliha93/Fairness-Analysis-Code | 9 | 32678 | <reponame>maliha93/Fairness-Analysis-Code
import numpy as np
from scipy.spatial import ConvexHull
from core.optimizers import SMLAOptimizer
class LinearShatterBFOptimizer(SMLAOptimizer):
def __init__(self, X, buffer_angle=5.0, has_intercept=False, use_chull=True):
self._samplef = self.get_linear_sample... | 2.625 | 3 |
vendor/pyLibrary/env/big_data.py | klahnakoski/auth0-api | 0 | 32679 | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: <NAME> (<EMAIL>)
#
from __future__ import absolute_import, division, unicode_literals
fr... | 2.6875 | 3 |
chapter_10_testing_and_tdd/dependent/test_dependent_mocked_test.py | Tm2197/Python-Architecture-Patterns | 12 | 32680 | from unittest.mock import patch
from dependent import parameter_dependent
@patch('math.sqrt')
def test_negative(mock_sqrt):
assert parameter_dependent(-1) == 0
mock_sqrt.assert_not_called()
@patch('math.sqrt')
def test_zero(mock_sqrt):
mock_sqrt.return_value = 0
assert parameter_dependent(0) == 0
... | 3.25 | 3 |
test_world_rowing/test_dashboard.py | matthewghgriffiths/rowing | 1 | 32681 | <filename>test_world_rowing/test_dashboard.py<gh_stars>1-10
import pytest
from world_rowing import dashboard
def test_dashboard_main():
dashboard.main(block=False)
def test_dashboard_predict():
dash = dashboard.Dashboard.load_last_race()
live_data, intermediates = dash.race_tracker.update_livedata()... | 1.671875 | 2 |
plerr/tests/test_package.py | b2bs-team/pylint-errors | 2 | 32682 | """Tests a package installation on a user OS."""
import pathlib
import subprocess
import unittest
class TestPlErrPackage(unittest.TestCase):
def test_plerr_error_getter(self):
# Given: a command to get a description of a pylint error by an
# error code.
command = ['python3', '-m', 'plerr',... | 2.859375 | 3 |
src/api2db/install/make_lab.py | TristenHarr/api2db | 45 | 32683 | import os
_lab_components = """from api2db.ingest import *
CACHE=True # Caches API data so that only a single API call is made if True
def import_target():
return None
def pre_process():
return None
def data_features():
return None
def post_process():
return None
if __name__ == "__main__":
... | 2.515625 | 3 |
30-39/37. sliceview/sliceview.py | dcragusa/PythonMorsels | 1 | 32684 | <filename>30-39/37. sliceview/sliceview.py<gh_stars>1-10
from collections.abc import Sequence
class SliceView(Sequence):
def __init__(self, sequence, start=None, stop=None, step=None):
self.sequence = sequence
self.range = range(*slice(start, stop, step).indices(len(sequence)))
def __len__(se... | 2.953125 | 3 |
docs/examples/use_cases/video_superres/common/loss_scaler.py | cyyever/DALI | 3,967 | 32685 | <gh_stars>1000+
import torch
class LossScaler:
def __init__(self, scale=1):
self.cur_scale = scale
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
return False
# `overflow... | 2.546875 | 3 |
shop/forms.py | dwx9/test | 1 | 32686 | #-*- coding: utf-8 -*-
"""Forms for the django-shop app."""
from django import forms
from django.conf import settings
from django.forms.models import modelformset_factory
from django.utils.translation import ugettext_lazy as _
from shop.backends_pool import backends_pool
from shop.models.cartmodel import CartItem
from... | 2.453125 | 2 |
conflowgen/tests/posthoc_analyses/test_quay_side_throughput_analysis.py | 1grasse/conflowgen | 5 | 32687 | <gh_stars>1-10
import datetime
import unittest
from conflowgen.domain_models.arrival_information import TruckArrivalInformationForPickup, \
TruckArrivalInformationForDelivery
from conflowgen.domain_models.container import Container
from conflowgen.domain_models.data_types.container_length import ContainerLength
fr... | 2.15625 | 2 |
backend/tests/access/test_access_user_remove.py | fjacob21/mididecweb | 0 | 32688 | from src.access import UserRemoveAccess
from generate_access_data import generate_access_data
def test_remove_user_access():
sessions = generate_access_data()
user = sessions['user'].users.get('user')
useraccess = UserRemoveAccess(sessions['user'], user)
manageraccess = UserRemoveAccess(sessions['mana... | 2.265625 | 2 |
tests/gdb/execute_nacl_manifest_twice.py | kapkic/native_client | 1 | 32689 | <filename>tests/gdb/execute_nacl_manifest_twice.py
# -*- python2 -*-
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from gdb_test import AssertEquals
import gdb_test
def test(gdb):
# The seco... | 2.03125 | 2 |
dev/3_30_2018/UPS_Main.py | npwebste/UPS_Controller | 0 | 32690 | <gh_stars>0
# Universal Power Supply Controller
# USAID Middle East Water Security Initiative
#
# Developed by: <NAME>
# Primary Investigator: <NAME>
#
# Version History (mm_dd_yyyy)
# 1.00 03_24_2018_NW
#
######################################################
# Import Libraries
import Config
import time
import sqlite3... | 2.296875 | 2 |
bioconverters/utils.py | jakelever/biotext | 6 | 32691 | import re
import unicodedata
# Remove empty brackets (that could happen if the contents have been removed already
# e.g. for citation ( [3] [4] ) -> ( ) -> nothing
def remove_brackets_without_words(text: str) -> str:
fixed = re.sub(r"\([\W\s]*\)", " ", text)
fixed = re.sub(r"\[[\W\s]*\]", " ", fixed)
... | 3.265625 | 3 |
pylinx/core.py | raczben/pylinx | 0 | 32692 | #!/usr/bin/env python3
#
# Import built in packages
#
import logging
import platform
import os
import time
import socket
import subprocess
import signal
import psutil
from .util import setup_logger
from .util import PylinxException
import re
# Import 3th party modules:
# - wexpect/pexpect to launch... | 2.0625 | 2 |
b0012_integer_to_roman.py | savarin/algorithms | 1 | 32693 | <reponame>savarin/algorithms
lookup = [
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i"),
]
def to_roman(integer):
#
"""
"""
for decimal, roman in lookup:
if decimal <= integer:
return roman + to_roman(integer - decimal)
return ""
def main():
print... | 3.78125 | 4 |
IAD-Laboratory-Work-1/include/dispatch.py | TolimanStaR/Intelligent-Data-Analysis-Minor | 0 | 32694 | from .service import *
import multiprocessing
import threading
__recognizer = None
def init_session(*args) -> None:
global __recognizer
# __recognizer = LiveSpeech()
# daemon = multiprocessing.Process(target=__recognizer.daemon(), args=(), )
# daemon.start()
# r = threading.Thread(target=shell... | 2.453125 | 2 |
behave_tests/steps/get_events.py | Sindhuja-SRL/back-end | 0 | 32695 | from behave import *
import requests
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
use_step_matcher("re")
@given("that I am a registered host of privilege walk events and exists events on my username")
def step_impl(context):
context.username = "12thMan"
conte... | 2.4375 | 2 |
P20-Stack Abstract Data Type/Stack - Base Converter.py | necrospiritus/Python-Working-Examples | 0 | 32696 | <filename>P20-Stack Abstract Data Type/Stack - Base Converter.py
class Stack:
def __init__(self):
self.items = []
def is_empty(self): # test to see whether the stack is empty.
return self.items == []
def push(self, item): # adds a new item to the top of the stack.
self.items.appe... | 4.0625 | 4 |
model_api/model_training/trigger_ner/model/soft_encoder.py | INK-USC/LEAN-LIFE | 21 | 32697 | """soft_encoder.py: Encoding sentence with LSTM.
It encodes sentence with Bi-LSTM.
After encoding, it uses all tokens for sentence, and extract some parts for trigger.
Written in 2020 by <NAME>.
"""
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn as nn
import torch
from ..uti... | 3 | 3 |
TrajPlot/main.py | CodesDope/python-pro-course-projects | 0 | 32698 | <gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
import math
angle = float(input("Enter angle (degree): "))
velocity = float(input("Enter Velocity (m/s): "))
g = 9.81
cos_theta = math.cos(math.radians(angle))
sin_theta = math.sin(math.radians(angle))
v_x = velocity * cos_theta
v_y = velocity * sin_the... | 3.703125 | 4 |
myscrumy/remiljscrumy/urls.py | mikkeyiv/Django-App | 0 | 32699 | <reponame>mikkeyiv/Django-App<gh_stars>0
from django.urls import include,path
from remiljscrumy import views
app_name = 'remiljscrumy'
urlpatterns = [
path('',views.index,name='index'),
path('<int:goal_id>/', views.move_goal, name = "move_goal"),
path('accounts/', include('django.contri... | 1.570313 | 2 |