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
vaurien/tests/test_util.py
mozilla-libs/vaurien
131
12663443
<reponame>mozilla-libs/vaurien<gh_stars>100-1000 import unittest from vaurien.util import chunked class TestUtil(unittest.TestCase): def test_chunked(self): self.assertEqual(sum(list(chunked(7634, 2049))), 7634)
data_utils/extraction.py
lcylcy/GLM_copa
212
12663479
<reponame>lcylcy/GLM_copa import nltk import glob import json import os nltk.download('punkt') class NLTKSegmenter: def __init(self): pass @staticmethod def segment_string(article): return nltk.tokenize.sent_tokenize(article) wiki_path = "data/extracted" output_path = "formatted/wiki-k...
ctc_fast/decoder/setup.py
SrikarSiddarth/stanford-ctc
268
12663498
<filename>ctc_fast/decoder/setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("bg_decoder", ["bg_decoder.pyx"]), Extension("clm_decoder", ["clm_decoder.pyx"...
leo/modes/eiffel.py
ATikhonov2/leo-editor
1,550
12663508
<filename>leo/modes/eiffel.py # Leo colorizer control file for eiffel mode. # This file is in the public domain. # Properties for eiffel mode. properties = { "lineComment": "--", } # Attributes dict for eiffel_main ruleset. eiffel_main_attributes_dict = { "default": "null", "digit_re": "", ...
axcell/models/linking/proposals_filters.py
Kabongosalomon/axcell
335
12663509
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from ...pipeline_logger import pipeline_logger import pandas as pd from enum import Enum class FilterOutReason(Enum): TrainDataset = "train-dataset" DevDataset = "dev-dataset" EmptyModelName = "empty-model-name" ModelCompeting = ...
tests/test_header.py
michkoll/python-evtx
525
12663585
<gh_stars>100-1000 from fixtures import * import Evtx.Evtx as evtx def test_file_header(system): ''' regression test parsing some known fields in the file header. Args: system (bytes): the system.evtx test file contents. pytest fixture. ''' fh = evtx.FileHeader(system, 0x0) # collecte...
monitor/database/queries.py
philippnormann/chia-monitor
148
12663594
from datetime import datetime, timedelta from typing import Optional, Tuple from monitor.database.events import (BlockchainStateEvent, ConnectionsEvent, FarmingInfoEvent, HarvesterPlotsEvent, SignagePointEvent, WalletBalanceEvent) from sqlalchemy.orm import Session from sqlalchemy....
examples/domain-adaptation/plot_otda_color_images.py
Pseudomanifold/POT
830
12663609
# -*- coding: utf-8 -*- """ ============================= OT for image color adaptation ============================= This example presents a way of transferring colors between two images with Optimal Transport as introduced in [6] [6] <NAME>., <NAME>., <NAME>., & <NAME>. (2014). Regularized discrete optimal transpor...
janome/__init__.py
narupo/janome
748
12663647
<filename>janome/__init__.py from janome.version import JANOME_VERSION as __version__ __all__ = [ "__version__", ]
PyObjCTest/test_nsenumerator.py
Khan/pyobjc-framework-Cocoa
132
12663656
from PyObjCTools.TestSupport import * import objc from Foundation import * import Foundation class TestNSEnumeratorInteraction(TestCase): def setUp(self): self.arrayContainer = NSArray.arrayWithArray_(range(100)) def testNoFastEnumeration(self): self.assertNotHasAttr(Foundation, 'NSFastEnumer...
src/offazure/azext_offazure/vendored_sdks/offazure/models/_azure_migrate_v2_enums.py
Mannan2812/azure-cli-extensions
207
12663664
<gh_stars>100-1000 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Genera...
tests/test_mock.py
zyfra/ebonite
270
12663692
<gh_stars>100-1000 import pytest from tests.conftest import MockMixin class A: def method(self): """aaaa""" def method2(self): return 2 class B(A, MockMixin): def method(self): return 1 def test_mock_mixin(): b = B() assert b.method() == 1 b.method.assert_called()...
sphinxcontrib/napoleon/_upstream.py
SimBioSysInc/napoleon
124
12663700
# -*- coding: utf-8 -*- """ sphinxcontrib.napoleon._upstream ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Functions to help compatibility with upstream sphinx.ext.napoleon. :copyright: Copyright 2013-2018 by <NAME>, see AUTHORS. :license: BSD, see LICENSE for details. """ def _(message, *args): """ ...
tools/row_to_column/convert_row_to_column.py
kaiker19/incubator-doris
3,562
12663714
# 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 ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
mindmeld/components/_util.py
ritvikshrivastava/mindmeld
580
12663717
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Cisco Systems, Inc. and others. 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...
libs/JAF/BasePlugin.py
sc979/jenkins-attack-framework
451
12663733
import base64 import logging import queue import sys from urllib.parse import urlparse import requests.exceptions as req_exc from libs import jenkinslib def _logging_fatal(msg, *args, **kwargs): logging.critical(msg, *args, **kwargs) exit(1) class HijackStdOut: def __enter__(self): # Preserve ...
tests/integration/cli/assets_test.py
gamechanger/dusty
421
12663734
import os import tempfile import time from dusty.systems.virtualbox import asset_is_set, run_command_on_vm from dusty import constants from dusty.source import Repo from dusty.memoize import reset_memoize_cache from ...testcases import DustyIntegrationTestCase from ...fixtures import assets_fixture class TestAssetsCL...
Anaconda-files/Program_18a.py
arvidl/dynamical-systems-with-applications-using-python
106
12663740
# Program 18a: Generating a multifractal image. # Save the image. # See Figure 18.1(b). import numpy as np import matplotlib.pyplot as plt from skimage import exposure, io, img_as_uint p1, p2, p3, p4 = 0.3, 0.4, 0.25, 0.05 p = [[p1, p2], [p3, p4]] for k in range(1, 9, 1): M = np.zeros([2 ** (k + 1), 2 ** (k + 1)]...
utils/testing/base.py
maznu/peering-manager
127
12663784
import json from ipaddress import IPv4Address, IPv4Interface, IPv6Address, IPv6Interface from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.core.exceptions import FieldDoesNotExist from django.db.models import ManyToManyField from django.forms...
tests/test_integration.py
guillaumehuet/SolidsPy
190
12663794
# -*- coding: utf-8 -*- """ Integration tests for solidspy """ import numpy as np from scipy.sparse.linalg import eigsh import solidspy.postprocesor as pos import solidspy.assemutil as ass import solidspy.solutil as sol def test_4_elements(): """2×2 mesh with uniaxial load""" nodes = np.array([ [...
malaya_speech/train/model/uis_rnn/model.py
ishine/malaya-speech
111
12663803
import tensorflow as tf _INITIAL_SIGMA2_VALUE = 0.1 class CoreRNN(tf.keras.layers.Layer): def __init__( self, observation_dim=256, rnn_hidden_size=512, rnn_depth=1, rnn_dropout=0.0, rnn_cell=tf.keras.layers.GRU, **kwargs, ): super(CoreRNN, self)...
tests/url_fixtures.py
shibli049/expynent
438
12663807
<filename>tests/url_fixtures.py<gh_stars>100-1000 # -*- coding: utf-8 -*- INVALID_URLS = [ 'http://', 'http://.', 'http://..', 'http://../', 'http://?', 'http://??', 'http://??/', 'http://#', 'http://##', 'http://##/', 'http://foo.bar?q=Spaces should be encoded', '//', ...
mara_pipelines/commands/python.py
timgates42/mara-pipelines
1,398
12663817
"""Commands for running python functions and scripts""" import inspect import shlex import sys import json from html import escape from typing import Union, Callable, List from ..incremental_processing import file_dependencies from ..logging import logger from mara_page import html, _ from .. import pipelines class...
Algo and DSA/LeetCode-Solutions-master/Python/distribute-candies-to-people.py
Sourav692/FAANG-Interview-Preparation
3,269
12663819
<reponame>Sourav692/FAANG-Interview-Preparation # Time: O(n + logc), c is the number of candies # Space: O(1) class Solution(object): def distributeCandies(self, candies, num_people): """ :type candies: int :type num_people: int :rtype: List[int] """ # find max inte...
cape_webservices/tests/test_api/test_client.py
edwardmjackson/cape-webservices
164
12663828
<gh_stars>100-1000 # Copyright 2018 BLEMUNDSBURY AI LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
scripts/inference.py
thienquang199x/SAM
351
12663836
<filename>scripts/inference.py from argparse import Namespace import os import time from tqdm import tqdm from PIL import Image import numpy as np import torch from torch.utils.data import DataLoader import sys sys.path.append(".") sys.path.append("..") from configs import data_configs from datasets.inference_dataset...
tests/unit/resources/activity/test_alerts.py
doziya/hpeOneView
107
12663877
<filename>tests/unit/resources/activity/test_alerts.py # -*- coding: utf-8 -*- ### # (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP # # 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 t...
tests/unit/test_common_subprocess.py
windies21/loopchain
105
12663892
<reponame>windies21/loopchain """Test Common Process""" import logging import time import unittest from loopchain.baseservice import CommonSubprocess from loopchain.utils import loggers loggers.set_preset_type(loggers.PresetType.develop) loggers.update_preset() class TestCommonSubprocess(unittest.TestCase): d...
mistral/actions/legacy.py
shubhamdang/mistral
205
12663904
# Copyright 2020 Nokia Software. # # 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 agr...
02_Python/Random_Forest_Classifier.py
milaan9/Clustering_Algorithms_from_Scratch
126
12663913
<filename>02_Python/Random_Forest_Classifier.py import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier RSEED = 50 # Load in data df = pd.read_csv('https://s3.amazonaws.com/projects-rf/clean_data.csv') # Full dataset: https://www...
leonardo/module/media/utils.py
timgates42/django-leonardo
102
12663918
<gh_stars>100-1000 from .models import Folder, MEDIA_MODELS def handle_uploaded_file(file, folder=None, is_public=True): '''handle uploaded file to folder match first media type and create media object and returns it file: File object folder: str or Folder isinstance is_public: boolean ''' ...
cardio/dataset/dataset/utils_random.py
lbdvriesGT/cardio
101
12663965
<gh_stars>100-1000 """ contains data utils """ import warnings import numpy as np def make_rng(seed=None): """ Create a random number generator Parameters ---------- seed : bool, int, Generator, BitGenerator, RandomState a random state - False - returns None - None or True -...
external-deps/qdarkstyle/qdarkstyle/colorsystem.py
Earthman100/spyder
7,956
12663992
# colorsystem.py is the full list of colors that can be used to easily create themes. class Gray: B0 = '#000000' B10 = '#19232D' B20 = '#293544' B30 = '#37414F' B40 = '#455364' B50 = '#54687A' B60 = '#60798B' B70 = '#788D9C' B80 = '#9DA9B5' B90 = '#ACB1B6' B100 = '#B9BDC1' ...
cisco-ios-xr/ydk/models/cisco_ios_xr/ntp.py
CiscoDevNet/ydk-py
177
12664007
<gh_stars>100-1000 """ ntp This module contains definitions for the Calvados model objects. This module contains a collection of YANG definitions for Cisco IOS\-XR syadmin NTP configuration. This module contains definitions for the following management objects\: NTP configuration data Copyright (c) 2013\-2016 by C...
test/circuit/library/ansatzes/utils/vibrational_op_label_creator.py
jschuhmac/qiskit-nature
132
12664035
<gh_stars>100-1000 # This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modificatio...
rnn/chatbot/seq2seq_conversation_model/tokenizer.py
llichengtong/yx4
128
12664047
# coding=utf8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import re import sys from tensorflow.python.platform import gfile from settings import VOCAB_DICT_FILE _PAD = "_PAD" _GO = "_GO" _EOS = "_EOS" _UNK = "_UNK" _START_VOCAB = [_PAD, _G...
autovideo/common/denormalize.py
HuaizhengZhang/autovideo
233
12664088
<reponame>HuaizhengZhang/autovideo ''' Copyright 2021 D3M Team Copyright (c) 2021 DATA Lab at Texas A&M University 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...
scripts/update_stlib_from_cpython.py
mementum/brython
5,926
12664099
<gh_stars>1000+ # compare Brython stdlib and CPython stdlib import os import filecmp import shutil bdir = os.path.join(os.path.dirname(os.getcwd()), "www", "src", "Lib") p_old_dir = r'c:\Python39\Lib' p_new_dir = r'c:\Python310\Lib' for dirpath, dirnames, filenames in os.walk(bdir): if "site-packages" in dir...
alg/edm/network/student_network.py
loramf/mlforhealthlabpub
171
12664158
from .base_network import * class StudentNetwork(BaseNetwork): def __init__(self, in_dim : int, out_dim : int, width : int, ): super(StudentNetwork, self).__init__() self.in_dim = in_dim self.out_dim = out_dim self.width = width self.layer...
mmtbx/suitename/unit-test/UnitTest.py
dperl-sol/cctbx_project
155
12664161
<gh_stars>100-1000 from __future__ import nested_scopes, generators, division, absolute_import from __future__ import with_statement, print_function import os, sys, inspect from io import StringIO currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(current...
test/correctness/conftest.py
kolesa-team/fdb-document-layer
176
12664196
#!/usr/bin/python # # conftest.py # # This source file is part of the FoundationDB open source project # # Copyright 2013-2019 Apple Inc. and the FoundationDB project 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 ...
2021.09.21-netgear-circle/upgrade_attack.py
bbhunter/NotQuite0DayFriday
756
12664202
<reponame>bbhunter/NotQuite0DayFriday<filename>2021.09.21-netgear-circle/upgrade_attack.py #!/usr/bin/env python from multiprocessing import Process from time import sleep import argparse import http.server import re import socketserver import socket from scapy.all import * def build_dns_response(query, name): ...
backend/r2dec/mdec-r2dec/mdecr2dec/__main__.py
clayne/mdec
317
12664265
from mdecr2dec import R2decService from mdecbase import mdec_main if __name__ == '__main__': mdec_main(R2decService)
tests/mock_objects.py
JPTIZ/asciimatics
3,197
12664288
<filename>tests/mock_objects.py from asciimatics.effects import Effect from asciimatics.exceptions import StopApplication, NextScene class MockEffect(Effect): """ Dummy Effect use for some UTs. """ def __init__(self, count=10, stop=True, swallow=False, next_scene=None, frame_rate=1, s...
homeassistant/components/eq3btsmart/const.py
MrDelik/core
30,023
12664295
"""Constants for EQ3 Bluetooth Smart Radiator Valves.""" PRESET_PERMANENT_HOLD = "permanent_hold" PRESET_NO_HOLD = "no_hold" PRESET_OPEN = "open" PRESET_CLOSED = "closed"
alembic/versions/3bc50ecd0bb_add_generic_id_support.py
bigblue/pynab
161
12664296
"""add generic id support Revision ID: 3bc50ecd0bb Revises: <PASSWORD> Create Date: 2015-10-28 19:25:26.378971 """ # chunk size to process tv/movies PROCESS_CHUNK_SIZE = 5000 # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '30688404cda' from alembic import op import sqlalchemy as sa fro...
src/api/accesscontrolprofile.py
piwaniuk/critic
216
12664333
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2015 the Critic contributors, Opera Software ASA # # 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/LI...
google_problems/problem_83.py
loftwah/Daily-Coding-Problem
129
12664348
"""This problem was asked by Google. You are writing an AI for a 2D map game. You are somewhere in a 2D grid, and there are coins strewn about over the map. Given the position of all the coins and your current position, find the closest coin to you in terms of Manhattan distance. That is, you can move around up, d...
script/createTestData/main.py
bitkylin/ClusterDeviceManager
379
12664364
from utils import device_create from utils import namecreater from datetime import datetime import random db = device_create.get_creator("172.16.58.3", "bitkyTest") device = db.Device employee = db.Employee device.drop() employee.drop() # 生成并插入 device 集合 result = device.insert_many( [{'GroupId': group_id, '...
pyntcloud/neighbors/r_neighbors.py
bernssolg/pyntcloud-master
1,142
12664370
import numpy as np def r_neighbors(kdtree, r): """ Get indices of all neartest neighbors with a distance < r for each point Parameters ---------- kdtree: pyntcloud.structrues.KDTree The KDTree built on top of the points in point cloud r: float Maximum distance to consider a neigh...
Trakttv.bundle/Contents/Libraries/Shared/exception_wrappers/manager.py
disrupted/Trakttv.bundle
1,346
12664374
<filename>Trakttv.bundle/Contents/Libraries/Shared/exception_wrappers/manager.py from pyemitter import Emitter class ExceptionSource(object): APSW = 'apsw' Peewee = 'peewee' class Manager(Emitter): def add(self, source, exc_info, name=None): if not exc_info or len(exc_info) != 3: ...
idiot/checks/firewall.py
snare/idiot
145
12664376
""" Firewall check for Idiot. """ import biplist import idiot from idiot import CheckPlugin class FirewallCheck(CheckPlugin): name = "Firewall" def run(self): try: d = biplist.readPlist('/Library/Preferences/com.apple.alf.plist') enabled = (d['globalstate'] >= 1) exce...
migrations/versions/5d3c326dd901_add_created_and_updated_date_to_notebook.py
snowdensb/braindump
631
12664377
"""Add Created and Updated date to Notebook Revision ID: 5d3c326dd901 Revises: <PASSWORD> Create Date: 2016-08-29 10:39:23.609605 """ # revision identifiers, used by Alembic. revision = '5d3c326dd901' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto ...
hata/discord/embed/__init__.py
ToxicKidz/hata
173
12664383
<gh_stars>100-1000 from .embed import * from .embed_base import * from .embed_core import * __all__ = ( *embed.__all__, *embed_base.__all__, *embed_core.__all__, )
pyhashcat/sre_yield/tests/test_fastdivmod.py
security-geeks/hacking-tools
198
12664390
#!/usr/bin/env python2 # # Copyright 2011-2014 Google Inc. # # 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 applicabl...
alipay/aop/api/domain/AlipayGongyiModelTest.py
antopen/alipay-sdk-python-all
213
12664403
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.AlipayGongyiUserInfoTest import AlipayGongyiUserInfoTest class AlipayGongyiModelTest(object): def __init__(self): self._buyer = None self._buyer_email = None ...
crawler/gather/middlewares.py
shifei123/test
283
12664417
# -*-coding:utf-8-*- from scrapy import signals from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware import random class RandomUserAgentMiddleware(UserAgentMiddleware): def __init__(self, user_agent='Scrapy', user_agent_list=None): super(RandomUserAgentMiddleware, self).__init__(user_a...
roll_engine/models/batches.py
js882829/tars
371
12664431
<reponame>js882829/tars<filename>roll_engine/models/batches.py from __future__ import absolute_import from django.db import models from roll_engine.fsm import BatchFSMixin from roll_engine.mixins import BatchMixin from roll_engine.exceptions import DeploymentError from .base import FSMedModel, InheritanceMetaclass ...
sky130/custom/scripts/sp_to_spice.py
d-m-bailey/open_pdks
103
12664449
<filename>sky130/custom/scripts/sp_to_spice.py #!/usr/bin/env python3 # # sp_to_spice --- # # This script runs as a filter to foundry_install.sh and converts file # names ending with ".sp" to ".spice". If the file has multiple extensions # then all are stripped before adding ".spice". # # This script is a filter to be...
torchfusion/layers/layers.py
fbremer/TorchFusion
250
12664478
import torch.nn as nn import torch import torch.nn.functional as F from torchfusion.initializers import * from torch.nn.modules.conv import _ConvNd,_ConvTransposeMixin,_single,_pair,_triple from torch.nn.modules.batchnorm import _BatchNorm class MultiSequential(nn.Sequential): def __init__(self, *args): s...
chapter10-图像描述(Image Caption)/config.py
1364354238/PYTORCH_LEARNING
137
12664498
<filename>chapter10-图像描述(Image Caption)/config.py #coding:utf8 class Config: caption_data_path='caption.pth'# 经过预处理后的人工描述信息 img_path='/home/cy/caption_data/' # img_path='/mnt/ht/aichallenger/raw/ai_challenger_caption_train_20170902/caption_train_images_20170902/' img_feature_path = 'results.pth' # 所有图...
nuplan/common/maps/nuplan_map/test/test_intersection.py
motional/nuplan-devkit
128
12664501
from typing import Any, Dict import pytest from nuplan.common.actor_state.state_representation import Point2D from nuplan.common.maps.abstract_map import SemanticMapLayer from nuplan.common.maps.abstract_map_objects import Intersection from nuplan.common.maps.nuplan_map.map_factory import NuPlanMapFactory from nuplan...
tools/linux/tk2bar.py
sz6636/DataCore
144
12664511
<reponame>sz6636/DataCore from tkreader import TkReader import pandas as pd import numpy as np import datetime as dt import traceback from test._mock_backport import inplace bar_fields = ['date', 'trade_date', 'time', 'volume_inc', 'turnover_inc', 'settle', 'oi', 'open', 'high', 'low', 'close', 'volume'...
tika-parsers/src/main/resources/org/apache/tika/parser/captioning/tf/model_wrapper.py
dedabob/tika
1,299
12664522
#!/usr/bin/env python # 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 ASF licenses this file # to you under the Apache License, Version 2.0 (the ...
tests/test_ridgereg.py
GabrielWen/spartan
156
12664528
<filename>tests/test_ridgereg.py from spartan.examples import ridge_regression import test_common from test_common import millis from spartan import expr, util import time N_EXAMPLES = 100 N_DIM = 3 ITERATION = 10 class TestRidgeRegression(test_common.ClusterTest): def test_ridgereg(self): ridge_regression.run(...
moto/firehose/exceptions.py
oakbramble/moto
5,460
12664536
<gh_stars>1000+ """Exceptions raised by the Firehose service.""" from moto.core.exceptions import JsonRESTError class ConcurrentModificationException(JsonRESTError): """Existing config has a version ID that does not match given ID.""" code = 400 def __init__(self, message): super().__init__("Con...
midi_ddsp/utils/file_utils.py
magenta/midi-ddsp
169
12664565
"""Utility functions for file io and file path reading.""" # Copyright 2021 The DDSP 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/license...
skgstat/tests/test_metric_space.py
mmaelicke/scikit-gstat
141
12664616
import pytest import numpy as np import skgstat as skg import scipy # produce a random dataset np.random.seed(42) rcoords = np.random.gamma(40, 10, size=(500, 2)) np.random.seed(42) rvals = np.random.normal(10, 4, 500) def test_invalid_dist_func(): # instantiate metrix space ms = skg.MetricSpace(rcoords, dist...
tensorpack/dataflow/dataset/camvid.py
Bhaskers-Blu-Org2/petridishnn
121
12664620
from ..base import RNGDataFlow from ...utils import logger,fs import os import numpy as np def load_data_from_npzs(fnames): if not isinstance(fnames, list): fnames = [fnames] Xs = [] Ys = [] for fname in fnames: d = np.load(fname) logger.info('Loading from {}'.format(fname)) ...
server/app/services/publish/models.py
goodfree/ActorCloud
173
12664627
<reponame>goodfree/ActorCloud from sqlalchemy import func from sqlalchemy.dialects.postgresql import JSONB from actor_libs.database.orm import BaseModel, db, ModelMixin __all__ = ['PublishLog', 'TimerPublish'] class PublishLog(ModelMixin, db.Model): """ controlType: 1:Publish,2:Read,3:Write,4 Execute p...
setup.py
freemansw1/trackpy
315
12664645
<gh_stars>100-1000 import os import versioneer from setuptools import setup try: descr = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() except OSError: descr = '' # In some cases, the numpy include path is not present by default. # Let's try to obtain it. try: import numpy except Impor...
descarteslabs/workflows/types/primitives/tests/test_number.py
descarteslabs/descarteslabs-python
167
12664652
import operator import pytest import numpy as np from ...core import ProxyTypeError from ...containers import Tuple, List from ...identifier import parameter from ..bool_ import Bool from ..string import Str from ..number import Float, Int, Number, _binop_result from ...core.tests.utils import operator_test class ...
keras_image_captioning/word_vectors_test.py
ashishpatel26/keras-image-captioning
116
12664655
<filename>keras_image_captioning/word_vectors_test.py import pytest from .preprocessors import CaptionPreprocessor from .word_vectors import Glove, Fasttext class WordVectorTestBase(object): _WORD_VECTOR = None @pytest.fixture def word_vector(self, mocker): mocker.patch.object(self._WORD_VECTOR,...
tests/test_s3/test_s3_replication.py
gtourkas/moto
5,460
12664666
<filename>tests/test_s3/test_s3_replication.py import boto3 import pytest import sure # noqa # pylint: disable=unused-import from botocore.exceptions import ClientError from moto import mock_s3 from uuid import uuid4 DEFAULT_REGION_NAME = "us-east-1" @mock_s3 def test_get_bucket_replication_for_unexisting_bucket()...
deps/npm/node_modules/node-gyp/gyp/test/gyp-defines/gyptest-regyp.py
loganfsmyth/node
140
12664675
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that when the same value is repeated for a gyp define, duplicates are stripped from the regeneration rule. """ import os impor...
blogs/tests/test_models.py
ewjoachim/pythondotorg
911
12664688
from django.test import TestCase from django.utils import timezone from ..models import BlogEntry, Feed class BlogModelTest(TestCase): def test_blog_entry(self): now = timezone.now() b = BlogEntry.objects.create( title='Test Entry', summary='Test Summary', pu...
test_values.py
tomaarsen/word_forms
570
12664719
# Test values must be in the form [(text_input, expected_output), (text_input, expected_output), ...] test_values = [ ( "president", { "n": { "president", "presidentship", "presidencies", "presidency", "presi...
src/enamlnative/widgets/chronometer.py
codelv/enaml-native
237
12664721
<reponame>codelv/enaml-native """ Copyright (c) 2017, <NAME>. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on May 20, 2017 @author: jrm """ from atom.api import ( Typed, ForwardTyped, Long, Str, Enum, Bool, observe, set_default ...
nlu/pipe/utils/data_conversion_utils.py
milyiyo/nlu
480
12664725
<reponame>milyiyo/nlu<gh_stars>100-1000 """Get data into JVM for prediction and out again as Spark Dataframe""" import logging logger = logging.getLogger('nlu') import pyspark from pyspark.sql.functions import monotonically_increasing_id import numpy as np import pandas as pd from pyspark.sql.types import StringType, ...
hard-gists/3018bf3643f80798bde75c17571a38a9/snippet.py
jjhenkel/dockerizeme
1,139
12664730
<filename>hard-gists/3018bf3643f80798bde75c17571a38a9/snippet.py #!/usr/bin/python # # Simple script intended to perform Carpet Bombing against list # of provided machines using list of provided LSA Hashes (LM:NTLM). # The basic idea with Pass-The-Hash attack is to get One hash and use it # against One machine. There...
test/unit/webdriver/log_test.py
appium/python-clien
1,383
12664744
#!/usr/bin/env python # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software...
junior_class/chapter-3-Computer_Vision/code/CNN_Basis/BatchNorm2D.py
wwhio/awesome-DeepLearning
1,150
12664752
# Copyright (c) 2021 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 appli...
cook/core/rules.py
jachris/cook
130
12664761
<reponame>jachris/cook<filename>cook/core/rules.py import functools import os import traceback from . import graph, misc, system def rule(func): """Create a new rule. Calling it will be spawning a task. This function should be used as a decorator. The passed function must be a generator which follows th...
src/exabgp/reactor/api/command/announce.py
pierky/exabgp
1,560
12664774
# encoding: utf-8 """ line/watchdog.py Created by <NAME> on 2017-07-01. Copyright (c) 2009-2017 Exa Networks. All rights reserved. License: 3-clause BSD. (See the COPYRIGHT file) """ from exabgp.reactor.api.command.command import Command from exabgp.reactor.api.command.limit import match_neighbors from exabgp.reactor...
Python/compute_GT_image_metrics.py
kokizzu/OmniPhotos
129
12664779
<filename>Python/compute_GT_image_metrics.py #!/usr/bin/env python # coding: utf-8 # get_ipython().run_line_magic('pylab', 'inline') import csv from math import sqrt import imageio import numpy as np import os # import cv2 from skimage.metrics import structural_similarity def calculate_psnr(img1, img2, max_value=25...
ProcessHandler/lib/workers/base.py
rfyiamcool/ProcessHandler
101
12664806
<filename>ProcessHandler/lib/workers/base.py<gh_stars>100-1000 #coding=utf-8 import os import signal import logging from ProcessHandler.lib.utils import close_on_exec from ProcessHandler.lib.sock import create_sockets from ProcessHandler.lib.utils import _setproctitle, reopen_log_file MAXSIZE = (1 << 31) - 1 class ...
examples/onedrive/upload_file.py
rikeshtailor/Office365-REST-Python-Client
544
12664808
<filename>examples/onedrive/upload_file.py import os from examples import acquire_token_by_client_credentials, test_user_principal_name from office365.graph_client import GraphClient client = GraphClient(acquire_token_by_client_credentials) target_drive = client.users[test_user_principal_name].drive local_path = "...
text_to_code_brainfuck/main.py
DazEB2/SimplePyScripts
117
12664817
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' def text_to_code_brainfuck(text): commands_brainfuck = [] for c in text: commands_brainfuck.append('+' * ord(c) + '.') return '>'.join(commands_brainfuck) if __name__ == '__main__': text = 'Hello World!' # text = "...
veros/diagnostics/__init__.py
AkasDutta/veros
115
12664824
<filename>veros/diagnostics/__init__.py from veros.diagnostics.api import create_default_diagnostics, initialize, diagnose, output # noqa: F401
solutions/LeetCode/Python3/12.py
timxor/leetcode-journal
854
12664840
<reponame>timxor/leetcode-journal __________________________________________________________________________________________________ 56ms class Solution: def intToRoman(self, num: int) -> str: res = '' return self.toPartRom(num//1000, 'M--') + \ self.toPartRom((num % 1000)//100...
application/api/migrations/0002_auto_20190128_1515.py
cqkenuo/w12scan
864
12664888
<gh_stars>100-1000 # Generated by Django 2.1.4 on 2019-01-28 07:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='W12scan_domains', new_name='dom...
src/detext/layers/id_embed_layer.py
StarWang/detext
1,229
12664895
import tensorflow as tf from detext.layers.embedding_layer import create_embedding_layer from detext.utils.parsing_utils import InputFtrType, InternalFtrType DEFAULT_MIN_LEN = 1 DEFAULT_MAX_LEN = 100 class IdEmbedLayer(tf.keras.layers.Layer): """ ID embedding layer""" def __init__(self, num_id_fields, embe...
Polar/polar_flower.py
pyecharts/pyecharts_gallery
759
12664900
import math from pyecharts import options as opts from pyecharts.charts import Polar data = [] for i in range(361): t = i / 180 * math.pi r = math.sin(2 * t) * math.cos(2 * t) data.append([r, i]) c = ( Polar() .add_schema(angleaxis_opts=opts.AngleAxisOpts(start_angle=0, min_=0)) .add("flower",...
ichnaea/webapp/gunicorn_settings.py
mikiec84/ichnaea
348
12664904
""" Contains :ref:`Gunicorn configuration settings <gunicorn:settings>` and hook functions. """ # Disable keep-alive keepalive = 0 def post_worker_init(worker): worker.wsgi(None, None) def worker_exit(server, worker): from ichnaea.webapp.app import worker_exit worker_exit(server, worker)
src/scan.py
almartin82/bayeslite
964
12664905
# -*- coding: utf-8 -*- # Copyright (c) 2010-2016, MIT Probabilistic Computing 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 at # # http://www.apache.org/licenses/LICENS...
setup.py
danieldaeschle/swapy
834
12664959
from setuptools import setup setup( name='swapy', version='0.2.2', description='Easy and modular web development', author='<NAME>', author_email='<EMAIL>', url='https://github.com/danieldaeschle/swapy', packages=['swapy'], install_requires=['werkzeug', 'jinja2'], license='MIT' )
tools/gen_nvm_devices.py
Neradoc/circuitpython
3,010
12664964
import sys import cascadetoml import pathlib import typer from jinja2 import Template def main(input_template: pathlib.Path, output_path: pathlib.Path): flashes = cascadetoml.filter_toml(pathlib.Path("../../data/nvm.toml"), []) template = Template(input_template.read_text()) settings = {"nvms": []} ...
setup/nuke/nuke_path/menu.py
bumpybox/core
168
12664968
import avalon.api import avalon.nuke avalon.api.install(avalon.nuke)
dictionary/models/managers/entry.py
ankitgc1/django-sozluk-master
248
12665016
<filename>dictionary/models/managers/entry.py from django.db import models from django.db.models import Q class EntryManager(models.Manager): # Includes ONLY the PUBLISHED entries by NON-NOVICE authors def get_queryset(self): return super().get_queryset().exclude(Q(is_draft=True) | Q(author__is_novice...
tests/CompileTests/Python_tests/test2011_007.py
maurizioabba/rose
488
12665018
<gh_stars>100-1000 def foo(bar): bar + 1