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 |
|---|---|---|---|---|---|---|
src/lesson_developer_tools/unittest_truth.py | jasonwee/asus-rt-n14uhp-mrtg | 3 | 20900 | import unittest
class TruthTest(unittest.TestCase):
def testAssertTrue(self):
self.assertTrue(True)
def testAssertFalse(self):
self.assertFalse(False)
| 2.78125 | 3 |
tia/trad/monitor_mainTr.py | jmakov/market_tia | 1 | 20901 | import sys
import time
from tia.trad.tools.io.follow import followMonitor
import tia.configuration as conf
from tia.trad.tools.errf import eReport
import ujson as json
import matplotlib.pyplot as plt
import math
import collections
import logging
from tia.trad.tools.ipc.processLogger import PROCESS_NAME
LOGGER_NAME = P... | 1.921875 | 2 |
irocr/config.py | guidj/ir-orc | 1 | 20902 | <filename>irocr/config.py
import os
import os.path
import ConfigParser
PROJECT_BASE = ''.join([os.path.dirname(os.path.abspath(__file__)), "/../"])
CONFIG_FILE = ''.join([PROJECT_BASE, 'config.ini'])
_UNSET = object()
class ConfigurationError(Exception):
pass
def get(section, option=None, type=None, fallback=... | 2.546875 | 3 |
mmtbx/ions/tst_environment.py | jbeilstenedmands/cctbx_project | 0 | 20903 | <reponame>jbeilstenedmands/cctbx_project
# -*- coding: utf-8; py-indent-offset: 2 -*-
from __future__ import division
from mmtbx.ions.environment import ChemicalEnvironment
import mmtbx.ions.identify
from mmtbx import ions
import mmtbx.monomer_library.pdb_interpretation
from mmtbx import monomer_library
from mmtbx.io... | 1.976563 | 2 |
extinfo/extractors/fileinfo_com.py | rpdelaney/extinfo | 0 | 20904 | import re
from ..utils import Report, fetch
SITE = "fileinfo.com"
PATH = "/extension"
def extract(extension: str) -> list[Report]:
soup = fetch(site=SITE, path=PATH, extension=extension)
description_short = soup.find_all("h2")[0].text.strip()
infoboxes = soup.find_all(attrs={"class": "infoBox"})
de... | 2.78125 | 3 |
style/api/routers/prediction.py | imagination-ai/kerem-side-projects-monorepo | 0 | 20905 | from fastapi import APIRouter
from pydantic import BaseModel
from style.predict.servable.serve import get_servable
router = APIRouter()
class PredictionRequest(BaseModel):
text: str
model_name: str
@router.get("/")
async def index():
return {"success": True, "message": "Predictions Router is working!... | 2.515625 | 3 |
pyrepl/iconsole.py | thinkle/snippets | 0 | 20906 | from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell()
| 1.335938 | 1 |
src/tests/ftest/pool/create_capacity_test.py | berserk-fury/daos | 0 | 20907 | #!/usr/bin/python3
"""
(C) Copyright 2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import time
from pool_test_base import PoolTestBase
from server_utils import ServerFailed
class PoolCreateTests(PoolTestBase):
# pylint: disable=too-many-ancestors,too-few-public-methods
"""Pool cre... | 2.375 | 2 |
async-utils/setup.py | goc9000/python-library | 0 | 20908 | <filename>async-utils/setup.py
from setuptools import setup, find_packages
setup(
name='atmfjstc-async-utils',
version='0.1.0',
author_email='<EMAIL>',
package_dir={'': 'src'},
packages=find_packages(where='src'),
install_requires=[
],
zip_safe=True,
description="Utilities for ... | 1.234375 | 1 |
msg_scheduler/analyzer.py | buaales/tt_offline_scheduler | 5 | 20909 | import subprocess
import sys
from collections import defaultdict
import pandas as pd
import networkx
import random
import functools
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from .model import Network, Link, Frame, Node
import io
if sys.platform == 'darwin':
matplo... | 2.390625 | 2 |
endpoints/cotect-endpoints/cotect_endpoints/security.py | JNKielmann/cotect | 19 | 20910 | <gh_stars>10-100
import logging
import os
import firebase_admin
from fastapi import HTTPException, Security, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.security.api_key import APIKeyCookie, APIKeyHeader, APIKeyQuery
from firebase_admin import auth
from cotect_endpoints.u... | 2.078125 | 2 |
ui/Pytest/test_Range.py | MoisesHenr/OCEAN | 15 | 20911 | # Author: <NAME>
# this class handle the functions tests of controller of the component of the numerical features
import pytest
import sys
from PyQt5 import QtWidgets
from ui.mainTest import StaticObjects
@pytest.mark.parametrize('slider', [1, 2.9, False, ('t1', 't2'), None])
def test_CIR_setSlider_wrong_paramet... | 2.328125 | 2 |
tools/clean_autogen_protos.py | embeddery/stackrox | 22 | 20912 | #!/usr/bin/env python3
import argparse
import pathlib
GENERATED_EXTENSIONS = ["pb.go", "pb.gw.go", "swagger.json"]
def find_files(path, fileglob):
files_full = list(path.glob(fileglob))
return files_full
def strip_path_extension(filelist):
# We cannot use Path.stem directly as it doesn't handle doubl... | 2.734375 | 3 |
skbl/helpers.py | spraakbanken/skblportalen | 2 | 20913 | """Define different helper functions."""
import datetime
import json
import re
import sys
import urllib.parse
from urllib.request import Request, urlopen
import icu
import markdown
from flask import current_app, g, make_response, render_template, request, url_for
from flask_babel import gettext
from . import static_... | 2.65625 | 3 |
boundaries/migrations/0001_initial.py | MinnPost/represent-boundaries | 20 | 20914 | <reponame>MinnPost/represent-boundaries<filename>boundaries/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class JSONField(models.TextField):
"""Mocks jsonfield 0.92's column-type behavi... | 2.421875 | 2 |
gitz/git/reference_branch.py | rec/gitz | 24 | 20915 | <reponame>rec/gitz
from . import functions
from ..program import ARGS
from ..program import ENV
from ..program import PROGRAM
def reference_branch(remote_branches=None):
remote_branches = remote_branches or functions.remote_branches()
remote, *rest = ARGS.reference_branch.split('/', maxsplit=1)
if rest:
... | 2.78125 | 3 |
cookies/apps.py | hamishwillee/http_tester_site | 0 | 20916 | from django.apps import AppConfig
class CookiesConfig(AppConfig):
name = 'cookies'
| 1.171875 | 1 |
src/single_pendulum.py | dpopchev/Computation_python | 0 | 20917 | #!/usr/bin/env python3
# do not hesitate to debug
import pdb
# python computation modules and visualization
import numpy as np
import sympy as sy
import scipy as sp
import matplotlib.pyplot as plt
from sympy import Q as syQ
sy.init_printing(use_latex=True,forecolor="White")
def Lyapunov_stability_test_linear(ev):
... | 3.40625 | 3 |
web/accounts/views.py | drejkim/reading-quantified-server | 2 | 20918 | <gh_stars>1-10
from django.shortcuts import render
from rest_framework import mixins
from rest_framework import permissions
from rest_framework import viewsets
from rest_framework.decorators import action
from .models import User
from .serializers import UserSerializer
# Create your views here.
class UserViewSet(mix... | 2.140625 | 2 |
fixit/common/pseudo_rule.py | sk-/Fixit | 313 | 20919 | <filename>fixit/common/pseudo_rule.py<gh_stars>100-1000
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import abc
import ast
import io
import tokenize
from pathlib import Path
from typing i... | 2.203125 | 2 |
homeschool/referrals/tests/test_models.py | chriswedgwood/homeschool | 154 | 20920 | <reponame>chriswedgwood/homeschool<filename>homeschool/referrals/tests/test_models.py
from homeschool.referrals.tests.factories import ReferralFactory
from homeschool.test import TestCase
class TestReferral(TestCase):
def test_factory(self):
referral = ReferralFactory()
assert referral.referring_... | 2.25 | 2 |
slackwebhook/__init__.py | FoundryGroup/Slack-Webhook | 0 | 20921 | <gh_stars>0
################################################################################
# Python package __init__.py file.
#
# Author: <NAME>
# Date: 12/20/2016
#
################################################################################
from slackwebhook import slackwebhook
| 1.492188 | 1 |
scripts/fasta2vcf.py | jodyphelan/pathogenseq | 0 | 20922 | <reponame>jodyphelan/pathogenseq
#! /usr/bin/env python
import sys
import pathogenseq as ps
ref_file = sys.argv[1]
query_file = sys.argv[2]
prefix = sys.argv[3]
ps.mauve_call_variants(ref_file,query_file,prefix)
cmd = "bgzip -f %s.vcf" % prefix
ps.run_cmd(cmd)
| 1.757813 | 2 |
test/__init__.py | miguelcarrasco/anothercryptosolver | 0 | 20923 | __author__ = 'deon'
| 0.960938 | 1 |
job_scheduler/cache/__init__.py | konkolorado/job-scheduler | 0 | 20924 | from job_scheduler.cache.base import ScheduleCache
from job_scheduler.cache.fake import FakeScheduleCache
from job_scheduler.cache.redis import RedisScheduleCache
all = ["ScheduleCache", "RedisScheduleCache", "FakeScheduleCache"]
| 1.304688 | 1 |
programming/python/ex004.py | Vinicius-Moraes20/personal-projects | 0 | 20925 | valor = input("Digite algo: ")
print("É do tipo", type(valor))
print("Valor numérico:", valor.isnumeric())
print("Valor Alfa:", valor.isalpha())
print("Valor Alfanumérico:", valor.isalnum())
print("Valor ASCII:", valor.isascii())
print("Valor Decimal", valor.isdecimal())
print("Valor Printavel", valor.isprintable()) | 3.828125 | 4 |
backend/src/util/observable.py | r2binx/heimboard | 6 | 20926 | <gh_stars>1-10
from typing import List
class Observable:
_observers: List = []
def __init__(self):
self._observers = []
def subscribe(self, observer):
self._observers.append(observer)
def notify_observers(self, *args, **kwargs):
for obs in self._observers:
obs.no... | 2.84375 | 3 |
ae-tpcc-polyjuice-rl/training/PG.py | derFischer/Polyjuice | 23 | 20927 | #coding=utf-8
import numpy as np
import tensorflow as tf
import os
import sys
import time
import shutil
import re
import signal
import subprocess
import numpy as np
import math
from Policy import *
np.set_printoptions(threshold=np.inf)
BASELINES = 1
class MultiBaseline:
def __init__(self, baseline_number):
... | 2.109375 | 2 |
src/data/preprocessors/__init__.py | paulwarkentin/tf-ssd-vgg | 5 | 20928 | ##
## /src/data/preprocessors/__init__.py
##
## Created by <NAME> <<EMAIL>> on 15/07/2018.
## Updated by <NAME> <<EMAIL>> on 15/07/2018.
##
from .bbox_preprocessor import BBoxPreprocessor
from .default_preprocessor import DefaultPreprocessor
from .image_preprocessor import ImagePreprocessor
| 0.957031 | 1 |
camera.py | chenhsuanlin/signed-distance-SRN | 94 | 20929 | import numpy as np
import os,sys,time
import torch
import torch.nn.functional as torch_F
import collections
from easydict import EasyDict as edict
import util
class Pose():
def __call__(self,R=None,t=None):
assert(R is not None or t is not None)
if R is None:
if not isinstance(t,torch... | 2.46875 | 2 |
solutions/python3/problem1265.py | tjyiiuan/LeetCode | 0 | 20930 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
1265. Print Immutable Linked List in Reverse
You are given an immutable linked list, print out all values of each node in reverse with the help of the following
interface:
ImmutableListNode: An interface of immutable linked list, you are given the head of the list.
You need to ... | 4.59375 | 5 |
standard.py | futureisatyourhand/self-supervised-learning | 1 | 20931 | <reponame>futureisatyourhand/self-supervised-learning
# -*- coding: utf-8 -*-
# --------------------------------------
# @Time : 2021/5/12$ 12:12$
# @Author : <NAME>
# @Email : <EMAIL>
# @File : network.py
# Description : details(i.e., online network,online projector network, online predictor,classifier, targe... | 2.5625 | 3 |
aqualogic/frames.py | mj-sakellaropoulos/aqualogic | 0 | 20932 | from enum import Enum, unique
class Frames(Enum):
FRAME_DLE = 0x10
FRAME_STX = 0x02
FRAME_ETX = 0x03
# Local wired panel (black face with service button)
FRAME_TYPE_LOCAL_WIRED_KEY_EVENT = b'\x00\x02'
# Remote wired panel (white face)
FRAME_TYPE_REMOTE_WIRED_KEY_EVENT = b'\x00\x03'
# ... | 2.515625 | 3 |
Python/Sum/main.py | drtierney/hyperskill-problems | 5 | 20933 | <reponame>drtierney/hyperskill-problems<filename>Python/Sum/main.py<gh_stars>1-10
num1 = input()
num2 = input()
num3 = input()
print(int(num1) + int(num2) + int(num3))
| 3.34375 | 3 |
Python/scheduledEventsInteractiveTool.py | Azure-Samples/virtual-machines-python-scheduled-events-central-logging | 7 | 20934 | <gh_stars>1-10
#!/usr/bin/python
import json
import socket
import sys
import getopt
import logging
from enum import Enum
from datetime import datetime
import base64
import hmac
import hashlib
import time
import urllib.request
import urllib.parse
import configparser
metadata_url = 'http://169.254.169.254/metadata/sche... | 2.015625 | 2 |
E2E_TOD/config.py | kingb12/pptod | 54 | 20935 | import logging, time, os
class Config:
def __init__(self, data_prefix):
# data_prefix = r'../data/'
self.data_prefix = data_prefix
self._multiwoz_damd_init()
def _multiwoz_damd_init(self):
self.vocab_path_train = self.data_prefix + '/multi-woz-processed/vocab'
self.data... | 2.125 | 2 |
advanced_functionality/inference_pipeline_sparkml_xgboost_car_evaluation/preprocessor.py | jpmarques19/tensorflwo-test | 5 | 20936 | from __future__ import print_function
import time
import sys
import os
import shutil
import csv
import boto3
from awsglue.utils import getResolvedOptions
import pyspark
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from pyspark.ml.feature import StringIndexer, VectorIndexer, OneHotEncoder, Vec... | 2.5625 | 3 |
response/response.py | benyamin-7/simple-snmp-collector | 0 | 20937 | from datetime import datetime
__author__ = 'aGn'
__copyright__ = "Copyright 2018, Planet Earth"
class Response(object):
"""Response Class"""
def __init__(self):
self.socket = None
@staticmethod
def publisher(
module, meta_data,
**kwargs
):
"""
Pack... | 2.65625 | 3 |
properjpg/filesmanager.py | vitorrloureiro/properjpg | 3 | 20938 | import mimetypes
import os
from pathlib import Path
def ignore_files(dir: str, files: list[str]):
"""
Returns a list of files to ignore.
To be used by shutil.copytree()
"""
return [f for f in files if Path(dir, f).is_file()]
def get_input_images(input_folder: Path, output_path: Path):
"""
... | 3.484375 | 3 |
mcoc/cdt_core/fetch_data.py | sumitb/mcoc-v3 | 0 | 20939 | <reponame>sumitb/mcoc-v3<filename>mcoc/cdt_core/fetch_data.py
from ..abc import MixinMeta
import json
import re
class FetchData(MixinMeta):
"""CDT FetchData functions"""
## No cog dependencies##
# def __init__(self, bot: Red):
# """init"""
# self.bot = bot
async def aioh... | 2.28125 | 2 |
evaluate_network_example.py | VU-BEAM-Lab/DNNBeamforming | 1 | 20940 | <gh_stars>1-10
# Copyright 2020 <NAME>, <NAME>, and <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the license at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... | 2.0625 | 2 |
nexus_constructor/geometry/slit/slit_geometry.py | ess-dmsc/nexus-geometry-constructor | 0 | 20941 | from typing import List
from PySide2.QtGui import QVector3D
from nexus_constructor.common_attrs import SHAPE_GROUP_NAME, CommonAttrs
from nexus_constructor.model.component import Component
from nexus_constructor.model.geometry import OFFGeometryNoNexus
class SlitGeometry:
def __init__(self, component: Component... | 2.328125 | 2 |
part4/test.py | willogy-team/insights--tensorflow | 0 | 20942 | <reponame>willogy-team/insights--tensorflow<gh_stars>0
import os
import argparse
import numpy as np
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import matplotlib.pyplot as plt
fro... | 2 | 2 |
tlg_bot.py | macrergate/PIK_monitor | 0 | 20943 | <gh_stars>0
import telegram
from flatten_dict import flatten
import os
import time
import datetime
from pik import PIKData
from helpers import hash_vals, dump_data, load_data, compare
class Credentials(object):
def __init__(self, credentials_json):
self.__credentials = load_data(credentials_json)
... | 2.4375 | 2 |
CopyrightHeaderChecker.py | medazzo/CopyRitghHeaderChecker- | 2 | 20944 | <reponame>medazzo/CopyRitghHeaderChecker-<filename>CopyrightHeaderChecker.py
#!/usr/bin/python
# @author <NAME> , Paris, France
#
import os
import time
import ntpath
import sys
import json
import argparse
from os.path import join, getsize
from shutil import copyfile
behaviour = """{
"reporting": true ,
"updatefil... | 2.171875 | 2 |
PYTHON/singly_linked_list.py | ceccs17d55/open-source-contribution | 2 | 20945 | <gh_stars>1-10
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
linked_list = ''
while temp:
linked_list += str(temp.data) + " ... | 4.15625 | 4 |
addons/odoo_marketplace/models/res_config.py | marionumza/vocal_v12 | 0 | 20946 | # -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# License URL : https://store.webkul.com/license.html/
# All Rights Reserved.
#
#
#
# This pr... | 1.875 | 2 |
igf_data/utils/tools/picard_util.py | imperial-genomics-facility/data-management-python | 7 | 20947 | <reponame>imperial-genomics-facility/data-management-python
import os,subprocess
from shlex import quote
import pandas as pd
from igf_data.utils.singularity_run_wrapper import execute_singuarity_cmd
from igf_data.utils.fileutils import check_file_path,get_temp_dir
class Picard_tools:
'''
A class for runnin... | 2.21875 | 2 |
app/utils/NetworkingUtils.py | DiegoSilva776/linkehub_insigth_api | 2 | 20948 | # -*- coding: utf-8 -*-
import sys
import os
import json
import http.client
import urllib
import time
sys.path.append("../")
from models.ApiInstance import ApiInstance
from utils.ConstantUtils import ConstantUtils
'''
NetworkingUtils is responsible for holding the external URLs and the default parameters
o... | 2.578125 | 3 |
utils.py | michaelpatrickpurcell/balanced-nontransitive-dice | 0 | 20949 | import numpy as np
from scipy.special import factorial
from itertools import permutations, product
from pysat.solvers import Minisat22, Minicard
from pysat.pb import PBEnc
from clauses import build_clauses, build_max_min_clauses
from clauses import build_permutation_clauses
from clauses import build_cardinality_lits,... | 2.296875 | 2 |
pkg/agents/team4/trainingAgent/findBestConfigs.py | SOMAS2021/SOMAS2021 | 13 | 20950 | <filename>pkg/agents/team4/trainingAgent/findBestConfigs.py
# TODO: autmatate finding best agents
| 1.085938 | 1 |
tests/storage/psql_dos/migrations/django_branch/test_0043_default_link_label.py | mkrack/aiida-core | 153 | 20951 | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | 1.867188 | 2 |
tests/src/SI/MAP/School_Map_regression_testing.py | JalajaTR/cQube | 0 | 20952 | import time
import unittest
from Data.parameters import Data
from SI.MAP.check_infrascore_with_download_functionality import SchoolInfra_scores
from SI.MAP.check_sc_map_clusterwise_records import test_school_map_schoollevel_records
from SI.MAP.click_on_anydistrict_and_download_csv import download_icon
from SI.MAP.clic... | 2.375 | 2 |
src/manual/melt_oxcgrt2.py | lshtm-gis/WHO_PHSM_Cleaning | 0 | 20953 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 15:24:46 2020
@author: hamishgibbs
"""
import pandas as pd
import re
import numpy as np
#%%
ox = pd.read_csv('https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest_withnotes.csv')
#%%
ox = ox[0:100]
#%%
ox.fil... | 2.90625 | 3 |
src/wildfires/cache/same_call.py | akuhnregnier/wildfires | 1 | 20954 | <filename>src/wildfires/cache/same_call.py
# -*- coding: utf-8 -*-
"""Decorator guaranteeing uniform function calls."""
from inspect import Parameter, signature
def extract_uniform_args_kwargs(f, *args, ignore=None, **kwargs):
"""Extract uniform arguments given a function and the parameters it is called with.
... | 2.84375 | 3 |
models/mnist_model.py | dcurry09/Tensorflow-Project-OOP | 0 | 20955 | #!/usr/bin/env python3
"""
Implements a TF Model class by inheriting the Model base class.
@author: <NAME>
@version: 1.0
"""
from base.base_model import BaseModel
import tensorflow as tf
class MnistModel(BaseModel):
def __init__(self, config):
"""
Constructor to initialize the TF model class by ... | 3.671875 | 4 |
tilemap.py | AI0702/Among-Us-clone | 0 | 20956 | <filename>tilemap.py
import pygame as pg
from settings import *
import pytmx
class Map:
def __init__(self, filename):
self.data = []
with open(filename, 'rt') as f:
for line in f:
self.data.append(line.strip())
self.tilewidth = len(self.data[0])
... | 3.109375 | 3 |
exdir/utils/path.py | knc-neural-calculus/exdir | 67 | 20957 | try:
import pathlib
except ImportError as e:
try:
import pathlib2 as pathlib
except ImportError:
raise e
def name_to_asserted_group_path(name):
path = pathlib.PurePosixPath(name)
if path.is_absolute():
raise NotImplementedError(
"Absolute paths are currently not... | 2.796875 | 3 |
bids2nda/main.py | Shotgunosine/BIDS2NDA | 0 | 20958 | #!/usr/bin/env python
#
# import modules used here -- sys is a very standard one
from __future__ import print_function
import argparse
import csv
import logging
import zipfile
from collections import OrderedDict
from glob import glob
import os
import sys
import nibabel as nb
import json
import pandas as pd
import num... | 2.09375 | 2 |
ds2/sorting/bubblesort.py | aslisabanci/datastructures | 159 | 20959 | def bubblesort(L):
keepgoing = True
while keepgoing:
keepgoing = False
for i in range(len(L)-1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1], L[i]
keepgoing = True
| 3.671875 | 4 |
src/features/threshold.py | HninPwint/nba-career-prediction | 1 | 20960 | <reponame>HninPwint/nba-career-prediction<filename>src/features/threshold.py
class threshold:
def threshold(num, threshold):
if ( threshold < 0 ) || ( threshold >= 1 )
error('threshold input must be in the range [0,1]');
end
fractional = num - floor( num );
idx1 = fractional > thr... | 2.796875 | 3 |
cheers/settings/prod.py | bahattincinic/cheers | 3 | 20961 | from .base import *
import os
import dj_database_url
ALLOWED_HOSTS = ['*']
DEBUG = False
MIDDLEWARE += [
'whitenoise.middleware.WhiteNoiseMiddleware'
]
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
] + INSTALLED_APPS
DATABASES = {
'default': dj_database_url.config()
}
EMAIL_USE_TLS = True
EM... | 1.703125 | 2 |
week2/problem1.py | jgathogo/python_level_1 | 1 | 20962 | import os
import sys
"""
Notes:
- It's great that you've used functions even though we haven't reached that part of the course.
Also, the naming of the function is clear and a good variable name.
- Typically, the docstring for the function starts immediately after the triple quote otherwise we
introduce a newline (... | 3.875 | 4 |
Graphs/dijkstra_algorithm.py | hemraj4545/Data-Structures-and-Algorithms-in-Python | 3 | 20963 | """
>>> G = Graph(6)
>>> G.insert(0, 1, 3)
>>> G.insert(0, 2, 7)
>>> G.insert(0, 4, 8)
>>> G.insert(0, 5, 1)
>>> G.insert(1, 2, 2)
>>> G.insert(1, 4, 13)
>>> G.insert(2, 3, 15)
>>> G.insert(3, 5, 17)
>>> G.insert(4, 5, 9)
>>> G.dijkstra(0)[0]
[0, 3, 5, 20, 8, 1]
>>> G... | 4 | 4 |
src/7/accessing_variables_defined_inside_a_closure/example2.py | tuanavu/python-gitbook | 14 | 20964 | # Example of faking classes with a closure
import sys
class ClosureInstance:
def __init__(self, locals=None):
if locals is None:
locals = sys._getframe(1).f_locals
# Update instance dictionary with callables
self.__dict__.update((key,value) for key, value in locals.items()
... | 3.609375 | 4 |
miniamf/adapters/_array.py | zackw/pyamf | 14 | 20965 | <reponame>zackw/pyamf
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
U{array<http://docs.python.org/library/array.html>} adapter module.
Will convert all array.array instances to a python list before encoding. All
type information is lost (but degrades nicely).
@since: 0.5
"""
from __future__... | 1.960938 | 2 |
KristaBackup/common/schemes/__init__.py | javister/krista-backup | 7 | 20966 | from .scheme_factory import SchemeFactory
from .schemes import schemes
_default_scheme_id = 'default'
def get_scheme(scheme_id=None):
"""Возвращает схему по scheme_id.
Args:
scheme_id: Строка, уникальное имя схемы.
Returns:
Scheme или None, если схемы с scheme_id не существует.
""... | 2.65625 | 3 |
data/utils.py | dojoteef/synst | 81 | 20967 | '''
Utilities useful for datasets
'''
import os
from functools import partial
from urllib.request import urlretrieve
import requests
from tqdm import tqdm
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.sampler import BatchSampler, RandomSampler, SequentialSampler
from data.sampler import Se... | 2.671875 | 3 |
check_changelog.py | pllim/action-check_astropy_changelog | 0 | 20968 | <reponame>pllim/action-check_astropy_changelog
import json
import os
import sys
from astropy_changelog import loads
from github import Github
event_name = os.environ['GITHUB_EVENT_NAME']
if event_name not in ('pull_request_target', 'pull_request'):
print(f'No-op for {event_name}')
sys.exit(0)
event_jsonfile ... | 2.4375 | 2 |
examples/python/example-05-async.py | lukasm91/serialbox2 | 1 | 20969 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
##===-----------------------------------------------------------------------------*- Python -*-===##
##
## S E R I A L B O X
##
## This file is distributed under terms of BSD license.
## See LICENSE.txt for more information.
##
##===-... | 2.125 | 2 |
johnny_cache/cache.py | Sonictherocketman/cache-proxy | 3 | 20970 | from dataclasses import dataclass
from datetime import datetime, timedelta
import json
import os.path
from dateutil.parser import parse
import pytz
import redis
from redis.lock import LockError
import requests
from . import settings
from .logger import logger
UNCACHED_HEADERS = (
'Age',
'Cache-Control',
... | 2.484375 | 2 |
discretizer.py | WeiXuanChan/PIMRMeshfree | 0 | 20971 | '''
File: discretizer.py
Description: function definition
History:
Date Programmer SAR# - Description
---------- ---------- ----------------------------
Author: <NAME> 29Apr2016 - Created
'''
import numpy as np
from . import pinm as pinm
from stl import mesh
from mpl_toolkits import mplot3d
fro... | 2.28125 | 2 |
app/utils/urls.py | withshubh/memegen | 0 | 20972 | from urllib.parse import parse_qs, urlencode, urlparse
from .. import settings
def normalize(request, url: str) -> str:
parts = urlparse(url)
url = f"{settings.BASE_URL}{parts.path}"
if "background" in parts.query:
background = parse_qs(parts.query)["background"][0]
else:
background =... | 2.84375 | 3 |
src/westpa/core/reweight/__init__.py | burntyellow/adelman_ci | 140 | 20973 | <filename>src/westpa/core/reweight/__init__.py
'''
Function(s) for the postanalysis toolkit
'''
import logging
log = logging.getLogger(__name__)
from . import _reweight
from ._reweight import (stats_process, reweight_for_c)
from .matrix import FluxMatrix
| 1.546875 | 2 |
src/hydro/conf/settings_base.py | aolarchive/Hydro | 42 | 20974 | <reponame>aolarchive/Hydro
# Hydro settings
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en-us'
APPLICATION_NAME = 'HYDRO'
SECRET_KEY = '<KEY>
# SESSION_TIMEOUT is used in validate_session_active decorator to see if the
# session is active.
SECOND = 1
MINUTE = SECOND * 60
SECONDS_IN_DAY = SECOND*86400
MYSQL_CACHE_DB = 'cache... | 1.976563 | 2 |
project/Fast/django/decorators/auth.py | fael07/DRF-Project | 0 | 20975 | from ...forms.checks import check_is_logged
from django.shortcuts import redirect
def no_login_required(view_function):
def exec_view_function(*args, **kwargs):
request = args[0]
if check_is_logged(request):
return redirect('/')
return view_function(*args, **kwargs) ... | 1.890625 | 2 |
gp_models.py | deepmind/active_ops | 13 | 20976 | <reponame>deepmind/active_ops<gh_stars>10-100
# Copyright 2020 DeepMind Technologies Limited.
# 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
#... | 2.265625 | 2 |
hpvm/projects/torch2hpvm/torch2hpvm/graph_builder.py | vzyrianov/hpvm-autograd | 0 | 20977 | from collections import defaultdict
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Tuple, Union
import networkx as nx
import onnx
from . import graph_ir as g
from .onnx_attr import get_node_shape, node_attr_to_dict, node_to_shape
PathLike = Union[str, Path]
GraphT = onnx.GraphProto
NodeT... | 2.765625 | 3 |
analysis/plotting/multi_sites.py | jm9e/FL_Pipeline | 0 | 20978 | import csv
import json
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
formats = ['png', 'pdf', 'svg', 'eps']
metrics = [
{'gmetric': 'groc', 'lmetric': 'lroc', 'metric': 'AUC'},
{'gmetric': 'gauc', 'lmetric': 'lauc', 'metric': 'PRAUC'},
]
datasets = [
... | 2.609375 | 3 |
HackerRank/CtCI/array_left_rotation.py | mahasak/Practice | 0 | 20979 | def array_left_rotation(a, n, k):
return a[k:] + a[0:k]
n, k = map(int, raw_input().strip().split(' '))
a = map(int, raw_input().strip().split(' '))
answer = array_left_rotation(a, n, k);
print ' '.join(map(str,answer))
| 3.40625 | 3 |
examples/sudoku/sudoku_cores.py | SRI-CSL/yices2_python_bindings | 8 | 20980 | <reponame>SRI-CSL/yices2_python_bindings
#!/usr/bin/env python
"""Using unsat cores to give hints."""
from SudokuLib import Puzzle
from Solver import Solver
from yices.Yices import Yices
from yices.Census import Census
puzzle_blank = [
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, ... | 2.625 | 3 |
www/python/src/app.py | Destokado/funpedia | 0 | 20981 | <reponame>Destokado/funpedia
import os
import flask
import mwoauth
import yaml
from flask import request, Response
app = flask.Flask(__name__)
# Load configuration from YAML file
__dir__ = os.path.dirname(__file__)
app.config.update(
yaml.safe_load(open(os.path.join(__dir__, 'config.yaml'))))
if __name__ == '_... | 2.859375 | 3 |
test/external_repo/repo.bzl | Vertexwahn/depend_on_what_you_use | 0 | 20982 | <reponame>Vertexwahn/depend_on_what_you_use
def load_external_repo():
native.local_repository(
name = "ext_repo",
path = "test/external_repo/repo",
)
| 1.289063 | 1 |
filter_plugins/general.py | stackhpc/ansible-role-luks | 3 | 20983 | # Copyright (c) 2020 StackHPC Ltd.
#
# 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 wr... | 2.1875 | 2 |
aws-dev/awsdev8/flaskstart.py | PacktPublishing/-AWS-Certified-Developer---Associate-Certification | 13 | 20984 | #!/usr/bin/env python
from flask import Flask, request,Response
import logging
import os
import json
import cognitoHelper as cog
#logging config
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',level=logging.INFO,datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
#globals
MODULE = "... | 2.46875 | 2 |
hallo/function.py | joshcoales/Hallo | 1 | 20985 | <filename>hallo/function.py
from abc import ABC, abstractmethod
from typing import Set, Type, Optional
from hallo.events import (
EventSecond,
EventMinute,
EventHour,
EventDay,
EventPing,
EventMessage,
EventJoin,
EventLeave,
EventQuit,
EventNameChange,
EventKick,
EventIn... | 3.234375 | 3 |
mbl-core/tests/devices/open-ports-checker/mbl/open_ports_checker/open_ports_checker.py | edmund-troche/mbl-core | 5 | 20986 | #!/usr/bin/env python3
# Copyright (c) 2019 Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This script checks for checker for unwanted TCP/UDP open ports."""
import os
import json
import logging
from enum import Enum
import mbl.open_ports_checker.connection as connect... | 2.359375 | 2 |
eval_odom.py | nikola3794/kitti-odom-eval | 110 | 20987 | # Copyright (C) <NAME> 2019. All rights reserved.
import argparse
from kitti_odometry import KittiEvalOdom
parser = argparse.ArgumentParser(description='KITTI evaluation')
parser.add_argument('--result', type=str, required=True,
help="Result directory")
parser.add_argument('--align', type=str,
... | 2.71875 | 3 |
flappy_bird.py | wandreuscv/IA_learn_flappy_bird | 0 | 20988 | import pygame
import random
import os
import time
import neat
import visualize
import pickle
import bcolors as b
pygame.font.init()
SCORE_MAX = [0, 0, 0]
WIN_WIDTH = 600
WIN_HEIGHT = 800
FLOOR = 730
STAT_FONT = pygame.font.SysFont("comicsans", 50)
END_FONT = pygame.font.SysFont("comicsans", 70)
DRAW_LINES = False
WI... | 2.9375 | 3 |
src/cd.py | laura-rieger/deep-explanation-penalization | 105 | 20989 | <reponame>laura-rieger/deep-explanation-penalization
#original from https://github.com/csinva/hierarchical-dnn-interpretations/blob/master/acd/scores/cd.py
import torch
import torch.nn.functional as F
from copy import deepcopy
from torch import sigmoid
from torch import tanh
import numpy as np
stabilizing_constant... | 2.65625 | 3 |
spacy/lang/pt/stop_words.py | cedar101/spaCy | 12 | 20990 | <reponame>cedar101/spaCy
# coding: utf8
from __future__ import unicode_literals
STOP_WORDS = set(
"""
à às área acerca ademais adeus agora ainda algo algumas alguns ali além ambas ambos antes
ao aos apenas apoia apoio apontar após aquela aquelas aquele aqueles aqui aquilo
as assim através atrás até aí
baixo bast... | 2.40625 | 2 |
miaschiev_ui.py | DarkStarSword/miasmata-fixes | 10 | 20991 | <filename>miaschiev_ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'miaschiev.ui'
#
# Created: Wed Aug 06 17:13:17 2014
# by: pyside-uic 0.2.15 running on PySide 1.2.1
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class U... | 1.4375 | 1 |
layers/db/db/tests/test_db.py | NASA-IMPACT/hls-sentinel2-downloader-serverless | 0 | 20992 | import os
import pytest
from assertpy import assert_that
from ..models.granule import Granule
from ..models.granule_count import GranuleCount
from ..models.status import Status
from ..session import _get_url, get_session, get_session_maker
@pytest.mark.usefixtures("db_connection_secret")
def test_that_db_correctly_... | 2.21875 | 2 |
dexp/processing/utils/_test/test_normalise.py | haesleinhuepf/dexp | 16 | 20993 | import numpy as np
import pytest
from arbol import aprint
from dexp.processing.utils.normalise import Normalise
from dexp.utils.backends import Backend
from dexp.utils.testing.testing import execute_both_backends
@execute_both_backends
@pytest.mark.parametrize(
"dexp_nuclei_background_data",
[dict(length_xy=... | 2.203125 | 2 |
pyCameras/__init__.py | imr-luh/pyCameras | 2 | 20994 | __version__ = '0.0.1'
from . import utils
from .utils import *
| 1.09375 | 1 |
sdfspu/sdf_net.py | soundmaking/sdfspu | 0 | 20995 | <reponame>soundmaking/sdfspu
import socket
def get_ip():
# https://stackoverflow.com/a/28950776/9471339
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
... | 2.859375 | 3 |
pysparkling/sql/expressions/literals.py | ptallada/pysparkling | 260 | 20996 | from ..utils import AnalysisException
from .expressions import Expression
class Literal(Expression):
def __init__(self, value):
super().__init__()
self.value = value
def eval(self, row, schema):
return self.value
def __str__(self):
if self.value is True:
retur... | 2.96875 | 3 |
filter_ICA.py | MadsJensen/RP_scripts | 0 | 20997 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 8 14:45:02 2014.
@author: mje
"""
import mne
import sys
from mne.io import Raw
from mne.preprocessing import ICA, create_eog_epochs, create_ecg_epochs
import matplotlib
matplotlib.use('Agg')
from my_settings import *
subject = sys.argv[1]
# SETTINGS
n_j... | 1.804688 | 2 |
typish/_types.py | georgeharker/typish | 16 | 20998 | <filename>typish/_types.py<gh_stars>10-100
"""
PRIVATE MODULE: do not import (from) it directly.
This module contains types that are not available by default.
"""
import typing
from inspect import Parameter
T = typing.TypeVar('T')
KT = typing.TypeVar('KT')
VT = typing.TypeVar('VT')
Empty = Parameter.empty
Unknown = ... | 2.21875 | 2 |
avidaspatial/transform_data.py | emilydolson/avida-spatial-tools | 1 | 20999 | <reponame>emilydolson/avida-spatial-tools
from .utils import *
from scipy.spatial.distance import pdist
import scipy.cluster.hierarchy as hierarchicalcluster
def rank_environment_and_phenotypes(environment, phenotypes, k=15):
"""
Clusters sets of resources/tasks using a weighted hamming distance such
that... | 3.15625 | 3 |