max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 7 115 | max_stars_count int64 101 368k | id stringlengths 2 8 | content stringlengths 6 1.03M |
|---|---|---|---|---|
OpenCV/Colorization/colorize_image.py | AathmanT/cv-tricks.com | 326 | 11198601 | # Script is based on https://github.com/richzhang/colorization/blob/master/colorization/colorize.py
import numpy as np
import argparse
import cv2 as cv
def parse_args():
parser = argparse.ArgumentParser(description='iColor: deep interactive colorization')
parser.add_argument('--input', help='Path to image or v... |
janitor/functions/fill.py | vishalbelsare/pyjanitor | 225 | 11198604 | from enum import Enum
from operator import methodcaller
from typing import Hashable, Iterable, Union
import pandas as pd
import pandas_flavor as pf
from janitor.utils import check, check_column, deprecated_alias
from multipledispatch import dispatch
@pf.register_dataframe_method
def fill_direction(df: pd.DataFrame, ... |
ev3dev2/wheel.py | TheVinhLuong102/ev3dev-lang-python | 306 | 11198660 | <filename>ev3dev2/wheel.py
#!/usr/bin/env python3
"""
Wheel and Rim classes
A great reference when adding new wheels is http://wheels.sariel.pl/
"""
from math import pi
class Wheel(object):
"""
A base class for various types of wheels, tires, etc. All units are in mm.
One scenario where one of the chil... |
research/setup.py | 873040/Abhishek | 153 | 11198707 | """Setup script for object_detection."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['Pillow>=1.0', 'Matplotlib>=2.1', 'Cython>=0.28.1']
setup(
name='object_detection',
version='0.1',
install_requires=REQUIRED_PACKAGES,
include_package_data=True,
packag... |
src/ttkbootstrap/__init__.py | dmalves/ttkbootstrap | 406 | 11198729 | from ttkbootstrap.style import Style
from ttkbootstrap.style import Bootstyle
from ttkbootstrap.widgets import *
from ttkbootstrap.window import Window, Toplevel
from tkinter.scrolledtext import ScrolledText
from tkinter import Variable, StringVar, IntVar, BooleanVar, DoubleVar
from tkinter import Canvas, Menu, Text
f... |
falsy/loader/yaml.py | marco-souza/falsy | 127 | 11198743 | <reponame>marco-souza/falsy
import os
# import pprint
import yaml
class LoaderMeta(type):
def __new__(metacls, __name__, __bases__, __dict__):
"""Add include constructer to class."""
# register the include constructor on the class
cls = super().__new__(metacls, __name__, __bases__, __di... |
src/yolo_utils.py | greck2908/BMW-YOLOv3-Training-Automation | 192 | 11198766 | import os
import re
import json
import subprocess
from pathlib import Path
from tensorboardX import SummaryWriter
current_map: float = None
current_iteration: int = 0
tensorboard_writer: bool = False
working_dir: str = None
summaries_path: Path = None
status_path: Path = None
pid_path: Path = None
# Create summary w... |
test_project/core/migrations/0003_book_similar_books.py | violuke/djangoql | 807 | 11198783 | <filename>test_project/core/migrations/0003_book_similar_books.py
# Generated by Django 2.1.2 on 2018-11-11 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_book_genre'),
]
operations = [
migrations.AddField(
... |
models/SelectionGAN/semantic_synthesis/models/networks/generator.py | xianjian-xie/pose-generation | 445 | 11198798 | <reponame>xianjian-xie/pose-generation
"""
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.base_network impo... |
dashlivesim/dashlib/sessionid.py | Dash-Industry-Forum/dash-live-source-simulator | 133 | 11198854 | <reponame>Dash-Industry-Forum/dash-live-source-simulator<gh_stars>100-1000
"""Session IDs to allow for tracing sessions."""
import random
MAX_NUMBER = 2**32 - 1
def generate_session_id():
"Generate a session ID as hex string."
return "%08x" % random.randint(0, MAX_NUMBER)
|
crossplane/errors.py | Triple-Z/crossplane | 525 | 11198865 | # -*- coding: utf-8 -*-
class NgxParserBaseException(Exception):
def __init__(self, strerror, filename, lineno):
self.args = (strerror, filename, lineno)
self.filename = filename
self.lineno = lineno
self.strerror = strerror
def __str__(self):
if self.lineno is not Non... |
tests/test_imap_utf7.py | thepeshka/imap_tools | 344 | 11198903 | import unittest
from imap_tools import imap_utf7
class ImapUtf7Test(unittest.TestCase):
data = (
('Test', b'Test'),
('Test One more', b'Test One more'),
('Might & Magic', b'Might &- Magic'),
('Might & magic', b'Might &- magic'),
('Imap&\xffworld', b'Imap&-&AP8-world'),
... |
example/with_keras.py | IcyW/stagesepx | 369 | 11198904 | <filename>example/with_keras.py
"""
classify with keras model
"""
from keras.models import Sequential
from stagesepx.cutter import VideoCutter
from stagesepx.classifier.keras import KerasClassifier
from stagesepx.reporter import Reporter
from stagesepx.video import VideoObject
video_path = "../demo.mp4"
video = Vide... |
wouso/core/ui.py | ruxandraS/wouso | 117 | 11198906 | from django.db import models
from wouso.core.game.models import Game
class BlockLibrary(object):
def __init__(self):
self.parts = {}
def get_blocks(self):
return self.parts.keys()
def get_block(self, key, context):
block = self.parts.get(key, '')
if callable(block):
... |
server/gunicorn_config.py | huhansan666666/flask_reddit | 461 | 11198915 | # Refer to the following link for help:
# http://docs.gunicorn.org/en/latest/settings.html
command = '/home/lucas/www/reddit.lucasou.com/reddit-env/bin/gunicorn'
pythonpath = '/home/lucas/www/reddit.lucasou.com/reddit-env/flask_reddit'
bind = '127.0.0.1:8040'
workers = 1
user = 'lucas'
accesslog = '/home/lucas/logs/red... |
axcell/errors.py | Kabongosalomon/axcell | 335 | 11198959 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
class PipelineError(Exception):
pass
class UnpackError(PipelineError):
pass
class LatexConversionError(PipelineError):
pass
|
LeetCode_problems/Running Sum of 1d Array/solution.py | gbrls/CompetitiveCode | 165 | 11198964 | <gh_stars>100-1000
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
# declare array to return
output = list()
# compute running sum for each index
for i in range(len(nums)):
output.append(sum(nums[:i+1]))
return output
|
exercises/fr/exc_01_09.py | Jette16/spacy-course | 2,085 | 11199003 | import spacy
nlp = spacy.load("fr_core_news_sm")
text = "Le constructeur Citröen présente la e-Méhari Courrèges au public."
# Traite le texte
doc = ____
# Itère sur les entités
for ____ in ____.____:
# Affiche le texte de l'entité et son label
print(____.____, ____.____)
# Obtiens la portion pour "e-Méhari... |
numpyro/nn/masked_dense.py | karm-patel/numpyro | 1,394 | 11199012 | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from jax import random
from jax.nn.initializers import glorot_normal, normal
import jax.numpy as jnp
def MaskedDense(mask, bias=True, W_init=glorot_normal(), b_init=normal()):
"""
As in jax.example_libraries.stax, each layer ... |
alipay/aop/api/domain/AlipayCommerceDataSendModel.py | snowxmas/alipay-sdk-python-all | 213 | 11199015 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceDataSendModel(object):
def __init__(self):
self._channel = None
self._op_code = None
self._op_data = None
self._scene_code = None
self._scene... |
openbook_auth/views/users/serializers.py | TamaraAbells/okuna-api | 164 | 11199023 | <reponame>TamaraAbells/okuna-api<gh_stars>100-1000
from rest_framework import serializers
from django.conf import settings
from openbook_auth.models import UserProfile, User
from openbook_auth.validators import username_characters_validator, user_username_exists
from openbook_circles.models import Circle
from openbook... |
data_structures/Queue/python/queue_using_stack.py | avi-pal/al-go-rithms | 1,253 | 11199024 | # Using the given stack implementation
# Done in the directory data_structures/Stack/Python/Stack.py
class Stack(object):
def __init__(self, limit = 10):
# Initialize stack as empty array
self.stack = []
self.limit = limit
# Return and remove the last element of the stack array... |
bcs-ui/backend/components/bcs_api.py | laodiu/bk-bcs | 599 | 11199033 | <filename>bcs-ui/backend/components/bcs_api.py
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License")... |
tests/python/twitter/common/dirutil/test_dirutil.py | zhouyijiaren/commons | 1,143 | 11199045 | <reponame>zhouyijiaren/commons<gh_stars>1000+
import atexit
import os
import tempfile
from twitter.common import dirutil
import mox
import pytest
def test_mkdtemp_setup_teardown():
m = mox.Mox()
def faux_cleaner():
pass
DIR1, DIR2 = 'fake_dir1__does_not_exist', 'fake_dir2__does_not_exist'
m.StubOutWit... |
Training/MOOC Tensorflow 2.0/BeiDa/class2/p19_mse.py | church06/Pythons | 177 | 11199046 | import tensorflow as tf
import numpy as np
SEED = 23455
rdm = np.random.RandomState(seed=SEED) # 生成[0,1)之间的随机数
x = rdm.rand(32, 2)
y_ = [[x1 + x2 + (rdm.rand() / 10.0 - 0.05)] for (x1, x2) in x] # 生成噪声[0,1)/10=[0,0.1); [0,0.1)-0.05=[-0.05,0.05)
x = tf.cast(x, dtype=tf.float32)
w1 = tf.Variable(tf.random.normal([2,... |
tests/check_byte_order_marker_test.py | christhekeele/pre-commit-hooks | 2,864 | 11199055 | <gh_stars>1000+
from pre_commit_hooks import check_byte_order_marker
def test_failure(tmpdir):
f = tmpdir.join('f.txt')
f.write_text('ohai', encoding='utf-8-sig')
assert check_byte_order_marker.main((str(f),)) == 1
def test_success(tmpdir):
f = tmpdir.join('f.txt')
f.write_text('ohai', encoding=... |
utils/CopyJniFile.py | RookieTerry/520apkhook | 390 | 11199072 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import shutil
def forceMergeFlatDir(srcDir, dstDir):
if not os.path.exists(dstDir):
os.makedirs(dstDir)
for item in os.listdir(srcDir):
srcFile = os.path.join(srcDir, item)
dstFile = os.path.join(dstDir, item)
forceCopyFile(s... |
wolframclient/evaluation/cloud/__init__.py | jldohmann/WolframClientForPython | 358 | 11199099 | <reponame>jldohmann/WolframClientForPython
from __future__ import absolute_import, print_function, unicode_literals
from wolframclient.evaluation.cloud.asynccloudsession import (
WolframAPICallAsync,
WolframCloudAsyncSession,
)
from wolframclient.evaluation.cloud.base import SecuredAuthenticationKey, UserIDPas... |
physt/io/root.py | janpipek/physt | 123 | 11199100 | """ROOT format I/O
See also
--------
- https://github.com/scikit-hep/uproot
- https://root.cern.ch
"""
import os
from typing import Optional
import uproot3
from physt.histogram_base import HistogramBase
def write_root(histogram: HistogramBase, hfile: uproot3.write.TFile.TFileUpdate, name: str):
"""Write histog... |
tests/test_app.py | smallwat3r/shhh | 243 | 11199105 | import json
import re
import unittest
from datetime import datetime, timedelta
from http import HTTPStatus
from types import SimpleNamespace
from urllib.parse import urlparse
import responses
from flask import url_for
from shhh.entrypoint import create_app
from shhh.extensions import db, scheduler
from shhh.models im... |
tests/test_gltf.py | thachdo/trimesh | 1,882 | 11199107 | <reponame>thachdo/trimesh
try:
from . import generic as g
except BaseException:
import generic as g
# Khronos' official file validator
# can be installed with the helper script:
# `trimesh/docker/builds/gltf_validator.bash`
_gltf_validator = g.find_executable('gltf_validator')
def validate_glb(data):
"""... |
modules/face/samples/landmarks_demo.py | ptelang/opencv_contrib | 7,158 | 11199108 | import random
import numpy as np
import cv2 as cv
frame1 = cv.imread(cv.samples.findFile('lena.jpg'))
if frame1 is None:
print("image not found")
exit()
frame = np.vstack((frame1,frame1))
facemark = cv.face.createFacemarkLBF()
try:
facemark.loadModel(cv.samples.findFile('lbfmodel.yaml'))
except cv.error:
... |
middleware/BaseMiddleWare.py | AxueWong/django-restfulapi | 242 | 11199116 | <reponame>AxueWong/django-restfulapi
from rest_framework.response import Response
from rest_framework import utils
import json, os, copy, re, jwt, time
from django.shortcuts import render
from django.utils.deprecation import MiddlewareMixin
from rest_framework import status
import urllib
from django.http import QueryDi... |
pgmpy/factors/FactorSet.py | echoyi/pgmpy | 2,144 | 11199126 | #!/usr/bin/env python3
from functools import reduce
from pgmpy.factors.base import BaseFactor
class FactorSet(object):
r"""
Base class of *DiscreteFactor Sets*.
A factor set provides a compact representation of higher dimensional factor
:math:`\phi_1\cdot\phi_2\cdots\phi_n`
For example the fa... |
tensorflow_federated/python/tests/backend_accelerators_test.py | zhihansh/federated-oss | 1,918 | 11199137 | # Copyright 2020, The TensorFlow Federated Authors.
#
# 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 o... |
insights/tests/test_file_permissions.py | lhuett/insights-core | 121 | 11199149 | import pytest
from insights.util.file_permissions import FilePermissions
from insights.core import FileListing
from insights.tests import test_file_listing, context_wrap
PERMISSIONS_TEST_EXCEPTION_VECTORS = [
('-rw------ 1 root root 762 Sep 23 002 /etc/ssh/sshd_config', True),
('bash: ls: command not found', T... |
examples/python/tsa_dates.py | CCHiggins/statsmodels | 6,931 | 11199159 | <filename>examples/python/tsa_dates.py
#!/usr/bin/env python
# coding: utf-8
# DO NOT EDIT
# Autogenerated from the notebook tsa_dates.ipynb.
# Edit the notebook and then sync the output with this file.
#
# flake8: noqa
# DO NOT EDIT
# # Dates in timeseries models
import pandas as pd
import matplotlib.pyplot as plt
... |
release/stubs.min/Autodesk/Revit/DB/__init___parts/ElementType.py | htlcnn/ironpython-stubs | 182 | 11199164 | class ElementType(Element,IDisposable):
""" Base class for all Types within Autodesk Revit. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def Duplicate(self,name):
"""
Duplicate(self: ElementType,name: str) -> ElementType
Duplicates an existing element type and assig... |
src/robomaster/servo.py | yukaryote/RoboMaster-SDK | 204 | 11199175 | <gh_stars>100-1000
# -*-coding:utf-8-*-
# Copyright (c) 2020 DJI.
#
# 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 in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0... |
observations/r/political_knowledge.py | hajime9652/observations | 199 | 11199181 | <filename>observations/r/political_knowledge.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def polit... |
tests/unit/test_html_conversion.py | joelostblom/dash-docs | 379 | 11199185 | import pytest
import sys
from dash_docs.convert_to_html import convert_to_html
@pytest.mark.skipif(
sys.version_info < (3, 7),
reason="skip non-essential, potentially flaky tests"
)
def test_html_conversion():
exceptions = []
success = []
dcc_link = []
from dash_docs.chapter_index import URL_TO... |
hatsploit/core/utils/update.py | EntySec/HatSploit | 139 | 11199186 | #!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2022 EntySec
#
# 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... |
deps/src/boost_1_65_1/libs/mpi/test/python/ring_test.py | shreyasvj25/turicreate | 11,356 | 11199192 | <reponame>shreyasvj25/turicreate
# Copyright (C) 2006 <NAME> <<EMAIL>g.gregor -at- gmail.com>.
# Use, modification and distribution is subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Test basic communication.
import boo... |
hypernets/dispatchers/process/grpc/process_broker_service.py | Enpen/Hypernets | 1,080 | 11199272 | import queue
import subprocess
import time
from threading import Thread
from grpc import RpcError
from hypernets.dispatchers.process.grpc.proto import proc_pb2_grpc
from hypernets.dispatchers.process.grpc.proto.proc_pb2 import DataChunk
from hypernets.utils import logging
logger = logging.get_logger(__name__)
clas... |
recipes/msdfgen/all/conanfile.py | rockandsalt/conan-center-index | 562 | 11199276 | <filename>recipes/msdfgen/all/conanfile.py
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import os
required_conan_version = ">=1.33.0"
class MsdfgenConan(ConanFile):
name = "msdfgen"
description = "Multi-channel signed distance field generator"
license = "... |
tests/exceptions/source/backtrace/nested_wrapping.py | ponponon/loguru | 11,391 | 11199301 | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=False, backtrace=True, diagnose=False)
def f(i):
1 / i
@logger.catch
@logger.catch()
def a(x):
f(x)
a(0)
with logger.catch():
with logger.catch():
f(0)
try:
try:
f(0)
except Ze... |
tests/refinement_test.py | ericwxia/SpectralCluster | 327 | 11199326 | import unittest
import numpy as np
from spectralcluster import refinement
ThresholdType = refinement.ThresholdType
SymmetrizeType = refinement.SymmetrizeType
class TestCropDiagonal(unittest.TestCase):
"""Tests for the CropDiagonal class."""
def test_3by3_matrix(self):
matrix = np.array([[1, 2, 3], [3, 4, 5]... |
installer/core/terraform/resources/aws/cloudwatch.py | jonico/pacbot | 1,165 | 11199330 | from core.terraform.resources import TerraformResource
from core.config import Settings
from core.providers.aws.boto3 import cloudwatch_log
from core.providers.aws.boto3 import cloudwatch_event
class CloudWatchEventRuleResource(TerraformResource):
"""
Base resource class for Terraform AWS Cloudwatch event rul... |
tests/st/ops/test_sqrt.py | tianjiashuo/akg | 286 | 11199338 | # Copyright 2021 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... |
GPU-Re-Ranking/extension/adjacency_matrix/setup.py | TxuanYu/Person_reID_baseline_pytorch | 3,358 | 11199346 | <gh_stars>1000+
"""
Understanding Image Retrieval Re-Ranking: A Graph Neural Network Perspective
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
Project Page : https://github.com/Xuanmeng-Zhang/gnn-re-ranking
Paper: https://arxiv.org/abs/2012.07620v2
==============================================... |
torchdistill/models/classification/__init__.py | AhmedHussKhalifa/torchdistill | 576 | 11199353 | <reponame>AhmedHussKhalifa/torchdistill
from torchdistill.models.classification import densenet, resnet, wide_resnet
from torchdistill.models.registry import MODEL_FUNC_DICT
CLASSIFICATION_MODEL_FUNC_DICT = dict()
CLASSIFICATION_MODEL_FUNC_DICT.update(MODEL_FUNC_DICT)
|
models/match/multiview-simnet/data/preprocess.py | ziyoujiyi/PaddleRec | 2,739 | 11199363 | #encoding=utf-8
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
twitchio/message.py | rn4n/TwitchIO | 514 | 11199392 | <filename>twitchio/message.py
"""
The MIT License (MIT)
Copyright (c) 2017-2021 TwitchIO
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 righ... |
tests/save_delete_hooks/models.py | bpeschier/django | 5,079 | 11199399 | <reponame>bpeschier/django
"""
Adding hooks before/after saving and deleting
To execute arbitrary code around ``save()`` and ``delete()``, just subclass
the methods.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unico... |
ivy/array/device.py | saurbhc/ivy | 161 | 11199400 | # global
import abc
# ToDo: implement all device methods here as public class methods
class ArrayWithDevice(abc.ABC):
pass
|
seahub/file_participants/migrations/0001_initial.py | MJochim/seahub | 420 | 11199411 | <reponame>MJochim/seahub
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-08-28 02:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import seahub.base.fields
class Migration(migrations.Migration):
initial = True
dependencies =... |
examples/pandocfilters/abc.py | jacobwhall/panflute | 361 | 11199437 | #!/usr/bin/env python
"""
Pandoc filter to process code blocks with class "abc" containing
ABC notation into images. Assumes that abcm2ps and ImageMagick's
convert are in the path. Images are put in the abc-images directory.
"""
import hashlib
import os
import sys
from pandocfilters import toJSONFilter, Para, Image... |
test/geometry/test_homography.py | Ishticode/kornia | 418 | 11199442 | import random
import pytest
import torch
from torch.autograd import gradcheck
import kornia
import kornia.testing as utils
from kornia.geometry.homography import (
find_homography_dlt,
find_homography_dlt_iterated,
oneway_transfer_error,
sample_is_valid_for_homography,
symmetric_transfer_error,
)
... |
core/dbt/config/renderer.py | tomasfarias/dbt-core | 799 | 11199443 | <filename>core/dbt/config/renderer.py<gh_stars>100-1000
from typing import Dict, Any, Tuple, Optional, Union, Callable
from dbt.clients.jinja import get_rendered, catch_jinja
from dbt.context.target import TargetContext
from dbt.context.secret import SecretContext
from dbt.context.base import BaseContext
from dbt.cont... |
megatron/data/gpt_dataset.py | adammoody/Megatron-DeepSpeed | 2,869 | 11199447 | # coding=utf-8
# Copyright (c) 2020, NVIDIA 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.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
compiler_gym/views/observation.py | sahirgomez1/CompilerGym | 562 | 11199490 | # 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.
from typing import Callable, Dict, List
from deprecated.sphinx import deprecated
from compiler_gym.service.connection import ServiceError
fro... |
tests/auths/test_jwt.py | abersheeran/asgi-ratelimit | 136 | 11199492 | import jwt
import pytest
from ratelimit.auths import EmptyInformation
from ratelimit.auths.jwt import create_jwt_auth
@pytest.mark.parametrize(
"scope, user, group",
[
(
{
"headers": (
(
b"authorization",
... |
watchmen/database/table/oracle_table_definition.py | Insurance-Metrics-Measure-Advisory/watchman-data-connector | 125 | 11199523 | from sqlalchemy import MetaData, Table, Column, String, CLOB, Date, DateTime, Integer
from watchmen_boot.config.config import settings
metadata = MetaData()
def get_primary_key(table_name):
return get_pid(table_name)
def get_pid(table_name):
if table_name == 'topics':
return 'topicId'
elif ta... |
s3prl/downstream/sv_voxceleb1/dataset.py | hhhaaahhhaa/s3prl | 856 | 11199526 | <filename>s3prl/downstream/sv_voxceleb1/dataset.py
import os
import re
import sys
import time
import random
import pickle
import tqdm
import torch
import torchaudio
import numpy as np
from torch import nn
from pathlib import Path
from sox import Transformer
from torchaudio import load
from librosa.util import find_fi... |
desktop/core/ext-py/Pygments-1.3.1/pygments/formatters/terminal.py | kokosing/hue | 5,079 | 11199528 | <reponame>kokosing/hue
# -*- coding: utf-8 -*-
"""
pygments.formatters.terminal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Formatter for terminal output with ANSI sequences.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.formatter im... |
grr/client/grr_response_client/client_actions/file_finder_utils/__init__.py | nkrios/grr | 4,238 | 11199530 | <gh_stars>1000+
#!/usr/bin/env python
"""Implementation of utilities used in the client-side file-finder."""
|
robot-server/robot_server/service/session/session_types/__init__.py | knownmed/opentrons | 235 | 11199534 | <filename>robot-server/robot_server/service/session/session_types/__init__.py
from .check_session import CheckSession # noqa: F401
from .tip_length_calibration import TipLengthCalibration # noqa: F401
from .deck_calibration_session import DeckCalibrationSession # noqa: F401
from .pipette_offset_calibration import Pi... |
pythran/graph.py | jeanlaroche/pythran | 1,647 | 11199573 | '''
Minimal directed graph replacement for networkx.DiGraph
This has the sole advantage of being a standalone file that doesn't bring any
dependency with it.
'''
class DiGraph(object):
def __init__(self):
# adjacency[i][j] = True means j is a successor of i
self._adjacency = {}
self._edges... |
pypiserver/__init__.py | NoOneSurvives/docker-pypi-server | 1,257 | 11199584 | <reponame>NoOneSurvives/docker-pypi-server
import functools
import pathlib
import re as _re
import sys
import typing as t
from pypiserver.bottle import Bottle
from pypiserver.config import Config, RunConfig, strtobool
version = __version__ = "2.0.0dev1"
__version_info__ = tuple(_re.split("[.-]", __version__))
__updat... |
server.py | yutiansut/paperbroker | 227 | 11199593 | from flask import Flask, request, send_from_directory
from paperbroker import PaperBroker
from paperbroker.orders import Order
import ujson
# initialize a PaperBroker with defaults
broker = PaperBroker()
# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='... |
py/torch_tensorrt/fx/test/passes/test_fuse_permute_linear_trt.py | NVIDIA/Torch-TensorRT | 430 | 11199628 | <reponame>NVIDIA/Torch-TensorRT
# Owner(s): ["oncall: gpu_enablement"]
import torch
import torch_tensorrt.fx.tracer.acc_tracer.acc_ops as acc_ops
from torch.testing._internal.common_utils import run_tests
from torch_tensorrt.fx.passes.lower_basic_pass import (
fuse_permute_linear,
trt_transposed_linear,
)
from... |
recipes/sota/2019/lm_analysis/filter_segmentations.py | Zilv1128/test1 | 5,921 | 11199718 | <reponame>Zilv1128/test1<gh_stars>1000+
import sys
from collections import defaultdict
def count(MIN_SIL_LENGTH, align_file):
lines = []
with open(align_file) as fin:
lines = fin.readlines()
res = {}
res["word_counter"] = [0] * 100 # number of word in each small chunk
res["chunk_counter... |
netutils_linux_monitoring/layout.py | henkaru/netutils-linux | 749 | 11199720 | <filename>netutils_linux_monitoring/layout.py
# coding=utf-8
""" Everything about console output's layout """
from prettytable import PrettyTable
from six import print_
def make_table(header, align_map=None, rows=None):
""" Wrapper for pretty table """
table = PrettyTable()
table.horizontal_char = table... |
doc/en/example/fixtures/test_fixtures_order_scope.py | markshao/pytest | 9,225 | 11199781 | import pytest
@pytest.fixture(scope="session")
def order():
return []
@pytest.fixture
def func(order):
order.append("function")
@pytest.fixture(scope="class")
def cls(order):
order.append("class")
@pytest.fixture(scope="module")
def mod(order):
order.append("module")
@pytest.fixture(scope="pac... |
dizoo/multiagent_particle/config/cooperative_navigation_qtran_config.py | sailxjx/DI-engine | 464 | 11199790 | from copy import deepcopy
from ding.entry import serial_pipeline
from easydict import EasyDict
n_agent = 5
collector_env_num = 4
evaluator_env_num = 2
num_landmarks = n_agent
main_config = dict(
env=dict(
num_landmarks=num_landmarks,
max_step=100,
n_agent=n_agent,
collector_env_num=... |
neptune/new/attributes/series/series.py | Raalsky/neptune-client | 254 | 11199813 | <filename>neptune/new/attributes/series/series.py
#
# Copyright (c) 2020, Neptune Labs Sp. z o.o.
#
# 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/LICENS... |
scripts/ltr_msmarco-passage/append_d2q_to_collection_jsonl.py | keleog/pyserini | 451 | 11199828 | <reponame>keleog/pyserini
#
# Pyserini: Reproducible IR research with sparse and dense representations
#
# 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/LICEN... |
aws-stackreference-architecture/application/src/backend/helloworld.py | spara/examples | 1,628 | 11199871 | <reponame>spara/examples
from flask import Flask, request, render_template, jsonify
import pg8000
import random
import os
import requests
hash = random.getrandbits(128)
app = Flask(__name__)
@app.route('/')
def helloworld():
return jsonify(
message="hello world",
hash=str(hash),
postgre... |
chapter2_training/cifar10/train/src/configurations.py | sudabon/ml-system-in-actions | 133 | 11199898 | import os
from logging import getLogger
from src.constants import CONSTANTS, PLATFORM_ENUM
logger = getLogger(__name__)
class PlatformConfigurations:
platform = os.getenv("PLATFORM", PLATFORM_ENUM.DOCKER.value)
if not PLATFORM_ENUM.has_value(platform):
raise ValueError(f"PLATFORM must be one of {[v.... |
agentnet/objective/base.py | mraihan19/AgentNet | 337 | 11199900 | from __future__ import division, print_function, absolute_import
import theano.tensor as T
import theano
from ..utils.format import check_list, unpack_list
class BaseObjective(object):
"""
Instance, that:
- determines rewards for all actions agent takes given environment state and agent action.
"... |
corehq/motech/fhir/tests/test_models.py | akashkj/commcare-hq | 471 | 11199904 | import doctest
from contextlib import contextmanager
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import ProtectedError
from django.test import TestCase
from nose.tools import assert_in
from corehq.apps.data_dictionary.models import CasePr... |
examples/delete_vowels.py | timmahrt/praatIO | 208 | 11199942 | <reponame>timmahrt/praatIO<filename>examples/delete_vowels.py
"""
Praatio example for deleting the vowels from the textgrids and audio files
"""
import os
from os.path import join
import copy
from praatio import textgrid
from praatio import praatio_scripts
from praatio import audio
from praatio.utilities import utils... |
library/mmap.py | creativemindplus/skybison | 278 | 11199952 | <filename>library/mmap.py<gh_stars>100-1000
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
# $builtin-init-module$
from _builtins import _builtin, _int_guard, _type_subclass_guard, _unimplemented
def _mmap_new(cls, fileno, length, flags, prot, offset):
_builti... |
pahelix/utils/language_model_tools.py | agave233/PaddleHelix | 454 | 11199973 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
RecoHI/HiTracking/python/hiTobTecStep_cff.py | malbouis/cmssw | 852 | 11199989 | from __future__ import absolute_import
import FWCore.ParameterSet.Config as cms
import RecoTracker.IterativeTracking.iterativeTkConfig as _cfg
from RecoTracker.IterativeTracking.TobTecStep_cff import tobTecStepSeedLayersPair,tobTecStepSeedLayersTripl,tobTecStepHitDoubletsPair,tobTecStepHitDoubletsTripl,tobTecStepHitTri... |
notebook/pandas_str_num_conversion.py | vhn0912/python-snippets | 174 | 12600048 | <filename>notebook/pandas_str_num_conversion.py
import pandas as pd
print(pd.__version__)
# 0.23.0
df = pd.DataFrame({'i': [0, 10, 200], 'f': [0, 0.9, 0.09],
's_i': ['0', '10', '200'], 's_f': ['0', '0.9', '0.09']})
print(df)
# i f s_i s_f
# 0 0 0.00 0 0
# 1 10 0.90 10 ... |
pnacl/driver/tests/driver_env_test.py | cohortfsllc/cohort-cocl2-sandbox | 2,151 | 12600053 | <filename>pnacl/driver/tests/driver_env_test.py
#!/usr/bin/python
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests of the pnacl driver.
This tests the driver_env functionality.
"""
impor... |
backend/django/test/core_utils/test_core_utils_annotate.py | RTIInternational/SMART | 185 | 12600061 | <filename>backend/django/test/core_utils/test_core_utils_annotate.py
from test.conftest import TEST_QUEUE_LEN
from test.util import assert_obj_exists
from core.models import AssignedData, Data, DataLabel, DataQueue, Label
from core.utils.utils_annotate import (
assign_datum,
get_assignments,
label_data,
... |
examples/gdb_api.py | tkmikan/pwntools | 8,966 | 12600067 | <filename>examples/gdb_api.py
#!/usr/bin/env python3
"""An example of using GDB Python API with Pwntools."""
from pwn import *
def check_write(gdb, exp_buf):
"""Check that write() was called with the expected arguments."""
fd = gdb.parse_and_eval('$rdi').cast(gdb.lookup_type('int'))
assert fd == 1, fd
... |
src/sage/tests/books/computational-mathematics-with-sagemath/sol/nonlinear_doctest.py | fchapoton/sage | 1,742 | 12600078 | <reponame>fchapoton/sage<gh_stars>1000+
## -*- encoding: utf-8 -*-
"""
This file (./sol/nonlinear_doctest.sage) was *autogenerated* from ./sol/nonlinear.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file w... |
ding/interaction/base/common.py | sailxjx/DI-engine | 464 | 12600102 | import random
import string
from abc import ABCMeta, abstractmethod
from typing import Optional, Callable, Mapping, Any, Dict
_LENGTH_OF_RANDOM_TOKEN = 64
def random_token(length: Optional[int] = None) -> str:
"""
Overview:
Generate random hex token
Arguments:
- length (:obj:`Optional[int... |
libsaas/services/twilio/numbers.py | MidtownFellowship/libsaas | 155 | 12600109 | <gh_stars>100-1000
from libsaas import http, parsers
from libsaas.services import base
from libsaas.services.twilio import resource
class AvailablePhoneNumbersBase(resource.TwilioResource):
path = '{0}'
def get_url(self):
path = self.path.format(self.object_id)
return '{0}/{1}'.format(self.... |
baselines/baseline_simple.py | Qin-Folks/graph-generation | 532 | 12600126 | <gh_stars>100-1000
from main import *
from scipy.linalg import toeplitz
import pyemd
import scipy.optimize as opt
def Graph_generator_baseline_train_rulebased(graphs,generator='BA'):
graph_nodes = [graphs[i].number_of_nodes() for i in range(len(graphs))]
graph_edges = [graphs[i].number_of_edges() for i in rang... |
tests/test_config.py | upwork/python-upwork | 150 | 12600138 | <reponame>upwork/python-upwork
from upwork import config
def test_config_initialization():
cfg = config.Config(
{
"consumer_key": "keyxxxxxxxxxxxxxxxxxxxx",
"consumer_secret": "<KEY>",
"access_token": "<KEY>",
"access_token_secret": "<KEY>",
}
)
... |
parsing/sym2id.py | mfernezir/YellowFin | 455 | 12600151 | from __future__ import print_function
from utils import _build_vocab
import sys
if __name__ == '__main__':
if len(sys.argv) != 2:
print('usage: python sym2id.py train.gz')
sys.exit(0)
vocabs = _build_vocab(sys.argv[1])
for word, i in vocabs.iteritems():
print(word, i)
|
main_extract_TrainingSet_P.py | ryanxingql/MFQEv2.0 | 117 | 12600153 | """Extract training set.
Randomly select frame to patch.
Patches are stored in several npys.
Each npy contains several batches.
So there are n x batch_size patches in each npy.
Return: a few npy with shape (n x width_patch x width_height x 1), dtype=np.float32 \in [0,1]."""
import os, glob, gc, h5py
import numpy as np... |
Chapter18/SQLite/insert_data.py | add54/ADMIN_SYS_PYTHON | 116 | 12600158 | import sqlite3
con_obj = sqlite3.connect("test.db")
with con_obj:
cur_obj = con_obj.cursor()
cur_obj.execute("INSERT INTO books VALUES ('Pride and Prejudice', '<NAME>')")
cur_obj.execute("INSERT INTO books VALUES ('<NAME>', '<NAME>')")
cur_obj.execute("INSERT INTO books VALUES ('The Lord of the Rings', '<NAME>')"... |
lib/model/pcl/pcl.py | BarneyQiao/pcl.pytorch | 233 | 12600240 | from __future__ import absolute_import
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils.boxes as box_utils
import utils.blob as blob_utils
import utils.net as net_utils
from core.config import cfg
import numpy as np
from sklearn.cluster import KMeans
try:
xrange # Python 2... |
Stereo_Online_Adaptation.py | wtyuan96/Real-time-self-adaptive-deep-stereo | 385 | 12600252 | import tensorflow as tf
import numpy as np
import argparse
import Nets
import os
import sys
import time
import cv2
import json
import datetime
import shutil
from matplotlib import pyplot as plt
from Data_utils import data_reader,weights_utils,preprocessing
from Losses import loss_factory
from Sampler import sampler_fac... |
osp/citations/validate_config.py | davidmcclure/open-syllabus-project | 220 | 12600260 | <gh_stars>100-1000
import inflect
from osp.citations.utils import tokenize_field
from osp.common.utils import read_yaml
class Validate_Config:
def __init__(self, package='osp.citations', path='config/validate.yml'):
"""
Read the config file.
"""
self.config = read_yaml(packag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.