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 |
|---|---|---|---|---|---|---|
hoomd/communicator.py | EdwardZX/hoomd-blue | 204 | 8400 | # Copyright (c) 2009-2021 The Regents of the University of Michigan
# This file is part of the HOOMD-blue project, released under the BSD 3-Clause
# License.
"""MPI communicator."""
from hoomd import _hoomd
import hoomd
import contextlib
class Communicator(object):
"""MPI communicator.
Args:
mpi_c... | 2.703125 | 3 |
src/affinity-propagation/generate_data.py | dominc8/affinity-propagation | 1 | 8401 | <filename>src/affinity-propagation/generate_data.py
from config import DataGeneratorCfg
from sklearn.datasets.samples_generator import make_blobs
import numpy as np
def generate():
data, true_labels = make_blobs(n_samples=DataGeneratorCfg.n_samples, centers=DataGeneratorCfg.centers, cluster_std=DataGeneratorCfg.cl... | 3 | 3 |
peon/tests/test_project/test_file/test_function_def/test_functions/test_reflection_at_line.py | roch1990/peon | 32 | 8402 | import _ast
from peon.src.project.file.function_def.function import FunctionLint
class ReflectionAtLineFixture:
empty_node = _ast.Pass
is_instance_at_first_lvl = _ast.FunctionDef(id='isinstance', lineno=1)
type_at_first_lvl = _ast.FunctionDef(id='type', lineno=1)
is_instance_at_second_lvl = _ast.Func... | 2.515625 | 3 |
db2_funcs.py | Nama/A.T.S.P.-Website | 4 | 8403 | ###############################################################################
# #
'''Website Database-connection-related features''' #
# #
... | 2.46875 | 2 |
nlp/handler.py | rgschmitz1/tcss702 | 0 | 8404 | <filename>nlp/handler.py
from minio import Minio
import json
import os
from .Inspector import Inspector
from .topic_model import topic_model
#def handle(event):
def handle(event, context):
with open("/var/openfaas/secrets/minio-access-key") as f:
access_key = f.read()
with open("/var/openfaas/secrets/m... | 2.25 | 2 |
src/pve_exporter/cli.py | jmangs/prometheus-pve-exporter | 0 | 8405 | """
Proxmox VE exporter for the Prometheus monitoring system.
"""
import sys
from argparse import ArgumentParser
from pve_exporter.http import start_http_server
def main(args=None):
"""
Main entry point.
"""
parser = ArgumentParser()
parser.add_argument('config', nargs='?', default='pve.yml',
... | 2.640625 | 3 |
workers/repo_info_worker/repo_info_worker.py | vinodkahuja/augur | 2 | 8406 | #SPDX-License-Identifier: MIT
import logging, os, sys, time, requests, json
from datetime import datetime
from multiprocessing import Process, Queue
import pandas as pd
import sqlalchemy as s
from workers.worker_base import Worker
# NOTE: This worker primarily inserts rows into the REPO_INFO table, which serves the pr... | 2.5 | 2 |
benchmark/my_argparser.py | victor-estrade/SystGradDescent | 2 | 8407 | # coding: utf-8
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
import argparse
def parse_args_tolerance():
parser = argparse.ArgumentParser(description='just for tolerance')
parser.add_argument("--tolerance"... | 2.296875 | 2 |
src/main/python/main.py | SarthakJariwala/Shockley-Queisser-Calculator | 1 | 8408 | <reponame>SarthakJariwala/Shockley-Queisser-Calculator
from fbs_runtime.application_context.PyQt5 import ApplicationContext, cached_property
from fbs_runtime.platform import is_windows, is_mac
# system imports
import sys
# module imports
from PyQt5 import uic, QtWidgets
from PyQt5.QtWidgets import QMessageBox
import ... | 2.125 | 2 |
helpus/core.py | tov101/HelpUs | 0 | 8409 | <filename>helpus/core.py
import io
import logging
import os
import sys
from PyQt5 import QtGui, QtCore, QtWidgets
from helpus import icon_file_path
from helpus import __version__
LOGGER = logging.getLogger('HelpUs')
LOGGER.setLevel(logging.DEBUG)
class XStream(QtCore.QObject):
_stdout = None
_stderr = None
... | 2.125 | 2 |
biothings/hub/dataindex/indexer_schedule.py | newgene/biothings.api | 30 | 8410 | import math
class Schedule():
def __init__(self, total, batch_size):
self._batch_size = batch_size
self._state = ""
self.total = total
self.scheduled = 0
self.finished = 0
@property
def _batch(self):
return math.ceil(self.scheduled / self._batch_size)
... | 3.515625 | 4 |
examples/py/async-basic.py | voBits/ccxt | 73 | 8411 | <filename>examples/py/async-basic.py
# -*- coding: utf-8 -*-
import asyncio
import os
import sys
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root + '/python')
import ccxt.async as ccxt # noqa: E402
async def test_gdax():
gdax = ccxt.gdax()
markets = ... | 2.90625 | 3 |
pymclevel/test/__init__.py | bennettdc/MCEdit-Unified | 673 | 8412 | __author__ = 'Rio'
| 1.007813 | 1 |
xview/datasets/wrapper.py | ethz-asl/modular_semantic_segmentation | 20 | 8413 | from abc import ABCMeta, abstractmethod
class DataWrapper:
"""Interface for access to datasets."""
__metaclass__ = ABCMeta
@abstractmethod
def next(self):
"""Returns next minibatch for training."""
return NotImplementedError
| 3.078125 | 3 |
partd/core.py | jrbourbeau/partd | 2 | 8414 | <gh_stars>1-10
from __future__ import absolute_import
import os
import shutil
import locket
import string
from toolz import memoize
from contextlib import contextmanager
from .utils import nested_get, flatten
# http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python
valid_chars = "-_... | 2.640625 | 3 |
pretraining/model_ensemble.py | VITA-Group/Adv-SS-Pretraining | 32 | 8415 | <filename>pretraining/model_ensemble.py
'''
model ensemble for cifar10 // input size(32,32)
'''
import torch
import torchvision
import copy
import torch.nn as nn
from resnetv2 import ResNet50 as resnet50v2
def split_resnet50(model):
return nn.Sequential(
model.conv1,
model.laye... | 2.609375 | 3 |
scripts/ccdf.py | glciampaglia/HoaxyBots | 0 | 8416 | # -*- coding: utf-8 -*-
""" Function that implement Complement the Complementary Cumulative
Distribution Function (CCDF).
"""
#
# written by <NAME> <<EMAIL>>
import numpy as np
import pandas as pd
def ccdf(s):
"""
Parameters:
`s`, series, the values of s should be variable to be handled
Return:
... | 3.171875 | 3 |
lifelines/fitters/kaplan_meier_fitter.py | eliracho37/lifelines | 0 | 8417 | # -*- coding: utf-8 -*-
from __future__ import print_function
import numpy as np
import pandas as pd
from lifelines.fitters import UnivariateFitter
from lifelines.utils import _preprocess_inputs, _additive_estimate, StatError, inv_normal_cdf,\
median_survival_times
from lifelines.plotting import plot_loglogs
cla... | 3.21875 | 3 |
pydmfet/qcwrap/pyscf_rhf.py | fishjojo/pydmfe | 3 | 8418 | import numpy as np
from pydmfet import tools
from .fermi import find_efermi, entropy_corr
from pyscf import ao2mo, gto, scf, dft, lib
from pydmfet.qcwrap import fermi
import time
from functools import reduce
def scf_oei( OEI, Norb, Nelec, smear_sigma = 0.0):
OEI = 0.5*(OEI.T + OEI)
eigenvals, eigenvecs = np.l... | 2 | 2 |
backends/fortify/summarize-fortify.py | tautschnig/one-line-scan | 16 | 8419 | #!/usr/bin/env python
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENS... | 2.65625 | 3 |
aiolookin/__init__.py | bachya/aiolookin | 0 | 8420 | """Define the aiolookin package."""
from .device import async_get_device # noqa
| 1.039063 | 1 |
odepy/collision_space.py | yuemingl/ode-python-1 | 9 | 8421 | <reponame>yuemingl/ode-python-1
# -*- coding: utf-8 -*-
from .common import loadOde
from .common import dGeomID
from .common import dSpaceID
from .common import dVector3
from ctypes import POINTER
from ctypes import CFUNCTYPE
from ctypes import c_void_p
from ctypes import c_int32
dNearCallback = CFUNCTYPE(None, c_vo... | 2.234375 | 2 |
bst.py | phildavis17/DS_A | 0 | 8422 | class BSTNode:
def __init__(self, data = None) -> None:
self.data = data
self.left = None
self.right = None
def __repr__(self) -> str:
return(f"BSTNode({self.data})")
def __str__(self) -> str:
return str(self.data)
def __eq__(self, o: object) -> ... | 3.703125 | 4 |
pctest/test_publish.py | DaveWK/pyth-client | 0 | 8423 | <filename>pctest/test_publish.py<gh_stars>0
#!/usr/bin/python3
# pip3 install websockets
import asyncio
import websockets
import json
import datetime
import sys
class test_publish:
idnum = 1
def __init__( self, sym, price, spread ):
self.symbol = sym
self.pidnum = test_publish.idnum
test_publish.idnu... | 2.328125 | 2 |
Python/other/merge_interval.py | TechSpiritSS/NeoAlgo | 897 | 8424 | '''
Given an array of intervals, merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].... | 4.40625 | 4 |
tests/test_all.py | InnovativeTravel/humilis-lambdautils | 0 | 8425 | """Unit tests."""
import inspect
import json
from mock import Mock
import os
import sys
import uuid
import pytest
# Add the lambda directory to the python library search path
lambda_dir = os.path.join(
os.path.dirname(inspect.getfile(inspect.currentframe())), '..')
sys.path.append(lambda_dir)
import lambdautils... | 2.328125 | 2 |
packages/starcheck/post_regress.py | sot/ska_testr | 0 | 8426 | import os
from testr.packages import make_regress_files
regress_files = ['starcheck.txt',
'starcheck/pcad_att_check.txt']
clean = {'starcheck.txt': [(r'\s*Run on.*[\n\r]*', ''),
(os.environ['SKA'], '')],
'starcheck/pcad_att_check.txt': [(os.environ['SKA'], '')]}
m... | 1.867188 | 2 |
testsite/wsgi.py | stungkit/djaodjin-saas | 0 | 8427 | <reponame>stungkit/djaodjin-saas<gh_stars>0
"""
WSGI config for testsite project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
t... | 1.710938 | 2 |
authserver/maildaemons/forwarder/server.py | jdelic/authserver | 8 | 8428 | <reponame>jdelic/authserver
#!/usr/bin/env python3 -u
# -* encoding: utf-8 *-
import argparse
import asyncore
import json
import logging
import signal
import sys
import os
from types import FrameType
from typing import Tuple, Sequence, Any, Union, Optional, List, Dict
from concurrent.futures import ThreadPoolExecutor... | 1.75 | 2 |
services/backend/project/api/sites.py | kzkaneoka/custom-job-search | 0 | 8429 | <gh_stars>0
import requests
from bs4 import BeautifulSoup, element
class Indeed:
def __init__(self, words, location, offset):
self.url = "https://www.indeed.com/jobs?as_and={}&l={}&sort=date&start={}".format(
"+".join(set(d.strip().lower() for d in words.split(",") if d)),
"+".join... | 2.90625 | 3 |
product_details/utils.py | gene1wood/django-product-details | 0 | 8430 | <reponame>gene1wood/django-product-details<filename>product_details/utils.py
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from product_details import settings_defaults
def settings_fallback(key):
"""Grab user-defined settings, or fall back to default."""
try:
... | 2.0625 | 2 |
kattis/Soda Slurper.py | jaredliw/python-question-bank | 1 | 8431 | # CPU: 0.06 s
possessed, found, condition = map(int, input().split())
possessed += found
count = 0
while possessed >= condition:
div, mod = divmod(possessed, condition)
count += div
possessed = div + mod
print(count)
| 3.25 | 3 |
efficientdet/dataset/csv_.py | HyunjiEllenPak/automl | 0 | 8432 | <gh_stars>0
"""
Copyright 2017-2018 yhenon (https://github.com/yhenon/)
Copyright 2017-2018 Fizyr (https://fizyr.com)
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/licen... | 2.171875 | 2 |
hoover/site/wsgi.py | hoover/hoover | 15 | 8433 | <gh_stars>10-100
from . import events # noqa
from django.core.wsgi import get_wsgi_application
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hoover.site.settings")
application = get_wsgi_application()
| 1.351563 | 1 |
submodules/hal/analysis/constraintTurnover/turnoverModel.py | pbasting/cactus | 0 | 8434 | #!/usr/bin/env python
#Copyright (C) 2013 by <NAME>
#
#Released under the MIT license, see LICENSE.txt
#!/usr/bin/env python
"""This is a two-state continuous time markov model: 0: unconstratined. 1: constrained. There are two transition rates to go between states. lossRate: 1->0 and gainRate: 0->1. Probability M... | 2.78125 | 3 |
SimpleBudget/SimpleBudget/budgets/tests.py | speratus/SimpleBudget | 0 | 8435 | from django.test import TestCase
from .validators import validate_budget_period
from .models import Budget, Expense, Payment
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
class ExpenseTestCases(TestCase):
def setUp(self) -> None:
user = User.objects.create... | 2.546875 | 3 |
feed/migrations/0002_remove_player_finished_decks.py | kubapi/hater | 0 | 8436 | <reponame>kubapi/hater
# Generated by Django 3.2.3 on 2021-06-13 19:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('feed', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='player',
name='finished_... | 1.140625 | 1 |
var/spack/repos/builtin/packages/abacus/package.py | jeanbez/spack | 0 | 8437 | # Copyright 2013-2022 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)
import re
from spack.package import *
class Abacus(MakefilePackage):
"""ABACUS (Atomic-orbital Based Ab-initio Com... | 1.648438 | 2 |
test/regression/features/arithmetic/mult.py | ppelleti/berp | 137 | 8438 | print(18 * 1234)
print(18 * 1234 * 2)
print(0 * 1)
print(1 * 0)
print(0.0 * 1.0)
print(1.0 * 0.0)
| 2.296875 | 2 |
001146StepikPyBegin/Stepik001146PyBeginсh02p05st15C09_20200411.py | SafonovMikhail/python_000577 | 0 | 8439 | num = int(input())
d1 = (num % 10 ** 4) // 10 ** 3
d2 = (num % 10 ** 3) // 10 ** 2
d3 = (num % 10 ** 2) // 10
d4 = num % 10
print("Цифра в позиции тысяч равна", d1)
print("Цифра в позиции сотен равна", d2)
print("Цифра в позиции десятков равна", d3)
print("Цифра в позиции единиц равна", d4)
# print("Python", , "is the ... | 3.796875 | 4 |
WP3/Task3.2/spark/shared/addcountry2dataset.py | on-merrit/ON-MERRIT | 2 | 8440 | <filename>WP3/Task3.2/spark/shared/addcountry2dataset.py
import csv
from os import listdir
from os.path import isfile, join
from osgeo import ogr
from multiprocessing import Pool
driver = ogr.GetDriverByName('GeoJSON')
countryFile = driver.Open("../data/external/countries.json")
layer = countryFile.GetLayer()
class... | 2.734375 | 3 |
ai-experiments/sudoku/rdisplay.py | Henchel-Santillan/open-ai | 0 | 8441 | import cv2
import numpy as np
def process_core(image):
'''
Returns an inverted preprocessed binary image, with noise
reduction achieved with greyscaling, Gaussian Blur, Otsu's Threshold, and
an open morph.
'''
#apply greyscaling, Gaussian Blur, and Otsu's Threshold
greyscale = cv2.cvtColor... | 3.109375 | 3 |
pythia/tasks/base_task.py | abhiskk/pythia | 2 | 8442 | <filename>pythia/tasks/base_task.py
# Copyright (c) Facebook, Inc. and its affiliates.
"""
Tasks come above datasets in hierarchy level. In case you want to
implement a new task, you need to inherit ``BaseTask`` class. You need
to implement ``_get_available_datasets`` and ``_preprocess_item`` functions
to complete the ... | 2.328125 | 2 |
src/gauss_n.py | Konstantysz/InterGen | 0 | 8443 | <reponame>Konstantysz/InterGen
from numba import jit
import numpy as np
@jit(nopython=True, parallel=True)
def gauss_n(X, Y, mu_x = 0.0, mu_y = 0.0, amp = 1.0, sigma = 3.0):
'''
Function that generates 2D discrete gaussian distribution.
Boosted with Numba: works in C and with parallel computing.
Param... | 3.28125 | 3 |
satori.core/satori/core/export/pc.py | Cloud11665/satori-git | 4 | 8444 | <reponame>Cloud11665/satori-git<gh_stars>1-10
# vim:ts=4:sts=4:sw=4:expandtab
from token import token_container
from satori.core.export.type_helpers import DefineException
AccessDenied = DefineException('AccessDenied', 'You don\'t have rights to call this procedure')
class PCDeny(object):
def __call__(__pc__self... | 2.078125 | 2 |
appimagebuilder/orchestrator.py | AppImageCrafters/AppImageBuilder | 0 | 8445 | <reponame>AppImageCrafters/AppImageBuilder<filename>appimagebuilder/orchestrator.py
# Copyright 2021 <NAME>
#
# 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, includi... | 1.992188 | 2 |
API_Collections/googlemap_geocode.py | Musketeer-Liu/Auto_Coding_Tools_Box | 0 | 8446 | <gh_stars>0
# python3 --> Enter Python Shell
# from geocode import getGeocodeLocation
# getGeocodeLocation("Place you wanto to query")
import httplib2
import json
def getGeocodeLocation(inputString):
google_api_key = "<KEY>"
locatationString = inputString.replace(" ", "+")
url = ('https://maps.googleapi... | 3.140625 | 3 |
backend/core/actions/actionGenerator.py | makakken/roseguarden | 0 | 8447 | <reponame>makakken/roseguarden<gh_stars>0
"""
The roseguarden project
Copyright (C) 2018-2020 <NAME>,
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your op... | 2.296875 | 2 |
lib/csv/csv.py | arnscott/gcounter | 0 | 8448 | """
MIT License
Copyright (c) 2018 <NAME>
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, publish, distri... | 2.546875 | 3 |
Module01/LearningQGIS_ThirdEdition_Code/Chapter6_code/export_map.py | karant17/Test | 7 | 8449 | from PyQt4.QtGui import QImage, QPainter
from PyQt4.QtCore import QSize
# configure the output image
width = 800
height = 600
dpi = 92
img = QImage(QSize(width, height), QImage.Format_RGB32)
img.setDotsPerMeterX(dpi / 25.4 * 1000)
img.setDotsPerMeterY(dpi / 25.4 * 1000)
# get the map layers and extent
layers ... | 2.5 | 2 |
tools/generate_cropped_dataset.py | DIVA-DIA/DIVA-DAF | 3 | 8450 | <reponame>DIVA-DIA/DIVA-DAF
"""
Load a dataset of historic documents by specifying the folder where its located.
"""
import argparse
# Utils
import itertools
import logging
import math
from datetime import datetime
from pathlib import Path
from torchvision.datasets.folder import has_file_allowed_extension, pil_loader... | 2.46875 | 2 |
run.py | seanzhangJM/torch_model_demo | 0 | 8451 | <gh_stars>0
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/12/27 14:04
# @Author : zhangjianming
# @Email : <EMAIL>
# @File : run_task.py
# @Software: PyCharm
import sys
sys.path.extend(["."])
from torch_model_demo.task.run_task import train_fashion_demo
if __name__ == '__main__':
train_f... | 1.820313 | 2 |
practice/4_tracking/tracker.py | OrangeRedeng/CV-SUMMER-CAMP-2021 | 13 | 8452 | <gh_stars>10-100
import numpy as np
import math
import logging as log
import sys
from tqdm import tqdm
from common.feature_distance import calc_features_similarity
from common.common_objects import DetectedObject, validate_detected_object, Bbox
from common.common_objects import get_bbox_center, get_dist, calc_bbox_area... | 2.03125 | 2 |
gm2m/managers.py | mikewolfd/django-gm2m | 0 | 8453 | from django.db import router
from django.db.models import Q, Manager
from django.db import connections
from .contenttypes import ct, get_content_type
from .query import GM2MTgtQuerySet
class GM2MBaseManager(Manager):
use_in_migration = True
def __init__(self, instance):
super(GM2MBaseM... | 2.03125 | 2 |
rastreador-de-bolso/TwitterListener.py | vitorduarte/RastreadorDeBolso | 1 | 8454 | from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import logging
import coloredlogs
import os
import pathlib
import time
import twitter as tt
from utils import retry
from fetch_likes import get_user_likes, login
from conf.settings import USER_ID, USERNAME, PASSWORD
CURR_PATH = path... | 2.359375 | 2 |
smartexcel/tests/data/data_models/dummy.py | pierrealixt/SmartExcel | 0 | 8455 | class Dummy():
def __init__(self, data):
self.name = data['name']
self.age = data['age']
self.city = data['city']
class DummyData():
def __init__(self):
self.results = [
Dummy({
'name': 'PA',
'age': 29,
'city': 'Paris'... | 3.515625 | 4 |
ASR_TransV1/Load_sp_model.py | HariKrishna-Vydana/ASR_Transformer | 1 | 8456 | <gh_stars>1-10
#!/usr/bin/python
import sys
import os
from os.path import join, isdir
import sentencepiece as spm
#--------------------------
def Load_sp_models(PATH):
PATH_model = spm.SentencePieceProcessor()
PATH_model.Load(join(PATH))
return PATH_model
#--------------------------
| 1.921875 | 2 |
fiepipedesktoplib/gitlabserver/shell/manager.py | leith-bartrich/fiepipe_desktop | 0 | 8457 | <filename>fiepipedesktoplib/gitlabserver/shell/manager.py<gh_stars>0
import typing
from fiepipelib.gitlabserver.data.gitlab_server import GitLabServer
from fiepipelib.gitlabserver.routines.manager import GitLabServerManagerInteractiveRoutines
from fiepipedesktoplib.gitlabserver.shell.gitlab_hostname_input_ui import Gi... | 1.695313 | 2 |
fairseq/models/wav2vec/eteh_model/transformer/repeat.py | gaochangfeng/fairseq | 0 | 8458 | import torch
class MultiSequential(torch.nn.Sequential):
"""Multi-input multi-output torch.nn.Sequential"""
def forward(self, *args):
for m in self:
args = m(*args)
return args
def repeat(N, fn):
"""repeat module N times
:param int N: repeat time
:param function fn:... | 3.0625 | 3 |
torch_lib/Nets.py | troncosoae/jetson-exp | 0 | 8459 | <filename>torch_lib/Nets.py<gh_stars>0
import torch
import torch.nn as nn
import torch.nn.functional as F
class MediumNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(
3, out_channels=6, kernel_size=5, padding=0)
self.pool1 = nn.MaxPool2d(kernel_siz... | 2.6875 | 3 |
test123.py | umousesonic/zinc | 0 | 8460 | from runner import runner
if __name__ == '__main__':
r = runner()
p = 'public class main{public static void main (String[] args){' \
'public String StudentAnswer(String myInput){' \
'return "myOutput"; ' \
'}System.out.println("hello world!");}}'
print (r.sendCode(p, '')) | 2.75 | 3 |
beancount_bot/bot.py | dumbPy/beancount_bot | 0 | 8461 | <reponame>dumbPy/beancount_bot
import traceback
import telebot
from telebot import apihelper
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, MessageEntity, Message, CallbackQuery
from beancount_bot import transaction
from beancount_bot.config import get_config, load_config
from beancount_bot.disp... | 2.03125 | 2 |
test/unit/metrics/test_group_sklearn_wrappers.py | GeGao2014/fairlearn | 2 | 8462 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import pytest
import numpy as np
import sklearn.metrics as skm
import fairlearn.metrics as metrics
# ======================================================
a = "a"
b = "b"
c = "c"
Y_true = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0... | 2.3125 | 2 |
deeplearning/tf_util.py | cbschaff/nlimb | 12 | 8463 | """
Adapted from OpenAI Baselines.
"""
import numpy as np
import tensorflow as tf # pylint: ignore-module
import random
import copy
import os
import functools
import collections
import multiprocessing
def switch(condition, then_expression, else_expression):
"""Switches between two operations depending on a scala... | 2.8125 | 3 |
Util/constant.py | RoboCupULaval/StrategyAI | 13 | 8464 | # Under MIT License, see LICENSE.txt
""" Module définissant des constantes de programmations python pour l'IA """
from enum import Enum
ROBOT_RADIUS = 90
ROBOT_DIAMETER = ROBOT_RADIUS * 2
ROBOT_CENTER_TO_KICKER = 60
BALL_RADIUS = 21
MAX_PLAYER_ON_FIELD_PER_TEAM = 6
BALL_OUTSIDE_FIELD_BUFFER = 200
# Radius and angle... | 3.3125 | 3 |
src/transbigdata/CoordinatesConverter.py | cirno1w/transport | 1 | 8465 | <gh_stars>1-10
import numpy as np
x_pi = 3.14159265358979324 * 3000.0 / 180.0
pi = 3.1415926535897932384626
a = 6378245.0
ee = 0.00669342162296594323
def gcj02tobd09(lng, lat):
"""
Convert coordinates from GCJ02 to BD09
Parameters
-------
lng : Series or number
Longitude
lat : Se... | 2.734375 | 3 |
cloudify_rest_client/exceptions.py | aleixsanchis/cloudify-rest-client | 0 | 8466 | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... | 1.960938 | 2 |
sample-demo-lambda-app/lambda_function.py | sriharshams-aws/aws-codeguru-profiler-python-demo-application | 6 | 8467 | <gh_stars>1-10
import boto3
import logging
import os
from random import randrange
from urllib.request import urlopen
# It is not recommended to enable DEBUG logs in production,
# this is just to show an example of a recommendation
# by Amazon CodeGuru Profiler.
logging.getLogger('botocore').setLevel(logging.DEBUG)
S... | 2.421875 | 2 |
api/error_handler.py | chuo06/palindrome | 0 | 8468 | from functools import wraps
from werkzeug.exceptions import HTTPException
from api.exceptions import MessageNotFound
def api_error_handler(func):
@wraps(func)
def handle_errors(*args, **kwargs):
try:
return func(*args, **kwargs)
except MessageNotFound as e:
return e.mes... | 2.5 | 2 |
src/nile/core/run.py | kootsZhin/nile | 121 | 8469 | """Command to run Nile scripts."""
import logging
from importlib.machinery import SourceFileLoader
from nile.nre import NileRuntimeEnvironment
def run(path, network):
"""Run nile scripts passing on the NRE object."""
logger = logging.getLogger()
logger.disabled = True
script = SourceFileLoader("scrip... | 2.046875 | 2 |
Python/Basic Data Types/Lists/Solution.py | PawarAditi/HackerRank | 219 | 8470 | <reponame>PawarAditi/HackerRank
array = []
for _ in range(int(input())):
command = input().strip().split(" ")
cmd_type = command[0]
if (cmd_type == "print"):
print(array)
elif (cmd_type == "sort"):
array.sort()
elif (cmd_type == "reverse"):
array.reverse()
elif (cmd_type ... | 3.8125 | 4 |
dbestclient/ml/density.py | horeapinca/DBEstClient | 0 | 8471 | <filename>dbestclient/ml/density.py
# Created by <NAME> at 2019-07-23
# All right reserved
# Department of Computer Science
# the University of Warwick
# <EMAIL>
from sklearn.neighbors import KernelDensity
class DBEstDensity:
def __init__(self, kernel=None):
if kernel is None:
self.kernel = '... | 2.515625 | 3 |
setup.py | panchambanerjee/access_spotify | 4 | 8472 | #!/usr/bin/env python
import setuptools
from setuptools import setup
from os import path
# Read the package requirements
with open("requirements.txt", "r") as f:
requirements = [line.rstrip("\n") for line in f if line != "\n"]
# Read the contents of the README file
this_directory = path.abspath(path.dirname(__fi... | 1.914063 | 2 |
mundiapi/models/update_plan_request.py | hugocpolos/MundiAPI-PYTHON | 10 | 8473 | # -*- coding: utf-8 -*-
"""
mundiapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class UpdatePlanRequest(object):
"""Implementation of the 'UpdatePlanRequest' model.
Request for updating a plan
Attributes:
name (string): Plan's n... | 2.359375 | 2 |
hearthstone/hslog/utils.py | bertokhoury/python-hearthstone | 1 | 8474 | <filename>hearthstone/hslog/utils.py
from hearthstone.enums import GameTag, TAG_TYPES
def parse_enum(enum, value):
if value.isdigit():
value = int(value)
elif hasattr(enum, value):
value = getattr(enum, value)
else:
raise Exception("Unhandled %s: %r" % (enum, value))
return value
def parse_tag(tag, value)... | 2.890625 | 3 |
ejemplo_clase_00.py | ernestoarzabala/Curso-Python-Utch | 0 | 8475 | <gh_stars>0
# Archivo ejemplo 00 de creacion de clases en Python
from math import gcd # greatest common denominator = Maximo Comun Divisor (MCD)
class Fraccion:
""" La clase Fraccion: Una fraccion es un part de enteros: un numerador (num)
y un denominador (den !=0 ) cuyo MCD es 1.
"""
def __init_... | 3.578125 | 4 |
addons14/base_rest/__init__.py | odoochain/addons_oca | 1 | 8476 | from . import models
from . import components
from . import http
| 1.125 | 1 |
recs/live_project_popularity_recommender.py | WingCode/live-project | 0 | 8477 | import os
import pandas as pd
class LiveProjectPopularityBasedRecs:
def __init__(self):
self.charts = {}
charts_folder = "charts"
if os.path.isdir(charts_folder):
for file in os.listdir("charts"):
name, ext = file.split('.')
if ext == "csv" an... | 3.0625 | 3 |
resource/pypi/cffi-1.9.1/testing/cffi0/snippets/distutils_module/setup.py | hipnusleo/Laserjet | 0 | 8478 | <filename>resource/pypi/cffi-1.9.1/testing/cffi0/snippets/distutils_module/setup.py<gh_stars>0
from distutils.core import setup
import snip_basic_verify
setup(
py_modules=['snip_basic_verify'],
ext_modules=[snip_basic_verify.ffi.verifier.get_extension()])
| 1.273438 | 1 |
pce/src/testing/test_pce.py | elise-baumgartner/onramp | 2 | 8479 | #!../env/bin/python
"""A simple test script for the PCE portion of OnRamp.
Usage: ./test_pce.py
This script is only intended to be run in a fresh install of the repository. It
has side-effects that could corrupt module and user data if run in a production
setting.
Prior to running this script, ensure that onramp/pce... | 2.109375 | 2 |
tobac/plotting.py | w-herbst/tobac | 36 | 8480 | <filename>tobac/plotting.py<gh_stars>10-100
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import logging
from .analysis import lifetime_histogram
from .analysis import histogram_cellwise,histogram_featurewise
import numpy as np
def plot_tracks_mask_field_loop(track,field,mask,features,axes=N... | 1.773438 | 2 |
api/urls.py | nf1s/covid-backend | 0 | 8481 | from sanic import Blueprint
from sanic_transmute import add_route
from .views import (
get_all,
get_status_by_country_id,
get_status_by_country_name,
get_deaths,
get_active_cases,
get_recovered_cases,
get_confirmed_cases,
list_countries,
)
cases = Blueprint("cases", url_prefix="/cases")... | 1.851563 | 2 |
scribdl/test/test_download.py | fatshotty/scribd-downloader | 182 | 8482 | <filename>scribdl/test/test_download.py
from ..downloader import Downloader
import os
import pytest
@pytest.fixture
def cwd_to_tmpdir(tmpdir):
os.chdir(str(tmpdir))
def test_audiobook_download(cwd_to_tmpdir, monkeypatch):
audiobook_url = "https://www.scribd.com/audiobook/237606860/100-Ways-to-Motivate-Your... | 2.34375 | 2 |
app/migrations/0005_auto_20210619_2310.py | hungitptit/boecdjango | 0 | 8483 | <gh_stars>0
# Generated by Django 3.2.4 on 2021-06-19 16:10
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20210619_1802'),
]
operations = [
migrations.AddField(
model_name='com... | 1.78125 | 2 |
vision_datasets/common/dataset_registry.py | shonohs/vision-datasets | 0 | 8484 | <filename>vision_datasets/common/dataset_registry.py
import copy
import json
from .dataset_info import DatasetInfoFactory
class DatasetRegistry:
"""
A central registry of all available datasets
"""
def __init__(self, datasets_json: str):
self.datasets = [DatasetInfoFactory.create(d) for d in ... | 2.390625 | 2 |
yasql/apps/sqlorders/views.py | Fanduzi/YaSQL | 443 | 8485 | # -*- coding:utf-8 -*-
# edit by fuzongfei
import base64
import datetime
# Create your views here.
import json
from django.http import Http404, HttpResponse
from django.utils import timezone
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.exceptions ... | 2.03125 | 2 |
perp_adj.py | shmakn99/Knowledge-Graph-VG | 0 | 8486 | <gh_stars>0
import glove_util as gut
import numpy as np
from sklearn.decomposition import TruncatedSVD
import json
with open('freq_count_pred.json') as f:
freq_count_pred = json.load(f)
def get_pc(sentences):
svd = TruncatedSVD(n_components=1, n_iter=7, random_state=0)
svd.fit(sentences)
return svd.components_
... | 2.171875 | 2 |
crypt.py | ElyTgy/VaultDB | 2 | 8487 | # Importing Fernet class
from cryptography.fernet import Fernet
# Importing dump and load function
from pickle import dump,load
# To generate a strong pw
def generate_pw():
from random import choice
choices = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=.,/<>?;:\\|[... | 3.484375 | 3 |
oecp/executor/null.py | openeuler-mirror/oecp | 0 | 8488 | # -*- encoding=utf-8 -*-
"""
# **********************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# [oecp] is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL ... | 1.914063 | 2 |
courses/models.py | Biswa5812/CaramelIT-Django-Backend | 1 | 8489 | from django.db import models
from django.utils import timezone
# Course Category
class Course_category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=100)
date_of_creation = models.DateTimeField(default=timezone.now)
# Course Subcategory
class ... | 2.203125 | 2 |
dino/validation/events/message/limit_msg_length.py | thenetcircle/dino | 150 | 8490 | <reponame>thenetcircle/dino
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwar... | 1.820313 | 2 |
zabbix/prom2zabbix.py | tldr-devops/telegraf-monitoring-agent-setup | 0 | 8491 | <filename>zabbix/prom2zabbix.py<gh_stars>0
#!/usr/bin/env python
# Script for parsing prometheus metrics format and send it into zabbix server
# MIT License
# https://github.com/Friz-zy/telegraf-monitoring-agent-setup
import re
import os
import sys
import time
import json
import socket
import optparse
try:
from u... | 2.421875 | 2 |
NAS/run_NAS.py | gatech-sysml/CompOFA | 20 | 8492 | <reponame>gatech-sysml/CompOFA<gh_stars>10-100
# CompOFA – Compound Once-For-All Networks for Faster Multi-Platform Deployment
# Under blind review at ICLR 2021: https://openreview.net/forum?id=IgIk8RRT-Z
#
# Implementation based on:
# Once for All: Train One Network and Specialize it for Efficient Deployment
# <NAME>,... | 2.203125 | 2 |
application/model/radar_score_20180117/score_calculate.py | ace-gabriel/chrome-extension | 4 | 8493 | <gh_stars>1-10
# coding: utf-8
import pickle
# import json
# import types
path = 'application/model/radar_score_20180117/'
def f(x, x_range, score):
bottom = 20
y = []
for i in x:
if i < x_range[0]:
pos = 0
else:
for j in range(len(x_range)):
if j == len(x_range) - 1 or \
... | 2.6875 | 3 |
Dominant_cell.py | xi6th/Python_Algorithm | 0 | 8494 | <filename>Dominant_cell.py
#!/bin/python3
import math
import os
import random
import re
import sys
from typing import Counter
#
# Complete the 'numCells' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY grid as parameter.
#
def numCells(grid):
# Write y... | 3.734375 | 4 |
evetool/urls.py | Sult/evetool | 0 | 8495 | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
urlpatterns = [
# Examples:
# url(r'^$', 'evetool.views.home', name='home'),
url(r'^', include('users.urls')),
url(r'^', include('apis.urls')),
] + static(settings.STATIC_URL, document_... | 1.648438 | 2 |
actvenv.py | lastone9182/console-keep | 0 | 8496 | <filename>actvenv.py<gh_stars>0
import os
# virtualenv
SCRIPTDIR = os.path.realpath(os.path.dirname(__file__))
venv_name = '_ck'
osdir = 'Scripts' if os.name is 'nt' else 'bin'
venv = os.path.join(venv_name, osdir, 'activate_this.py')
activate_this = (os.path.join(SCRIPTDIR, venv))
# Python 3: exec(open(...).read()),... | 2.03125 | 2 |
testing/scripts/checklicenses.py | zealoussnow/chromium | 14,668 | 8497 | <reponame>zealoussnow/chromium
#!/usr/bin/env python
# Copyright 2015 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 json
import os
import sys
import common
def main_run(args):
with common.temporary_file() as... | 2.203125 | 2 |
autoPyTorch/utils/benchmarking/benchmark_pipeline/for_autonet_config.py | gaohuan2015/Auto-PyTorch | 1 | 8498 | <reponame>gaohuan2015/Auto-PyTorch
from autoPyTorch.utils.config.config_option import ConfigOption
from autoPyTorch.pipeline.base.sub_pipeline_node import SubPipelineNode
import traceback
class ForAutoNetConfig(SubPipelineNode):
def fit(self, pipeline_config, autonet, instance, data_manager, run_id, task_id):
... | 2.40625 | 2 |
csv/query_csv.py | RobustPerception/python_examples | 31 | 8499 | <gh_stars>10-100
import csv
import requests
import sys
"""
A simple program to print the result of a Prometheus query as CSV.
"""
if len(sys.argv) != 3:
print('Usage: {0} http://prometheus:9090 a_query'.format(sys.argv[0]))
sys.exit(1)
response = requests.get('{0}/api/v1/query'.format(sys.argv[1]),
p... | 3.28125 | 3 |