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
setup.py
idex-biometrics/fusesoc
829
27816
<gh_stars>100-1000 # Copyright FuseSoC contributors # Licensed under the 2-Clause BSD License, see LICENSE for details. # SPDX-License-Identifier: BSD-2-Clause import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="fusesoc", ...
amadeus/shopping/availability/__init__.py
minjikarin/amadeus-python
125
27833
from ._flight_availabilities import FlightAvailabilities __all__ = ['FlightAvailabilities']
crits/comments/urls.py
dutrow/crits
738
27851
<reponame>dutrow/crits<filename>crits/comments/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^remove/(?P<obj_type>\S+)/(?P<obj_id>\S+)/$', views.remove_comment, name='crits-comments-views-remove_comment'), url(r'^(?P<method>\S+)/(?P<obj_type>\S+)/(?P<obj_id>\S+)/$', views....
tests/test_bitshares.py
silverchen0402/python-bitshares
102
27853
<filename>tests/test_bitshares.py # -*- coding: utf-8 -*- import mock import string import unittest import random from pprint import pprint from bitshares import BitShares from bitshares.account import Account from bitsharesbase.operationids import getOperationNameForId from bitshares.amount import Amount from bitshare...
kivy/tests/pyinstaller/simple_widget/project/widget.py
Galland/kivy
13,889
27864
<filename>kivy/tests/pyinstaller/simple_widget/project/widget.py<gh_stars>1000+ from kivy.uix.widget import Widget class MyWidget(Widget): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) def callback(*l): self.x = self.y self.fbind('y', callback) ...
api/guids/urls.py
gaybro8777/osf.io
628
27880
<gh_stars>100-1000 from django.conf.urls import url from api.guids import views app_name = 'osf' urlpatterns = [ url(r'^(?P<guids>\w+)/$', views.GuidDetail.as_view(), name=views.GuidDetail.view_name), ]
cogdl/models/emb/rotate.py
cenyk1230/cogdl
1,072
27893
import torch from torch import Tensor import torch.nn as nn import torch.nn.functional as F from .. import BaseModel, register_model from .knowledge_base import KGEModel @register_model("rotate") class RotatE(KGEModel): r""" Implementation of RotatE model from the paper `"RotatE: Knowledge Graph Embedding by...
Lib/fontTools/ttLib/tables/T_S_I_B_.py
twardoch/fonttools-py27
240
27902
<reponame>twardoch/fonttools-py27 from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from .T_S_I_V_ import table_T_S_I_V_ class table_T_S_I_B_(table_T_S_I_V_): pass
calico/datadog_checks/calico/check.py
davidlrosenblum/integrations-extras
158
27950
<reponame>davidlrosenblum/integrations-extras from datadog_checks.base import OpenMetricsBaseCheckV2 from .metrics import METRIC_MAP class CalicoCheck(OpenMetricsBaseCheckV2): def __init__(self, name, init_config, instances=None): super(CalicoCheck, self).__init__( name, init_con...
dojo/unittests/tools/test_cloudsploit_parser.py
art-tykh/django-DefectDojo
1,772
27956
from django.test import TestCase from dojo.models import Test from dojo.tools.cloudsploit.parser import CloudsploitParser class TestCloudsploitParser(TestCase): def test_cloudsploit_parser_with_no_vuln_has_no_findings(self): testfile = open("dojo/unittests/scans/cloudsploit/cloudsploit_zero_vul.json") ...
corehq/ex-submodules/phonelog/management/commands/migrate_device_entry.py
dimagilg/commcare-hq
471
27959
<reponame>dimagilg/commcare-hq from datetime import datetime, timedelta from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection from phonelog.models import OldDeviceReportEntry, DeviceReportEntry COLUMNS = ( "xform_id", "i", "msg", "type", "date", "se...
tensorflow/standard/reinforcement_learning/rl_on_gcp_demo/trainer/ddpg_agent.py
VanessaDo/cloudml-samples
1,552
27971
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
observations/r/unemp_dur.py
hajime9652/observations
199
27998
# -*- 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 unemp_dur(path): """Unemployment Duration Journal of Business Econ...
vissl/models/heads/__init__.py
blazejdolicki/vissl
2,512
28004
<gh_stars>1000+ # 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 pathlib import Path from typing import Callable from classy_vision.generic.registry_utils import import_all_modules FIL...
homeassistant/components/ridwell/const.py
MrDelik/core
30,023
28026
"""Constants for the Ridwell integration.""" import logging DOMAIN = "ridwell" LOGGER = logging.getLogger(__package__) DATA_ACCOUNT = "account" DATA_COORDINATOR = "coordinator" SENSOR_TYPE_NEXT_PICKUP = "next_pickup"
models/__init__.py
dudtjakdl/OpenNMT-Korean-To-English
1,491
28036
from .EncoderRNN import EncoderRNN from .DecoderRNN import DecoderRNN from .TopKDecoder import TopKDecoder from .seq2seq import Seq2seq
panel/layout/spacer.py
sthagen/holoviz-panel
601
28037
""" Spacer components to add horizontal or vertical space to a layout. """ import param from bokeh.models import Div as BkDiv, Spacer as BkSpacer from ..reactive import Reactive class Spacer(Reactive): """ The `Spacer` layout is a very versatile component which makes it easy to put fixed or responsive ...
reddit2telegram/channels/r_gentlemanboners/app.py
mainyordle/reddit2telegram
187
28038
<gh_stars>100-1000 #encoding:utf-8 from utils import weighted_random_subreddit subreddit = weighted_random_subreddit({ 'BeautifulFemales': 0.25, 'cutegirlgifs': 0.25, 'gentlemanboners': 0.25, 'gentlemanbonersgifs': 0.25 }) t_channel = '@r_gentlemanboners' def send_post(submission, r2t): return ...
pytorch_ares/third_party/free_adv_train/multi_restart_pgd_attack.py
thu-ml/realsafe
107
28064
<reponame>thu-ml/realsafe """ Implementation of attack methods. Running this file as a program will evaluate the model and get the validation accuracy and then apply the attack to the model specified by the config file and store the examples in an .npy file. """ from __future__ import absolute_import from __futu...
ch17/yunqiCrawl/yunqiCrawl/scrapy_redis/connection.py
AaronZhengkk/SpiderBook
990
28069
<gh_stars>100-1000 import redis # Default values. REDIS_URL = None REDIS_HOST = 'localhost' REDIS_PORT = 6379 FILTER_URL = None FILTER_HOST = 'localhost' FILTER_PORT = 6379 FILTER_DB = 0 def from_settings(settings): url = settings.get('REDIS_URL', REDIS_URL) host = settings.get('REDIS_HOST', REDIS_HOST) ...
modules/tools/open_space_visualization/open_space_roi_visualizer.py
jzjonah/apollo
22,688
28115
#!/usr/bin/env python3 ############################################################################### # Copyright 2018 The Apollo 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...
gfauto/gfauto/test_util.py
KishkinJ10/graphicsfuzz
519
28130
# -*- coding: utf-8 -*- # Copyright 2019 The GraphicsFuzz 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 obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
core/management_utils.py
crydotsnake/djangogirls
446
28144
import djclick as click from django.conf import settings from django.utils.translation import gettext_lazy as _ from .forms import AddOrganizerForm from .slack_client import slack # "Get organizers info" functions used in 'new_event' and 'copy_event' management commands. def get_main_organizer(): """ We're ...
tools/Vitis-AI-Quantizer/vai_q_tensorflow2.x/setup.py
hito0512/Vitis-AI
848
28149
# Copyright 2019 The TensorFlow 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 applica...
src/django_perf_rec/settings.py
adamchainz/django-perf-rec
147
28167
import sys from typing import Any from django.conf import settings if sys.version_info >= (3, 8): from typing import Literal ModeType = Literal["once", "none", "all"] else: ModeType = str class Settings: defaults = {"HIDE_COLUMNS": True, "MODE": "once"} def get_setting(self, key: str) -> Any:...
test/test_igp_shortcuts.py
tim-fiola/network_traffic_modeler_py3
102
28206
<filename>test/test_igp_shortcuts.py import unittest from pyNTM import FlexModel from pyNTM import ModelException from pyNTM import PerformanceModel class TestIGPShortcuts(unittest.TestCase): def test_traffic_on_shortcut_lsps(self): """ Verify Interface and LSP traffic when IGP shortcuts enabled ...
src/pipelines/epidemiology/sd_humdata.py
chrismayemba/covid-19-open-data
430
28246
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
lexical-parse-float/etc/limits.py
sjurajpuchky/rust-lexical
249
28248
<gh_stars>100-1000 #!/usr/bin/env python3 """ Generate the numeric limits for a given radix. This is used for the fast-path algorithms, to calculate the maximum number of digits or exponent bits that can be exactly represented as a native value. """ import math def is_pow2(value): '''Calculate if a value is a p...
prototyper/build/stages/wsgi_app.py
vitalik/django-prototyper
114
28261
<filename>prototyper/build/stages/wsgi_app.py from ..base import BuildStage from pathlib import Path TPL = """\"\"\" WSGI config for {0} project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deploymen...
quetz/migrations/versions/30241b33d849_add_task_pending_state.py
maresb/quetz
108
28300
<gh_stars>100-1000 """add task pending state Revision ID: 30241b33d849 Revises: cd<PASSWORD> Create Date: 2021-01-07 14:39:43.251123 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = 'cd404ed93cc0' branch_labels = None depends_on = None d...
basic_auth/handler.py
andrei-shabanski/s3pypi
249
28323
import base64 import hashlib import json import logging from dataclasses import dataclass import boto3 log = logging.getLogger() region = "us-east-1" def handle(event: dict, context): request = event["Records"][0]["cf"]["request"] try: authenticate(request["headers"]) except Exception as e: ...
examples/py/async-generator-multiple-tickers.py
diwenshi61/ccxt
24,910
28343
<gh_stars>1000+ # -*- coding: utf-8 -*- import asyncio import ccxt.async_support as ccxt async def poll(tickers): i = 0 kraken = ccxt.kraken() while True: symbol = tickers[i % len(tickers)] yield (symbol, await kraken.fetch_ticker(symbol)) i += 1 await asyncio.sleep(kraken...
assets/src/ba_data/python/bastd/mapdata/rampage.py
Benefit-Zebra/ballistica
317
28357
# Released under the MIT License. See LICENSE for details. # # This file was automatically generated from "rampage.ma" # pylint: disable=all points = {} # noinspection PyDictCreation boxes = {} boxes['area_of_interest_bounds'] = (0.3544110667, 5.616383286, -4.066055072) + (0.0, 0.0,...
dockerpty/__init__.py
tedivm/dockerpty
129
28374
# dockerpty. # # Copyright 2014 <NAME> <<EMAIL>> # # 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 ag...
database/models.py
zdresearch/Nettacker
884
28376
<reponame>zdresearch/Nettacker #!/usr/bin/env python3 # -*- coding: utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import (Column, Integer, Text, DateTime) Base = declarative_base() class Report(Base): """...
CodeIA/venv/Lib/site-packages/absl/testing/_parameterized_async.py
Finasty-lab/IA-Python
38,667
28381
<reponame>Finasty-lab/IA-Python # Lint as: python3 # Copyright 2020 The Abseil 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 # #...
services/core/Ambient/ambient/agent.py
gnmerritt/volttron
406
28414
<gh_stars>100-1000 # -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # # Copyright (c) 2017, Battelle Memorial Institute # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are me...
src/torchphysics/utils/data/__init__.py
uwe-iben/torchphysics
203
28416
from .dataloader import PointsDataset, PointsDataLoader
rls/algorithms/single/ddqn.py
StepNeverStop/RLs
371
28421
#!/usr/bin/env python3 # encoding: utf-8 import torch.nn.functional as F from rls.algorithms.single.dqn import DQN from rls.common.decorator import iton from rls.utils.torch_utils import n_step_return class DDQN(DQN): """ Double DQN, https://arxiv.org/abs/1509.06461 Double DQN + LSTM, https...
hyperglass/execution/drivers/agent.py
blkmajik/hyperglass
298
28443
"""Execute validated & constructed query on device. Accepts input from front end application, validates the input and returns errors if input is invalid. Passes validated parameters to construct.py, which is used to build & run the Netmiko connections or hyperglass-frr API calls, returns the output back to the front e...
examples/hover_example.py
kail85/mpldatacursor
165
28456
""" Demonstrates the hover functionality of mpldatacursor as well as point labels and a custom formatting function. Notice that overlapping points have both labels displayed. """ import string import matplotlib.pyplot as plt import numpy as np from mpldatacursor import datacursor np.random.seed(1977) x, y = np.random....
tapas/utils/attention_utils_test.py
apurvak/tapas
816
28458
<filename>tapas/utils/attention_utils_test.py # coding=utf-8 # Copyright 2019 The Google AI Language Team 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.or...
VA/main/utils/cluster.py
YuJaceKim/Activity-Recognition-with-Combination-of-Deeply-Learned-Visual-Attention-and-Pose-Estimation
343
28464
import numpy as np # import matplotlib.pyplot as plt from scipy.cluster.vq import kmeans # def plothist(x): # vmin = x.min()-1 # vmax = x.max()+1 # bins = np.arange(vmin, vmax, (vmax - vmin)/50) # plt.hist(x, bins=bins) # plt.show() # def scatterpred(pred): # plt.scatter(pred[:,0], pred[:,1]) ...
moto/logs/metric_filters.py
gtourkas/moto
5,460
28490
def find_metric_transformation_by_name(metric_transformations, metric_name): for metric in metric_transformations: if metric["metricName"] == metric_name: return metric def find_metric_transformation_by_namespace(metric_transformations, metric_namespace): for metric in metric_transformatio...
tests/test_win_app.py
koyoki/Airtest
6,140
28502
# encoding=utf-8 from airtest.core.win import Windows import unittest import numpy import time from testconf import try_remove SNAPSHOT = "win_snapshot.png" class TestWin(unittest.TestCase): @classmethod def setUpClass(cls): w = Windows() w.start_app("calc") time.sleep(1) cl...
src/tools/nuscenes-devkit/prediction/tests/test_backbone.py
jie311/TraDeS
475
28511
import unittest import torch from torchvision.models.resnet import BasicBlock, Bottleneck from nuscenes.prediction.models.backbone import ResNetBackbone, MobileNetBackbone class TestBackBones(unittest.TestCase): def count_layers(self, model): if isinstance(model[4][0], BasicBlock): n_convs ...
test/pytest/service-bluetooth/test_pairing_hmi_perspective.py
bitigchi/MuditaOS
369
28519
# Copyright (c) 2017-2021, <NAME>. All rights reserved. # For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md import time import pytest from harness import log from harness.dom_parser_utils import * from harness.interface.defs import key_codes from bt_fixtures import * @pytest.mark.rt1051 @pytest.mark.us...
test/test_mean_average_precision.py
JuanchoWang/xcenternet
171
28531
import numpy as np import tensorflow as tf import unittest from xcenternet.model.evaluation.overlap import compute_overlap from xcenternet.model.evaluation.mean_average_precision import MAP class TestMeanAveragePrecision(unittest.TestCase): def setUp(self): self.map_bboxes = np.array( [ ...
tests/integration/test_user_defined_object_persistence/test.py
pdv-ru/ClickHouse
15,577
28535
<filename>tests/integration/test_user_defined_object_persistence/test.py import pytest from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) instance = cluster.add_instance('instance', stay_alive=True) @pytest.fixture(scope="module", autouse=True) def started_cluster(): try: ...
underworld/conditions/_conditions.py
longgangfan/underworld2
116
28556
<filename>underworld/conditions/_conditions.py ##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~## ## ## ## This file forms part of the Underworld geophysics modelling application. ## ## ...
scripts/geodata/phrases/extraction.py
Fillr/libpostal
3,489
28562
<reponame>Fillr/libpostal<gh_stars>1000+ import csv import six from collections import defaultdict, Counter from itertools import izip, islice from geodata.text.tokenize import tokenize, token_types from geodata.encoding import safe_encode class FrequentPhraseExtractor(object): ''' Extract common multi-word...
test/hummingbot/connector/exchange/bitfinex/test_bitfinex_api_order_book_data_source.py
BGTCapital/hummingbot
3,027
28566
<filename>test/hummingbot/connector/exchange/bitfinex/test_bitfinex_api_order_book_data_source.py import asyncio import json from unittest import TestCase from aioresponses import aioresponses import hummingbot.connector.exchange.bitfinex.bitfinex_utils as utils from hummingbot.connector.exchange.bitfinex import BITF...
components/gpio_control/GPIODevices/simple_button.py
steffakasid/RPi-Jukebox-RFID
1,010
28580
import time from signal import pause import logging import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) logger = logging.getLogger(__name__) map_edge_parse = {'falling':GPIO.FALLING, 'rising':GPIO.RISING, 'both':GPIO.BOTH} map_pull_parse = {'pull_up':GPIO.PUD_UP, 'pull_down':GPIO.PUD_DOWN, 'pull_off':GPIO.PUD_OFF} map_edg...
services/ui_backend_service/tests/integration_tests/tasks_test.py
runsascoded/metaflow-service
103
28584
import pytest import time from .utils import ( init_app, init_db, clean_db, add_flow, add_run, add_step, add_task, add_artifact, _test_list_resources, _test_single_resource, add_metadata, get_heartbeat_ts ) pytestmark = [pytest.mark.integration_tests] # Fixtures begin @pytest.fixture def cli(loop, aiohtt...
tests/unit/test_parameters/test_geometric_parameters.py
manjunathnilugal/PyBaMM
330
28594
<reponame>manjunathnilugal/PyBaMM # # Tests for the standard parameters # import pybamm import unittest class TestGeometricParameters(unittest.TestCase): def test_macroscale_parameters(self): geo = pybamm.geometric_parameters L_n = geo.L_n L_s = geo.L_s L_p = geo.L_p L_x =...
L1Trigger/DTTrigger/python/dtTriggerPrimitiveDigis_cfi.py
ckamtsikis/cmssw
852
28654
<filename>L1Trigger/DTTrigger/python/dtTriggerPrimitiveDigis_cfi.py import FWCore.ParameterSet.Config as cms from L1TriggerConfig.DTTPGConfigProducers.L1DTTPGConfigFromDB_cff import * dtTriggerPrimitiveDigis = cms.EDProducer("DTTrigProd", debug = cms.untracked.bool(False), # DT digis input tag digiTag = c...
pythran/tests/cases/diffusion_pure_python.py
davidbrochart/pythran
1,647
28665
# Reference: http://continuum.io/blog/the-python-and-the-complied-python #pythran export diffusePurePython(float [][], float [][], int) #runas import numpy as np;lx,ly=(2**7,2**7);u=np.zeros([lx,ly],dtype=np.double);u[int(lx/2),int(ly/2)]=1000.0;tempU=np.zeros([lx,ly],dtype=np.double);diffusePurePython(u,tempU,500) #be...
torrent_client/algorithms/uploader.py
x0x/polygon
141
28675
<filename>torrent_client/algorithms/uploader.py<gh_stars>100-1000 import asyncio import itertools import logging import random import time from typing import List, Iterable, cast from torrent_client.algorithms.peer_manager import PeerManager from torrent_client.models import Peer, TorrentInfo from torrent_client.utils...
pylayers/antprop/tests/test_subarray.py
usmanwardag/pylayers
143
28688
from pylayers.antprop.aarray import * import matplotlib.pyplot as plt import pdb print('--------------') print('antprop/test_subarray.py') print('--------------') fcGHz = 60 lamda = 0.3/fcGHz N1 = [ 4,4,1] N2 = [ 2,2,1] dm1 = [lamda/2.,lamda/2.,0] dm2 = [3*lamda,3*lamda,0] A1 = AntArray(fGHz=np.array([fcGHz]),N=N...
pyorient/ogm/commands.py
spy7/pyorient
142
28727
<reponame>spy7/pyorient from ..utils import to_str class VertexCommand(object): def __init__(self, command_text): self.command_text = command_text def __str__(self): return to_str(self.__unicode__()) def __unicode__(self): return u'{}'.format(self.command_text) class CreateEdgeCo...
g2pk/special.py
elbum/g2pK
136
28746
# -*- coding: utf-8 -*- ''' Special rule for processing Hangul https://github.com/kyubyong/g2pK ''' import re from g2pk.utils import gloss, get_rule_id2text rule_id2text = get_rule_id2text() ############################ vowels ############################ def jyeo(inp, descriptive=False, verbose=False): rule =...
ivi/tektronix/__init__.py
sacherjj/python-ivi
161
28749
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights ...
scripts/logfetch/search.py
madhuri7112/Singularity
692
28790
import os import re import fnmatch from logfetch_base import log, is_in_date_range from termcolor import colored def find_cached_logs(args): matching_logs = [] log_fn_match = get_matcher(args) for filename in os.listdir(args.dest): if fnmatch.fnmatch(filename, log_fn_match) and in_date_range(args, ...
Codes/Liam/001_two_sum.py
liuxiaohui1221/algorithm
256
28809
<reponame>liuxiaohui1221/algorithm # 执行用时 : 348 ms # 内存消耗 : 13 MB # 方案:哈希表 class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # 创建哈希表{value:idx} record = {} # 遍数组 for idx...
tests/test_socfaker_application.py
priamai/soc-faker
122
28825
def test_socfaker_application_status(socfaker_fixture): assert socfaker_fixture.application.status in ['Active', 'Inactive', 'Legacy'] def test_socfaker_application_account_status(socfaker_fixture): assert socfaker_fixture.application.account_status in ['Enabled', 'Disabled'] def test_socfaker_name(socfaker_f...
questions/max-number-of-k-sum-pairs/Solution.py
marcus-aurelianus/leetcode-solutions
141
28828
""" You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array.   Example 1: Input: nums = [1,2,3,4], k = 5 Output: 2 Explanation: Starting with ...
csv2ofx/mappings/starling.py
mibanescu/csv2ofx
153
28836
<reponame>mibanescu/csv2ofx from __future__ import ( absolute_import, division, print_function, unicode_literals) from operator import itemgetter def fixdate(ds): dmy = ds.split('/') # BUG (!?): don't understand but stolen from ubs-ch-fr.py return '.'.join((dmy[1], dmy[0], dmy[2])) mapping = { '...
Source/Tools/BindTool/writer.py
ssinai1/rbfx
441
28841
<filename>Source/Tools/BindTool/writer.py<gh_stars>100-1000 class InterfaceWriter(object): def __init__(self, output_path): self._output_path_template = output_path + '/_{key}_{subsystem}.i' self._fp = { 'pre': {}, 'post': {}, } def _write(self, key, subsystem, ...
training/scripts/trainer/src/convert/convert.py
TommyTeaVee/training
2,442
28876
<reponame>TommyTeaVee/training<filename>training/scripts/trainer/src/convert/convert.py<gh_stars>1000+ import os import argparse import numpy as np import tensorflow as tf from tensorflow.python.platform import gfile from tensorflow.python.framework import dtypes from tensorflow.python.tools import strip_unused_lib ...
plugins/modules/oci_resource_manager_template.py
slmjy/oci-ansible-collection
108
28881
<reponame>slmjy/oci-ansible-collection<gh_stars>100-1000 #!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/g...
mayan/apps/documents/tests/test_links.py
bonitobonita24/Mayan-EDMS
343
28898
from django.urls import reverse from ..links.document_file_links import ( link_document_file_delete, link_document_file_download_quick ) from ..links.favorite_links import ( link_document_favorites_add, link_document_favorites_remove ) from ..links.trashed_document_links import link_document_restore from ..mod...
insights/parsers/ceph_insights.py
lhuett/insights-core
121
28901
<reponame>lhuett/insights-core<gh_stars>100-1000 """ ceph_insights - command ``ceph insights`` ========================================= """ import json import re from .. import CommandParser, parser from insights.specs import Specs @parser(Specs.ceph_insights) class CephInsights(CommandParser): """ Parse the...
test/__init__.py
shikajiro/picosdk-python-wrappers
114
28921
# # Copyright (C) 2018 Pico Technology Ltd. See LICENSE file for terms. #
testing/MLDB-1104-input-data-spec.py
kstepanmpmg/mldb
665
28926
# # MLDB-1104-input-data-spec.py # mldb.ai inc, 2015 # This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. # import unittest import datetime import random from mldb import mldb, ResponseException class InputDataSpecTest(unittest.TestCase): @classmethod def setUpClass(cls): cls...
tests/tensors/similarity_functions/dot_product_test.py
richarajpal/deep_qa
459
28934
<reponame>richarajpal/deep_qa<filename>tests/tensors/similarity_functions/dot_product_test.py<gh_stars>100-1000 # pylint: disable=no-self-use,invalid-name import numpy from numpy.testing import assert_almost_equal import keras.backend as K from deep_qa.tensors.similarity_functions.dot_product import DotProduct class...
zipline/pipeline/common.py
lv-cha/zipline-chinese
606
28998
<reponame>lv-cha/zipline-chinese<filename>zipline/pipeline/common.py """ Common constants for Pipeline. """ AD_FIELD_NAME = 'asof_date' ANNOUNCEMENT_FIELD_NAME = 'announcement_date' CASH_FIELD_NAME = 'cash' CASH_AMOUNT_FIELD_NAME = 'cash_amount' BUYBACK_ANNOUNCEMENT_FIELD_NAME = 'buyback_date' DAYS_SINCE_PREV = 'days_s...
docs/ASH/notebooks/object-segmentation-on-azure-stack/score.py
RichardZhaoW/AML-Kubernetes
176
29016
import os import json import time import torch # Called when the deployed service starts def init(): global model global device # Get the path where the deployed model can be found. model_filename = 'obj_segmentation.pkl' model_path = os.path.join(os.environ['AZUREML_MODEL_DIR'], model_filename) ...
pox/info/debug_deadlock.py
korrigans84/pox_network
416
29019
<reponame>korrigans84/pox_network # Copyright 2012 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
wadi.py
sensepost/wadi
137
29090
import sys import os from multiprocessing import Process, Queue, Manager from threading import Timer from wadi_harness import Harness from wadi_debug_win import Debugger import time import hashlib def test(msg): while True: print 'Process 2:' + msg #print msg def test2(): print 'Process 1' tim...
apps/flow/run.py
rainydaygit/testtcloudserver
349
29104
from apps.flow.settings import config if config.SERVER_ENV != 'dev': from gevent import monkey monkey.patch_all() else: pass from apps.flow.views.deploy import deploy from apps.flow.views.flow import flow from library.api.tFlask import tflask def create_app(): app = tflask(config) register_blue...
etl/parsers/etw/Microsoft_Windows_SecurityMitigationsBroker.py
IMULMUL/etl-parser
104
29133
<filename>etl/parsers/etw/Microsoft_Windows_SecurityMitigationsBroker.py # -*- coding: utf-8 -*- """ Microsoft-Windows-SecurityMitigationsBroker GUID : ea8cd8a5-78ff-4418-b292-aadc6a7181df """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct fro...
android/replace_apk_resource_pro/replace_source.py
roceys/tools_python
130
29145
<filename>android/replace_apk_resource_pro/replace_source.py #!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: xag @license: Apache Licence @contact: <EMAIL> @site: http://www.xingag.top @software: PyCharm @file: replace_source.py @time: 4/25/19 10:46 @description:替换apk的资源文件 """ from f...
train/solver.py
nhonth/DeLF-pytorch
315
29156
<reponame>nhonth/DeLF-pytorch #!/usr/bin/env python # -*- coding: utf-8 -*- ''' PyTorch Implementation of training DeLF feature. Solver for step 1 (finetune local descriptor) nashory, 2018.04 ''' import os, sys, time import shutil import torch import torch.nn as nn import torch.optim as optim from torch.autograd impo...
src/oci/autoscaling/models/cron_execution_schedule.py
Manny27nyc/oci-python-sdk
249
29200
<gh_stars>100-1000 # coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LIC...
thirdparty/his_evaluators/his_evaluators/utils/video.py
tj-eey/impersonator
1,717
29218
# -*- coding: utf-8 -*- # @Time : 2019-08-02 18:31 # @Author : <NAME> # @Email : <EMAIL> import os import cv2 import glob import shutil from multiprocessing import Pool from concurrent.futures import ProcessPoolExecutor from functools import partial from tqdm import tqdm import numpy as np import subprocess de...
parsifal/apps/reviews/migrations/0020_searchresult.py
ShivamPytho/parsifal
342
29244
<reponame>ShivamPytho/parsifal<filename>parsifal/apps/reviews/migrations/0020_searchresult.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import parsifal.apps.reviews.models import django.db.models.deletion class Migration(migrations.Migration): depen...
mastiff/plugins/analysis/EXE/EXE-singlestring.py
tt1379/mastiff
164
29245
#!/usr/bin/env python """ Copyright 2012-2013 The MASTIFF Project, All Rights Reserved. This software, having been partly or wholly developed and/or sponsored by KoreLogic, Inc., is hereby released under the terms and conditions set forth in the project's "README.LICENSE" file. For a list of all contributors...
tests/ext/test_ext_plugin.py
tomekr/cement
826
29252
<reponame>tomekr/cement from cement.ext.ext_plugin import CementPluginHandler # module tests class TestCementPluginHandler(object): def test_subclassing(self): class MyPluginHandler(CementPluginHandler): class Meta: label = 'my_plugin_handler' h = MyPluginHandler() ...
opensanctions/crawlers/eu_fsf.py
quantumchips/opensanctions
102
29257
from prefixdate import parse_parts from opensanctions import helpers as h from opensanctions.util import remove_namespace def parse_address(context, el): country = el.get("countryDescription") if country == "UNKNOWN": country = None # context.log.info("Addrr", el=el) return h.make_address( ...
tools/Sikuli/DoReplace.sikuli/DoReplace.py
marmyshev/vanessa-automation
296
29288
click(Pattern("Bameumbrace.png").similar(0.80)) sleep(1) click("3abnb.png") exit(0)
openfda/deploy/tests/adae/test_endpoint.py
hobochili/openfda
388
29300
<filename>openfda/deploy/tests/adae/test_endpoint.py # coding=utf-8 import inspect import sys from openfda.tests.api_test_helpers import * def test_nullified_records(): NULLIFIED = ['USA-FDACVM-2018-US-045311', 'USA-FDACVM-2018-US-048571', 'USA-FDACVM-2018-US-046672', 'USA-FDACVM-2017-US-070108', 'U...
Chapter08/chapter8_sflowtool_1.py
stavsta/Mastering-Python-Networking-Second-Edition
107
29309
#!/usr/bin/env python3 import sys, re for line in iter(sys.stdin.readline, ''): if re.search('agent ', line): print(line.strip())
pkgs/nbconvert-4.1.0-py27_0/lib/python2.7/site-packages/nbconvert/filters/markdown.py
wangyum/anaconda
652
29343
<gh_stars>100-1000 """Markdown filters This file contains a collection of utility filters for dealing with markdown within Jinja templates. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import print_function import os import subprocess from ...
datasets/__init__.py
Masterchef365/pvcnn
477
29365
from datasets.s3dis import S3DIS
preprocess/conll_to_factors.py
thilakshiK/wmt16-scripts
132
29398
<reponame>thilakshiK/wmt16-scripts<filename>preprocess/conll_to_factors.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: <NAME> # Distributed under MIT license # take conll file, and bpe-segmented text, and produce factored output import sys import re from collections import namedtuple Word = namedtuple(...
Interview Preparation Kit/01 - Warm-up Challenges/04 - Repeated String.py
srgeyK87/Hacker-Rank-30-days-challlenge
275
29420
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/repeated-string/problem # Difficulty: Easy # Max Score: 20 # Language: Python # ======================== # Solution # ======================== import os # Complete the repeatedStrin...
docs/sample_code/debugging_info/src/dataset.py
mindspore-ai/docs
288
29434
# 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...
.setup/bin/input_forum_data.py
zeez2030/Submitty
411
29445
#!/usr/bin/env python3 import os import sys import json from datetime import datetime from submitty_utils import dateutils def generatePossibleDatabases(): current = dateutils.get_current_semester() pre = 'submitty_' + current + '_' path = "/var/local/submitty/courses/" + current return [pre + name for name in ...
webspider/utils/log.py
chem2099/webspider
256
29461
# coding: utf-8 import os import logging.config from webspider import setting LOG_FILE_PATH = os.path.join(setting.BASE_DIR, 'log', 'spider_log.txt') LOGGING_CONFIG = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'default': { 'format': '%(asctime)s- %(module)s:%(l...
apps/show_plots.py
avdmitry/convnet
293
29507
import glob import matplotlib.pyplot as plt import numpy as np import sys plt.ion() data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_train.log')) valid_data_files = list(glob.glob(sys.argv[1]+'/mnist_net_*_valid.log')) for fname in data_files: data = np.loadtxt(fname).reshape(-1, 3) name = fname.split('/')[...