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 |
|---|---|---|---|---|---|---|
seventweets/handlers/base.py | sbg/seventweets | 2 | 38600 | from flask import Blueprint, current_app, jsonify
from seventweets.exceptions import error_handler
from seventweets import tweet
base = Blueprint('base', __name__)
@base.route('/')
@error_handler
def index():
original = tweet.count('original')
retweets = tweet.count('retweet')
return jsonify({
'n... | 2.25 | 2 |
rasahub_humhub/humhub.py | tomofu74/rasahub-humhub | 0 | 38601 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
# import rasahub_google_calendar
from time import gmtime, time, strftime
import json
import locale
import logging
import math
import mysql.c... | 2.4375 | 2 |
tf_pose/test.py | Artia-Inspirenet/module-2 | 0 | 38602 | from pycocotools.coco import COCO
import json
with open('person_keypoints_val2017.json') as f:
data = json.load(f)
coco = COCO('person_keypoints_val2017.json')
def search(id):
for annotation in data['annotations']:
if annotation['image_id']==id:
print(annotation)
#print(data... | 2.578125 | 3 |
py/pysparkling/ml/algo.py | gerbenoostra/sparkling-water | 0 | 38603 | <filename>py/pysparkling/ml/algo.py<gh_stars>0
from pyspark import since, keyword_only
from pyspark.ml.param.shared import *
from pyspark.ml.util import JavaMLReadable, JavaMLWritable
from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaTransformer, _jvm
from pyspark.sql import SparkSession
from pysparkling imp... | 2.1875 | 2 |
bonds/users/templatetags/email_extras.py | ghostforpy/bonds-docker | 2 | 38604 | <gh_stars>1-10
from django import template
# from ..models import *
# from bonds.friends.models import UserFriends
# from django.core.exceptions import ObjectDoesNotExist
register = template.Library()
@register.filter(name='return_number_with_sign')
def return_number_with_sign(num):
return "{0:+.2f}".format(floa... | 2.265625 | 2 |
mongox/fields.py | Collector0/mongox | 1 | 38605 | <gh_stars>1-10
import typing
import bson
from pydantic import Field
from pydantic.fields import ModelField as PydanticModelField
__all__ = ["Field", "ObjectId"]
class ObjectId(bson.ObjectId):
"""
Pydantic ObjectId field with validators
"""
@classmethod
def __get_validators__(cls) -> typing.Gene... | 2.453125 | 2 |
cogs/System.py | Naman-Biswajit/Discord-Bot-Perceus | 0 | 38606 | import discord
from discord.ext import commands
class System(commands.Cog):
def __init__(self, perceus):
self.perceus = perceus
@commands.Cog.listener()
async def on_ready(self):
print('Logged in as: ')
print(self.perceus.user.name)
print(self.perceus.user.id)
prin... | 2.484375 | 2 |
command.py | floydawong/tomato_time | 0 | 38607 | import sublime_plugin
from .tomato_time import get_tomato
class CreateTomatoCommand(sublime_plugin.TextCommand):
def show_desc_panel(self):
window = self.view.window()
caption = "Tomato Time Description:"
def on_done(desc):
self.tomato.set_desc(desc)
self.tomato.se... | 2.796875 | 3 |
Pacote Download/Ex043_12_IMC.py | BrunoCruzIglesias/Python | 0 | 38608 | # Cálculo de IMC
print("Vamos calcular seu IMC?")
nome = input("Digite o seu nome: ")
peso = float(input("Olá, {}, agora digite seu peso (em Kg, Ex: 68.9): " .format(nome)))
altura = float(input("Digite sua altura (em m, Ex: 1.80): "))
media = peso / (altura * altura)
print('Seu IMC é: {:.1f}'.format(media))
if media ... | 3.953125 | 4 |
2020/day2/password.py | DanielKillenberger/AdventOfCode | 0 | 38609 | <gh_stars>0
with open("input.txt", "r") as input_file:
input = input_file.read().split("\n")
passwords = list(map(lambda line: [list(map(int, line.split(" ")[0].split("-"))), line.split(" ")[1][0], line.split(" ")[2]], input))
valid = 0
for password in passwords:
count_letter = password[2].count(password[1])... | 3.640625 | 4 |
scripts/gen_cert.py | SUNET/sunet-auth-server | 1 | 38610 | # -*- coding: utf-8 -*-
import argparse
import os
import sys
from base64 import b64encode
from datetime import datetime, timedelta
from cryptography import x509
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives... | 2.234375 | 2 |
tests/apis/test_files.py | ninoseki/uzen | 76 | 38611 | <gh_stars>10-100
import asyncio
import pytest
from fastapi.testclient import TestClient
from app.models.script import Script
@pytest.mark.usefixtures("scripts_setup")
def test_files(client: TestClient, event_loop: asyncio.AbstractEventLoop):
first = event_loop.run_until_complete(Script.all().first())
sha256... | 2.25 | 2 |
src/compas_ui/rhino/forms/info.py | BlockResearchGroup/compas_ui | 0 | 38612 | <filename>src/compas_ui/rhino/forms/info.py
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import Eto.Drawing
import Eto.Forms
import Rhino.UI
import Rhino
class InfoForm(Eto.Forms.Dialog[bool]):
def __init__(self, text, title="Info", width=800, heigh... | 1.929688 | 2 |
python-hello/src/main/python/FizzBuzz.py | demo-pool/languages-all | 0 | 38613 | # -*- coding=utf-8 -*-
import sys
n = int(sys.argv[1])
print(n)
for i in range(1, n + 1):
整除5 = i % 5 == 0
整除3 = i % 3 == 0
if 整除3 and 整除5:
print('FizzBuzz')
elif 整除3:
print("Fizz")
elif 整除5:
print("Buzz")
else:
print(i)
| 3.90625 | 4 |
MaaSSim/driver.py | Farnoud-G/MaaSSim | 0 | 38614 | <reponame>Farnoud-G/MaaSSim
################################################################################
# Module: driver.py
# Description: Driver agent
# <NAME> @ TU Delft, The Netherlands
################################################################################
from enum import Enum
import time
class dr... | 2.875 | 3 |
nomogram.py | maxipi/head-loss-nomogram | 1 | 38615 | from math import pi
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import minimize_scalar
__author__ = "<NAME>"
__credits__ = ["<NAME>"]
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "0.1"
__license__ = "MIT"
# gravitational acceleration
g = 9.81 # m/s²
#... | 2.96875 | 3 |
21. generadores.py | JSNavas/CursoPython2.7 | 0 | 38616 | lista = ["bienvenido "]
ciclo = (c * 4 for c in lista)
print ciclo
print ciclo.next()
for cadena in ciclo:
print cadena
print
n = input("Factorial de: ")
def factorial(n):
i = 1
while n > 1:
i = n * i
yield i
n -= 1
for fact in factorial(n):
print fact
| 3.953125 | 4 |
d2/detr/__init__.py | reubenwenisch/detr_custom | 8,849 | 38617 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .config import add_detr_config
from .detr import Detr
from .dataset_mapper import DetrDatasetMapper
| 0.847656 | 1 |
models/__init__.py | Rozi1/MobileNetV2_CIFAR10 | 0 | 38618 | <gh_stars>0
from .mobilenetv2 import *
| 1.15625 | 1 |
clients/KelsonD/validator.py | KelsonDenton/battleships | 0 | 38619 | <reponame>KelsonDenton/battleships
import math
class MoveValidator:
# class takes coordinates, orient, spaces, and board as constructors
def __init__(self, coord, orient, spaces, board):
self.coordinate = coord
self.orientation = orient
self.space = spaces
self.playerBoard = b... | 3.921875 | 4 |
tests/test_lights.py | kevinlondon/python-room-indicator | 1 | 38620 | <filename>tests/test_lights.py<gh_stars>1-10
import pytest
from mock import patch
from pubsub import pub
from meetingbot import lights
class TestLittleBits:
@patch.object(lights, "change_littlebits_power")
def test_subscription_calls_change_lights(self, littlebits_mock):
pub.subscribe(lights.change_l... | 2.359375 | 2 |
task_2/csv_process.py | meklon/python_geekbrains | 0 | 38621 | <filename>task_2/csv_process.py<gh_stars>0
import os
from os import listdir
from os.path import isfile, join
from pathlib import Path
from typing import Dict
from typing import List
from chardet.universaldetector import UniversalDetector
from pandas import DataFrame
def get_file_list(files_path: str) -> List[str]:
... | 3.0625 | 3 |
bbbs/afisha/tests/test_urls.py | AnnaKPolyakova/bbbs | 2 | 38622 | from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient, APITestCase
from bbbs.afisha.factories import EventFactory
from bbbs.afisha.models import EventParticipant
from bbbs.common.factories import CityFactory
from bbbs.users.factories import UserFactory
from... | 1.984375 | 2 |
scripts/pdb_tofasta.py | XiyuChenFAU/kgs_vibration_entropy | 1 | 38623 | #!/usr/bin/env python2.7
import pdb_structure
import sys
import os.path
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: "+sys.argv[0]+" <pdb-file>")
sys.exit(1)
pdbFile = sys.argv[1]
struc = pdb_structure.PDBFile(pdbFile)
name = os.path.basename(pdbFile).replace("... | 2.140625 | 2 |
normalizing_flows/flows/flow.py | TanguyUrvoy/normalizing-flows | 15 | 38624 | <reponame>TanguyUrvoy/normalizing-flows<gh_stars>10-100
import tensorflow as tf
import tensorflow_probability as tfp
from typing import List
from .transform import Transform, AmortizedTransform
class Flow(AmortizedTransform):
def __init__(self, steps: List[Transform], input_shape=None, name='flow', *args, **kwargs... | 2.546875 | 3 |
src/mainmodulename/plugins/type_one_plugin/__init__.py | portikCoder/basic_python_plugin_project | 1 | 38625 | <reponame>portikCoder/basic_python_plugin_project
# Copyright (c) 2021 portikCoder. All rights reserved.
# See the license text under the root package.
from typing import Type
from mainmodulename.common.plugin_template import Plugin
from mainmodulename.plugins.type_one_plugin.type_one_plugin import TypeOnePlugin
PL... | 2.015625 | 2 |
submissions/Flanagin/myLogic.py | dysomni/aima-python | 0 | 38626 |
music = {
'kb': '''
Instrument(Flute)
Piece(Undine, Reinecke)
Piece(Carmen, Bourne)
(Instrument(x) & Piece(w, c) & Era(c, r)) ==> Program(w)
Era(Reinecke, Romantic)
Era(Bourne, Romantic)
''',
'queries': '''
Program(x)
''',
}
life = {
'kb': '''
Musician(x) ==> Stressed(x)
(Student(x) & Te... | 2.046875 | 2 |
python/stack_of_plates.py | Zetinator/cracking_the_coding_interview | 0 | 38627 | """3.3 Stack of Plates: Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
Therefore, in real life, we would likely start a new stack when the previous stack exceeds some
threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be
composed of several stacks a... | 3.984375 | 4 |
theory/3rd_sprint/django_orm.py | abi83/YaPractice | 3 | 38628 | # Создайте модель мероприятия для сайта-афиши.
# У модели должны быть такие поля:
# Название мероприятия (name), не больше 200 символов
# Дата и время проведения мероприятия (start_at)
# Описание мероприятия (description)
# Адрес электронной почты организатора мероприятия (contact)
# Пользователь, который создал меропр... | 2.140625 | 2 |
ovf2numpy.py | mikrl/mumate | 1 | 38629 | from __future__ import division, print_function
import os
import os.path as fs
import numpy as np
import pandas as pd
import re
### PURPOSE: Takes a directory containing N files of the form mXXXXXX.ovf ###
### and imports them to an N x X x Y x Z x 3 numpy array ###
### where X,Y,Z are the number of cells in x,y... | 2.84375 | 3 |
scrap_jobs/__main__.py | andytan0727/scrap-jobs | 0 | 38630 | <gh_stars>0
"""
Main entry for scrap_jobs module. To be run from console
"""
from scrap_jobs.app import App
from scrap_jobs.scraper.jobstreet import JobStreetScraper
if __name__ == '__main__':
key = input('Please input your search key: ')
location = input(
'Please enter your preferred locati... | 2.65625 | 3 |
fetcher/proxyFetcher.py | PaleNeutron/proxy_pool | 0 | 38631 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: proxyFetcher
Description :
Author : JHao
date: 2016/11/25
-------------------------------------------------
Change Activity:
2016/11/25: proxyFetcher
---------------------------... | 2.359375 | 2 |
python/toy/weather_wechat.py | tagwan/scripts | 0 | 38632 | <reponame>tagwan/scripts
import requests
import json
import datetime
def weather(city):
url = "http://wthrcdn.etouch.cn/weather_mini?city=%s" % city
try:
data = requests.get(url).json()['data']
city = data['city']
ganmao = data['ganmao']
today_weather = data['forecast'][0]
... | 3.078125 | 3 |
tests/test_drive_sample.py | chyroc/pylark | 7 | 38633 | # Code generated by lark_sdk_gen. DO NOT EDIT.
import unittest
import pylark
import pytest
from tests.test_conf import app_all_permission, app_no_permission
from tests.test_helper import mock_get_tenant_access_token_failed
def mock(*args, **kwargs):
raise pylark.PyLarkError(scope="scope", func="func", code=1, ms... | 1.992188 | 2 |
modules/seloger/constants.py | Phyks/Flatisfy | 15 | 38634 | from woob.capabilities.housing import POSTS_TYPES, HOUSE_TYPES
TYPES = {POSTS_TYPES.RENT: 1,
POSTS_TYPES.SALE: 2,
POSTS_TYPES.FURNISHED_RENT: 1,
POSTS_TYPES.VIAGER: 5}
RET = {HOUSE_TYPES.HOUSE: '2',
HOUSE_TYPES.APART: '1',
HOUSE_TYPES.LAND: '4',
HOUSE_TYPES.PARKING: '3'... | 1.320313 | 1 |
syncopy/nwanalysis/granger.py | kajal5888/syncopy | 0 | 38635 | # -*- coding: utf-8 -*-
#
# Implementation of Granger-Geweke causality
#
#
# Builtin/3rd party package imports
import numpy as np
def granger(CSD, Hfunc, Sigma):
"""
Computes the pairwise Granger-Geweke causalities
for all (non-symmetric!) channel combinations
according to Equation 8 in [1]_.
The... | 2.875 | 3 |
sailfish/kernel/__init__.py | macfadyen/sailfish | 9 | 38636 | """
A Python module to facilitate JIT-compiled CPU-GPU agnostic compute kernels.
Kernel libraries are collections of functions written in C code that can be
compiled for CPU execution using a normal C compiler via the CFFI module, or
for GPU execution using a CUDA or ROCm compiler via cupy.
"""
from . import library
... | 1.929688 | 2 |
spring_cloud/commons/client/loadbalancer/supplier/base.py | haribo0915/Spring-Cloud-in-Python | 5 | 38637 | <reponame>haribo0915/Spring-Cloud-in-Python
# -*- coding: utf-8 -*-
"""
Since the load-balancer is responsible for choosing one instance
per service request from a list of instances. We need a ServiceInstanceListSupplier for
each service to decouple the source of the instances from load-balancers.
"""
# standard librar... | 2.921875 | 3 |
Chapter 07/Chap07_Example7.71.py | Anancha/Programming-Techniques-using-Python | 0 | 38638 | myl1 = []
num = int(input("Enter the number of elements: "))
for loop in range(num):
myl1.append(input(f"Enter element at index {loop} : "))
print(myl1)
print(type(myl1))
myt1 = tuple(myl1)
print(myt1)
print(type(myt1))
print("The elements of tuple object are: ")
for loop in myt1:
print(loop) | 4.3125 | 4 |
pytplot/tplot_math/split_vec.py | xnchu/PyTplot | 12 | 38639 | <reponame>xnchu/PyTplot<gh_stars>10-100
import pytplot
import numpy as np
def split_vec(tvar, new_name=None, columns='all', suffix=None):
"""
Splits up 2D data into many 1D tplot variables.
.. note::
This analysis routine assumes the data is no more than 2 dimensions. If there are more, they may ... | 3.234375 | 3 |
packages/artfx/mayaLib/tests/maya_test.py | Soulayrol/Pipeline | 0 | 38640 | import os
import sys
import maya.standalone
import mayaLib
print("=" * 30)
print("This is mayaLib package test")
print("=" * 30)
print("Initializing maya standalone ...")
maya.standalone.initialize(name="python")
# Create engine
maya_engine = mayaLib.MayaEngine()
print("Engine : " + str(maya_engine))
# Get engine p... | 2.46875 | 2 |
22. Generate Parentheses/solution1.py | sunshot/LeetCode | 0 | 38641 | <reponame>sunshot/LeetCode<gh_stars>0
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return ['']
if n == 1:
return ['()']
if n == 2:
result = []
result.append('()()')
result.ap... | 3.140625 | 3 |
examples/openmdao.examples.mdao/openmdao/examples/mdao/sellar_BLISS.py | swryan/OpenMDAO-Framework | 0 | 38642 | """
Solution of the Sellar analytical problem using classic BLISS.
(Bi-Level Integrated System Synthesis)
MDA solved with a Broyden solver.
Global sensitivity calculated by finite-differencing the MDA-coupled
system. The MDA should be replaced with solution of the GSE to fully
match the ori... | 2.59375 | 3 |
simulation/aws-robomaker-sample-application-deepracer/simulation_ws/src/sagemaker_rl_agent/markov/rollout_worker.py | Lacan82/deepracer | 16 | 38643 | <filename>simulation/aws-robomaker-sample-application-deepracer/simulation_ws/src/sagemaker_rl_agent/markov/rollout_worker.py
"""
this rollout worker:
- restores a model from disk
- evaluates a predefined number of episodes
- contributes them to a distributed memory
- exits
"""
import argparse
import json
import math... | 2.109375 | 2 |
odin/bay/vi/losses.py | tirkarthi/odin-ai | 0 | 38644 | <filename>odin/bay/vi/losses.py
import inspect
from typing import Callable, List, Union
import numpy as np
import tensorflow as tf
from odin.bay.helpers import kl_divergence
from tensorflow import Tensor
from tensorflow_probability.python.distributions import Distribution, Normal
from typing_extensions import Literal
... | 2.1875 | 2 |
scraper/settings.py | Red-Pheonix/test_scraping | 0 | 38645 | <filename>scraper/settings.py<gh_stars>0
# Scrapy settings for scraper project
BOT_NAME = 'scraper'
SPIDER_MODULES = ['scraper.spiders']
NEWSPIDER_MODULE = 'scraper.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Googlebot-News'
# Obey robots.txt rules
ROBOTST... | 1.828125 | 2 |
Intern/variables2.py | AalsiCodeMan/Notebook-Ex | 1 | 38646 | <reponame>AalsiCodeMan/Notebook-Ex
## Data Categorisation
'''
1) Whole Number (Ints) - 100, 1000, -450, 999
2) Real Numbers (Floats) - 33.33, 44.01, -1000.033
3) String - "Bangalore", "India", "Raj", "abc123"
4) Boolean - True, False
Variables in python are dynamic in nature
'''
a = 10
print(a)
print(type(a))
a =... | 3.203125 | 3 |
migrations/versions/b0c12eb8ae59_initial_migration.py | edumorris/pomodoro | 1 | 38647 | """Initial Migration
Revision ID: b0c12eb8ae59
Revises: <PASSWORD>
Create Date: 2020-07-15 11:44:46.190193
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### com... | 1.648438 | 2 |
PycharmProjects/PythonExercicios/ex045.py | RodrigoMASRamos/Projects.py | 0 | 38648 | # Exercício Python #045 - GAME: <NAME> e Tesoura
#
# Crie um programa que faça o computador jogar JOKENPÔ com você.
# Aprenda a arrumar as cores nas respostas!
from random import choice
from random import randint # Maneira utilizada na resolução deste exercício
from time import sleep
print('\033[1;31mATENÇÃO! ESTE ... | 4.0625 | 4 |
im2txt/losses.py | wangheda/ImageCaption-UnderFitting | 8 | 38649 | # Copyright 2016 Google 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 2.40625 | 2 |
code_legacy/PostfixLogSummary.py | rhymeswithmogul/starttls-everywhere | 339 | 38650 | <filename>code_legacy/PostfixLogSummary.py
#!/usr/bin/env python
import argparse
import collections
import os
import re
import sys
import time
import Config
TIME_FORMAT = "%b %d %H:%M:%S"
# TODO: There's more to be learned from postfix logs! Here's one sample
# observed during failures from the sender vagrant vm:
... | 1.898438 | 2 |
provarme_dashboard/migrations/0006_auto_20190623_1914.py | arferreira/dropazul_app | 0 | 38651 | # Generated by Django 2.0.5 on 2019-06-23 19:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('provarme_dashboard', '0005_devolution_traffic'),
]
operations = [
migrations.RemoveField(
model_name='devolution',
name='add... | 1.484375 | 1 |
enemy_bot/enemy_bot_level8/burger_war/scripts/dummyArReader.py | kenkenjlab/burger_war_kit | 1 | 38652 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This is dummy ar marker reader node.
mainly for judge server test.
by <NAME>.
'''
from time import sleep
import rospy
from std_msgs.msg import String
if __name__ == "__main__":
rospy.init_node("qr_reader")
# publish qr_val
qr_val_pub = rosp... | 2.046875 | 2 |
morph_net/framework/op_handler_decorator_test.py | nmoezzi/morph-net | 1 | 38653 | <gh_stars>1-10
"""Tests for morph_net.framework.op_regularizer_decorator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from morph_net.framework import conv2d_source_op_handler
from morph_net.framework import generic_regularizers
from morph_net.framewo... | 2.53125 | 3 |
code/chokudai_S002_g_01.py | KoyanagiHitoshi/AtCoder | 3 | 38654 | <filename>code/chokudai_S002_g_01.py
from functools import reduce
from fractions import gcd
n=int(input())
for i in range(n):
a,b=map(int,input().split())
print(gcd(a,b)) | 3.21875 | 3 |
simple_clinic/cli.py | sebanie15/simple_clinic | 0 | 38655 | <reponame>sebanie15/simple_clinic
"""Console script for simple_clinic."""
import sys
import click
class ActiveDoctor(object):
def __init__(self):
self.id = 0
active = click.make_pass_decorator(ActiveDoctor, ensure=True)
@click.group()
@click.option('--id', type=int, help='')
@active
def cli(active, i... | 2.46875 | 2 |
tests/script/test_p2pk.py | meherett/btmhdw | 3 | 38656 | #!/usr/bin/env python3
import json
import os
from pybytom.script import (
get_public_key_hash, get_p2pkh_program, get_p2wpkh_program, get_p2wpkh_address
)
# Test Values
base_path = os.path.dirname(__file__)
file_path = os.path.abspath(os.path.join(base_path, "..", "values.json"))
values = open(file_path, "r")
_ ... | 2.421875 | 2 |
src/GradeHelpUtil.py | blackpan2/PyGrade | 1 | 38657 | <filename>src/GradeHelpUtil.py
import os
import shutil
import subprocess
from Colorify import red, cyan
from DiffJob import prepare, diff, student_output
__author__ = '<NAME>'
def cd_into_assignment(top_level, student, config):
# Tries to move into the assignment folder (as set in the config.ini) within the stud... | 3.109375 | 3 |
src/SigasiProjectCreator/createSigasiProjectFromListOfFiles.py | mderveeuw-si/SigasiProjectCreator | 11 | 38658 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2008-2017 Sigasi
:license: BSD, see LICENSE for more details.
"""
import os
from SigasiProjectCreator.ArgsAndFileParser import ArgsAndFileParser
from SigasiProjectCreator.Creator import SigasiProjectCreator
from SigasiProjectCreator import VhdlVersi... | 2.484375 | 2 |
imagepypelines_image/Resize.py | jmaggio14/imagepypelines_image | 1 | 38659 | <reponame>jmaggio14/imagepypelines_image
from .util import dtype_type_check,\
interpolation_type_check,\
channel_type_check,\
get_cv2_interp_type
from .imports import import_opencv
from .blocks import ImageBlock
cv2 = import_opencv()
import numpy as np
import... | 2.890625 | 3 |
csvorm/relations.py | AppexX/python-csvorm | 2 | 38660 | class RelationType(object):
ONE_TO_MANY = "one_to_many"
ONE_TO_ONE = "one_to_one"
class Relation(object):
def __init__(self, cls):
self.cls = cls
class HasOne(Relation):
def get(self, id):
return self.cls.get(id=id)
class HasMany(Relation):
def get(self, id):
value = []... | 3.390625 | 3 |
benchmarks/compare_with_others.py | ProLoD/icontract-hypothesis | 57 | 38661 | #!/usr/bin/env python3
"""Benchmark icontract against deal when used together with hypothesis."""
import os
import sys
import timeit
from typing import List
import deal
import dpcontracts
import hypothesis
import hypothesis.extra.dpcontracts
import hypothesis.strategies
import icontract
import tabulate
import icontr... | 2.515625 | 3 |
experiments/plot.py | henrytseng/srcnn | 125 | 38662 | from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
results_dir = Path('results')
results_dir.mkdir(exist_ok=True)
# Performance plot
for scale in [3, 4]:
for test_set in ['Set5', 'Set14']:
time = []
psnr = []
model = []
for save_dir in sorted(Path('.').g... | 2.203125 | 2 |
main.py | deepkick/Visualization-of-the-number-of-Covid19-infected-people-by-Python | 0 | 38663 | <reponame>deepkick/Visualization-of-the-number-of-Covid19-infected-people-by-Python
import tkinter
import translate
from translate import translate
def btn_click():
lang = str(translate(txt_1.get()))
txt_2.insert(0, lang)
# 画面作成
tki = tkinter.Tk()
tki.geometry('300x300')
tki.title('翻訳機')
# ラベル
lbl_1 = tki... | 3.515625 | 4 |
tests/commands/test_cloud.py | pm3310/sagify | 3 | 38664 | <gh_stars>1-10
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from click.testing import CliRunner
import sagify
from sagify.config.config import Config
from sagify.__main__ import cli
class TestUploadData(object):
def test_upload_data_happy_case(self):
runner = C... | 2.328125 | 2 |
Matplotlib.py | claw0ed/DataSci | 0 | 38665 | # Matplotlib
# 파이썬 데이터과학 관련 시각화 페키지
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#%matplotlib inline # 주피터 노트북에서 show() 호출없이도
# 그래프를 그릴수 있게 해 줌
# data = np.arange(10)
# plt.plot(data)
# plt.show()
# 산점도 - 100의 표준정규분포 난수 생성
list = []
for i in range(100): # 0 ... | 2.984375 | 3 |
pmaf/sequence/_sequence/_nucleotide.py | mmtechslv/PhyloMAF | 1 | 38666 | <reponame>mmtechslv/PhyloMAF<filename>pmaf/sequence/_sequence/_nucleotide.py
import warnings
warnings.simplefilter("ignore", category=FutureWarning)
from pmaf.internal.io._seq import SequenceIO
from pmaf.sequence._shared import (
validate_seq_mode,
mode_as_str,
mode_as_skbio,
sniff_mode,
)
from pmaf.se... | 2.296875 | 2 |
src/main.py | faheem77/FASTAPI-on-Scrapped-Data | 4 | 38667 | <filename>src/main.py
from fastapi import FastAPI, Response
import events_service as _service
app = FastAPI()
@app.get("/")
async def root():
return {"message": "hello world"}
@app.get("/events")
async def events():
return _service.get_all_events()
@app.get("/events/{month}")
async def events_month(month... | 2.765625 | 3 |
rollservice/tests/test_dice_seq.py | stallmanifold/pnpdr | 0 | 38668 | from django.contrib.auth.models import User
from rollservice.models import DiceSequence
import rest_framework.test as rf_test
import rest_framework.status as status
import rest_framework.reverse as reverse
import hypothesis.extra.django
import hypothesis.strategies as strategies
import unittest
class DiceSeq... | 2.328125 | 2 |
tests/unit/test_metrics.py | chryssa-zrv/UA_COMET | 0 | 38669 | # -*- coding: utf-8 -*-
import unittest
import numpy as np
import torch
from comet.metrics import RegressionReport, WMTKendall
class TestMetrics(unittest.TestCase):
def test_regression_report(self):
report = RegressionReport()
a = np.array([0, 0, 0, 1, 1, 1, 1])
b = np.arange(7)
... | 2.40625 | 2 |
models/edhoc/draftedhoc-20200301/oracle.py | hoheinzollern/EDHOC-Verification | 0 | 38670 | <filename>models/edhoc/draftedhoc-20200301/oracle.py<gh_stars>0
#!/usr/bin/python3
import sys, re
from functools import reduce
DEBUG = False
#DEBUG = True
# Put prios between 0 and 100. Above 100 is for default strategy
MAXNPRIO = 200 # max number of prios, 0 is lowest prio
FALLBACKPRIO = MAXNPRIO # max number ... | 2.484375 | 2 |
examples/models/train_relgan.py | DANISHFAYAZNAJAR/nalp | 18 | 38671 | import tensorflow as tf
from nalp.corpus import TextCorpus
from nalp.datasets import LanguageModelingDataset
from nalp.encoders import IntegerEncoder
from nalp.models import RelGAN
# Creating a character TextCorpus from file
corpus = TextCorpus(from_file='data/text/chapter1_harry.txt', corpus_type='char')
# Creating... | 3.109375 | 3 |
setup.py | thomasms/filecompare | 0 | 38672 | from setuptools import setup
setup(name='filecompare',
version='0.1',
description='A package for comparing text and JSON files.',
url='https://github.com/thomasms/filecompare',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=[
'filecompare',
... | 1.234375 | 1 |
python/testData/keywordCompletion/finallyInExcept.py | jnthn/intellij-community | 2 | 38673 | try:
a = 1
except:
a = 2
fina<caret> | 1.09375 | 1 |
tests/test_text/test_text.py | mateusz-obszanski/my-python-utils | 0 | 38674 | from text import longest_common_substring
from text._utils import suffix_array
import itertools
class HelperTestMixin:
"""
author: Anonta (https://stackoverflow.com/users/5798361/anonta)
source: https://stackoverflow.com/questions/51456472/python-fastest-algorithm-to-get-the-most-common-prefix-out-of-a-li... | 3.203125 | 3 |
201409/3.py | L-LYR/csp-sol | 0 | 38675 | <reponame>L-LYR/csp-sol<gh_stars>0
# Time: 03/18/21
# Author: HammerLi
# Tags: [Simulation]
# Title: 字符串匹配
# Content:
# 给出一个字符串和多行文字,在这些文字中找到字符串出现的那些行。
# 你的程序还需支持大小写敏感选项:当选项打开时,表示同一个字母的大写和小写看作不同的字符;
# 当选项关闭时,表示同一个字母的大写和小写看作相同的字符。
tar = input()
strict = bool(int(input()))
n = int(input())
for i in range(0, n):
... | 3.078125 | 3 |
manage.py | Vanzct/xp | 0 | 38676 | <gh_stars>0
# coding=utf-8
__author__ = 'Van'
import os
import sys
from flask.ext.script import Manager, Shell
# from flask.ext.migrate import Migrate, MigrateCommand
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from app import create_app
mode = os.getenv('APP_CONFIG_MODE') or 'default'
if mode:
m... | 2.390625 | 2 |
dni/mlp.py | DingKe/pytorch_workplace | 184 | 38677 | <gh_stars>100-1000
import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
from torch.autograd import Variable
# Hyper Parameters
input_size = 784
hidden_size = 256
dni_size = 1024
num_classes = 10
num_epochs = 50
batch_size = 500
learning_rate = 1e-3
use_c... | 2.640625 | 3 |
dorkbot_extract_dll.py | dyussekeyev/dorkbot-c2-extractor | 0 | 38678 | <reponame>dyussekeyev/dorkbot-c2-extractor<gh_stars>0
import pefile
import base64
from Crypto.Cipher import ARC4
datas = list()
def get_offset(resource_dir):
if hasattr(resource_dir, 'entries'):
for entry in resource_dir.entries:
if hasattr(entry, 'directory'):
get_of... | 2.15625 | 2 |
train-xception.py | jGsch/kaggle-dfdc | 124 | 38679 | <filename>train-xception.py<gh_stars>100-1000
import os
import csv
import shutil
import random
from PIL import Image
import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import Dataset, DataLoader
import xception_conf as config
from model_def import xception
from augmentation... | 2.453125 | 2 |
katas/beta/identifying_top_users_and_their_corresponding_purchases.py | the-zebulan/CodeWars | 40 | 38680 | <reponame>the-zebulan/CodeWars
from collections import Counter
from itertools import chain
def id_best_users(*args):
best_users = set.intersection(*(set(a) for a in args))
cnt = Counter(chain(*args))
users = {}
for k, v in cnt.iteritems():
if k in best_users:
users.setdefault(v, []... | 2.625 | 3 |
supriya/ugens/LFNoise1.py | deeuu/supriya | 0 | 38681 | <reponame>deeuu/supriya
import collections
from supriya import CalculationRate
from supriya.synthdefs import UGen
class LFNoise1(UGen):
"""
A ramp noise generator.
::
>>> supriya.ugens.LFNoise1.ar()
LFNoise1.ar()
"""
### CLASS VARIABLES ###
__documentation_section__ = "No... | 2.28125 | 2 |
Hackerrank/Max Array Sum/Max Array Sum.py | rahil-1407/Data-Structure-and-Algorithms | 51 | 38682 | """
Given an array of integers, find the subset of non-adjacent elements with the maximum sum.
Calculate the sum of that subset. It is possible that the maximum sum is , the case when all elements are negative.
"""
def maxSubsetSum(arr):
n = len(arr) # n = length of the array
dp = [0]*n # create a dp ... | 4 | 4 |
landlab/components/lake_fill/__init__.py | saraahsimon/landlab | 0 | 38683 | <gh_stars>0
from .lake_fill_barnes import LakeMapperBarnes
__all__ = ["LakeMapperBarnes"]
| 0.980469 | 1 |
corehq/apps/hqadmin/management/commands/static_analysis.py | andyasne/commcare-hq | 471 | 38684 | import os
import re
import subprocess
from collections import Counter
from django.conf import settings
from django.core.management.base import BaseCommand
import datadog
from dimagi.ext.couchdbkit import Document
from corehq.feature_previews import all_previews
from corehq.toggles import all_toggles
class Datadog... | 1.914063 | 2 |
dsample.py | her/dsample | 3 | 38685 | <gh_stars>1-10
import argparse
import cv2
class DSample:
SUPPORTED_FORMATS = (
".bmp",
".dib",
".jpeg",
".jpg",
".jpe",
".jp2",
".png",
".pbm",
".pgm",
".ppm",
".sr",
".ras",
".tif",
".tiff",
)
... | 2.703125 | 3 |
tests/test_times.py | Invarato/sort_in_disk_project | 3 | 38686 | <gh_stars>1-10
# -*- coding: utf-8 -*-
#
# @autor: <NAME>
# @version 1.0
from datetime import datetime
"""
Several tests
"""
count = 20000000
if __name__ == "__main__":
start = datetime.now()
print("[if] start: {}".format(start))
val = True
for _ in range(1, count):
if val:
v =... | 3.296875 | 3 |
backend/src/controllers/util/time_util.py | tmdt-buw/gideon-ts | 0 | 38687 | import datetime
import datetime as dt
import pytz
def current_time():
return dt.datetime.now().strftime("%H:%M:%S")
def time_string_to_js_timestamp(time: datetime) -> int:
# js need * 1000 because of different standards
timezone = pytz.timezone("UTC")
return round(timezone.localize(time).timestamp()... | 3.078125 | 3 |
django_auto_model/tests/utils/test_get_now.py | dipasqualew/django-auto-model | 0 | 38688 | """
Tests for snakelize
module: django_auto_model.utils
"""
import datetime
from django_auto_model.utils import get_now
def test_is_datetime():
"""Should be a datetime instance"""
now = get_now()
assert isinstance(now, datetime.datetime)
def test_value_is_close_to_now():
"""Should be close enough to t... | 3.015625 | 3 |
setup.py | cid-chan/vsutil | 25 | 38689 | from setuptools import setup, find_packages
from setuptools.command.test import test
from distutils.util import convert_path
# We can't import the submodule normally as that would "run" the main module
# code while the setup script is meant to *build* the module.
# Besides preventing a whole possible mess of issues w... | 1.984375 | 2 |
duffel_api/api/booking/seat_maps.py | duffelhq/duffel-api-python | 2 | 38690 | from ...http_client import HttpClient
from ...models import SeatMap
class SeatMapClient(HttpClient):
"""Client to interact with Seat Maps"""
def __init__(self, **kwargs):
self._url = "/air/seat_maps"
super().__init__(**kwargs)
def get(self, offer_id):
"""GET /air/seat_maps"""
... | 2.6875 | 3 |
nicos_mlz/refsans/setups/elements/alphai.py | jkrueger1/nicos | 12 | 38691 | <filename>nicos_mlz/refsans/setups/elements/alphai.py
description = 'Alphai alias device'
group = 'lowlevel'
devices = dict(
alphai = device('nicos.devices.generic.DeviceAlias'),
)
| 1.34375 | 1 |
src/core/migrations/0055_merge_20190305_1616.py | metabolism-of-cities/ARCHIVED-metabolism-of-cities-platform-v3 | 0 | 38692 | <reponame>metabolism-of-cities/ARCHIVED-metabolism-of-cities-platform-v3<filename>src/core/migrations/0055_merge_20190305_1616.py
# Generated by Django 2.1.2 on 2019-03-05 16:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0054_auto_20190305_1613'),
... | 1.078125 | 1 |
afwf_fts_anything/__init__.py | MacHu-GWU/afwf_fts_anything-project | 20 | 38693 | # -*- coding: utf-8 -*-
"""
Full text search workflow for Alfred.
"""
from ._version import __version__
__short_description__ = "Full text search workflow for Alfred."
__license__ = "MIT"
__author__ = "<NAME>"
__author_email__ = "<EMAIL>"
__maintainer__ = "<NAME>"
__maintainer_email__ = "<EMAIL>"
__github_username__... | 0.953125 | 1 |
users/home_work.py | annadokuchaeva2002/python-home-bot | 0 | 38694 | from main import dp
from aiogram import types
from aiogram.dispatcher.filters.builtin import Text
@dp.message_handler(Text(equals="Все задания 🤩"))
async def vse_zadaniya(msg: types.Message):
await msg.answer(text="<b>Ваши задания:</b>\n\nскоро наполню")
@dp.message_handler(Text(equals="Добавить 📝"))
async d... | 2.609375 | 3 |
vcorelib/paths/context.py | vkottler/vcorelib | 1 | 38695 | <reponame>vkottler/vcorelib
"""
A module for context managers related to file-system paths.
"""
# built-in
from contextlib import contextmanager
from os import chdir as _chdir
from pathlib import Path as _Path
from typing import Iterator as _Iterator
# internal
from vcorelib.paths import Pathlike as _Pathlike
from vc... | 2.578125 | 3 |
tf.py | thuyduongtt/region_based_active_learning | 0 | 38696 | <filename>tf.py
def test_tf():
import tensorflow as tf
from utils import list_devices
list_devices()
gpu_available = tf.test.is_gpu_available()
print('GPU available:', gpu_available)
with tf.Session(config=tf.ConfigProto(log_device_placement=True)).as_default() as sess:
print('Session ... | 2.515625 | 3 |
smartmirror/authorization.py | not4juu/SmartMirror | 0 | 38697 | <reponame>not4juu/SmartMirror<filename>smartmirror/authorization.py
import cv2
import os
import sys
import pickle
import face_recognition
from threading import Thread
from smartmirror.Logger import Logger
PATH = os.path.dirname(os.path.realpath(__file__))
if sys.platform != 'linux':
PATH = PATH.replace("\\", '/')
... | 2.515625 | 3 |
xlsx2html/core.py | waldobeest/xlsx2html | 0 | 38698 | <filename>xlsx2html/core.py<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import openpyxl
import six
from openpyxl.styles.colors import COLOR_INDEX, aRGB_REGEX
from xlsx2html.format import format_cell
DEFAULT_BORDER_STYLE = {
'style': 'solid',
'width': '1px',
}
BORDER_STYLES = {... | 2.546875 | 3 |
bin/python/filterfasta.py | reid-wagner/proteomics-pipelines | 2 | 38699 | #!/usr/bin/env python
import Bio
from Bio import SeqIO
import sys
filt = []
seqs = list(SeqIO.parse(sys.argv[1],'fasta'))
minlen = int(sys.argv[2])
maxlen = int(sys.argv[3])
output = sys.argv[4]
for rec in seqs:
s = str(rec.seq)
l = len(s)
if ((l >= minlen) and (l <= maxlen)):
filt.append(rec... | 2.765625 | 3 |