content stringlengths 7 928k | avg_line_length float64 3.5 33.8k | max_line_length int64 6 139k | alphanum_fraction float64 0.08 0.96 | licenses list | repository_name stringlengths 7 104 | path stringlengths 4 230 | size int64 7 928k | lang stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|
from __future__ import annotations
from asyncio import iscoroutine
from contextlib import AsyncExitStack
from typing import Any, Callable
import attr
from anyio import create_task_group
from anyio.abc import TaskGroup
from ..abc import AsyncEventBroker
from ..events import Event
from ..util import reentrant
from .ba... | 33.859649 | 94 | 0.701036 | [
"MIT"
] | agronholm/apscheduler | src/apscheduler/eventbrokers/async_local.py | 1,930 | Python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-07 15:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
def add_author_to_blog(apps, schema_editor): # pylint: disable=unused-argument
"""Author is the claimant"""
Blog = apps.ge... | 35.615385 | 168 | 0.645788 | [
"BSD-3-Clause"
] | elena-kolomeets/lowfat | lowfat/migrations/0090_auto_20170307_1518.py | 1,389 | Python |
from __future__ import annotations
from abc import abstractmethod
from typing import Any, Generic, Optional, TypeVar
from goodboy.errors import Error
from goodboy.messages import DEFAULT_MESSAGES, MessageCollectionType, type_name
from goodboy.schema import Rule, SchemaWithUtils
N = TypeVar("N")
class NumericBase(G... | 34.929825 | 87 | 0.630169 | [
"MIT"
] | andryunin/goodboy | src/goodboy/types/numeric.py | 5,973 | Python |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A tool to extract a build, executed by a buildbot slave.
"""
import optparse
import os
import shutil
import sys
import tracebac... | 39.400722 | 80 | 0.678761 | [
"BSD-3-Clause"
] | bopopescu/build | scripts/slave/extract_build.py | 10,914 | Python |
#!/Users/fahmi.abdulaziz/PycharmProjects/tmdb/bin/python3.8
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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/l... | 34.576923 | 88 | 0.630701 | [
"MIT"
] | fahmi-aa/tmdb | bin/fixup_oslogin_v1_keywords.py | 6,293 | Python |
# coding:utf-8
from django import forms
from django.conf import settings
from django.contrib.admin.widgets import AdminTextareaWidget
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.utils.http import urlencode
from . import settings as USettings
from .comman... | 39.220339 | 168 | 0.610631 | [
"MIT"
] | Jeyrce/ishare | DjangoUeditor/widgets.py | 7,260 | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from math import cos, sin, pi
from tqdm import tqdm
import open3d as o3d
def render(pointcloud_file_path, estimate_normals_radius, estimate_normals_max_nn):
pointcloud = o3d.io.read_point_cloud(pointcloud_file_path, print_progress=True)
... | 37.148718 | 99 | 0.633214 | [
"MIT"
] | 565353780/pointcloud-manage | PointCloudClass/renderer.py | 7,244 | Python |
from raven.utils.testutils import TestCase
from raven.utils.wsgi import get_headers, get_host, get_environ, get_client_ip
class GetHeadersTest(TestCase):
def test_tuple_as_key(self):
result = dict(get_headers({
('a', 'tuple'): 'foo',
}))
self.assertEquals(result, {})
def t... | 32.824742 | 78 | 0.612437 | [
"BSD-3-Clause"
] | 0-wiz-0/raven-python | tests/utils/wsgi/tests.py | 3,184 | Python |
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | 41.528571 | 98 | 0.71259 | [
"Apache-2.0"
] | pradh/data | scripts/proteinInteractionEBI/parse_ebi_test.py | 5,814 | Python |
import socket
import sys
from config import ip, port
net = 0
sock = None
try:
if sys.argv[1] == '--connect':
sock = socket.socket()
try:
sock.connect((sys.argv[2], int(sys.argv[3])))
print('Подключение к игре установлено.')
except:
print(f'Неудалось подкл... | 31.709677 | 89 | 0.563581 | [
"MIT"
] | Mogekoff/nachess | server.py | 1,170 | Python |
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('__all__')
| 21.333333 | 53 | 0.729167 | [
"MIT"
] | RodrigoBLima/app-django-react | django_app/students/serializers.py | 192 | Python |
import os
import pathlib
from dotenv import load_dotenv, find_dotenv
from fpdf import FPDF
#envelope size: 110 by 145 mm
# Elliot Torres
# 4321 Loser Road
# La Crescenta, CA 91214
#
# Ryan Lee
# 1234 Boomer Road
# La Crescenta, CA 91214
load_dotenv(find_dotenv())
# types out address on envelope
def sendmail(
... | 25.5 | 72 | 0.634532 | [
"MIT"
] | Ahsoka/bdaybot | bdaybot/snailmail.py | 1,836 | Python |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BST:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Average: O(log(n)) time | O... | 30.666667 | 86 | 0.578804 | [
"MIT"
] | Ajaykumar98/Algorithms | leetcode.com/python/98_Validate_Binary_Search_Tree.py | 2,208 | Python |
from enum import Enum
from typing import List, Optional, Type, Union
import click
from ..types import NotSet
class CSVOption(click.Choice):
def __init__(self, choices: Type[Enum]):
self.enum = choices
super().__init__(tuple(choices.__members__))
def convert(
self, value: str, param:... | 33.95122 | 98 | 0.640805 | [
"MIT"
] | PrayagS/schemathesis | src/schemathesis/cli/options.py | 1,392 | Python |
import nltk
# nltk.download('stopwords') #if doesnt work download all these first
# nltk.download('punkt')
# nltk.download('averaged_perceptron_tagger')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
stop_words = set(stopwords.words('english'))
meaning_with_example = {
... | 30.570093 | 81 | 0.642006 | [
"Apache-2.0"
] | ruchind159/grammar_correction | part_of_speech.py | 3,323 | Python |
from __future__ import print_function
import sys
from metapub import PubMedFetcher
from metapub import FindIt
# examples of different formats:
# 18612690: PubMedArticle with multiple AbstractText sections
# 1234567: PubMedArticle with no abstract whatsoever
# 20301546: PubMedBookArticle from GeneReviews
####
impor... | 27.428571 | 98 | 0.707031 | [
"Apache-2.0"
] | DocMT/metapub | bin/demo_get_PubMedArticle_by_pmid.py | 2,304 | Python |
from skimage.measure import find_contours
from skimage import io
from skimage.color import rgb2gray
from matplotlib import pyplot as plt
image = io.imread('contour_finding_test.png')
# image = io.imread('FlowchartDiagram.png')
image = rgb2gray(image)
out = find_contours(image)
print(len(out))
# Find contours at a con... | 24.068966 | 54 | 0.73639 | [
"Apache-2.0"
] | egonw/pyamiimage | pyimage/contour.py | 698 | Python |
import numpy as np
from numpy import (reciprocal, einsum, maximum, minimum, zeros_like,
atleast_1d, squeeze)
from scipy.linalg import eig, eigvals, matrix_balance, norm
from harold._classes import Transfer, transfer_to_state
from harold._discrete_funcs import discretize
from harold._arg_utils import ... | 37.602 | 79 | 0.604489 | [
"MIT"
] | TavaresFilipe/harold | harold/_time_domain.py | 18,814 | Python |
#
# Copyright 2020 Logical Clocks AB
#
# 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 ag... | 29.885714 | 76 | 0.640057 | [
"Apache-2.0"
] | DhananjayMukhedkar/feature-store-api | python/hsfs/constructor/join.py | 2,092 | Python |
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tflearn.layers.conv import global_avg_pool
#######################
# 3d functions
#######################
# convolution
# 3D unet graph
def unet(inputI, output_channel):
"""3D U-net"""
phase_flag = 1
concat_dim = 4
conv1_1 = conv3d(
... | 34.819182 | 126 | 0.597065 | [
"MIT"
] | JohnleeHIT/Brats2019 | src/models.py | 22,145 | Python |
#!/usr/bin/env python2
# -*- encoding: utf-8 -*-
import pygame
import sys
import numpy as np
CONST_LOCK_FILE = "lock.txt"
#CONST_GRAPH_FILE = "../tsptours/graph.tsp"
CONST_GRAPH_FILE = "graph.tsp"
CONST_STOP = "STOP"
CONST_CUSTOM_FILE = None
def main():
pygame.init()
screen = pygame.display.set_mode((700,7... | 39.923077 | 145 | 0.509152 | [
"MIT"
] | mattaereal/AntColonyOptimization | graphic/tsp_matt.py | 4,156 | Python |
def extractReMonsterWiki(item):
"""
Parser for 'Re:Monster Wiki'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'WATTT' in item['tags']:
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=fra... | 32.181818 | 89 | 0.714689 | [
"BSD-3-Clause"
] | fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractReMonsterWiki.py | 354 | Python |
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1... | 32.348558 | 149 | 0.623021 | [
"Apache-2.0"
] | activelan/awx | awx_collection/plugins/modules/tower_job_template.py | 13,457 | Python |
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
date_of_birth = models.DateField(blank=True, null=Tru... | 30.311111 | 75 | 0.744868 | [
"MIT"
] | pauljherrera/avantiweb | account/models.py | 1,364 | Python |
# -*- coding: utf-8 -*-
from irc3.plugins.command import command
@command
def echo(bot, mask, target, args):
"""Echo command
%%echo <words>...
"""
yield ' '.join(args['<words>'])
@command(permission='admin', public=False)
def adduser(bot, mask, target, args):
"""Add a user
%%adduse... | 19.933333 | 56 | 0.618729 | [
"MIT"
] | gawel/irc3 | examples/mycommands.py | 598 | Python |
###########################################################################
#
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/l... | 38.846154 | 80 | 0.635644 | [
"Apache-2.0"
] | quan/starthinker | starthinker/util/salesforce/quickstart.py | 1,010 | Python |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from metrics import power
from telemetry import test
from telemetry.core import util
from telemetry.page import page_measurement
from telemetr... | 31.122581 | 74 | 0.732172 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | Acidburn0zzz/chromium-1 | tools/perf/benchmarks/dromaeo.py | 4,824 | Python |
# ------------------------------------------------------------------------------------------------------
# Copyright (c) Leo Hanisch. All rights reserved.
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
# ---------------------------------------------------------... | 40.359551 | 145 | 0.612194 | [
"BSD-3-Clause"
] | Geetha-github-cloud/swarmlib | swarmlib/cuckoosearch/cuckoo_problem.py | 3,592 | Python |
import os
import tensorflow as tf
from merge.model import Model
def run_model_on_random_input(model):
batch_size = 1
height = 100
width = 200
inputs = {
'image': tf.random.uniform(shape=(batch_size, height, width, 3), minval=0, maxval=256, dtype='int32'),
'horz_split_points_probs': tf... | 33.5 | 117 | 0.681818 | [
"MIT"
] | matroshenko/SPLERGE_via_TF | merge/evaluation.py | 1,474 | Python |
from django.contrib import admin
from .models import Post, SurveyHistory
admin.site.register(Post)
admin.site.register(SurveyHistory)
| 22.5 | 39 | 0.82963 | [
"MIT"
] | functioncall/rescue-habit | blog/admin.py | 135 | Python |
"""
Mplot demo runner
"""
import enaml
from enaml.qt.qt_application import QtApplication
def run_demo():
with enaml.imports():
#from griddata_demo_ui import Main
from griddata_demo_model_ui import Main
app = QtApplication()
view = Main(custom_title='Matplotlib demo', mplot_style='darkis... | 17.041667 | 70 | 0.691932 | [
"Apache-2.0"
] | viz4biz/PyDataNYC2015 | tutorial/grid_data_demo_run.py | 409 | Python |
import os
import tempfile
from tests.STDF.STDFRecordTest import STDFRecordTest
from STDF import FAR
# File Attributes Record
# Functuion:
# Contains the information necessary to determine
# how to decode the STDF datacontained in the file.
def test_FAR():
far('<')
far('>')
def far(end):
# STDF v4... | 25.209677 | 62 | 0.672425 | [
"MIT"
] | awinia-github/Semi-ATE-STDF | tests/STDF/test_FAR.py | 1,563 | Python |
from academicInfo.models import Department
from faculty.forms import FacultySignupForm
from faculty.models import Faculty
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
class FacultySignupFormTest(TestCase):
def test_signup_form_label(self):
... | 32.293333 | 70 | 0.565648 | [
"MIT"
] | shreygoel7/Pinocchio | Pinocchio/faculty/tests/test_forms.py | 2,422 | Python |
#!/usr/bin/env python3
import sys
import re
class Num:
def __init__(self, value):
self.value = value
def __add__(self, num):
return Num(self.value * num.value)
def __mul__(self, num):
return Num(self.value + num.value)
s = 0
for line in sys.stdin:
line = line.replace("+", "... | 18.375 | 69 | 0.564626 | [
"MIT"
] | pauldraper/advent-of-code-2020 | problems/day-18/part_2.py | 441 | Python |
# -*- coding: utf-8 -*-
import warnings
# warnings.filterwarnings("ignore") # 抑制告警,并指定采取的措施
warnings.warn("# This is a test warning 111.")
print("Hello One")
warnings.filterwarnings("ignore", category=DeprecationWarning) # 抑制特定类型的警告
warnings.warn("# This is a test warning 222.", DeprecationWarning) # 被抑制
... | 30.238095 | 78 | 0.707087 | [
"Apache-2.0"
] | anliven/L-Python | Python3-Basics/Chapter11_Exception02_Warning.py | 869 | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to Test Deep Learning Model.
Contains a pipeline to test a deep learning model.
Revision History:
2021-11-20 (ANI717 - Animesh Bala Ani): Baseline Software.
Example:
$ python3 test.py
"""
#___Import Modules:
import torch
from torch.utils.dat... | 28.148649 | 142 | 0.614498 | [
"MIT"
] | ANI717/Self_Driving_CV_Repository | deep learning/test/test.py | 2,083 | Python |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... | 31.816832 | 180 | 0.67232 | [
"MIT"
] | RokPot/NiaPy | docs/source/conf.py | 6,439 | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=8
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Cir... | 26.4 | 80 | 0.667298 | [
"BSD-3-Clause"
] | UCLA-SEAL/QDiff | data/cirq_new/cirq_program/startCirq_Class18.py | 1,584 | Python |
# simple example demonstrating how to control a Tello using your keyboard.
# For a more fully featured example see manual-control-pygame.py
#
# Use W, A, S, D for moving, E, Q for rotating and R, F for going up and down.
# When starting the script the Tello will takeoff, pressing ESC makes it land
# and the script ex... | 30.057971 | 96 | 0.644648 | [
"MIT"
] | elizabethhng/DJITelloPy | examples/manual-control-opencv.py | 2,264 | Python |
# -*- coding: utf-8 -*-
"""Base exchange class"""
# -----------------------------------------------------------------------------
__version__ = '1.17.322'
# -----------------------------------------------------------------------------
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import NetworkE... | 40.16282 | 185 | 0.600177 | [
"MIT"
] | tssujt/ccxt | python/ccxt/base/exchange.py | 64,385 | Python |
from pydub import AudioSegment
from pydub.playback import play
import os
import utils
class audiofile:
def __init__(self, file):
""" Init audio stream """
self.file = file
def play(self):
""" Play entire file """
utils.displayInfoMessage('Playing Audio')
pathpa... | 25.965517 | 67 | 0.628154 | [
"MIT"
] | CoryXie/SpeechShadowing | AudioFile.py | 753 | Python |
"""Tasmota MQTT."""
import asyncio
import logging
from typing import Union
import attr
from .const import COMMAND_BACKLOG
DEBOUNCE_TIMEOUT = 1
_LOGGER = logging.getLogger(__name__)
class Timer:
"""Simple timer."""
def __init__(self, timeout, callback):
self._timeout = timeout
self._callba... | 27.545455 | 80 | 0.64934 | [
"MIT"
] | ascillato/hatasmota | hatasmota/mqtt.py | 2,424 | Python |
import os
from glyphsLib import GSFont
import pytest
from fontbakery.codetesting import (
assert_PASS,
assert_results_contain,
assert_SKIP,
GLYPHSAPP_TEST_FILE,
PATH_TEST_DATA,
portable_path,
TEST_FILE,
)
from fontbakery.message import Message
from fontbakery.status import PASS, FAIL, WARN... | 27.151786 | 87 | 0.66853 | [
"Apache-2.0"
] | paullinnerud/fontbakery | tests/test_codetesting.py | 6,082 | Python |
from gym_multigrid.multigrid import *
class CollectGameEnv(MultiGridEnv):
"""
Environment in which the agents have to collect the balls
"""
def __init__(
self,
size=10,
width=None,
height=None,
num_balls=[],
agents_index = [],
balls_index=[],
... | 28.232323 | 94 | 0.562433 | [
"Apache-2.0"
] | ArnaudFickinger/gym-multigrid | gym_multigrid/envs/collect_game.py | 2,795 | Python |
# ble_command_load_group.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Wed, Sep 1, 2021 5:05:57 PM
import sys
import asyncio
import logging
import argparse
from typing import Optional
from binascii import hexlify
from bleak import Blea... | 33 | 165 | 0.694444 | [
"MIT"
] | JKlingPhotos/OpenGoPro | demos/python/tutorial/tutorial_modules/tutorial_2_send_ble_commands/ble_command_load_group.py | 2,376 | Python |
import inspect
from collections import OrderedDict
from json.decoder import JSONDecodeError
from typing import Optional, Tuple, Union
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
from recipe_scrapers.settings import settings
from ._schemaorg import SchemaOrg
# some sites close thei... | 34.302817 | 110 | 0.625539 | [
"MIT"
] | AlexRogalskiy/recipe-scrapers | recipe_scrapers/_abstract.py | 4,871 | Python |
# Copyright 2015 The TensorFlow Authors. 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 applica... | 42.152514 | 92 | 0.678258 | [
"Apache-2.0"
] | AdityaPai2398/tensorflow | tensorflow/python/ops/nn.py | 51,131 | Python |
"""Benchmarks of Lasso regularization path computation using Lars and CD
The input data is mostly low rank but is a fat infinite tail.
"""
from collections import defaultdict
import gc
import sys
from time import time
import numpy as np
from sklearn.linear_model import lars_path, lars_path_gram
from sklearn.linear_m... | 34.301724 | 76 | 0.563961 | [
"BSD-3-Clause"
] | Giannos-G/scikit-learn_modified | benchmarks/lasso_replicas/bench_plot_lasso_path_83.py | 3,979 | Python |
# -*- encoding: utf-8 -*-
import re
from oops.utils import sudo_support
@sudo_support
def match(command, settings):
return ('command not found' in command.stderr.lower()
and u' ' in command.script)
@sudo_support
def get_new_command(command, settings):
return re.sub(u' ', ' ', command.script)
| 19.875 | 57 | 0.679245 | [
"MIT"
] | lardnicus/oops | oops/rules/fix_alt_space.py | 320 | Python |
from mmcv.cnn import ConvModule
from torch import nn
from torch.utils import checkpoint as cp
from .se_layer import SELayer
class InvertedResidual(nn.Module):
"""InvertedResidual block for MobileNetV2.
Args:
in_channels (int): The input channels of the InvertedResidual block.
out... | 34.511962 | 80 | 0.537224 | [
"Apache-2.0"
] | vietawake/mmSegmentation | mmseg/models/utils/inverted_residual.py | 7,213 | Python |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
import json
import glob
import os
import argparse
from typing import Tuple, Union, List
from collections import Counter
from tqdm import tqdm
from multiprocessing import Pool
pd.options.mode.chained_assignment = None # defa... | 39.833333 | 136 | 0.61466 | [
"MIT"
] | PDillis/coiltraine | analyze_dataset.py | 12,428 | Python |
#! /usr/bin/env python
#coding=utf-8
import ply.lex as lex
# LEX for parsing Python
# Tokens
tokens=('VARIABLE','NUMBER', 'IF', 'ELIF', 'ELSE', 'WHILE', 'FOR', 'PRINT', 'INC', 'LEN', 'GDIV', 'BREAK', 'LET')
literals=['=','+','-','*','(',')','{','}','<','>', ';', ',', '[', ']']
#Define of tokens
def t... | 14.013514 | 114 | 0.479267 | [
"MIT"
] | Spico197/PythonCompilerPrinciplesExp | py_lex.py | 1,037 | Python |
from maneuvers.kit import *
from maneuvers.strikes.aerial_strike import AerialStrike
class AerialShot(AerialStrike):
def intercept_predicate(self, car: Car, ball: Ball):
return ball.position[2] > 500
def configure(self, intercept: AerialIntercept):
ball = intercept.ball
... | 35.1 | 77 | 0.682336 | [
"MIT"
] | RLMarvin/RLBotPack | RLBotPack/BotimusPrime/maneuvers/strikes/aerial_shot.py | 702 | Python |
#from collections import Counter
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate
import backoff
import json
@backoff.on_exception(backoff.expo,
requests.exceptions.RequestException,
max_time=60)
def get_url(url):#, headers):
return reques... | 27.117647 | 182 | 0.676247 | [
"MIT"
] | fedorov/actcianable | scrapers/get_collections.py | 1,844 | Python |
from django.template.defaulttags import register
@register.filter
def get(data, key):
return data.get(key, '')
| 16.714286 | 48 | 0.735043 | [
"Apache-2.0"
] | TransparentHealth/smh-organization | apps/common/templatetags/smhtags.py | 117 | Python |
"""This script runs code quality checks on given Python files.
Note: This script assumes you use Poetry as your dependency manager.
Run the following in your terminal to get help on how to use this script:
```shell
poetry run python check_commit.py -h
```
"""
import argparse
import subprocess
from colorama import ... | 27.09434 | 78 | 0.605153 | [
"Apache-2.0"
] | Cocopyth/foodshare | check_commit.py | 2,872 | Python |
#!/usr/bin/env python3
# coding=utf8
from soco import SoCo
import socket
# http://docs.python-soco.com/en/latest/getting_started.html
class SpeakerSonos:
def __init__(self):
print("SpeakerSonos initialized!")
def do(self, params):
speaker = SoCo(socket.gethostbyname(params['host']))
p... | 27.195122 | 88 | 0.613453 | [
"MIT"
] | mrusme/melon | plugins/speaker_sonos.py | 1,115 | Python |
import os
'''
TableData deals with data that comes from MS Excel, csv, xml. More precisely, it expects
a single table which has headings in the first row. It converts between these formats and usually keeps
information on a round trip between those formats identical.
TableData also allows for simple transformations,... | 31.507157 | 130 | 0.541247 | [
"Apache-2.0"
] | mokko/Py-TableData | TableData.py | 15,407 | Python |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Prank(Package):
"""A powerful multiple sequence alignment browser."""
homepage = "htt... | 34.277778 | 96 | 0.613452 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | CreRecombinase/spack | var/spack/repos/builtin/packages/prank/package.py | 1,234 | Python |
import pytest
import math
import os
import sys
module_dir = os.path.dirname(__file__)
sys.path.append(os.path.join(module_dir, '..', 'intervalpy'))
from intervalpy import Interval
def test_intersection():
# closed, closed
d1 = Interval(0, 2, start_open=False, end_open=False)
d2 = Interval(1, 3, start_open... | 32.263345 | 107 | 0.647695 | [
"MIT"
] | diatche/interval-util-py | test/interval_test.py | 9,066 | Python |
#ABC026f
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
| 15.2 | 28 | 0.789474 | [
"Unlicense"
] | VolgaKurvar/AtCoder | ABC026/ABC026f.py | 76 | Python |
from setuptools import setup, find_packages
version = "2.5.4"
setup(
include_package_data=True,
name="metaflow",
version=version,
description="Metaflow: More Data Science, Less Engineering",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
author="M... | 25.833333 | 64 | 0.645161 | [
"Apache-2.0"
] | jinnovation/metaflow | setup.py | 775 | Python |
#!/usr/bin/env python
import glob
import re
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-c", "--calctime", dest="calctime", type=int, default=1400)
parser.add_option("-s", "--startdate", dest="startdate", type=int)
parser.add_option("-r", "--rootdir", dest="rootdir", default="/apps/mu... | 30.310345 | 102 | 0.632537 | [
"BSD-3-Clause"
] | Kaffeegangster/ml_monorepo | statarb/src/python/bin/get_calcres_files.py | 879 | Python |
# coding: utf-8
"""
Cherwell REST API
Unofficial Python Cherwell REST API library. # noqa: E501
The version of the OpenAPI document: 9.3.2
Contact: See AUTHORS.
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and pyth... | 50.182012 | 404 | 0.62053 | [
"Apache-2.0"
] | greenpau/pycherwell | pycherwell/api/teams_api.py | 94,300 | Python |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from collections import deque
from enum import Enum
import logging
impo... | 41.389362 | 310 | 0.611114 | [
"MIT"
] | Ilikenumber0/CoinKhongCoGiaTri | test/functional/test_framework/test_framework.py | 19,453 | Python |
from datetime import datetime
from typing import Any, List, Union
import pytest
from neuro_sdk import BlobCommonPrefix, BlobObject, Bucket, BucketEntry
from neuro_cli.formatters.blob_storage import (
BaseBlobFormatter,
LongBlobFormatter,
SimpleBlobFormatter,
)
class TestBlobFormatter:
buckets: Lis... | 29.011111 | 87 | 0.542704 | [
"Apache-2.0"
] | neuro-inc/platform-client-python | neuro-cli/tests/unit/formatters/test_blob_formatters.py | 2,611 | Python |
from pywebhdfs.webhdfs import PyWebHdfsClient as h
hdfs=h(host='sandbox.hortonworks.com',port='50070',user_name='raj_ops')
ls=hdfs.list_dir('/')
ls['FileStatuses']['FileStatus'][0]
hdfs.make_dir('/samples',permission=755)
f=open('/home/pcrickard/sample.csv')
d=f.read()
hdfs.create_file('/samples/sample.csv',... | 24.193548 | 108 | 0.736 | [
"MIT"
] | PacktPublishing/Mastering-Geospatial-Analysis-with-Python | Chapter16/B07333_16.py | 750 | Python |
# -*- coding: utf-8 -*-
"""
@author: alex
"""
import numpy as np
def main():
"""Main program execution."""
n,h1,h2,h3 = generate_ammonia_sites()
nList = [[1,2,3],[0],[0],[0]]
return [n,h1,h2,h3], nList
def generate_ammonia_sites():
"""Generate the locations for the atoms in the amm... | 17.885714 | 70 | 0.484026 | [
"MIT"
] | ajkerr0/kappa | kappa/lattice/ammonia.py | 626 | Python |
# -*- coding: utf-8 -*-
# an ugly hack to convert some stuff into other stuff...
# EDIT THESE #####################################################################
names_to_highlight = ['Eren AM',
'Delmont TO',
'Esen ÖC',
'Lee STM',
... | 44.776824 | 266 | 0.557749 | [
"MIT"
] | Ibrahimmohamed33/web | pubs.py | 10,446 | Python |
# MIT License
# Copyright (c) 2020 Andrew Wells
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, p... | 32.647727 | 185 | 0.540724 | [
"MIT"
] | andrewmw94/gandalf_2020_experiments | gridworld_hallways/make_grid_mdp.py | 5,746 | Python |
# pylint: disable=redefined-outer-name
from .utils import TestCase
from .utils import run_tests_assert_success
import itertools
import os
import slash
import pytest
from .utils.suite_writer import Suite
@pytest.mark.parametrize('parametrize', [True, False])
def test_class_name(suite, suite_test, test_type, parametri... | 34.842697 | 123 | 0.704611 | [
"BSD-3-Clause"
] | bheesham/slash | tests/test_test_metadata.py | 6,202 | Python |
# Time: O(n)
# Space: O(1)
#
# You are climbing a stair case. It takes n steps to reach to the top.
#
# Each time you can either climb 1 or 2 steps.
# In how many distinct ways can you climb to the top?
class Solution:
"""
:type n: int
:rtype: int
"""
def climbStairs(self, n):
prev, cur... | 22.516129 | 70 | 0.561605 | [
"MIT"
] | LimberenceCheng/LeetCode | Python/climbing-stairs.py | 698 | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Style testing.
# Author: Even Rouault <even dot rouault at mines dash paris dot org>
#
###################################################... | 33.575163 | 92 | 0.633444 | [
"MIT"
] | riseofthetigers/GDAL | autotest/ogr/ogr_style.py | 5,137 | Python |
import os.path
import time
from resource_management.core.exceptions import Fail
from resource_management.core.source import Template
from resource_management.core.source import StaticFile
from resource_management.core.source import DownloadSource
from resource_management.core.resources import Execute
from resource_man... | 65.926882 | 151 | 0.479123 | [
"Apache-2.0"
] | aries-demos/dataops | stacks/XIAOMATECH/1.0/services/BEACON/package/scripts/beacon.py | 30,656 | Python |
import pandas as pd
data=pd.read_csv("C:/Users/user/Documents/API_NY.GDP.PCAP.CD_DS2_en_csv_v2_1068945.csv") #your raw data obtained from world bank
import pandas as pd
import matplotlib.pyplot as plt
fulldataonly=data.dropna()
listofcountry=fulldataonly['Country Name']
listofcountry=list(listofcountry)
def findco... | 29.268817 | 129 | 0.649522 | [
"MIT"
] | ph7klw76/Data_science_project | Economic Growth & GDP per capita.py | 2,722 | Python |
# Monster Hot Air Balloon | (2435553)
if sm.getSkillByItem() == 0:# Check whether item has an vehicleID stored, 0 if false.
sm.chat("An Error occurred whilst trying to find the mount.")
elif sm.hasSkill(sm.getSkillByItem()):
sm.chat("You already have the 'Monster Hot Air Balloon' mount.")
else:
sm.consum... | 40.909091 | 86 | 0.708889 | [
"MIT"
] | Bia10/MapleEllinel-v203.4 | scripts/item/consume_2435553.py | 450 | Python |
import time
from dataclasses import dataclass
import jwt
from util.enum_util import EnumBase
class Role(EnumBase):
USER = "USER"
ADMIN = "ADMIN"
class Perm(EnumBase):
NONE = "NONE"
READ_MSG = "READ_MSG"
WRITE_MSG = "WRITE_MSG"
@dataclass
class Identity:
user: str
role: Role.to_enum()... | 23.333333 | 78 | 0.605263 | [
"MIT"
] | pkyosx/fastapi-example | fastapi_example/util/auth_util.py | 1,330 | Python |
# this works around a path issue with just calling
# coverage run -m doctest -v <rst-file>
import doctest
import sys
fails = 0
for filename in [
"tuples.rst",
"functions.rst",
"symbolic.rst",
"simplification.rst",
"differentiation.rst",
"symbolic_tuples.rst",
]:
result = doctest.testfile(... | 17.454545 | 50 | 0.661458 | [
"MIT"
] | jtauber/functional-differential-geometry | run_doctests.py | 384 | Python |
"""
The various serializers.
Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
"""
import array
import builtins
import uuid
import logging
import struct
import datetime
import decimal
import numbers
import inspect
import marshal
import json
import serpent
import msgpack
from . import er... | 40.487129 | 136 | 0.638316 | [
"MIT"
] | gst/Pyro5 | Pyro5/serializers.py | 20,446 | Python |
# Exercício número 3 da lista
n1 = int(input('DIgite um valor:'))
n2 = int(input('Digite outro valor:'))
soma = n1+n2
print('A soma entre {} e {} é {}'.format(n1, n2, soma)) | 34.6 | 55 | 0.641618 | [
"MIT"
] | FelipeDreissig/Prog-em-Py---CursoEmVideo | Mundo 1/Ex003 - soma.py | 176 | Python |
from django.contrib.sitemaps import Sitemap
from main.models import Algo, Code
class AlgoSitemap(Sitemap):
changefreq = "daily"
priority = 1
def items(self):
return Algo.objects.all()
def lastmod(self, obj):
return obj.created_at
def location(self, obj):
return "/" + obj.... | 20.066667 | 54 | 0.626246 | [
"Apache-2.0"
] | algorithms-gad/algoBook | main/algoSitemap.py | 602 | Python |
"""
Meta thinking: python objects & introspection
usefull documentation:
http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Metaprogramming.html
"""
import inspect
import pkgutil
from importlib import import_module
from types import ModuleType
from typing import Any, Callable, Dict, List, Optional, Type
... | 30.398876 | 83 | 0.582887 | [
"MIT"
] | rapydo/http-api | restapi/utilities/meta.py | 5,411 | Python |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitR06_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitR06_IsolatedLHS
"""
# Flag this instance as compiled now
self.is_compiled = True
super... | 29.921569 | 96 | 0.700524 | [
"MIT"
] | levilucio/SyVOLT | GM2AUTOSAR_MM/Properties/unit_contracts/HUnitR06_IsolatedLHS.py | 1,526 | Python |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.tools.mo.ops.eye import MXEye
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs
class EyeExtractor(FrontExt... | 34.666667 | 129 | 0.700855 | [
"Apache-2.0"
] | opencv/dldt | tools/mo/openvino/tools/mo/front/mxnet/eye_ext.py | 936 | Python |
__copyright__ = """
Copyright (C) 2009-2017 Andreas Kloeckner
Copyright (C) 2014-2017 Aaron Meurer
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... | 36.963899 | 106 | 0.547339 | [
"MIT"
] | chrisamow/pudb | pudb/debugger.py | 102,392 | Python |
import dis
import math
import os
import unittest
import sys
import ast
import _ast
import tempfile
import types
import textwrap
from test import support
from test.support import script_helper, requires_debug_ranges
from test.support.os_helper import FakePath
class TestSpecifics(unittest.TestCase):
def compile_si... | 34.496408 | 95 | 0.533211 | [
"MIT"
] | ScriptBox99/wagi-dotnet | examples/wagipython/wagi-python/opt/wasi-python/lib/python3.11/test/test_compile.py | 52,814 | Python |
# Python
import pytest
from unittest import mock
from contextlib import contextmanager
from awx.main.models import Credential, UnifiedJob
from awx.main.tests.factories import (
create_organization,
create_job_template,
create_instance,
create_instance_group,
create_notification_template,
create... | 28.89071 | 157 | 0.723284 | [
"Apache-2.0"
] | AdamVB/awx | awx/main/tests/conftest.py | 5,287 | Python |
import pytest
from djcookie_demo_proj.users.models import User
from djcookie_demo_proj.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> User:
return UserFactory()
| 20.133333 | 64 | 0.791391 | [
"MIT"
] | muutttu/djcookie_demo_proj | djcookie_demo_proj/conftest.py | 302 | Python |
#!/usr/bin/env python3
import sys
import os
import re
import argparse
import requests
from bs4 import BeautifulSoup as bs
version=1.1
print("""\033[1;36m
╦ ╦╔═╗╔╗ ╦═╗╔═╗╔═╗╔╦╗╔═╗╦═╗
║║║║╣ ╠╩╗ ╠╦╝║╣ ╠═╣║║║║╣ ╠╦╝
╚╩╝╚═╝╚═╝────╩╚═╚═╝╩ ╩╩ ╩╚═╝╩╚═
🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥
... | 31.816976 | 166 | 0.656857 | [
"MIT"
] | febinrev/web_reamer | web_reamer.py | 12,209 | Python |
from prettytable import PrettyTable
from collections import OrderedDict
def _fieldnames(rows):
def g():
for row in rows:
yield from row
d = OrderedDict((k, None) for k in g())
return list(d.keys())
def _echo_table(rows):
if not rows: return
fieldnames = _fieldnames(rows)
t... | 34.108 | 158 | 0.72546 | [
"MIT"
] | bmccary/utd | utd/script.py | 8,527 | Python |
""" Argparse utilities"""
import sys
from six import PY2
from argparse import ArgumentParser
try:
from argparse import _SubParsersAction
except ImportError:
_SubParsersAction = type(None)
class PatchArgumentParser:
_original_parse_args = None
_original_parse_known_args = None
_original_add_subpars... | 44.147208 | 118 | 0.64505 | [
"Apache-2.0"
] | nadeemshaikh-github/trains | trains/utilities/args.py | 8,697 | Python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Apr, 2019
@author: Nathan de Lara <[email protected]>
"""
from typing import Optional, Union
import numpy as np
from sknetwork.utils.check import check_seeds
def stack_seeds(n_row: int, n_col: int, seeds_row: Optional[Union[np.ndarray, dict]],
... | 30.877193 | 110 | 0.628409 | [
"BSD-3-Clause"
] | JulienSim001/scikit-network | sknetwork/utils/seeds.py | 1,760 | Python |
""" This module provides the unsafe things for targets/numbers.py
"""
from .. import types
from ..extending import intrinsic
from llvmlite import ir
@intrinsic
def viewer(tyctx, val, viewty):
""" Bitcast a scalar 'val' to the given type 'viewty'. """
bits = val.bitwidth
if isinstance(viewty.dtype, types.... | 30.071429 | 79 | 0.643705 | [
"BSD-2-Clause",
"Apache-2.0"
] | Hardcode84/numba | numba/unsafe/numbers.py | 1,684 | Python |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 3 23:07:15 2019
@author: ydima
"""
import logging
import os
from pathlib import Path
import random
import shlex
import string
from subprocess import PIPE, Popen
import tempfile
from typing import Dict, List, Optional, Union
import pandas as pd
from .constants import (... | 29.048387 | 119 | 0.600222 | [
"MIT"
] | alon-r/bcpandas | bcpandas/utils.py | 7,204 | Python |
_base_ = [
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py',
'../_base_/swa.py'
]
# model settings
model = dict(
type='ATSS',
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window7_224_22k.pth',
backbo... | 26.984848 | 121 | 0.685944 | [
"Apache-2.0"
] | VietDunghacker/VarifocalNet | configs/ddod/swin.py | 5,343 | Python |
# 電子レンジ
def get_E_Elc_microwave_d_t(P_Elc_microwave_cook_rtd, t_microwave_cook_d_t):
"""時刻別消費電力量を計算する
Parameters
----------
P_Elc_microwave_cook_rtd : float
調理時の定格待機電力, W
t_microwave_cook_d_t : ndarray(N-dimensional array)
1年間の全時間の調理時間を格納したND配列, h
d日t時の調理時間が年開始... | 22.74 | 77 | 0.664908 | [
"MIT"
] | jjj-design/pyhees | src/pyhees/section10_j1_f.py | 1,435 | Python |
import torch
import torch.nn as nn
from src.network import Conv2d
class MCNN(nn.Module):
def __init__(self, bn=False):
super(MCNN, self).__init__()
self.branch1 = nn.Sequential(Conv2d(1, 16, 9, same_padding=True, bn=bn),
nn.MaxPool2d(2),
... | 45.77551 | 81 | 0.436469 | [
"MIT"
] | DhenryD/CrowdCount-mcnn | src/models.py | 2,243 | Python |
from ... import create_engine
from ... import exc
from ...engine import url as sa_url
from ...testing.provision import configure_follower
from ...testing.provision import create_db
from ...testing.provision import drop_db
from ...testing.provision import follower_url_from_main
from ...testing.provision import log
from ... | 34.792793 | 78 | 0.651217 | [
"MIT"
] | 01king-ori/Kingsblog | virtual/lib/python3.7/site-packages/sqlalchemy/dialects/oracle/provision.py | 3,862 | Python |
from encapsulation_exercise.wild_cat_zoo.project.animal import Animal
class Cheetah(Animal):
MONEY_FOR_CARE = 60
def __init__(self, name, gender, age):
super().__init__(name, gender, age, self.MONEY_FOR_CARE) | 28.375 | 69 | 0.744493 | [
"MIT"
] | Veselin-Stoilov/software-university-OOP | encapsulation_exercise/wild_cat_zoo/project/cheetah.py | 227 | Python |
# -*- coding: utf-8 -*-
"""
pygments.lexers.other
~~~~~~~~~~~~~~~~~~~~~
Lexers for other languages.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, using, \
... | 46.441598 | 1,414 | 0.499528 | [
"Apache-2.0"
] | TheDleo/backplanejs | tools/yuidoc/bin/pygments/lexers/other.py | 107,772 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.