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
tests/modules/vim.py
MrFishFinger/powerline
11,435
82700
# vim:fileencoding=utf-8:noet _log = [] vars = {} vvars = {'version': 703} _tabpage = 0 _mode = 'n' _buf_purge_events = set() options = { 'paste': 0, 'ambiwidth': 'single', 'columns': 80, 'encoding': 'utf-8', } _last_bufnr = 0 _highlights = {} from collections import defaultdict as _defaultdict _environ = _defaultd...
database/msg/load.py
atztogo/spglib
131
82702
<reponame>atztogo/spglib from pathlib import Path import csv from ruamel.yaml import YAML def get_msg_numbers(): all_datum = [] with open(Path(__file__).resolve().parent / "msg_numbers.csv", 'r') as f: reader = csv.reader(f, delimiter=',') next(reader) # skip header for row in reader...
sys/debug/struct.py
pj1031999/mimiker
185
82710
<filename>sys/debug/struct.py import gdb import re from .utils import cast, relpath def cstr(val): try: return val.string() except gdb.MemoryError: return '[bad-ptr 0x%x]' % val.address def enum(v): return v.type.target().fields()[int(v)].name class ProgramCounter(): def __init__(s...
scale/queue/migrations/0006_auto_20160316_1625.py
kaydoh/scale
121
82736
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('queue', '0005_queue_node_required'), ] operations = [ migrations.RemoveField( model_name='queuedepthbyjobtype', ...
src/nvis/data.py
29ayush/simple_dqn
767
82756
<filename>src/nvis/data.py # ---------------------------------------------------------------------------- # Copyright 2015 Nervana Systems 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 #...
tinyboot.py
kragen/stoneknifeforth
322
82762
<gh_stars>100-1000 #!/usr/bin/python # -*- coding: utf-8 -*- """Tiny bootstrapping interpreter for the first bootstrap stage. Implements an extremely minimal Forth-like language, used to write tinyboot1.tbf1. The theory is that first we ‘compile’ the program by reading through it to find compile-time definitions and ...
tools/can_async_example.py
deafloo/ODrive
1,068
82780
import can bus1 = can.interface.Bus('can0', bustype='virtual') bus2 = can.interface.Bus('can0', bustype='virtual') msg1 = can.Message(arbitration_id=0xabcde, data=[1,2,3]) bus1.send(msg1) msg2 = bus2.recv() print(hex(msg1.arbitration_id)) print(hex(msg2.arbitration_id)) assert msg1.arbitration_id == msg2.arbitration...
tests/test_functions/http_flask_render_template/main.py
Daniel-Sanche/functions-framework-python
479
82781
<gh_stars>100-1000 # 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 agr...
File_organiser/clean_folder.py
elawang9/Scripting-and-Web-Scraping
119
82789
<filename>File_organiser/clean_folder.py<gh_stars>100-1000 from colorama import Fore import os all_paths=[] dir_name = input( 'Enter the name of directory you want to clear: ') extension = set() def source_path(dir_name): for root in os.walk("/home"): if dir_name == root[0].split('/')[-1]: all_paths.append(ro...
exercises/ja/solution_02_10_01.py
Jette16/spacy-course
2,085
82801
<reponame>Jette16/spacy-course<filename>exercises/ja/solution_02_10_01.py import spacy nlp = spacy.load("ja_core_news_md") doc1 = nlp("暖かい夏の日です") doc2 = nlp("外は晴れています") # doc1とdoc2の類似度を取得 similarity = doc1.similarity(doc2) print(similarity)
quantecon/tests/test_inequality.py
Smit-create/QuantEcon.py
1,462
82803
""" Tests for inequality.py """ import numpy as np from numpy.testing import assert_allclose, assert_raises from scipy.stats import linregress from quantecon import lorenz_curve, gini_coefficient, \ shorrocks_index, rank_size def test_lorenz_curve(): """ Tests `lorenz` function, which calculates the l...
tools/Sikuli/TypeHome.sikuli/DoCtrlF4.py
marmyshev/vanessa-automation
296
82827
<filename>tools/Sikuli/TypeHome.sikuli/DoCtrlF4.py type(Key.F4, KeyModifier.CTRL) sleep(1) exit(0)
macgraph/input/text_util.py
Octavian-ai/mac-graph
116
82836
<filename>macgraph/input/text_util.py from collections import Counter import tensorflow as tf import numpy as np from typing import List, Set import re import string from tqdm import tqdm import logging logger = logging.getLogger(__name__) from .util import read_gqa # ---------------------------------------------...
stravalib/tests/functional/test_client_write.py
jsamoocha/stravalib
599
82854
<filename>stravalib/tests/functional/test_client_write.py from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from io import BytesIO from stravalib import model, exc, attributes, unithelper as uh from stravalib.client import Client from stravalib.tests.functional import Fu...
prml/nn/normalization/batch_normalization.py
jinmang2/PRML
11,017
82871
<filename>prml/nn/normalization/batch_normalization.py import numpy as np from prml.nn.array.ones import ones from prml.nn.array.zeros import zeros from prml.nn.config import config from prml.nn.function import Function from prml.nn.network import Network class BatchNormalizationFunction(Function): def _forward(...
utils/regression/applications/fruntoctrl/FrunToCtrlExecutor.py
noahsherrill/force-riscv
111
82873
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PR...
app/migrations/0002_experiment_process_processstatus.py
tungpatrick/AutoOut
101
82882
# Generated by Django 2.2.1 on 2019-07-19 10:12 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.CreateModel( na...
agate/aggregations/deciles.py
andriyor/agate
663
82884
#!/usr/bin/env python from agate.aggregations.base import Aggregation from agate.aggregations.has_nulls import HasNulls from agate.aggregations.percentiles import Percentiles from agate.data_types import Number from agate.exceptions import DataTypeError from agate.utils import Quantiles from agate.warns import warn_nu...
iPERCore/tools/human_pose3d_estimators/spin/runner.py
JSssssss/iPERCore
2,223
82937
import torch import numpy as np from tqdm import tqdm from typing import Union, List, Tuple, Any, Dict from easydict import EasyDict from .dataset import preprocess, InferenceDataset, InferenceDatasetWithKeypoints from .network import build_spin from .. import BasePose3dRunner, BasePose3dRefiner, ACTIONS from iPERCor...
tests/bugs/test-200907231924.py
eLBati/pyxb
123
82959
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import pyxb.binding.generate import pyxb.binding.datatypes as xs import pyxb.binding.basis import pyxb.utils.domutils import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xm...
scripts/tests/ai2_internal/resume_daemon_test.py
MSLars/allennlp
11,433
82969
import pytest import sqlite3 from unittest.mock import call, Mock from allennlp.common.testing import AllenNlpTestCase from scripts.ai2_internal.resume_daemon import ( BeakerStatus, create_table, handler, logger, resume, start_autoresume, ) # Don't spam the log in tests. logger.removeHandler(...
networks/graph_cmr/models/geometric_layers.py
solomon-ma/PaMIR
374
82970
""" Useful geometric operations, e.g. Orthographic projection and a differentiable Rodrigues formula Parts of the code are taken from https://github.com/MandyMo/pytorch_HMR """ import torch def rodrigues(theta): """Convert axis-angle representation to rotation matrix. Args: theta: size = [B, 3] Ret...
zmq/cl-zmq.py
bit0fun/plugins
173
83024
<reponame>bit0fun/plugins<filename>zmq/cl-zmq.py #!/usr/bin/env python3 # Copyright (c) 2019 lightningd # Distributed under the BSD 3-Clause License, see the accompanying file LICENSE ############################################################################### # ZeroMQ publishing plugin for lightningd # # Using Twi...
convert_to_knowledge_repo.py
certara-ShengnanHuang/machine-learning
2,104
83032
""" Examples -------- Convert existing jupyter notebook to an airbnb knowledge repo format - python convert_to_knowledge_repo.py --ml_repo . --knowledge_repo knowledge-repo Deploying the webapp - knowledge_repo --repo knowledge-repo deploy """ import os import re import json import subprocess from dateutil import par...
neuralnets/ELMoWordEmbeddings.py
nirvana0311/Elmo_experiment
390
83047
<reponame>nirvana0311/Elmo_experiment import urllib.request as urllib2 import urllib.parse as urlparse from urllib.request import urlretrieve import logging import numpy as np from allennlp.commands.elmo import ElmoEmbedder, DEFAULT_OPTIONS_FILE, DEFAULT_WEIGHT_FILE import pickle as pkl import os import gzip import sys...
tdda/rexpy/testseq.py
jjlee42/tdda
232
83057
from __future__ import print_function from tdda.rexpy import extract from tdda.rexpy.seq import common_string_sequence from tdda.rexpy.relib import re x = extract(['Roger', 'Coger', 'Doger'], tag=True, as_object=True) print(x) patternToExamples = x.pattern_matches() sequences = [] for j, (pattern, examples) in enum...
tests/test_query.py
adamchainz/django-postgres-extra
529
83060
from django.db import models from django.db.models import Case, F, Q, Value, When from psqlextra.expressions import HStoreRef from psqlextra.fields import HStoreField from .fake_model import get_fake_model def test_query_annotate_hstore_key_ref(): """Tests whether annotating using a :see:HStoreRef expression wo...
examples/issues/issue372.py
tgolsson/appJar
666
83100
import sys sys.path.append("../../") from appJar import gui def showPositions(): for widg in app.getContainer().grid_slaves(): row, column = widg.grid_info()["row"], widg.grid_info()["column"] print(widg, row, column) with gui("Grid Demo", "300x300", sticky="news", expand="both") as app: for ...
qcodes/dataset/descriptions/versioning/converters.py
riju-pal/QCoDeS_riju
223
83103
""" This module contains functions which implement conversion between different (neighbouring) versions of RunDescriber. """ from typing import Dict, List from ..dependencies import InterDependencies_ from ..param_spec import ParamSpec, ParamSpecBase from .rundescribertypes import (RunDescriberV0Dict, RunDescriberV...
utest/test/api/my_lib_args.py
hugovk/SeleniumLibrary
792
83108
<reponame>hugovk/SeleniumLibrary from SeleniumLibrary.base import LibraryComponent, keyword class my_lib_args(LibraryComponent): def __init__(self, ctx, arg1, arg2, *args, **kwargs): LibraryComponent.__init__(self, ctx) self.arg1 = arg1 self.arg2 = arg2 self.args = args sel...
odps/mars_extension/__init__.py
wjsi/aliyun-odps-python-sdk
412
83112
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2018 Alibaba Group Holding 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-...
l10n_br_point_of_sale/models/__init__.py
kaoecoito/odoo-brasil
181
83180
<reponame>kaoecoito/odoo-brasil<gh_stars>100-1000 # -*- coding: utf-8 -*- # © 2016 <NAME> <<EMAIL>>, Trustcode # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import pos_order from . import pos_session from . import invoice_eletronic from . import account_journal from . import pos_payment_m...
scripts/remove_after_use/verify_groups_guardian_migration.py
gaybro8777/osf.io
628
83196
"""Script to verify permissions have transferred post groups/guardian. "docker-compose run --rm web python3 -m scripts.remove_after_use.verify_groups_guardian_migration" """ import logging from random import randint from website.app import setup_django setup_django() from django.apps import apps from django.contrib....
test/scenario_test/route_server_malformed_test.py
alistairking/gobgp
2,938
83206
# Copyright (C) 2015 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
Packs/CaseManagement-Generic/Scripts/LinkIncidentsButton/LinkIncidentsButton.py
diCagri/content
799
83208
<filename>Packs/CaseManagement-Generic/Scripts/LinkIncidentsButton/LinkIncidentsButton.py<gh_stars>100-1000 import demistomock as demisto action = demisto.getArg('action') if action not in ['link', 'unlink']: action = 'link' demisto.results(demisto.executeCommand("linkIncidents", {"linkedIncidentIDs": demisto.get...
recipes/Python/578874_Tkinter_simultaneous_scrolling/recipe-578874.py
tdiprima/code
2,023
83215
<reponame>tdiprima/code<filename>recipes/Python/578874_Tkinter_simultaneous_scrolling/recipe-578874.py # Author: <NAME> # Uncomment the next line to see my email # print "Author's email: ", "61706c69636163696f6e616d656469646140676d61696c2e636f6d".decode("hex") try: import Tkinter as tk import ttk except ImportEr...
benchmark/bench_file_handler.py
YoavCohen/logbook
771
83220
"""Benchmarks the file handler""" from logbook import Logger, FileHandler from tempfile import NamedTemporaryFile log = Logger('Test logger') def run(): f = NamedTemporaryFile() with FileHandler(f.name) as handler: for x in xrange(500): log.warning('this is handled')
tests/test_chi_ssa_51.py
MAYANK25402/city-scrapers
255
83245
from datetime import datetime from os.path import dirname, join import pytest from city_scrapers_core.constants import COMMISSION, PASSED from city_scrapers_core.utils import file_response from freezegun import freeze_time from city_scrapers.spiders.chi_ssa_51 import ChiSsa51Spider test_response = file_response( ...
src/output_parser/SarifHolder.py
damian-cs/smartbugs2
194
83255
import attr import pandas from sarif_om import * from src.exception.VulnerabilityNotFoundException import VulnerabilityNotFoundException VERSION = "2.1.0" SCHEMA = "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json" class SarifHolder: def __init__(self): self....
node/tests/k8st/tests/test_simple.py
mikestephen/calico
3,973
83355
<reponame>mikestephen/calico # Copyright (c) 2018 Tigera, Inc. 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 # # Unle...
WebMirror/management/rss_parser_funcs/feed_parse_extractIsogashiineetoWordpressCom.py
fake-name/ReadableWebProxy
193
83365
<filename>WebMirror/management/rss_parser_funcs/feed_parse_extractIsogashiineetoWordpressCom.py def extractIsogashiineetoWordpressCom(item): ''' Parser for 'isogashiineeto.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title']...
python/powerlift/tests/powerlift/bench/test_experiment.py
microsoft/interpret
2,122
83366
from powerlift.bench import Experiment, Store from powerlift.executors.docker import InsecureDocker from powerlift.executors.localmachine import LocalMachine from powerlift.executors.azure_ci import AzureContainerInstance import pytest import os def _add(x, y): return x + y def _err_handler(e): raise e d...
scale/ingest/scan/scanners/factory.py
kaydoh/scale
121
83388
"""Defines the factory for creating monitors""" from __future__ import unicode_literals import logging logger = logging.getLogger(__name__) _SCANNERS = {} def add_scanner_type(scanner_class): """Registers a scanner class so it can be used for Scale Scans :param scanner_class: The class definition for a sc...
Imaging/Core/Testing/Python/TestLassoStencil.py
forestGzh/VTK
1,755
83404
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # A script to test the vtkLassoStencilSource reader = vtk.vtkPNGReader() reader.SetDataSpacing(0.8,0.8,1.5) reader.SetDataOrigin(0.0,0.0,0.0) reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png") r...
node_launcher/logging.py
ryan-lingle/node-launcher
249
83448
import logging.config import os import structlog from node_launcher.constants import NODE_LAUNCHER_DATA_PATH, OPERATING_SYSTEM timestamper = structlog.processors.TimeStamper(fmt='%Y-%m-%d %H:%M:%S') pre_chain = [ # Add the log level and a timestamp to the event_dict if the log entry # is not from structlog. ...
examples/face_detection/main_video.py
Ishticode/kornia
418
83474
import argparse import cv2 import numpy as np import torch import kornia as K from kornia.contrib import FaceDetector, FaceDetectorResult, FaceKeypoint def draw_keypoint(img: np.ndarray, det: FaceDetectorResult, kpt_type: FaceKeypoint) -> np.ndarray: kpt = det.get_keypoint(kpt_type).int().tolist() return cv...
tests/oxml/unitdata/text.py
revvsales/python-docx-1
3,031
83481
<reponame>revvsales/python-docx-1<gh_stars>1000+ # encoding: utf-8 """ Test data builders for text XML elements """ from ...unitdata import BaseBuilder from .shared import CT_OnOffBuilder, CT_StringBuilder class CT_BrBuilder(BaseBuilder): __tag__ = 'w:br' __nspfxs__ = ('w',) __attrs__ = ('w:type', 'w:cl...
evm/utils/hexadecimal.py
zixuanzh/py-evm
137
83509
from __future__ import unicode_literals import codecs def encode_hex(value): return '0x' + codecs.decode(codecs.encode(value, 'hex'), 'utf8') def decode_hex(value): _, _, hex_part = value.rpartition('x') return codecs.decode(hex_part, 'hex')
saleor/graphql/payment/tests/mutations/test_payment_capture.py
eanknd/saleor
1,392
83521
<filename>saleor/graphql/payment/tests/mutations/test_payment_capture.py<gh_stars>1000+ from unittest.mock import patch import graphene from .....payment import TransactionKind from .....payment.gateways.dummy_credit_card import ( TOKEN_EXPIRED, TOKEN_VALIDATION_MAPPING, ) from .....payment.models import Char...
robobrowser_examples/get_html_as_bytes.py
DazEB2/SimplePyScripts
117
83527
<gh_stars>100-1000 #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from robobrowser import RoboBrowser browser = RoboBrowser( user_agent='Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0', parser='html.parser' ) browser.open('https://github.com') html = b...
topic-db/topicdb/util/profiler.py
anthcp-infocom/Contextualise
184
83532
# See URL: https://hakibenita.com/fast-load-data-python-postgresql import time from functools import wraps from memory_profiler import memory_usage # type: ignore def profile(fn): @wraps(fn) def inner(*args, **kwargs): fn_kwargs_str = ", ".join(f"{k}={v}" for k, v in kwargs.items()) print(f...
PyOpenGLExample/squares.py
DazEB2/SimplePyScripts
117
83545
import random from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * """ Generating squares This example will generate 25 squares each in a randomly chosen grayvalue. The grayvalue is chosen out of 25 different possiblities. Every redraw of the window will create a new set of squares. http://ww...
saleor/account/migrations/0023_auto_20180719_0520.py
elwoodxblues/saleor
15,337
83591
# Generated by Django 2.0.3 on 2018-07-19 10:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [("account", "0022_auto_20180718_0956")] operations = [ migrations.AlterModelOptions( name="user", options={ "permissions": ...
pylibui/controls/tab.py
superzazu/pylibui
222
83623
<reponame>superzazu/pylibui """ Python wrapper for libui. """ from pylibui import libui from .control import Control class Tab(Control): def __init__(self): """ Creates a new tab. """ super().__init__() self.control = libui.uiNewTab() def append(self, name, control...
pytextrank/positionrank.py
CaptXiong/pytextrank
899
83649
<reponame>CaptXiong/pytextrank #!/usr/bin/env python # -*- coding: utf-8 -*- # see license https://github.com/DerwenAI/pytextrank#license-and-copyright """ Implements the *PositionRank* algorithm. """ import typing from spacy.tokens import Doc # type: ignore # pylint: disable=E0401 from .base import BaseTextRankFa...
language/mentionmemory/utils/metric_utils_test.py
urikz/language
1,199
83670
# coding=utf-8 # Copyright 2018 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.org/licenses/LICENSE-2.0 # # Unless required by ...
mephisto/scripts/mturk/cleanup.py
padentomasello/Mephisto
167
83674
<gh_stars>100-1000 #!/usr/bin/env python3 # 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. """ Utility script that finds, expires, and disposes HITs that may not have been taking down during a...
better-bus-buffers/BBB_Polygons_Step1.py
d-wasserman/public-transit-tools
130
83686
<reponame>d-wasserman/public-transit-tools<filename>better-bus-buffers/BBB_Polygons_Step1.py #################################################### ## Tool name: BetterBusBuffers ## Created by: <NAME>, Esri, <EMAIL> ## Last updated: 5 December 2017 #################################################### ''' BetterBusBuffers...
examples/hlapi/v3arch/asyncore/sync/manager/cmdgen/specific-v3-engine-id.py
RKinsey/pysnmp
492
83689
""" Discover SNMPv3 SecurityEngineId ++++++++++++++++++++++++++++++++ Send SNMP GET request using the following scenario and options: * try to communicate with a SNMPv3 Engine using: * a non-existing user * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * if remote SNMP Engine ID is discovered, send SNMP GET ...
etl/parsers/etw/Microsoft_Windows_WiFiHotspotService.py
IMULMUL/etl-parser
104
83706
<reponame>IMULMUL/etl-parser<gh_stars>100-1000 # -*- coding: utf-8 -*- """ Microsoft-Windows-WiFiHotspotService GUID : 814182fe-58f7-11e1-853c-78e7d1ca7337 """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CStri...
tests/unit/utils/test_ssdp.py
ifraixedes/saltstack-salt
9,425
83712
<reponame>ifraixedes/saltstack-salt<filename>tests/unit/utils/test_ssdp.py """ :codeauthor: :email:`<NAME> <<EMAIL>>` """ import datetime import salt.utils.ssdp as ssdp import salt.utils.stringutils from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase, skipIf try: import py...
partial_weights.py
k5iogura/YOLOv2-chainer
387
83726
import time import cv2 import numpy as np from chainer import serializers, Variable import chainer.functions as F import argparse from darknet19 import * from yolov2 import * from yolov2_grid_prob import * from yolov2_bbox import * n_classes = 10 n_boxes = 5 partial_layer = 18 def copy_conv_layer(src, dst, layers): ...
pl_bolts/models/rl/__init__.py
lavoiems/lightning-bolts
822
83743
<reponame>lavoiems/lightning-bolts from pl_bolts.models.rl.advantage_actor_critic_model import AdvantageActorCritic from pl_bolts.models.rl.double_dqn_model import DoubleDQN from pl_bolts.models.rl.dqn_model import DQN from pl_bolts.models.rl.dueling_dqn_model import DuelingDQN from pl_bolts.models.rl.noisy_dqn_model i...
telemetry/telemetry/story/story_unittest.py
bopopescu/catapult-2
925
83790
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from telemetry import story from telemetry.story import shared_state # pylint: disable=abstract-method class SharedStateBar(shared_state.S...
Nimbus/settings/secret.sample.py
cgreencode/Nimbus
213
83797
<reponame>cgreencode/Nimbus """ Rename this file to 'secret.py' once all settings are defined """ SECRET_KEY = "..." HOSTNAME = "example.com" DATABASE_URL = "mysql://<user>:<password>@<host>/<database>" AWS_ACCESS_KEY_ID = "12345" AWS_SECRET_ACCESS_KEY = "12345"
funk_svd/dataset.py
grofers/funk-svd
151
83805
import datetime import numpy as np import os import pandas as pd import shutil import urllib.request import zipfile __all__ = [ 'fetch_ml_ratings', ] VARIANTS = { '100k': {'filename': 'u.data', 'sep': '\t'}, '1m': {'filename': 'ratings.dat', 'sep': r'::'}, '10m': {'filename': 'ratings.dat', 'sep': r'...
resources/code/translation.py
GCBallesteros/imreg_dft
167
83832
import os import scipy as sp import scipy.misc import imreg_dft as ird basedir = os.path.join('..', 'examples') # the TEMPLATE im0 = sp.misc.imread(os.path.join(basedir, "sample1.png"), True) # the image to be transformed im1 = sp.misc.imread(os.path.join(basedir, "sample2.png"), True) result = ird.translation(im0,...
pyexfil/Comm/DNSoTLS/constants.py
goffinet/PyExfil
603
83853
<filename>pyexfil/Comm/DNSoTLS/constants.py import os DNS_OVER_TLS_PORT = 853 CHUNK_SIZE = 128 CHECK_CERT = True # We recommend using valid certificates. An invalid certificate (self-signed) might trigger alerts on some systems. LOCAL_HOST = 'localhost' MAX_BUFFER = 4096 MAX_CLIEN...
questions/number-of-digit-one/Solution.py
marcus-aurelianus/leetcode-solutions
141
83856
<filename>questions/number-of-digit-one/Solution.py """ Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. Example: Input: 13 Output: 6 Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. """ class Solution: def countDigi...
modelchimp/migrations/0046_experimentasset.py
samzer/modelchimp-server
134
83857
<gh_stars>100-1000 # Generated by Django 2.1.7 on 2019-02-21 15:50 import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('modelchimp', '0045_remove_machinelearningmodel_deep_learning_...
fastapi/psql_minimum/dev.py
zacfrulloni/Rust-Full-Stack
1,091
83870
<filename>fastapi/psql_minimum/dev.py # source ./bin/activate import subprocess as cmd response = input("[d]ev, [t]est?\n") if response.startswith("t"): cp = cmd.run(f"pytest", check=True, shell=True) else: cp = cmd.run(f"uvicorn main:app --reload", check=True, shell=True)
tools/build_defs/fb_native_wrapper.bzl
pdlanl/react-native
118,175
83871
<reponame>pdlanl/react-native # 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. fb_native = struct( android_aar = native.android_aar, android_app_modularity = native.android_app_modula...
pyctuator/impl/spring_boot_admin_registration.py
SolarEdgeTech/pyctuator
118
83891
import http.client import json import logging import os import ssl import threading import urllib.parse from base64 import b64encode from datetime import datetime from http.client import HTTPConnection, HTTPResponse from typing import Optional, Dict from pyctuator.auth import Auth, BasicAuth # pylint: disable=too-ma...
solaris/nets/zoo/multiclass_segmentation.py
rbavery/solaris
367
83893
<gh_stars>100-1000 import torch from torch import nn from torchvision.models import vgg11, vgg16, resnet34 """ Code heavily adapted from ternaus robot-surgery-segmentation https://github.com/ternaus/robot-surgery-segmentation """ class MultiClass_Resnet34(nn.Module): def __init__(self, num_classes=1, num_filter...
shadowlands/sl_dapp/network_connection.py
kayagoban/shadowlands
140
83910
from shadowlands.sl_dapp import SLDapp, SLFrame import pyperclip, os import schedule from shadowlands.tui.debug import debug import pdb class NetworkConnection(SLDapp): def initialize(self): self.add_sl_frame( NetworkStrategies(self, 10, 26, title="Network Options")) self.connection_strategy = None def at...
src/contrib/hod/hodlib/Common/util.py
hoppinghippo/HadoopMapReduce
194
83932
#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 use thi...
jmetal/problem/multiobjective/zdt.py
12yuens2/jMetalPy
335
83936
from math import sqrt, pow, sin, pi, cos from jmetal.core.problem import FloatProblem from jmetal.core.solution import FloatSolution """ .. module:: ZDT :platform: Unix, Windows :synopsis: ZDT problem family of multi-objective problems. .. moduleauthor:: <NAME> <<EMAIL>> """ class ZDT1(FloatProblem): """...
nequip/scripts/train.py
mir-group/nequip
153
83951
""" Train a network.""" import logging import argparse # This is a weird hack to avoid Intel MKL issues on the cluster when this is called as a subprocess of a process that has itself initialized PyTorch. # Since numpy gets imported later anyway for dataset stuff, this shouldn't affect performance. import numpy as np ...
alibi_detect/cd/tabular.py
sugatoray/alibi-detect
1,227
83984
<filename>alibi_detect/cd/tabular.py import numpy as np from scipy.stats import chi2_contingency, ks_2samp from typing import Callable, Dict, List, Optional, Tuple, Union from alibi_detect.cd.base import BaseUnivariateDrift class TabularDrift(BaseUnivariateDrift): def __init__( self, x_ref...
idaes/generic_models/properties/core/reactions/tests/test_rate_forms.py
carldlaird/idaes-pse
112
83989
<gh_stars>100-1000 ################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-20...
tracardi/service/network.py
bytepl/tracardi
153
84000
<gh_stars>100-1000 import logging import socket from typing import Optional from tracardi.config import tracardi logger = logging.getLogger('utils.network') logger.setLevel(tracardi.logging_level) def get_local_ip() -> Optional[str]: try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.co...
chapter7/authentication/authentication.py
GoodMonsters/Building-Data-Science-Applications-with-FastAPI
107
84013
<reponame>GoodMonsters/Building-Data-Science-Applications-with-FastAPI<filename>chapter7/authentication/authentication.py from typing import Optional from tortoise.exceptions import DoesNotExist from chapter7.authentication.models import ( AccessToken, AccessTokenTortoise, UserDB, UserTortoise, ) from...
mcd/__init__.py
zwlanpishu/MCD
158
84025
"""Mel cepstral distortion (MCD) computations in python.""" # Copyright 2014, 2015, 2016, 2017 <NAME> # This file is part of mcd. # See `License` for details of license and warranty. __version__ = '0.5.dev1'
application/controllers/admin/order/logistic.py
mutalisk999/bibi
1,037
84049
<filename>application/controllers/admin/order/logistic.py # -*- coding: utf-8 -*- import json import os import datetime import time import random from copy import deepcopy from bson import ObjectId, json_util from itertools import chain from flask_admin import BaseView, expose from flask_babel import gettext as _ from ...
recipes/Python/578132_How_to_Mutate_a_Float/recipe-578132.py
tdiprima/code
2,023
84053
<gh_stars>1000+ import sys, struct, ctypes def set_float(obj, value): assert isinstance(obj, float), 'Object must be a float!' assert isinstance(value, float), 'Value must be a float!' stop = sys.getsizeof(obj) start = stop - struct.calcsize('d') array = ctypes.cast(id(obj), ctypes.POINTER(ctypes.c...
functional_tests/mp/04-pool.py
borisgrafx/client
3,968
84070
<filename>functional_tests/mp/04-pool.py #!/usr/bin/env python """pool with finish.""" import multiprocessing as mp import wandb import yea def do_run(num): run = wandb.init() run.config.id = num run.log(dict(s=num)) run.finish() return num def main(): wandb.require("service") wandb.se...
prompt_tuning/train/models.py
google-research/prompt-tuning
108
84075
# Copyright 2022 Google. # # 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, soft...
algorithms/strange-advertising.py
gajubadge11/HackerRank-1
340
84092
#!/bin/python3 import sys def calc_pattern(): max_n = 50 ads = 5 output = [] for i in range(max_n): output.append(ads//2) ads = (ads//2)*3 return output def viralAdvertising(n, pattern): return sum(pattern[:n]) if __name__ == "__main__": n = int(input().strip()) ...
spinup_utils/plot.py
kaixindelele/DRLib
226
84111
""" 相比于原始的plot.py文件,增加了如下的功能: 1.可以直接在pycharm或者vscode执行,也可以用命令行传参; 2.按exp_name排序,而不是按时间排序; 3.固定好每个exp_name的颜色; 4.可以调节曲线的线宽,便于观察; 5.保存图片到本地,便于远程ssh画图~ 6.自动显示全屏 7.图片自适应 8.针对颜色不敏感的人群,可以在每条legend上注明性能值,和性能序号 9.对图例legend根据性能从高到低排序,便于分析比较 10.提供clip_xaxis值,对训练程度进行统一截断,图看起来更整洁。 seaborn版本0.8.1 """ import seaborn as sns import p...
reblur_package/reblur_package/utils.py
adityakrishnavamsy/SelfDeblur
104
84137
<reponame>adityakrishnavamsy/SelfDeblur import torch import meshzoo def generate_2D_mesh(H, W): _, faces = meshzoo.rectangle( xmin = -1., xmax = 1., ymin = -1., ymax = 1., nx = W, ny = H, zigzag=True) x = torch.arange(0, W, 1).float().cuda() y = torch.arange(0, H, 1).float...
backend/src/baserow/contrib/database/api/views/grid/serializers.py
cjh0613/baserow
839
84139
<gh_stars>100-1000 from rest_framework import serializers from baserow.contrib.database.views.models import GridViewFieldOptions class GridViewFieldOptionsSerializer(serializers.ModelSerializer): class Meta: model = GridViewFieldOptions fields = ("width", "hidden", "order") class GridViewFilter...
output/examples/example6/view.py
cy15196/FastCAE
117
84140
<filename>output/examples/example6/view.py<gh_stars>100-1000 MainWindow.clearData() MainWindow.openPost3D() PostProcess.script_openFile(-1,"Post3D","%examplesPath%/water.vtk") PostProcess.script_openFile(-1,"Post3D","%examplesPath%/platform.vtk") PostProcess.script_applyClicked(-1,"Post3D") PostProcess.script_Propertie...
Engine/libs/freeType/src/tools/docmaker/sources.py
lampardwade/tetris_lua_playgroundOSS
175
84148
<filename>Engine/libs/freeType/src/tools/docmaker/sources.py<gh_stars>100-1000 # Sources (c) 2002-2004, 2006-2009, 2012 # <NAME> <<EMAIL>> # # # this file contains definitions of classes needed to decompose # C sources files into a series of multi-line "blocks". There are # two kinds of blocks: # # - norm...
IOPool/Common/test/testEdmConfigDump_cfg.py
ckamtsikis/cmssw
852
84156
import FWCore.ParameterSet.Config as cms process = cms.Process("PROD1") process.source = cms.Source("IntSource") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(3) ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string('testEdmProvDump.root'), outputComma...
raiden/tests/unit/transfer/mediated_transfer/test_mediation_fee.py
tirkarthi/raiden
2,101
84183
<reponame>tirkarthi/raiden from fractions import Fraction from typing import Tuple import pytest from hypothesis import HealthCheck, assume, example, given, settings from hypothesis.strategies import integers from raiden.tests.unit.transfer.test_channel import make_hash_time_lock_state from raiden.tests.utils import ...
rlbench/tasks/put_money_in_safe.py
Nicolinho/RLBench
619
84201
from typing import List, Tuple import numpy as np from pyrep.objects.shape import Shape from pyrep.objects.dummy import Dummy from pyrep.objects.proximity_sensor import ProximitySensor from rlbench.backend.task import Task from rlbench.backend.conditions import DetectedCondition, NothingGrasped from rlbench.backend.spa...
aerosandbox/aerodynamics/aero_3D/avl.py
msberk/AeroSandbox
322
84219
from aerosandbox.common import ExplicitAnalysis import aerosandbox.numpy as np import subprocess from pathlib import Path from aerosandbox.geometry import Airplane from aerosandbox.performance import OperatingPoint from typing import Union, List, Dict import tempfile import warnings class AVL(ExplicitAnalysis): "...
nasbench301/surrogate_models/bananas/bananas_src/bo/acq/__init__.py
Basvanstein/nasbench301
167
84225
<reponame>Basvanstein/nasbench301 """ Code for acquisition strategies. """
pycrc/expr.py
jbosboom/pycrc
118
84233
# pycrc -- parameterisable CRC calculation utility and C source code generator # # Copyright (c) 2017 <NAME> <<EMAIL>> # # 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 restric...
labml_nn/transformers/hour_glass/__init__.py
techthiyanes/annotated_deep_learning_paper_implementations
3,714
84307
<filename>labml_nn/transformers/hour_glass/__init__.py """ --- title: Hierarchical Transformers Are More Efficient Language Models summary: > This is an annotated implementation/tutorial of hourglass model in PyTorch. --- # Hierarchical Transformers Are More Efficient Language Models This is a [PyTorch](https://pyt...