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 |
|---|---|---|---|---|---|---|
beansdbadmin/core/client.py | ariesdevil/beansdbadmin | 11 | 400 | <filename>beansdbadmin/core/client.py
#!/usr/bin/python
# encoding: utf-8
'''a rich client
1. for one server (instead of multi like in libmc.Client)
2. encapsulate @, ?, gc ...
use is instead of libmc.Client
'''
import telnetlib
import logging
import libmc
import string
import urllib
import itertools
import w... | 2.25 | 2 |
Simulator/Geometry/RectOverlap.py | cuixiongyi/RBE595 | 0 | 401 | import matplotlib.pyplot
__author__ = 'xiongyi'
line1 = [(200, 100), (200, 400)]
line2 = [(190, 190), (210, 210)]
def overlap():
l1p1x = line1[0][0]
l1p1y = line1[0][1]
l1p2x = line1[1][0]
l1p2y = line1[1][1]
# make sure p1x < p2x
if l1p1x > l1p2x:
tmp = l1p1x
l1p1x = l1p2x
... | 3.125 | 3 |
gino/loader.py | p4l1ly/gino | 0 | 402 | <reponame>p4l1ly/gino<gh_stars>0
from sqlalchemy import select
from sqlalchemy.schema import Column
from .declarative import Model
class Loader:
@classmethod
def get(cls, value):
from .crud import Alias
if isinstance(value, Loader):
rv = value
elif isinstance(value, type)... | 2.515625 | 3 |
emission/clients/choice/choice.py | Andrew-Tan/e-mission-server | 0 | 403 | <gh_stars>0
# Standard imports
import logging
import math
import json
from uuid import UUID
from datetime import datetime, timedelta
import time
# Our imports
from emission.core.get_database import get_trip_db, get_section_db
import emission.analysis.result.carbon as carbon
import emission.core.common as common
import... | 2.234375 | 2 |
lib/formatter/text.py | ylafon/redbot | 0 | 404 | <gh_stars>0
#!/usr/bin/env python
"""
HAR Formatter for REDbot.
"""
__author__ = "<NAME> <<EMAIL>>"
__copyright__ = """\
Copyright (c) 2008-2010 <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 Sof... | 2.09375 | 2 |
lib/ioe_pot.py | ifurusato/ros | 9 | 405 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 by <NAME>. All rights reserved. This file is part
# of the Robot Operating System project, released under the MIT License. Please
# see the LICENSE file included as part of this package.
#
# author: <NAME>
# created: 2020-09-19
# modified: 2020-0... | 2.609375 | 3 |
stubs/micropython-esp32-1_12/urequests.py | RonaldHiemstra/micropython-stubs | 38 | 406 | """
Module: 'urequests' on esp32 1.12.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with ESP32')
# Stubber: 1.3.2
class Response:
''
def close():
pass
content = None
def json():
pass
text = None
def... | 1.6875 | 2 |
python/re_user.py | seckcoder/lang-learn | 1 | 407 | <filename>python/re_user.py
#!/usr/bin/env python
#-*- coding=utf-8 -*-
#
# Copyright 2012 Jike Inc. All Rights Reserved.
# Author: <EMAIL>
import re
from urlparse import urlparse
def parse1():
p = re.compile(r"/(?P<uid>\d+)/(?P<mid>\w+)")
o = urlparse("http://weibo.com/2827699110/yz62AlEjF")
m = p.search... | 3.109375 | 3 |
TransactionBook/gui_kivy/generic/MultiSelectPopUp.py | LukHad/AccountBook | 0 | 408 | <reponame>LukHad/AccountBook<filename>TransactionBook/gui_kivy/generic/MultiSelectPopUp.py
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg
from kivy.uix.anchorlayout import AnchorL... | 2.453125 | 2 |
Assignment1/Part2/Bridge2.py | MormonJesus69420/Knowledge-Based-Systems-Project | 0 | 409 | <reponame>MormonJesus69420/Knowledge-Based-Systems-Project
from dataclasses import dataclass, field
from typing import List
from Car2 import Car
@dataclass
class Bridge:
"""Bridge class simulating the behaviour of bridge in simulation.
On can set specific length and capacity for the bridge to change the over... | 4.21875 | 4 |
lib/tuner_interface.py | jefflundberg/locast2plex | 0 | 410 | <reponame>jefflundberg/locast2plex
import subprocess
import threading
import time
import errno
import socket
import urllib
import pathlib
from io import StringIO
from http.server import BaseHTTPRequestHandler, HTTPServer
import lib.stations as stations
import lib.epg2xml as epg2xml
import lib.channels_m3u as channels_... | 2.359375 | 2 |
{{ cookiecutter.project_name }}/{{ cookiecutter.project_name }}/local/pages/views.py | dcs3spp/cookiecutter-django-api | 0 | 411 | from django import template
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.template import loader
@login_required(login_url="/login/")
def index(request):
context = {}
context["segment"] = "index"
html_template = loader.get_template("index.html"... | 2.421875 | 2 |
audiomentations/core/utils.py | jeongyoonlee/audiomentations | 1 | 412 | <reponame>jeongyoonlee/audiomentations<filename>audiomentations/core/utils.py
import os
from pathlib import Path
import numpy as np
AUDIO_FILENAME_ENDINGS = (".aiff", ".flac", ".m4a", ".mp3", ".ogg", ".opus", ".wav")
def get_file_paths(
root_path, filename_endings=AUDIO_FILENAME_ENDINGS, traverse_subdirectories... | 3.09375 | 3 |
algorithm/python/LeetCode/isValid.py | HoneyS2/meaningful | 0 | 413 | <reponame>HoneyS2/meaningful
s = "([}}])"
stack = []
if len(s) % 2 == 1:
print(False)
exit()
for i in s:
if i == "(":
stack.append("(")
elif i == "[":
stack.append("[")
elif i == "{":
stack.append("{")
elif i == ")":
if len(stack) < 1:
print(False)
... | 3.890625 | 4 |
JupyterHTMLSlides/core.py | williamegomezo/JupyterSlides | 1 | 414 | import random
import string
import os
from IPython.display import display, HTML
from .utils import html_loader
from .utils import get_content
from jinja2 import Template
class JupyterSlides:
def __init__(
self,
content_path='./content.yaml',
table_contents=False
):
self.set_ba... | 2.3125 | 2 |
tests/test_wallet.py | NickeZ/lightning | 1 | 415 | from decimal import Decimal
from fixtures import * # noqa: F401,F403
from fixtures import TEST_NETWORK
from flaky import flaky # noqa: F401
from pyln.client import RpcError, Millisatoshi
from utils import (
only_one, wait_for, sync_blockheight, EXPERIMENTAL_FEATURES, COMPAT,
VALGRIND
)
import os
import pytes... | 2 | 2 |
microbepy/plot/mutation_plot.py | ScienceStacks/MicrobEPy | 1 | 416 | <filename>microbepy/plot/mutation_plot.py
"""Provides plots of mutations for Isolates and Lines."""
from microbepy.common import constants as cn
from microbepy.common.dataframe_sorter import DataframeSorter
from microbepy.common.isolate import Isolate
from microbepy.common import util
from microbepy.correlation impor... | 2.796875 | 3 |
semantic-segmentation/deeplabv3plus/dataset_utils.py | shikisawamura/nnabla-examples | 1 | 417 | <filename>semantic-segmentation/deeplabv3plus/dataset_utils.py
# Copyright (c) 2017 Sony Corporation. 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.a... | 2.625 | 3 |
train.py | shamilcm/fairseq-py | 1 | 418 | # Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
#
import collections
import os
imp... | 1.984375 | 2 |
storm_control/sc_library/log_timing.py | jeffmoffitt/storm-control | 0 | 419 | <gh_stars>0
#!/usr/bin/env python
"""
This parses a log file series (i.e. log, log.1, log.2, etc..) and
outputs timing and call frequency information for HAL messages.
Hazen 5/18
"""
from datetime import datetime
import os
pattern = '%Y-%m-%d %H:%M:%S,%f'
class Message(object):
"""
Storage for the timing o... | 3 | 3 |
django_simple_jsonschema/management/commands/check_schema.py | 38elements/django-simple-jsonschema | 1 | 420 | from django.core.management.base import BaseCommand
from django.utils import termcolors
from jsonschema import Draft4Validator
from jsonschema.exceptions import SchemaError
import json
class Command(BaseCommand):
can_import_settings = True
@property
def _jsonschema_exist(self):
from django.conf ... | 2.234375 | 2 |
lib/interface.py | keke185321/combine-copy- | 0 | 421 | import cv2, time
import numpy as np
import Tkinter
"""
Wraps up some interfaces to opencv user interface methods (displaying
image frames, event handling, etc).
If desired, an alternative UI could be built and imported into get_pulse.py
instead. Opencv is used to perform much of the data analysis, but there is no
re... | 3.125 | 3 |
nltk/tag/brill.py | FGDBTKD/nltk | 0 | 422 | # -*- coding: utf-8 -*-
# Natural Language Toolkit: Transformation-based learning
#
# Copyright (C) 2001-2018 NLTK Project
# Author: <NAME> <<EMAIL>>
# based on previous (nltk2) version by
# <NAME>, <NAME>, <NAME>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import print_fu... | 3.140625 | 3 |
superglue_parsers/wsc.py | agentsolaris/xlnn | 0 | 423 | import json
import logging
import sys
import numpy as np
import torch
from task_config import SuperGLUE_LABEL_MAPPING
from snorkel.mtl.data import MultitaskDataset
sys.path.append("..") # Adds higher directory to python modules path.
logger = logging.getLogger(__name__)
TASK_NAME = "WSC"
def get_char_index(tex... | 1.945313 | 2 |
simplimental/simplimental.py | TimmyCarbone/simplimental | 2 | 424 | import re
import json
__all__ = ["Simplimental"]
class Simplimental:
def __init__(self, text="This is not a bad idea"):
self.text = text
with open('simplimental/data/afinn.json') as data_file:
self.dictionary = json.load(data_file)
no_punctunation = re.sub(r"[^a-zA-Z ]+", " ", self.text)
self.toke... | 3.453125 | 3 |
Python/Examples/Macros/SettingsAxesOptimization.py | archformco/RoboDK-API | 161 | 425 | # This example shows how to read or modify the Axes Optimization settings using the RoboDK API and a JSON string.
# You can select "Axes optimization" in a robot machining menu or the robot parameters to view the axes optimization settings.
# It is possible to update the axes optimization settings attached to a robot o... | 3.046875 | 3 |
tests/test_grammar.py | Vipul97/SLR-Parser | 5 | 426 | <filename>tests/test_grammar.py
from slr_parser.grammar import Grammar
import unittest
class TestGrammar(unittest.TestCase):
def test_grammar(self):
with open('tests/test_grammar.txt') as grammar_file:
self.G = Grammar(grammar_file.read())
self.assertDictEqual(
{'E'... | 3.1875 | 3 |
insight/migrations/0001_initial.py | leonhead/chess-insight | 0 | 427 | # Generated by Django 3.1 on 2020-09-08 07:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='OpeningSystem',
fields=[
... | 1.851563 | 2 |
tests/test_merge.py | jmerizia/parallel-pytorch | 0 | 428 | <filename>tests/test_merge.py
import torch
import numpy as np
from mpi4py import MPI
from parallel_pytorch.ops import tensor_merge
from parallel_pytorch.utils import abort_on_exception
@abort_on_exception
def test_1():
worker_shape = [2, 2]
world = MPI.COMM_WORLD
num_workers = np.array(worker_shape).pro... | 2.125 | 2 |
day07/main.py | tebriel/aoc2021 | 0 | 429 | <filename>day07/main.py
"""Day 07"""
def process(filename):
with open(filename) as infile:
positions = [int(x) for x in infile.readline().strip().split(',')]
min_x = min(positions)
max_x = max(positions)
costs = {x: 0 for x in range(min_x, max_x + 1)}
for pos in costs.keys():
for ... | 3.203125 | 3 |
src/ceres_infer/utils.py | pritchardlabatpsu/cga | 0 | 430 | <filename>src/ceres_infer/utils.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
utilities
@author: boyangzhao
"""
import pandas as pd
import re
def int2ordinal(n):
# partially based on https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement
if (type(n) is int) or n.isdigit():
... | 2.859375 | 3 |
MAIN/Screens/Settings/category_2/__init__.py | aragubas/fogoso | 0 | 431 | <filename>MAIN/Screens/Settings/category_2/__init__.py
#!/usr/bin/python3.7
# Copyright 2020 Aragubas
#
# 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... | 1.960938 | 2 |
tests/test_toggle.py | ConnectionMaster/robotpy-wpilib-utilities | 14 | 432 | from robotpy_ext.control.toggle import Toggle
from robotpy_ext.misc.precise_delay import NotifierDelay
class FakeJoystick:
def __init__(self):
self._pressed = [False] * 2
def getRawButton(self, num):
return self._pressed[num]
def press(self, num):
self._pressed[num] = True
d... | 3.015625 | 3 |
tests/test.py | kjanik70/tflearn | 10,882 | 433 | '''
This file contains test cases for tflearn
'''
import tensorflow.compat.v1 as tf
import tflearn
import unittest
class TestActivations(unittest.TestCase):
'''
This class contains test cases for the functions in tflearn/activations.py
'''
PLACES = 4 # Number of places to match when testing fl... | 2.78125 | 3 |
infrastructure-provisioning/src/general/api/install_libs.py | roolrd/incubator-datalab | 66 | 434 | #!/usr/bin/python3
# *****************************************************************************
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ... | 1.84375 | 2 |
model_zoo/official/nlp/bert_thor/src/evaluation_config.py | GuoSuiming/mindspore | 55 | 435 | # Copyright 2020 Huawei Technologies Co., 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... | 1.625 | 2 |
portal/apps/core/management/commands/sync_articleviewedby.py | Artis-Physis/utopia-cms | 8 | 436 | # -*- coding: utf-8 -*-
# utopia-cms 2020. <NAME>.
from django.core.management import BaseCommand
from django.db.utils import IntegrityError
from apps import core_articleviewedby_mdb
from core.models import ArticleViewedBy
class Command(BaseCommand):
help = "Moves article viewed by data from mongodb to Django m... | 2.09375 | 2 |
examples/minkunet.py | dendisuhubdy/MinkowskiEngine | 1 | 437 | import torch
import torch.nn as nn
from torch.optim import SGD
import MinkowskiEngine as ME
from MinkowskiEngine.modules.resnet_block import BasicBlock, Bottleneck
from examples.common import data_loader
from examples.resnet import ResNetBase
class MinkUNetBase(ResNetBase):
BLOCK = None
PLANES = None
D... | 2.734375 | 3 |
setup.py | swfrench/nginx-access-tailer | 0 | 438 | """TODO."""
from setuptools import setup
setup(
name='nginx-access-tailer',
version='0.1',
author='swfrench',
url='https://github.com/swfrench/nginx-tailer',
packages=['nginx_access_tailer',],
license='BSD three-clause license',
entry_points={
'console_scripts': ['nginx-access-tail... | 1.101563 | 1 |
tests/integration/test_cmk_describe.py | oglok/CPU-Manager-for-Kubernetes | 0 | 439 | <filename>tests/integration/test_cmk_describe.py
# Copyright (c) 2017 Intel Corporation
#
# 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
#
#... | 2.0625 | 2 |
setup.py | richardARPANET/persistent-celery-beat-scheduler | 4 | 440 | #!/usr/bin/env python
# -*- coding: utf-8 -*
import os
from setuptools import find_packages, setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
with open('requirements.txt') as f:
install_requires = f.read().splitlines()
setup(
name... | 1.421875 | 1 |
tests/test_client.py | mgobec/python-memcached | 1 | 441 | import collections
import unittest
import driver
from driver.protocol import *
_server = ('localhost', 11211)
_dead_retry = 30
_socket_timeout = 3
_max_receive_size = 4096
class MockConnection(object):
def __init__(self,
server=_server,
dead_retry=30,
socket_tim... | 2.734375 | 3 |
GREYATOM-PROJECT----DATA--WRANGLING-WITH-PANDAS/code.py | Preethinaidu14/greyatom-python-for-data-science | 0 | 442 | # --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
path
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# code... | 2.9375 | 3 |
venv/Lib/site-packages/patsy/test_regressions.py | EkremBayar/bayar | 710 | 443 | # This file is part of Patsy
# Copyright (C) 2013 <NAME> <<EMAIL>>
# See file LICENSE.txt for license information.
# Regression tests for fixed bugs (when not otherwise better covered somewhere
# else)
from patsy import (EvalEnvironment, dmatrix, build_design_matrices,
PatsyError, Origin)
def test... | 2.15625 | 2 |
skimage/io/_plugins/pil_plugin.py | smheidrich/scikit-image | 3 | 444 | __all__ = ['imread', 'imsave']
import numpy as np
from PIL import Image
from ...util import img_as_ubyte, img_as_uint
def imread(fname, dtype=None, img_num=None, **kwargs):
"""Load an image from file.
Parameters
----------
fname : str or file
File name or file-like-object.
dtype : numpy ... | 3.359375 | 3 |
examples/tellurium-files/linearChain.py | ShaikAsifullah/distributed-tellurium | 1 | 445 | # -*- coding: utf-8 -*-
"""
Linear chain of reactions.
"""
from __future__ import print_function, division
import tellurium as te
model = '''
model feedback()
// Reactions:
J0: $X0 -> S1; (VM1 * (X0 - S1/Keq1))/(1 + X0 + S1 + S4^h);
J1: S1 -> S2; (10 * S1 - 2 * S2) / (1 + S1 + S2);
J2: S2 -> S3; (10 * S2... | 2.78125 | 3 |
backend/app/schemas/__init__.py | kommurisaikumar/savings-manager-server | 0 | 446 | from .users import User, UserCreate, UserUpdate
from .transactions import Transaction, TransactionCreate, TransactionUpdate
from .accounts import Account, AccountList, AccountSingle, AccountCreate, AccountUpdate
from .categories import Category, CategoryCreate, CategoryUpdate | 1.007813 | 1 |
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/s/super/super_with_arguments.py | ciskoinch8/vimrc | 463 | 447 | <filename>vimfiles/bundle/vim-python/submodules/pylint/tests/functional/s/super/super_with_arguments.py
class Foo:
pass
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__() # [super-with-arguments]
class Baz(Foo):
def __init__(self):
super().__init__()
class Qux(Foo):
d... | 2.65625 | 3 |
machine.py | yukti07/Dell_Hire_hack | 0 | 448 | <gh_stars>0
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from flask import flash
import numpy as... | 2.515625 | 3 |
TM-GCN-master/experiment_bitcoin_baseline_link_prediction.py | OsmanMalik/TM-GCN | 14 | 449 | # This version of the bitcoin experiment imports data preprocessed in Matlab, and uses the GCN baseline
# The point of this script is to do link prediction
# Imports and aliases
import pickle
import torch as t
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.datasets as datas... | 2.28125 | 2 |
elm_mnist/elm_mnist.py | ahara/-blog | 0 | 450 | <reponame>ahara/-blog
import cPickle
import numpy as np
from elm import ELMClassifier
from sklearn import linear_model
def load_mnist(path='../Data/mnist.pkl'):
with open(path, 'rb') as f:
return cPickle.load(f)
def get_datasets(data):
_train_x, _train_y = data[0][0], np.array(data[0][1]).reshape(le... | 3 | 3 |
Coding_Part/bob.py | qizhu8/CSCI6230-HW02 | 0 | 451 | # -*- coding: utf-8 -*-
#!/usr/bin/env python3
from PKC_Classes import NetworkUser, KDC
from DES import DES
from RSA_Class import RSA
import socket
import os
import sys
import threading
import time
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")
def reply_conn(conn, addr):
print('Accep... | 2.484375 | 2 |
proj/scripts/cluster/baselines/triplets_greyscale.py | zqma/IIC | 0 | 452 | <filename>proj/scripts/cluster/baselines/triplets_greyscale.py
from __future__ import print_function
import argparse
import itertools
import os
import pickle
import sys
from datetime import datetime
import matplotlib
import numpy as np
import torch
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import proj.a... | 2.34375 | 2 |
migrations/versions/0084_add_job_stats.py | cds-snc/notifier-api | 41 | 453 | """empty message
Revision ID: 0084_add_job_stats
Revises: 0083_add_perm_types_and_svc_perm
Create Date: 2017-05-12 13:16:14.147368
"""
# revision identifiers, used by Alembic.
revision = "0084_add_job_stats"
down_revision = "0083_add_perm_types_and_svc_perm"
import sqlalchemy as sa
from alembic import op
from sqlal... | 1.765625 | 2 |
addons/twofactor/tests/test_models.py | tsukaeru/RDM-osf.io | 11 | 454 | <reponame>tsukaeru/RDM-osf.io
import unittest
from future.moves.urllib.parse import urlparse, urljoin, parse_qs
import pytest
from addons.twofactor.tests.utils import _valid_code
from nose.tools import (assert_equal, assert_false, assert_is_none,
assert_is_not_none, assert_true)
from osf_tests.... | 2.0625 | 2 |
betterloader/standard_transforms.py | BinItAI/BetterLoader | 39 | 455 | <filename>betterloader/standard_transforms.py
import numpy as np
from torchvision import transforms
np.random.seed(1)
class TransformWhileSampling(object):
def __init__(self, transform):
self.transform = transform
def __call__(self, sample):
x1 = self.transform(sample)
x2 = self.tra... | 2.578125 | 3 |
lanedet/runner/utils/net_utils.py | ztjsw/lanedet | 1 | 456 | import torch
import os
from torch import nn
import numpy as np
import torch.nn.functional
from termcolor import colored
from .logger import get_logger
def save_model(net, optim, scheduler, recorder, is_best=False):
model_dir = os.path.join(recorder.work_dir, 'ckpt')
os.system('mkdir -p {}'.format(model_dir))
... | 2.21875 | 2 |
hexafuel_oil/hexafuel_oil_app/apps.py | zante95/Hexafuel-Oil | 0 | 457 | from django.apps import AppConfig #pragma: no cover
class HexafuelOilAppConfig(AppConfig): #pragma: no cover
name = 'hexafuel_oil_app'
| 1.171875 | 1 |
main.py | jonodrew/matchex | 0 | 458 | from __future__ import division
from timeit import default_timer as timer
import csv
import numpy as np
import itertools
from munkres import Munkres, print_matrix, make_cost_matrix
import sys
from classes import *
from functions import *
from math import sqrt
import Tkinter as tk
import tkFileDialog as filedialog
root... | 3.015625 | 3 |
pip_info/setup.py | 95616ARG/SyReNN | 36 | 459 | <reponame>95616ARG/SyReNN<filename>pip_info/setup.py
"""Setup script for PySyReNN.
Adapted from:
https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/
"""
import codecs
import os
import re
from setuptools import setup, find_packages
###############################################################... | 1.867188 | 2 |
neptune/generated/swagger_client/path_constants.py | jiji-online/neptune-cli | 0 | 460 | <filename>neptune/generated/swagger_client/path_constants.py
REST_PATH = u""
WS_PATH = u"/api/notifications/v1"
| 1.046875 | 1 |
load/__init__.py | andrewp-as-is/load.py | 0 | 461 | __all__ = ["load"]
import imp
import importlib
def load(name, path):
"""Load and initialize a module implemented as a Python source file and return its module object"""
if hasattr(importlib, "machinery"):
loader = importlib.machinery.SourceFileLoader(name, path)
return loader.load_module()
... | 2.703125 | 3 |
pygears/svgen/modules/sieve.py | Risto97/pygears | 0 | 462 | <gh_stars>0
import itertools
from pygears.common.sieve import sieve
from pygears.svgen.inst import SVGenInstPlugin
from pygears.svgen.svmod import SVModuleGen
from functools import partial
from pygears.svgen.svgen import SVGenPlugin
from pygears.svgen.util import svgen_visitor
from pygears.core.hier_node import HierVi... | 2.171875 | 2 |
examples/my_model_test.py | gzpyy/qlib | 0 | 463 | <gh_stars>0
#encoding=utf-8
import qlib
import pandas as pd
import pickle
import xgboost as xgb
import numpy as np
import re
from qlib.constant import REG_US
from qlib.utils import exists_qlib_data, init_instance_by_config
from qlib.workflow import R
from qlib.workflow.record_temp import SignalRecord, PortAnaRecord
fro... | 1.890625 | 2 |
realfastapi/routes/endpoints/default.py | wborbajr/RealFastAPI | 0 | 464 | from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def working():
return {"Working"}
| 2.109375 | 2 |
graphzoom/embed_methods/dgi/execute.py | junhoher/GraphZoom | 16 | 465 | <filename>graphzoom/embed_methods/dgi/execute.py
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
import networkx as nx
import time
from embed_methods.dgi.models import DGI, LogReg
from embed_methods.dgi.utils import process
def dgi(G, features):
batch_size = 1
nb_epochs = 10000
... | 2.15625 | 2 |
tools/ci/deploy_to_github_release.py | rodb70/RDMnet | 30 | 466 | <gh_stars>10-100
"""Deploys binaries to a GitHub release given the specified tag name."""
import argparse
import os
import time
from github import Github
THIS_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__))
GH_REPO_IDENT = "ETCLabs/RDMnet"
GH_USERNAME = "svc-etclabs"
GH_API_TOKEN = os.getenv("SVC_ETCLABS... | 2.625 | 3 |
matchms/filtering/add_losses.py | maximskorik/matchms | 0 | 467 | import logging
import numpy
from ..Fragments import Fragments
from ..typing import SpectrumType
logger = logging.getLogger("matchms")
def add_losses(spectrum_in: SpectrumType, loss_mz_from=0.0, loss_mz_to=1000.0) -> SpectrumType:
"""Derive losses based on precursor mass.
Parameters
----------
spect... | 2.453125 | 2 |
cornflow_client/schema/dictSchema.py | baobabsoluciones/cornflow-client | 3 | 468 | <filename>cornflow_client/schema/dictSchema.py<gh_stars>1-10
import re
from .dict_functions import gen_schema, ParameterSchema, sort_dict
from cornflow_client.constants import JSON_TYPES, DATASCHEMA
class DictSchema:
"""
A json-schema to dict-schema parser
"""
def __init__(self, jsonschema):
... | 2.453125 | 2 |
rspub/util/test/test_resourcefilter.py | EHRI/rspub-core | 1 | 469 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import platform
import unittest
import rspub.util.resourcefilter as rf
def on_windows():
opsys = platform.system()
return opsys == "Windows"
class TestPredicates(unittest.TestCase):
def test_directory_pattern_filter_empty(self):
dpf = r... | 2.453125 | 2 |
molecule/ubuntu/tests/test_grafana.py | fiaasco/grafana | 0 | 470 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_package(host):
""" check if packages are installed
"""
assert host.package('grafana').is_installed
def test_service(host)... | 2.078125 | 2 |
heatsink.py | sww1235/heatsink-calc | 1 | 471 | <gh_stars>1-10
"""Class representations of heatsinks."""
import math
from scipy import constants as const
from materials import Aluminium_6063 as aluminium
class Heatsink:
"""
A Heatsink.
Extended by form factor subclasses
"""
def __init__(self, material, configuration):
"""Init materi... | 3.046875 | 3 |
scripts/get_file_name_as_variable.py | amin-henteti/airflow-dags | 0 | 472 | <filename>scripts/get_file_name_as_variable.py<gh_stars>0
import inspect
def foo():
print(inspect.stack()[0][3])
foo() | 2 | 2 |
sovrin/test/did/helper.py | sovrin-foundation/old-sovrin | 3 | 473 | <reponame>sovrin-foundation/old-sovrin
import base58
from plenum.common.signer_did import DidSigner
from plenum.common.verifier import DidVerifier
from plenum.common.eventually import eventually
from plenum.test.helper import assertEquality
from sovrin.common.identity import Identity
MsgForSigning = {'sender': 'Mario... | 1.992188 | 2 |
tests/test_EdiblesSpectrum.py | jancami/edibles | 8 | 474 | <gh_stars>1-10
import astropy
import datetime
import numpy as np
from edibles.utils.edibles_spectrum import EdiblesSpectrum
def testEdiblesSpectrum(filename="tests/HD170740_w860_redl_20140915_O12.fits"):
# Spectrum information
sp = EdiblesSpectrum(filename=filename, fully_featured=True, noDATADIR=True)
a... | 2.03125 | 2 |
swift/common/ondisk.py | citrix-openstack-build/swift | 1 | 475 | <reponame>citrix-openstack-build/swift
# Copyright (c) 2010-2013 OpenStack, 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/licenses/LICENSE-2.0
#
# Unless r... | 2.296875 | 2 |
.OLD_FILES/dossiers2_old1/custom/cache.py | KIHestad/WoT-Dossier-Parser-Create-Struct | 0 | 476 | # uncompyle6 version 2.11.3
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
# Embedded file name: scripts/common/dossiers2/custom/cache.py
import nations
from items import vehicles
def getCache():
global _g_cache
return _g_cache
def ... | 2.296875 | 2 |
src/parser.py | harkiratbehl/PyGM | 2 | 477 | <gh_stars>1-10
#!/usr/bin/python
from code import TreeNode
from code import ThreeAddressCode
from lexer import tokens
from random import *
from symbol_table import SymbolTable
from symbol_table import SymbolTableNode
import logging
import ply.lex as lex
import ply.yacc as yacc
import sys
from codegen import conver... | 2.671875 | 3 |
render_video.py | frostburn/branch-cut-mandelbrot | 0 | 478 | <gh_stars>0
import argparse
import imageio
import progressbar
from _routines import ffi, lib
from pylab import *
from random import Random
RESOLUTIONS = {
"2160p": (3840, 2160),
"1440p": (2560, 1440),
"1080p": (1920, 1080),
"720p": (1280, 720),
"480p": (854, 480),
"360p": (640, 360),
"240p"... | 2.40625 | 2 |
tests/mqtt/test_subscribe.py | smurfix/hbmqtt | 0 | 479 | <filename>tests/mqtt/test_subscribe.py
# Copyright (c) 2015 <NAME>
#
# See the file license.txt for copying permission.
import anyio
import unittest
from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload
from hbmqtt.mqtt.packet import PacketIdVariableHeader
from hbmqtt.mqtt.constants import QOS_1, QOS_2
f... | 2.359375 | 2 |
examples/cmrc2018_example/main.trainer.py | fangd123/TextBrewer | 1,121 | 480 | <filename>examples/cmrc2018_example/main.trainer.py<gh_stars>1000+
import logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
level=logging.INFO,
)
logger = logging.getLogger("Main")
import os,random
import numpy as np
import torch
f... | 2.203125 | 2 |
gym/gym/benchmarks/__init__.py | youngwoon/DnC-RL-Tensorflow | 9 | 481 | <reponame>youngwoon/DnC-RL-Tensorflow<gh_stars>1-10
# EXPERIMENTAL: all may be removed soon
from gym.benchmarks import scoring
from gym.benchmarks.registration import benchmark_spec, register_benchmark, registry, register_benchmark_view # imports used elsewhere
register_benchmark(
id='Atari200M',
scorer=scor... | 1.65625 | 2 |
hypnettorch/data/timeseries/preprocess_audioset.py | pennfranc/hypnettorch | 31 | 482 | <filename>hypnettorch/data/timeseries/preprocess_audioset.py
#!/usr/bin/env python3
# Copyright 2020 <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/licens... | 2.234375 | 2 |
Posts/viewsAPI.py | CMPUT404-Fa21-Organization/CMPUT404-Project-Social-Distribution | 3 | 483 | from django.conf import settings
from django.core import serializers
from django.utils import timezone
import requests
from Posts.commentModel import Comments
#from Posts.commentView import add_Comment
from rest_framework import status
from rest_framework.decorators import api_view, authentication_classes, permission_c... | 1.96875 | 2 |
workers/tests/test_array_element.py | Open-EO/openeo-sentinelhub-python-driver | 2 | 484 | <reponame>Open-EO/openeo-sentinelhub-python-driver
import pytest
import sys, os
import xarray as xr
import numpy as np
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import process
from process._common import ProcessArgumentInvalid, ProcessArgumentRequired
@pytest.fixture
def generate_d... | 2.203125 | 2 |
gn/gn_to_bp.py | despairblue/esy-skia | 2,151 | 485 | <reponame>despairblue/esy-skia
#!/usr/bin/env python
#
# Copyright 2016 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Generate Android.bp for Skia from GN configuration.
import json
import os
import pprint
import string
import subprocess
import t... | 1.828125 | 2 |
python/ray/autoscaler/tags.py | firebolt55439/ray | 21,382 | 486 | """The Ray autoscaler uses tags/labels to associate metadata with instances."""
# Tag for the name of the node
TAG_RAY_NODE_NAME = "ray-node-name"
# Tag for the kind of node (e.g. Head, Worker). For legacy reasons, the tag
# value says 'type' instead of 'kind'.
TAG_RAY_NODE_KIND = "ray-node-type"
NODE_KIND_HEAD = "he... | 1.773438 | 2 |
tests/generation_test.py | stefan-feltmann/lands | 0 | 487 | import unittest
from worldengine.plates import Step, center_land, world_gen
from worldengine.world import World
from tests.draw_test import TestBase
class TestGeneration(TestBase):
def setUp(self):
super(TestGeneration, self).setUp()
def test_world_gen_does_not_explode_badly(self):
# FIXME ... | 2.765625 | 3 |
tests/test_models/test_components/test_discriminators/test_light_cnn.py | ChenShuwei1001/mmediting | 0 | 488 | <filename>tests/test_models/test_components/test_discriminators/test_light_cnn.py
import pytest
import torch
from mmedit.models.builder import build_component
from mmedit.models.components.discriminators.light_cnn import MaxFeature
def test_max_feature():
# cpu
conv2d = MaxFeature(16, 16, filter_type='conv2d... | 2.359375 | 2 |
src/consumer.py | ssichynskyi/web_metrics_posting | 0 | 489 | <filename>src/consumer.py
import json
import logging
from typing import Iterable
from kafka import KafkaConsumer
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
# I've used this example:
# https://github.com/aiven/aiven-examples/blob/master/kafka/python/consumer_example.py
# as well as Aive... | 2.625 | 3 |
pp2_model.py | BetterManlinfeng/hyperclasspptwo | 0 | 490 |
from tensorflow.keras import *
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, Sequential,regularizers
from tensorflow.keras.layers import Dropout
# from tensorflow.keras import *
# 定义一个3x3卷积!kernel_initializer='he_normal','glorot_normal'
from tensorflow.python... | 2.734375 | 3 |
medi/inference/utils.py | yuan-xy/medi | 3 | 491 | <reponame>yuan-xy/medi<filename>medi/inference/utils.py
""" A universal module with functions / classes without dependencies. """
import sys
import contextlib
import functools
import re
import os
from medi._compatibility import reraise
_sep = os.path.sep
if os.path.altsep is not None:
_sep += os.path.altsep
_pat... | 2.171875 | 2 |
run.py | Bioconductor/bioc_git_transition | 16 | 492 | """Bioconductor run git transition code.
This module assembles the classes for the SVN --> Git transition
can be run in a sequential manner.
It runs the following aspects fo the Bioconductor transition.
Note: Update the SVN dump
1. Run Bioconductor Software package transition
2. Run Bioconductor Experiment Data pac... | 2.59375 | 3 |
third_party/google-endpoints/dogpile/cache/region.py | tingshao/catapult | 2,151 | 493 | <gh_stars>1000+
from __future__ import with_statement
from .. import Lock, NeedRegenerationException
from ..util import NameRegistry
from . import exception
from ..util import PluginLoader, memoized_property, coerce_string_conf
from .util import function_key_generator, function_multi_key_generator
from .api import NO_V... | 2.234375 | 2 |
projectparallelprogrammeren/codesimulatie.py | fury106/ProjectParallelProgrammeren | 0 | 494 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Module projectparallelprogrammeren.codesimulatie
=================================================================
Deze module simuleert alles.
"""
import projectparallelprogrammeren
def simulatie():
"""
Deze functie voert alle versies uit zodat deze vergeleken kunnen wor... | 2.296875 | 2 |
test/test_aes.py | haruhi-dl/haruhi-dl | 32 | 495 | <gh_stars>10-100
#!/usr/bin/env python
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from haruhi_dl.aes import aes_decrypt, aes_encrypt, aes_cbc_decrypt, aes_cbc_encrypt, aes_decryp... | 2.3125 | 2 |
tests/unit/detection/test_detection_notebooks.py | titipakorn/computervision-recipes | 2 | 496 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This test is based on the test suite implemented for Recommenders project
# https://github.com/Microsoft/Recommenders/tree/master/tests
import papermill as pm
import pytest
import scrapbook as sb
from utils_cv.common.data... | 1.960938 | 2 |
configs/HDR/hdr/retinanet_r50_fpn_1x_coco_hdr_minmax_glob_gamma_2.py | ismailkocdemir/mmdetection | 0 | 497 | <gh_stars>0
_base_ = [
'../retinanet_r50_fpn_1x_coco.py',
'../../_base_/datasets/hdr_detection_minmax_glob_gamma.py',
]
# optimizer
# lr is set for a batch size of 8
optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_nor... | 1.390625 | 1 |
dj_twitter_clone_app/core_config/settings/staging.py | ivanprytula/dj_demo_app | 0 | 498 | """Placeholder/template for staging envs."""
| 1.046875 | 1 |
tests/test_command.py | vandana-11/cognito | 0 | 499 | <reponame>vandana-11/cognito
from cognito.check import Check
from cognito.table import Table
import os
import pytest
import pandas as pd
import numpy as np
from os import path
from sklearn import preprocessing
| 1.179688 | 1 |