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 |
|---|---|---|---|---|
probe/modules/antivirus/sophos/sophos.py | krisshol/bach-kmno | 248 | 12669401 | #
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 top-level directory
# of this distribution and at:
#
# http:... |
crowd_anki/export/deck_exporter.py | ll-in-anki/CrowdAnki | 391 | 12669416 | from abc import abstractmethod, ABC
from pathlib import Path
from ..anki.adapters.anki_deck import AnkiDeck
class DeckExporter(ABC):
@abstractmethod
def export_to_directory(self, deck: AnkiDeck, output_dir: Path, copy_media=True) -> Path:
pass
|
hfc/protos/gossip/message_pb2_grpc.py | roviso/hyberledger-py | 389 | 12669428 | <filename>hfc/protos/gossip/message_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from hfc.protos.gossip import message_pb2 as hfc_dot_protos_dot_gossip_dot_message__pb2
class GossipStub(object... |
node_launcher/node_set/bitcoind/bitcoind_software.py | ryan-lingle/node-launcher | 249 | 12669576 | <reponame>ryan-lingle/node-launcher
from node_launcher.constants import (
IS_LINUX,
IS_MACOS,
IS_WINDOWS,
OPERATING_SYSTEM,
TARGET_BITCOIN_RELEASE
)
from node_launcher.node_set.lib.software import Software
class BitcoindSoftware(Software):
def __init__(self):
super().__init__(
... |
addons/metadata.themoviedb.org.python/python/lib/tmdbscraper/tmdbapi.py | RetroFlix/retroflix.repo | 420 | 12669591 | # -*- coding: UTF-8 -*-
#
# Copyright (C) 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 option) any later version.
#
# This progra... |
packages/pyright-internal/src/tests/samples/lambda5.py | Jasha10/pyright | 3,934 | 12669614 | <gh_stars>1000+
# This sample tests the case where a lambda's type is determined using
# bidirectional type inference and one or more of the parameters
# corresponds to a generic type.
from typing import Callable, TypeVar, Generic, Any
T = TypeVar("T")
MsgT = TypeVar("MsgT", bound="Msg[Any]")
class Msg(Generic[T]):... |
qtrader/agents/persistence.py | aaron8tang/qtrader | 381 | 12669628 | <reponame>aaron8tang/qtrader<gh_stars>100-1000
import numpy as np
import pandas as pd
from qtrader.agents.base import Agent
from qtrader.utils.numpy import softmax
class PersistenceAgent(Agent):
"""Model-based **persistence** agent,
acting based on last observation
(i.e returns at t-1),
using softmax... |
src/purerpc/anyio_monkeypatch.py | decentral1se/purerpc | 143 | 12669641 | <gh_stars>100-1000
import os
import anyio
import logging
from anyio import run as _anyio_run
log = logging.getLogger(__name__)
def _new_run(func, *args, backend=None, backend_options=None):
if backend is None:
backend = os.getenv("PURERPC_BACKEND", "asyncio")
log.info("Selected {} backend".format(ba... |
src/clusto/drivers/locations/zones/basiczone.py | thekad/clusto | 216 | 12669678 | from clusto.drivers.base import Location
class BasicZone(Location):
"""
Basic zone driver.
"""
_clusto_type = "zone"
_driver_name = "basiczone"
|
examples/python-guide/Grabit_demo.py | fabsig/GPBoost | 310 | 12669710 | <filename>examples/python-guide/Grabit_demo.py
# -*- coding: utf-8 -*-
"""
Examples on how to use GPBoost for the Grabit model of Sigrist and Hirnschall (2019)
@author: <NAME>
"""
import sklearn.datasets as datasets
import numpy as np
import gpboost as gpb
"""
Example 1
"""
# simulate data
np.random.seed(1)
n = 1000... |
ssh_super_virus.py | HiMiC/scripts-averagesecurityguy | 877 | 12669715 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2013, AverageSecurityGuy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above co... |
Python/ToLowerCaseTest.py | TonnyL/Windary | 205 | 12669735 | <gh_stars>100-1000
from unittest import TestCase
from ToLowerCase import ToLowerCase
class ToLowerCaseTest(TestCase):
def test_toLowerCase(self):
tlc = ToLowerCase()
self.assertEqual(tlc.toLowerCase("Hello"), "hello")
self.assertEqual(tlc.toLowerCase("here"), "here")
self.assertE... |
spk_id/make_fefeats_cfg.py | ishine/pase | 428 | 12669737 | <gh_stars>100-1000
import json
import glob
import os
DATA_PATH = '../fefeats/bsz16/epoch0'
epoch = list(range(0, 13))
splits = ['train', 'test', 'valid']
MAX_WAVS_SPK = {'train':100,
'test':10,
'valid':10}
spk2count = {}
cfg = {}
splits = ['train', 'test', 'valid']
spk2split = {}#0
sp... |
website/meta/macros.py | sophieball/Cornell-Conversational-Analysis-Toolkit | 371 | 12669743 | # macro("example", lambda ctx: fetch(ctx, "site.title"))
|
doc/Programs/LecturePrograms/programs/RandomWalks/python/program4.py | kimrojas/ComputationalPhysicsMSU | 220 | 12669756 | # coding=utf-8
#
# 1D-randomwalk: A walker makes several steps,
# with a given number of walks pr. trial.
# Similar to program1, but this version also cumputes
# the probability of a gridpoint being "touched"
#
#Translated to Python by <NAME>
import numpy, sys, math
def mc_trial(number_walks,move_probability,walk_cum... |
pyxtal/miscellaneous/mol.py | ubikpt/PyXtal | 127 | 12669775 | <reponame>ubikpt/PyXtal<gh_stars>100-1000
from rdkit import Chem
from rdkit.Chem import AllChem
import pymatgen as mg
from glob import glob
data = {}
data["HAHCOI"] = "s1c2ccc3scc4ccc(c1)c2c34"
data["JAPWIH"] = "s1ccc2cc3sc4cc5ccsc5cc4c3cc12"
data["WEXBOS"] = "s1c(c2ccccc2)c(c2ccccc2)c2c1c(c(s2)c1ccccc1)c1ccccc1"
data[... |
generate/lib/run-firefox/cuddlefish/__init__.py | flamencist/browser-extensions | 102 | 12669793 | import sys
import os
import optparse
import webbrowser
from copy import copy
import simplejson as json
from cuddlefish import packaging
from cuddlefish.bunch import Bunch
from cuddlefish.version import get_version
MOZRUNNER_BIN_NOT_FOUND = 'Mozrunner could not locate your binary'
MOZRUNNER_BIN_NOT_FOUND_HELP = """
I ... |
python_toolbox/wx_tools/window_tools.py | hboshnak/python_toolbox | 119 | 12669798 | # Copyright 2009-2017 <NAME>.
# This program is distributed under the MIT license.
'''Defines various tools for manipulating windows.'''
import wx
from python_toolbox.freezing import Freezer
class WindowFreezer(Freezer):
'''Context manager for freezing the window while the suite executes.'''
def __init__(... |
ci/make_example_size_cmt.py | lostinspiration/yew | 8,292 | 12669807 | <gh_stars>1000+
from typing import Dict, List, Optional, Tuple
import os
import json
header = "| examples | master (KB) | pull request (KB) | diff (KB) | diff (%) |"
sep = "| --- | --- | --- | --- | --- |"
def format_size(size: Optional[int]) -> str:
if size is None:
return "N/A"
if size == 0:
... |
api.py | SIDN-IAP/attention-visualization | 134 | 12669819 | <gh_stars>100-1000
import torch
from transformers import (
AutoTokenizer,
AutoModel,
)
class AttentionGetter:
'''
Wrapper Class to store model object.
'''
def __init__(self, model_name: str):
'''
Each model has an associated tokenizer object.
Load both.
'''
... |
examples/basic_usage/run_skater_and_return _forecast_error.py | iklasky/timemachines | 253 | 12669820 | from timemachines.skaters.simple.thinking import thinking_slow_and_slow
from timemachines.skatertools.evaluation.evaluators import hospital_mean_square_error_with_sporadic_fit
if __name__=='__main__':
print(hospital_mean_square_error_with_sporadic_fit(f=thinking_slow_and_slow,n=120,fit_frequency=10)) |
controle_estoque/Views/mainVendas.py | jucimar1/controleEstoque | 134 | 12669839 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainVendas.ui',
# licensing of 'mainVendas.ui' applies.
#
# Created: Mon Mar 18 10:46:46 2019
# by: PyQt5-uic running on PyQt5 5.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore... |
atlas/foundations_core_cli/src/test/__init__.py | DeepLearnI/atlas | 296 | 12669862 | <reponame>DeepLearnI/atlas<filename>atlas/foundations_core_cli/src/test/__init__.py
import faker
from test.test_project import TestProject
from test.test_scaffold import TestScaffold
from test.test_command_line_interface import TestCommandLineInterface
from test.test_environment_fetcher import TestEnvironmentFetcher
... |
resnet/models/multi_pass_optimizer_tests.py | renmengye/rev-resnet-public | 357 | 12669883 | <filename>resnet/models/multi_pass_optimizer_tests.py
"""Unit tests for multi-tower model."""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import tensorflow as tf
from resnet.configs import get_config
from resnet.configs import test_con... |
examples/wav2vec/unsupervised/data/__init__.py | Shiguang-Guo/fairseq | 16,259 | 12669901 | <reponame>Shiguang-Guo/fairseq
# 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 .extracted_features_dataset import ExtractedFeaturesDataset
from .random_input_dataset import RandomInputD... |
pyeda/boolalg/test/test_bfarray.py | ivotimev/pyeda | 196 | 12669907 | <reponame>ivotimev/pyeda<filename>pyeda/boolalg/test/test_bfarray.py
"""
Test Boolean Function arrays
"""
from nose.tools import assert_raises
from pyeda.boolalg.bdd import bddvar, BinaryDecisionDiagram
from pyeda.boolalg.bfarray import (
exprzeros, exprvars,
fcat, farray,
uint2exprs, int2exprs,
)
from py... |
koalixcrm/accounting/views.py | Cataldir/koalixcrm | 290 | 12669911 | <reponame>Cataldir/koalixcrm
# -*- coding: utf-8 -*-
from os import path
from wsgiref.util import FileWrapper
from django.http import Http404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from koalixcrm.crm.exceptions import *
from koalixcrm.djangoUserExtension.exceptions import *
fr... |
tools/convert/voc2coco.py | Karybdis/mmdetection-mini | 834 | 12669996 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import os.path as osp
import json
import argparse
import xml.etree.ElementTree as ET
from mmdet import cv_core
START_BOUNDING_BOX_ID = 1
PRE_DEFINE_CATEGORIES = {}
def get(root, name):
vars = root.findall(name)
return vars
def get_and_check(root, name, le... |
examples/urllib3_chunked_response.py | Megarushing/pook | 304 | 12670055 | import pook
import urllib3
# Mock HTTP traffic only in the given context
with pook.use():
(pook.get('httpbin.org/chunky')
.reply(200)
.body(['returned', 'as', 'chunks'], chunked=True))
# Intercept request
http = urllib3.PoolManager()
r = http.request('GET', 'httpbin.org/chunky')
p... |
etc/run_notebooks.py | truongc2/data-describe | 294 | 12670079 | <filename>etc/run_notebooks.py
from pathlib import Path
import logging
import argparse
import json
import papermill as pm
def run_all_notebooks(args):
"""Run all notebooks in the example directory."""
for notebook in Path(__file__).parent.parent.glob("examples/*.ipynb"):
notebook_path = str(notebook.... |
06. Chapter_6/pandas/sklearn_line_profiler.py | Mikma03/High-performance-Python | 223 | 12670087 | import timeit
import pandas as pd
import matplotlib.pyplot
from sklearn.linear_model import base
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from line_profiler import LineProfiler
import numpy as np
from utility import ols_lstsq, ols_sklearn
# We learn that
#https://github.com/sc... |
pyBN/inference/__init__.py | seuzmj/pyBN | 126 | 12670113 | from pyBN.inference.map_exact import *
from pyBN.inference.marginal_approx import *
from pyBN.inference.marginal_exact import * |
Packs/Cymulate/Integrations/Cymulate/Cymulate_test.py | diCagri/content | 799 | 12670122 | import demistomock as demisto
from Cymulate import cymulate_test, fetch_incidents, cymulate_get_incident_info, Client, CymulateModuleTypeEnum
BASE_URL = 'https://api.cymulate.com/v1/'
MOKE_TEST = {"success": True, "data": ["Phishing Awareness", "Web Application Firewall",
"Late... |
titus/test/lib/testMath.py | jmilleralpine/hadrian | 127 | 12670138 | <gh_stars>100-1000
#!/usr/bin/env python
# Copyright (C) 2014 Open Data ("Open Data" refers to
# one or more of the following companies: Open Data Partners LLC,
# Open Data Research LLC, or Open Data Capital LLC.)
#
# This file is part of Hadrian.
# Licensed under the Apache License, Version 2.0 (the "License");
# y... |
nmtpytorch/layers/pool.py | tejas1995/nmtpytorch | 420 | 12670144 | import torch
class Pool(torch.nn.Module):
"""A pool layer with mean/max/sum/last options."""
def __init__(self, op_type, pool_dim, keepdim=True):
super().__init__()
self.op_type = op_type
self.pool_dim = pool_dim
self.keepdim = keepdim
assert self.op_type in ["last", "... |
deep-rl/lib/python2.7/site-packages/OpenGL/raw/GL/APPLE/vertex_array_range.py | ShujaKhalid/deep-rl | 210 | 12670162 | <reponame>ShujaKhalid/deep-rl<gh_stars>100-1000
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL... |
lemur/migrations/versions/4fe230f7a26e_.py | dck25/lemur | 1,656 | 12670175 | """Add 'ports' column to certificate_associations table
Revision ID: 4fe230f7a26e
Revises: <KEY>
Create Date: 2021-05-07 10:57:16.964743
"""
# revision identifiers, used by Alembic.
revision = '4fe230f7a26e'
down_revision = '<KEY>'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postg... |
train_DQN_script.py | gordicaleksa/pytorch-learn-reinforcement-learning | 102 | 12670183 | """
Implementation of the original DQN Nature paper:
https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf
Some of the complexity is captured via wrappers but the main components such as the DQN model itself,
the training loop, the memory-efficient replay buffer are implemented from ... |
atcoder/abc102/b.py | Ashindustry007/competitive-programming | 506 | 12670210 | #!/usr/bin/env python3
# https://abc102.contest.atcoder.jp/tasks/abc102_b
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(a[-1] - a[0])
|
windows/winproxy/apis/ktmw32.py | IMULMUL/PythonForWindows | 479 | 12670220 | <filename>windows/winproxy/apis/ktmw32.py
import ctypes
import windows.generated_def as gdef
from ..apiproxy import ApiProxy, NeededParameter
from ..error import fail_on_zero
class Ktmw32Proxy(ApiProxy):
APIDLL = "Ktmw32"
default_error_check = staticmethod(fail_on_zero)
@Ktmw32Proxy()
def CommitTransaction(... |
algoexpert.io/python/Search_In_Sorted_Matrix.py | XSoyOscar/Algorithms | 713 | 12670271 | <reponame>XSoyOscar/Algorithms
# https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix
# O(n + m) time | O(1) space
# where 'n' is the length of row and 'm' is the length on column
def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >=... |
SpoTwillio/lib/python3.6/site-packages/twilio/base/deserialize.py | Natfan/funlittlethings | 1,362 | 12670315 | import datetime
from decimal import Decimal, BasicContext
from email.utils import parsedate
import pytz
ISO8601_DATE_FORMAT = '%Y-%m-%d'
ISO8601_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
def iso8601_date(s):
"""
Parses an ISO 8601 date string and returns a UTC date object or the string
if the parsing failed... |
securityheaders/checkers/infourlcollector.py | th3cyb3rc0p/securityheaders | 151 | 12670357 | <reponame>th3cyb3rc0p/securityheaders<gh_stars>100-1000
#Collects all used URLs in a policy
from securityheaders.checkers import InfoCollector, Finding, FindingType, FindingSeverity
from securityheaders.models import ModelFactory
class InfoURLCollector(InfoCollector):
def check(self, headers, opt_options=dict()):
... |
aries_cloudagent/messaging/jsonld/tests/document_loader.py | kuraakhilesh8230/aries-cloudagent-python | 247 | 12670388 | from ....vc.tests.contexts import (
CITIZENSHIP_V1,
CREDENTIALS_V1,
EXAMPLES_V1,
ODRL,
SCHEMA_ORG,
SECURITY_V1,
SECURITY_V2,
)
from . import (
TEST_EURO_HEALTH,
TEST_SIGN_OBJ0,
TEST_SIGN_OBJ1,
TEST_SIGN_OBJ2,
TEST_VALIDATE_ERROR_OBJ2,
TEST_VERIFY_ERROR,
TEST_VERI... |
MicroTokenizer/cli/commands/train.py | howl-anderson/MicroTokenizer | 136 | 12670435 | from MicroTokenizer.training.train import train_from_configure
def train(output_dir, train_data, configure_file=None):
train_from_configure([train_data], output_dir, configure_file=configure_file)
if __name__ == "__main__":
import plac
print(plac.call(train))
|
examples/io_examples/pyglet_imshow.py | penguinflys/imgviz | 171 | 12670498 | <reponame>penguinflys/imgviz
#!/usr/bin/env python
import imgviz
def get_images():
data = imgviz.data.arc2017()
yield data["rgb"]
yield imgviz.depth2rgb(data["depth"], min_value=0.3, max_value=1)
yield imgviz.label2rgb(data["class_label"])
def main():
imgviz.io.pyglet_imshow(next(get_images()),... |
homeassistant/components/directv/entity.py | MrDelik/core | 30,023 | 12670528 | """Base DirecTV Entity."""
from __future__ import annotations
from directv import DIRECTV
from homeassistant.helpers.entity import DeviceInfo, Entity
from .const import DOMAIN
class DIRECTVEntity(Entity):
"""Defines a base DirecTV entity."""
def __init__(self, *, dtv: DIRECTV, address: str = "0") -> None:... |
deepcell/layers/location.py | jizhouh/deepcell-tf | 250 | 12670556 | # Copyright 2016-2021 The <NAME> at the California Institute of
# Technology (Caltech), with support from the Paul Allen Family Foundation,
# Google, & National Institutes of Health (NIH) under Grant U24CA224309-01.
# All rights reserved.
#
# Licensed under a modified Apache License, Version 2.0 (the "License");
# you ... |
test/python/tests/test_collect.py | bh107/bohrium | 236 | 12670676 | <gh_stars>100-1000
import util
class test_collect:
def init(self):
for t in util.TYPES.ALL:
cmd = "a = M.arange(%d, dtype=%s); " % (100, t)
yield cmd
def test_contract(self, cmd):
cmd += "res = a / 180.0 * 3.14"
return cmd
def test_contract_reverse(self, cm... |
tools/HackRF/firmware/tools/dumb_crc32.py | Charmve/BLE-Security-Att-Def | 149 | 12670693 | <filename>tools/HackRF/firmware/tools/dumb_crc32.py
class DumbCRC32(object):
def __init__(self):
self._remainder = 0xffffffff
self._reversed_polynomial = 0xedb88320
self._final_xor = 0xffffffff
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & ... |
anomalib/models/reverse_distillation/anomaly_map.py | openvinotoolkit/anomalib | 689 | 12670715 | """Compute Anomaly map."""
# Original Code
# Copyright (c) 2022 hq-deng
# https://github.com/hq-deng/RD4AD
# SPDX-License-Identifier: MIT
#
# Modified
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from typing import List, Tuple, Union
import torch
import torch.nn.functional as F
from k... |
plugins/cleanup_untagged/test/test_config.py | someengineering/resoto | 126 | 12670748 | from resotolib.config import Config
from resoto_plugin_cleanup_untagged import CleanupUntaggedPlugin
def test_config():
config = Config("dummy", "dummy")
CleanupUntaggedPlugin.add_config(config)
Config.init_default_config()
assert Config.plugin_cleanup_untagged.enabled is False
assert (
Co... |
tests/test_visualization.py | frankiert/layout-parser | 2,931 | 12670803 | <reponame>frankiert/layout-parser<gh_stars>1000+
# Copyright 2021 The Layout Parser team. 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/li... |
test/functional/feature_pos.py | HUSKI3/Neblio-Node | 138 | 12670810 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test staking in neblio
"""
from test_framework.test_framework import BitcoinTestFramework
from test_fr... |
zhihuAnswerSpider/spider/Proxy_pool.py | takhello/spider_collection | 106 | 12670824 | import requests
import yaml
import os
'''特别鸣谢项目:https://github.com/jhao104/proxy_pool 提供的代理池服务'''
'''这个类主要使用来对上述项目接口的进一步封装以方便调用'''
StopEvent = object()
class Proxy_pool():
# 默认本机ip,端口是https://github.com/jhao104/proxy_pool项目的默认端口。
host="127.0.0.1"
port="5010"
def __init__(self):
config=open... |
labs/iot/gps-lab/code/web-app/app.py | chagen24/iot-curriculum | 126 | 12670900 | import os
from flask import Flask, render_template
from azure.eventhub import EventHubConsumerClient
from flask_socketio import SocketIO
from threading import Thread
# Load the environment variables
maps_key = os.environ["MAPS_KEY"]
connection_string = os.environ["CONNECTION_STRING"]
consumer_group_name = "$Default"
... |
tests/matchers.py | mattdricker/lms | 113 | 12670927 | """Objects that compare equal to other objects for testing."""
from h_matchers import Any
from pyramid.response import Response
def temporary_redirect_to(location):
"""Return a matcher for any `HTTP 302 Found` redirect to the given URL."""
return Any.instance_of(Response).with_attrs(
{"status_code": ... |
src/main/anonymization/detection_anonymization.py | BMW-InnovationLab/BMW-Anonymization-API | 108 | 12670950 | <filename>src/main/anonymization/detection_anonymization.py
from anonymization.base_anonymization import BaseAnonymization
from PIL import ImageFilter, Image
def find_boxes(bbox):
nb = []
for i in bbox:
nb.append(i)
return nb
class DetectionAnonymization(BaseAnonymization):
def __init__(self... |
verde/tests/utils.py | fatiando/verde | 415 | 12670973 | # Copyright (c) 2017 The Verde Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Testing utilities.
"""
import pytest
try:
import numba
except ImportError:
numba =... |
Sources/Workflows/XLixian/iambus-xunlei-lixian/lixian_cli_parser.py | yagosys/AlfredWorkflow.com | 2,177 | 12670974 |
def expand_windows_command_line(args):
from glob import glob
expanded = []
for x in args:
try:
xx = glob(x)
except:
xx = None
if xx:
expanded += xx
else:
expanded.append(x)
return expanded
def expand_command_line(args):
import platform
return expand_windows_command_line(args) if platform.sys... |
min-char-rnn/markov-model.py | eliben/deep-learning-samples | 183 | 12670978 | # Simple n-gram (Markov chain) model for character-based text generation.
#
# Only tested with Python 3.6+
#
# <NAME> (http://eli.thegreenplace.net)
# This code is in the public domain
from __future__ import print_function
from collections import defaultdict, Counter
import random
import sys
# This is the length of ... |
kur/sources/text.py | greedyuser/kur | 867 | 12670996 | <gh_stars>100-1000
import linecache
import numpy
import json
from ..sources import ChunkSource, DerivedSource
###############################################################################
class TextLength(DerivedSource):
""" Data source for audio lengths.
"""
def __init__(self, source, num_entries):
... |
tests/helpers/test_bbox_helper.py | wqliu657/DSNet | 113 | 12671019 | <gh_stars>100-1000
import numpy as np
from helpers import bbox_helper
def test_lr2cw():
lr_bbox = np.array([[1, 3], [2, 7], [19, 50]])
output = bbox_helper.lr2cw(lr_bbox)
answer = np.array([[2, 2], [4.5, 5], [34.5, 31]])
assert np.isclose(output, answer).all()
lr_bbox = np.array([[1.25, 2.75], [... |
django_loci/channels/consumers.py | Purhan/django-loci | 205 | 12671042 | <reponame>Purhan/django-loci<filename>django_loci/channels/consumers.py<gh_stars>100-1000
from ..models import Location
from .base import BaseLocationBroadcast
class LocationBroadcast(BaseLocationBroadcast):
model = Location
|
src/gausskernel/dbmind/tools/ai_server/main.py | Yanci0/openGauss-server | 360 | 12671050 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#############################################################################
# Copyright (c): 2021, Huawei Tech. Co., Ltd.
# FileName : main.py
# Version :
# Date : 2021-4-7
# Description : Function entry file
################################################... |
goatools/grouper/sorter.py | flying-sheep/goatools | 477 | 12671052 | """Sorts GO IDs or user-provided sections containing GO IDs."""
__copyright__ = "Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved."
__author__ = "<NAME>"
import sys
import collections as cx
from goatools.wr_tbl import prt_txt
from goatools.grouper.sorter_nts import SorterNts
from goatools.grouper.sorter_g... |
Codeforces/Lucky Mask/solution.py | rsrahul1000/Hack-CP-DSA | 205 | 12671094 | # Function to calculate the mask of a number.
def split(n):
b = []
# Iterating the number by digits.
while n > 0:
# If the digit is lucky digit it is appended to the list.
if n % 10 == 4 or n % 10 == 7:
b.append(n % 10)
n //= 10
# Return the mask.
return b
# Inp... |
robomimic/scripts/split_train_val.py | akolobov/robomimic | 107 | 12671123 | """
Script for splitting a dataset hdf5 file into training and validation trajectories.
Args:
dataset (str): path to hdf5 dataset
filter_key (str): if provided, split the subset of trajectories
in the file that correspond to this filter key into a training
and validation set of trajectories, i... |
Chapter02/01_NASDAQ_TotalView-ITCH_Order_Book/create_message_spec.py | kksonge/Hands-On-Machine-Learning-for-Algorithmic-Trading | 944 | 12671143 | <filename>Chapter02/01_NASDAQ_TotalView-ITCH_Order_Book/create_message_spec.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
import pandas as pd
df = pd.read_excel('message_types.xlsx', sheet_name='messages', encoding='latin1').sort_values('id').drop('id', axis=1)
# basic cleaning
df.columns = ... |
mindspore_hub/info.py | mindspore-ai/hub | 153 | 12671161 | <filename>mindspore_hub/info.py
# 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 require... |
Examples/Services/service_one/main.py | Mr-Victor/kivybits | 251 | 12671228 | <filename>Examples/Services/service_one/main.py
from time import sleep
from kivy.logger import Logger
import zipfile
from os.path import exists
class Waiter(object):
"""
This class simply waits for the update to finish and then closes.
"""
def __init__(self):
super(Waiter, self).__init__()
... |
dtale_desktop/file_system.py | dennislwm/dtale-desktop | 154 | 12671282 | import os
import shutil
from tempfile import mkdtemp
from typing import List, Callable, Tuple, Union
import pandas as pd
from typing_extensions import Literal
from dtale_desktop.settings import settings
__all__ = ["fs"]
_SENTINEL = object()
_TimeStampFormat = Literal["pandas", "unix_seconds", "unix_milliseconds"]
... |
tests/tests_models/test_activation_fn.py | TomF98/torchphysics | 203 | 12671292 | <filename>tests/tests_models/test_activation_fn.py
import pytest
import torch
from torchphysics.models.activation_fn import AdaptiveActivationFunction
def test_create_adaptive_with_tanh():
adap_fn = AdaptiveActivationFunction(torch.nn.Tanh())
assert isinstance(adap_fn.activation_fn, torch.nn.Tanh)
assert... |
fabricio/apps/db/postgres.py | theoden-dd/fabricio | 291 | 12671308 | <gh_stars>100-1000
import multiprocessing
import os
from datetime import datetime
import six
from fabric import api as fab
from fabric.contrib import files
import fabricio
from fabricio import docker, utils
from fabricio.docker.base import Attribute
from fabricio.utils import Options
class PostgresqlBackupMixin(... |
remme/tp/context.py | FerrySchuller/remme-core | 129 | 12671330 | import logging
from google.protobuf.text_format import ParseError
from sawtooth_sdk.processor.exceptions import InternalError
from sawtooth_sdk.protobuf import state_context_pb2
from remme.settings import STATE_TIMEOUT_SEC
logger = logging.getLogger(__name__)
class CacheContextService:
def __init__(self, con... |
TWE-1/train.py | sysuhu/topical_word_embeddings | 330 | 12671349 | <reponame>sysuhu/topical_word_embeddings
#!/usr/bin/env python2
#-*- coding: UTF-8 -*-
#File: train.py
#Date: 20140810
#Author: <NAME> <<EMAIL>>
#Description Train the topic representation using the topic model and the word2vec's skip gram
import gensim #modified gensim version
import pre_process # read the wordmap an... |
tests/test_manylinux.py | hugovk/packaging | 388 | 12671442 | <reponame>hugovk/packaging
try:
import ctypes
except ImportError:
ctypes = None
import os
import platform
import sys
import types
import warnings
import pretend
import pytest
from packaging import _manylinux
from packaging._manylinux import (
_ELFFileHeader,
_get_elf_header,
_get_glibc_version,
... |
tests/config/test_cfg_alt.py | ThePrez/gunicorn | 6,851 | 12671501 | proc_name = "not-fooey"
|
mac/pyobjc-framework-Quartz/PyObjCTest/test_ciimage.py | albertz/music-player | 132 | 12671519 |
from PyObjCTools.TestSupport import *
from Quartz.QuartzCore import *
try:
long
except NameError:
long = int
try:
unicode
except NameError:
unicode = str
class TestCIImage (TestCase):
def testConstants(self):
self.assertIsInstance(kCIFormatARGB8, (int, long))
self.assertIsInstanc... |
ch04_linear/code/generate_data.py | wellszhao/intro_ds_wy_course | 146 | 12671523 | <gh_stars>100-1000
# -*- coding: UTF-8 -*-
"""
此脚本用于随机生成线性回归模型的训练数据
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def generate_data():
"""
随机生成数据
"""
# 规定随机数生成的种子
np.random.seed(4889)
# Python2和Python3的range并不兼容,所以使用list(range(10, 29))
x = np.array... |
L1Trigger/L1TMuon/python/simMuonQualityAdjusterDigis_cfi.py | ckamtsikis/cmssw | 852 | 12671526 | import FWCore.ParameterSet.Config as cms
import os
simMuonQualityAdjusterDigis = cms.EDProducer('L1TMuonQualityAdjuster',
bmtfInput = cms.InputTag("simBmtfDigis", "BMTF"),
omtfInput = cms.InputTag("simOmtfDigis", "OMTF"),
emtfInput = cms.InputTag("simEmtfDigis", "EMTF"),
bmtfBxOffset = cms.int32(0)... |
model/item.py | luerhard/remapy | 172 | 12671532 | <reponame>luerhard/remapy<filename>model/item.py
from datetime import datetime
import time
from pathlib import Path
import json
from api.remarkable_client import RemarkableClient
import utils.config
#
# DEFINITIONS
#
STATE_SYNCING = 1
STATE_SYNCED = 2
STATE_DELETED = 170591
RFC3339Nano = "%Y-%m-%dT%H:%M:%SZ"
#
# ... |
hover/utils/denoising.py | phurwicz/hover | 251 | 12671558 | import math
import numpy as np
import torch
from collections import defaultdict
from hover.utils.torch_helper import cross_entropy_with_probs
def loss_coteaching_directed(y_student, y_teacher, target, forget_rate):
"""
Subroutine for loss_coteaching_graph.
"""
num_remember = math.ceil((1 - forget_rate... |
examples/nitro.py | msabramo/diesel | 224 | 12671573 | <gh_stars>100-1000
from pynitro import NitroFrame
from diesel.protocols.nitro import DieselNitroSocket
from diesel import quickstart, quickstop
#loc = "tcp://127.0.0.1:4444"
loc = "inproc://foobar"
def server():
with DieselNitroSocket(bind=loc) as sock:
while True:
m = sock.recv()
... |
python-for-beginners/02 - Print/coding_challenge_solution.py | vijayraavi/c9-python-getting-started | 8,041 | 12671580 | # Here's a challenge for you to help you practice
# See if you can fix the code below
# print the message
# There was a single quote inside the string!
# Use double quotes to enclose the string
print("Why won't this line of code print")
# print the message
# There was a mistake in the function name
print('This line ... |
scripts/nvvpreader/nvvpreader.py | SymbioticLab/Salus | 104 | 12671669 | #
# Copyright 2019 <NAME> <<EMAIL>>
#
# This file is part of Salus
# (see https://github.com/SymbioticLab/Salus).
#
# 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.o... |
tests/em/static/test_DC_1D_jvecjtvecadj.py | Prithwijit-Chak/simpeg | 358 | 12671691 | <filename>tests/em/static/test_DC_1D_jvecjtvecadj.py
from __future__ import print_function
import unittest
import numpy as np
from discretize import TensorMesh
from SimPEG import (
maps,
data_misfit,
regularization,
inversion,
optimization,
inverse_problem,
tests,
)
from SimPEG.utils import ... |
typed_python/compiler/function_metadata.py | APrioriInvestments/typed_python | 105 | 12671735 | class FunctionMetadata:
def __init__(self):
self._constantReturnValue = ()
def setConstantReturnValue(self, value):
self._constantReturnValue = (value,)
def hasConstantReturnValue(self):
return self._constantReturnValue
def getConstantReturnValue(self):
return self._co... |
uq360/utils/transformers/original_features.py | Sclare87/UQ360 | 148 | 12671751 | from uq360.utils.transformers.feature_transformer import FeatureTransformer
class OriginalFeaturesTransformer(FeatureTransformer):
'''
Dummy/identity transformer which passes the data array through unchanged.
'''
def __init__(self):
super(OriginalFeaturesTransformer, self).__init__()
... |
Python/Biopython/read_seq.py | Gjacquenot/training-material | 115 | 12671759 | <filename>Python/Biopython/read_seq.py
#!/usr/bin/env python
from argparse import ArgumentParser
from Bio import SeqIO, SeqUtils
from collections import namedtuple
SeqStats = namedtuple('SeqStats', ['length', 'gc', 'weight'])
def compute_stats(seq):
stats = SeqStats
stats.length = len(seq)
stats.gc = Se... |
Python-3/basic_examples/decorator.py | ghiloufibelgacem/jornaldev | 1,139 | 12671765 | array = ['a', 'b', 'c']
def decorator(func):
def newValueOf(pos):
if pos >= len(array):
print("Oops! Array index is out of range")
return
func(pos)
return newValueOf
@decorator
def valueOf(index):
print(array[index])
valueOf(10)
|
aries_cloudagent/tails/error.py | kuraakhilesh8230/aries-cloudagent-python | 247 | 12671818 | """Tails server related errors."""
from ..core.error import BaseError
class TailsServerNotConfiguredError(BaseError):
"""Error indicating the tails server plugin hasn't been configured."""
|
src/sims4communitylib/utils/whims/common_satisfaction_reward_store_utils.py | velocist/TS4CheatsInfo | 118 | 12671843 | <reponame>velocist/TS4CheatsInfo<gh_stars>100-1000
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from typ... |
src/plugins/dhcp/test/vpp_dhcp.py | amithbraj/vpp | 751 | 12671907 | from vpp_object import VppObject
class VppDHCPProxy(VppObject):
def __init__(
self,
test,
dhcp_server,
dhcp_src_address,
rx_vrf_id=0,
server_vrf_id=0,
):
self._test = test
self._rx_vrf_id = rx_vrf_id
self._server_vrf_id = server_vrf_id
... |
xautodl/datasets/math_core.py | Joey61Liuyi/AutoDL-Projects | 817 | 12671924 | #####################################################
# Copyright (c) <NAME> [GitHub D-X-Y], 2021.05 #
#####################################################
from .math_static_funcs import (
LinearSFunc,
QuadraticSFunc,
CubicSFunc,
QuarticSFunc,
ConstantFunc,
ComposedSinSFunc,
ComposedCosSFun... |
packs/consul/actions/query_node.py | userlocalhost2000/st2contrib | 164 | 12671949 | <gh_stars>100-1000
from lib import action
class ConsulQueryNodeAction(action.ConsulBaseAction):
def run(self, node):
index, node = self.consul.catalog.node(node)
return node
|
flextensor/testing/others/hand-craft/schedule_gemm_vhls.py | imxian/FlexTensor | 135 | 12671955 | import heterocl as hcl
def kernel_gemm(A, B):
k = hcl.reduce_axis(0, A.shape[1], "k")
return hcl.compute(
(A.shape[0], B.shape[1]),
lambda i, j: hcl.sum(A[i, k] * B[k, j], axis=k),
"C")
def main():
M = 512
N = 512
K = 512
A = hcl.placeholder((M, K), dtype="float32", n... |
raiden/tests/unit/utils/test_formatting.py | tirkarthi/raiden | 2,101 | 12671998 | import os
from eth_utils import to_checksum_address as eth_utils_checksum
from raiden.utils.formatting import to_checksum_address
from raiden.utils.typing import Address
def test_random_addresses():
for _ in range(100):
address_bytes = Address(os.urandom(20))
assert eth_utils_checksum(address_by... |
sionna/channel/time_channel.py | NVlabs/sionna | 163 | 12672006 | #
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Layer for implementing the channel in the time domain"""
import tensorflow as tf
from . import GenerateTimeChannel, ApplyTimeChannel
from .utils import time_lag_discrete... |
tests/unit/modules/test_zenoss.py | babs/salt | 9,425 | 12672007 | import salt.modules.config as config
import salt.modules.zenoss as zenoss
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, call, patch
from tests.support.unit import TestCase
class ZenossTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.