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
lit_nlp/examples/models/glue_models_int_test.py
eichinflo/lit
2,854
12723478
"""Integration tests for lit_nlp.examples.models.glue_models.""" from absl.testing import absltest from lit_nlp.examples.models import glue_models import transformers class GlueModelsIntTest(absltest.TestCase): def test_sst2_model_predict(self): # Create model. model_path = "https://storage.googleapis.co...
boltstream/migrations/0004_user_uuid.py
geekpii/boltstream
1,735
12723488
<gh_stars>1000+ # Generated by Django 2.2 on 2019-05-12 18:20 import uuid from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("boltstream", "0003_streamsession")] operations = [ migrations.AddField( model_name="user", name="uuid"...
code/old-version/restrictedBoltzmannMachine.py
diksha42/erecognition
166
12723500
"""Implementation of restricted boltzmann machine You need to be able to deal with different energy functions This allows you to deal with real valued units. TODO: monitor overfitting """ __author__ = "<NAME>" __contact__ = "<EMAIL>" import numpy as np from common import * EXPENSIVE_CHECKS_ON = False # TODO: dif...
DynaMaze/DynaQ+.py
nabeelfarooqui98/Reinforcement-Learning-Implementation
116
12723568
<filename>DynaMaze/DynaQ+.py import numpy as np ROWS = 6 COLS = 9 S = (2, 0) G = (0, 8) BLOCKS = [(1, 2), (2, 2), (3, 2), (0, 7), (1, 7), (2, 7), (4, 5)] ACTIONS = ["left", "up", "right", "down"] class Maze: def __init__(self): self.rows = ROWS self.cols = COLS self.start = S sel...
__scraping__/centralbankofindia.co.in - scrapy/main.py
dhmo1900/python-examples
140
12723584
# author: Bartlomiej "furas" Burek (https://blog.furas.pl) # date: 2021.10.04 # # title: Scrapy returning None on querying by xpath # url: https://stackoverflow.com/questions/69442962/scrapy-returning-none-on-querying-by-xpath/69443343#69443343 # [Scrapy returning None on querying by xpath](https://stackoverflow.com/...
raiden/tests/benchmark/_codespeed.py
tirkarthi/raiden
2,101
12723603
<filename>raiden/tests/benchmark/_codespeed.py import json import os import warnings import requests try: _CODESPEED_USER = os.environ["CODESPEED_USER"] _CODESPEED_PASSWORD = os.environ["CODESPEED_PASSWORD"] _BENCHMARK_HOST = os.environ["BENCHMARK_HOST"] except KeyError: warnings.warn( "Code...
container_files/ipython_extra_config.py
kstepanmpmg/mldb
665
12723617
c = get_config() c.NotebookApp.ip = '{{IPYTHON_NB_LISTEN_ADDR}}' c.NotebookApp.port = {{IPYTHON_NB_LISTEN_PORT}} c.NotebookApp.open_browser = False c.NotebookApp.notebook_dir = u'{{IPYTHON_NB_DIR}}' c.NotebookApp.base_url = '{{HTTP_BASE_URL}}/{{IPYTHON_NB_PREFIX}}' c.NotebookApp.tornado_settings = {'static_url_prefix...
convertor.py
trankha1655/pan_pp.origin
329
12723647
<gh_stars>100-1000 import torch import mmcv import argparse import os.path as osp parser = argparse.ArgumentParser(description='Hyperparams') parser.add_argument('checkpoint', nargs='?', type=str, default=None) args = parser.parse_args() dir_name = args.checkpoint.split("/")[-2] checkpoint = torch.load(args.checkpoin...
pims/process.py
tsmbland/pims
208
12723694
<filename>pims/process.py from __future__ import (absolute_import, division, print_function, unicode_literals) import numpy as np from slicerator import pipeline, Pipeline import six @pipeline def as_grey(frame): """Convert a 2D image or PIMS reader to greyscale. This weights the col...
tests/test_project/app_correct/models.py
christianbundy/django-migration-linter
357
12723722
from django.db import models class A(models.Model): null_field = models.IntegerField(null=True) new_null_field = models.IntegerField(null=True)
ci-scripts/flatten_image.py
nstng/magma
539
12723732
""" Copyright 2022 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES O...
boost_adaptbx/command_line/inexact.py
dperl-sol/cctbx_project
155
12723786
from __future__ import absolute_import, division, print_function # LIBTBX_SET_DISPATCHER_NAME boost_adaptbx.inexact import boost_adaptbx.boost.python as bp import sys def run(args): assert len(args) == 0 print("Now creating a NaN in C++ as 0/0 ...") sys.stdout.flush() result = bp.ext.divide_doubles(0, 0) p...
torchbenchmark/models/fastNLP/test/modules/decoder/test_seq2seq_decoder.py
Chillee/benchmark
2,693
12723821
import unittest import torch from fastNLP import Vocabulary from fastNLP.embeddings import StaticEmbedding from fastNLP.modules import TransformerSeq2SeqDecoder from fastNLP.modules import LSTMSeq2SeqDecoder from fastNLP import seq_len_to_mask class TestTransformerSeq2SeqDecoder(unittest.TestCase): def test_cas...
python/fate_client/pipeline/interface/data.py
hubert-he/FATE
3,787
12723832
<reponame>hubert-he/FATE<gh_stars>1000+ # # Copyright 2019 The FATE 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/L...
datasets/data_path/gen_bdd100k_mot.py
anonymous4669/MOTR
191
12723857
import os import numpy as np import json import cv2 from tqdm import tqdm from collections import defaultdict def convert(img_dir, split, label_dir, save_label_dir, filter_crowd=False, filter_ignore=False): cat2id = {'train':6, 'car':3, 'bus':5, 'other person': 1, 'rider':2, 'pedestrian':1, 'other vehicle':3, '...
contrib/buildbot/test/test_testutil.py
syedrizwanmy/bitcoin-abc
1,266
12723880
<filename>contrib/buildbot/test/test_testutil.py #!/usr/bin/env python3 # # Copyright (c) 2020 The Bitcoin ABC developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import unittest from testutil import AnyWith class TestOb...
price_analysis/fit.py
kevaundray/research
1,351
12723943
<reponame>kevaundray/research<gh_stars>1000+ import spread import math import random o = spread.declutter(spread.load('diff_txs_price.csv')) diffs = [float(q[2]) for q in o] prices = [float(q[1]) for q in o] txs = [float(q[3]) for q in o] txfees = [float(q[4]) for q in o] def simple_estimator(fac): o = [1] ...
codigo/Live172/chalice-lambdas/app.py
BrunoPontesLira/live-de-python
572
12723948
from chalice import Chalice, Rate import logging app = Chalice(app_name='chalice-lambdas') app.log.setLevel(logging.DEBUG) @app.route('/') def index(): return {'message': 'Olar Chalice!'} @app.route('/batatinhas') def batatinhas(): return {'message': 'Olar batatinhas!'} @app.route('/query') def query():...
src/lib/_typeAliases.py
t3kt/raytk
108
12724015
from typing import Union, Optional from _stubs import * class StrParamT(Par, Union[Par, str]): def eval(self) -> str: pass class IntParamT(Par, Union[Par, str, int]): def eval(self) -> int: pass class FloatParamT(Par, Union[Par, str, float, int]): def eval(self) -> float: pass class DatParamT(Par, Union[Par, st...
scripts/data/kitti2bb3txt.py
wuzzh/master_thesis_code
206
12724017
""" Script for translating the KITTI 3D bounding box annotation format into the BB3TXT data format. A BB3TXT file is formatted like this: filename label confidence xmin ymin xmax ymax fblx fbly fbrx fbry rblx rbly ftly filename label confidence xmin ymin xmax ymax fblx fbly fbrx fbry rblx rbly ftly filename label conf...
roboticstoolbox/models/ETS/__init__.py
tassos/robotics-toolbox-python
749
12724045
from roboticstoolbox.models.ETS.Panda import Panda from roboticstoolbox.models.ETS.Frankie import Frankie from roboticstoolbox.models.ETS.Puma560 import Puma560 from roboticstoolbox.models.ETS.Planar_Y import Planar_Y from roboticstoolbox.models.ETS.Planar2 import Planar2 from roboticstoolbox.models.ETS.GenericSeven im...
mentalist/view/adder.py
qkum/mentalist
1,293
12724050
<gh_stars>1000+ import tkinter as Tk from functools import partial import datetime import tkinter.messagebox import locale from .base_words import BaseWordsNode, center_window from .const import NUMBER_LIST, DATE_FORMATS, SPECIAL_CHARACTERS from .. import model class AdderNode(BaseWordsNode): '''Append and Prepe...
Logistic Regression with StatsModels/logistic.py
joao-r-santos/DataSciencePython
5,070
12724074
<gh_stars>1000+ """ Created on Wed Sep 09 12:38:16 2015 @author: ujjwal.karn """ import pandas as pd #for handling datasets import statsmodels.api as sm #for statistical modeling import pylab as pl #for plotting import numpy as np #for numerical computation # read ...
macropy/experimental/test/pyxl_snippets.py
CyberFlameGO/macropy
2,061
12724087
# -*- coding: utf-8 -*- import re import unittest from xml.etree import ElementTree from macropy.case_classes import macros, case from macropy.experimental.pyxl_strings import macros, p # noqa: F811 from macropy.tracing import macros, require # noqa: F811, F401 from pyxl import html # noqa: F401 def normalize(st...
benchmarks/lucasb-eyer-heatmap/examples/customstamps.py
pointhi/benchmarks
206
12724088
#!/usr/bin/env python # heatmap - High performance heatmap creation in C. # # The MIT License (MIT) # # Copyright (c) 2013 <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 re...
RecoLocalCalo/Castor/test/castor_cfg.py
ckamtsikis/cmssw
852
12724092
<filename>RecoLocalCalo/Castor/test/castor_cfg.py import FWCore.ParameterSet.Config as cms process = cms.Process("CastorProducts") process.load("FWCore.MessageLogger.MessageLogger_cfi") # specify the correct database tags which contain the updated gains and channelquality flags process.load("CondCore.DBCommon.CondDB...
river/metrics/multioutput/micro.py
online-ml/creme
1,105
12724096
from river import metrics, utils from river.metrics.multioutput.base import MultiOutputMetric __all__ = ["MicroAverage"] class MicroAverage(MultiOutputMetric, metrics.base.WrapperMetric): """Micro-average wrapper. The provided metric is updated with the value of each output. Parameters ---------- ...
taskwiki/completion.py
Jasha10/taskwiki
465
12724107
<filename>taskwiki/completion.py from functools import reduce, wraps import re from tasklib import TaskWarrior from taskwiki import constants from taskwiki import regexp def complete_last_word(f): @wraps(f) def wrapper(self, arglead): before, sep, after = arglead.rpartition(' ') comps = f(se...
{{cookiecutter.project_slug}}/backend/app/app/api/api_v1/api.py
abnerjacobsen/full-stack
516
12724110
<filename>{{cookiecutter.project_slug}}/backend/app/app/api/api_v1/api.py<gh_stars>100-1000 # Import installed packages # Import app code from app.main import app from app.core import config from app.db.flask_session import db_session from .api_docs import docs from .endpoints import role from .endpoints import toke...
00Python/day12/PoliceVsTheif.py
HaoZhang95/PythonAndMachineLearning
937
12724184
""" 警察vs土匪 """ class Gun(object): def __init__(self, model, damage): # 型号 self.model = model # 杀伤力 self.damage = damage # 子弹数量,默认为0 self.bullet_count = 0 # 重写str def __str__(self): return "型号:%s, 杀伤力:%s, 子弹数量:%s" % ( self.model, sel...
projects/causal_scene_generation/causal_model/game_characters/procedural_generation/game_character_scene.py
amoskowitz14/causalML
354
12724209
<reponame>amoskowitz14/causalML from PIL import ImageOps, Image import os image_dict = { "Satyr": { "base_path": "../images/satyr/PNG/", "Attacking": "/reference/Attacking/attack.png", "Taunt": "/reference/Taunt/taunt.png", "Walking": "/reference/Walking/walking....
flaskblog/auth/models.py
davshen/Flog
202
12724247
<reponame>davshen/Flog from ..models import db class OAuth2Token(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(40)) token_type = db.Column(db.String(40)) access_token = db.Column(db.String(200)) refresh_token = db.Column(db.String(200)) expires_at = db.Co...
third_party/chromite/cbuildbot/stages/handle_changes_stages_unittest.py
zipated/src
2,151
12724263
# Copyright 2017 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Module containing the unit tests for handle_changes_stages.""" from __future__ import print_function import itertools import mock from chromite.cbui...
web/migrations/0014_auto_20200115_2239.py
nonomal/oh-my-rss
270
12724265
# Generated by Django 2.2.7 on 2020-01-15 14:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0013_auto_20200108_2257'), ] operations = [ migrations.AlterField( model_name='article', name='src_url', ...
leetcode/138.copy-list-with-random-pointer.py
geemaple/algorithm
177
12724282
<reponame>geemaple/algorithm # Definition for singly-linked list with a random pointer. # class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution(object): def copyRandomList(self, head): """ :type hea...
tests/test_structs.py
avivazran/UnrealEnginePython
2,350
12724320
<filename>tests/test_structs.py import unittest import unreal_engine as ue from unreal_engine.structs import ColorMaterialInput, Key from unreal_engine.structs import StaticMeshSourceModel, MeshBuildSettings class TestStructs(unittest.TestCase): def test_new_struct(self): material_input = ColorMaterialIn...
tests/test_utils.py
hoechenberger/pycircstat
125
12724331
from __future__ import absolute_import import numpy as np from numpy.testing import assert_allclose from pycircstat import utils
python/ql/test/experimental/dataflow/pep_328/package/subpackage2/moduleZ.py
timoles/codeql
4,036
12724332
eggs = "eggs"
backend/storage/async_s3.py
xuantan/viewfinder
645
12724335
# Copyright 2012 Viewfinder Inc. All Rights Reserved. """Async version of Amazon S3 access library. The "boto" open source library supports synchronous operations against S3, but does not have asynchronous support. In a high-scale server environment, this is a real problem, because it is not permissible to block thre...
examples/application_factory/web.py
aronianm/flask-apscheduler
942
12724339
"""Example web view for application factory.""" from flask import Blueprint from .extensions import scheduler from .tasks import task2 web_bp = Blueprint("web_bp", __name__) @web_bp.route("/") def index(): """Say hi!. :url: / :returns: hi! """ return "hi!" @web_bp.route("/add") def add(): ...
test/test_functions.py
codeclimate-testing/falcon
115
12724372
<reponame>codeclimate-testing/falcon<filename>test/test_functions.py<gh_stars>100-1000 from testing_helpers import wrap @wrap def nested(x): def f(y): return y+y return f(x) def test_nested(): nested(3) nested(3.0) nested([1]) @wrap def nested_closure(x): def f(y): return x + y return f(...
Python/Algorithms/Dynamic-Programming/0-1_knapsack.py
ThunderZ007/Data-Structures-and-Algorithms
245
12724378
# Input Cases t = int(input("\nTotal Test Cases : ")) for i in range(1,t+1): print(f"\n------------ CASE #{i} -------------") n = int(input("\nTotal Items : ")) m = int(input("Max Capacity : ")) v = [int(i) for i in input("\nValues : ").split(" ")] w = [int(i) for i in input("Weights : ").split(" ")] # Ta...
main.py
ssysm/DD_KaoRou2
187
12724417
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os, sys, requests from random import randint from PySide2.QtWidgets import QApplication, QSplashScreen from PySide2.QtGui import QFont, QPixmap, QIcon from PySide2.QtCore import Qt, QThread from utils.main_ui import MainWindow class downloadUpdates(QThread): def ...
brainstorm/layers/mask_layer.py
PyCN/brainstorm
1,473
12724426
#!/usr/bin/env python # coding=utf-8 from __future__ import division, print_function, unicode_literals from collections import OrderedDict from brainstorm.layers.base_layer import Layer from brainstorm.structure.buffer_structure import StructureTemplate from brainstorm.structure.construction import ConstructionWrappe...
leonardo/module/search/tasks.py
timgates42/django-leonardo
102
12724427
<gh_stars>100-1000 from __future__ import absolute_import import os from celery import shared_task from django.core import management from leonardo.decorators import catch_result from django.conf import settings @shared_task @catch_result def sync_search_indexes(): management.call_command('rebuild_index', intera...
release/stubs.min/System/__init___parts/HttpStyleUriParser.py
htlcnn/ironpython-stubs
182
12724447
class HttpStyleUriParser(UriParser): """ A customizable parser based on the HTTP scheme. HttpStyleUriParser() """
exercises/de/solution_03_14_03.py
Jette16/spacy-course
2,085
12724472
<filename>exercises/de/solution_03_14_03.py from spacy.lang.de import German nlp = German() people = ["<NAME>", "<NAME>", "<NAME>"] # Erstelle eine Liste von Patterns für den PhraseMatcher patterns = list(nlp.pipe(people))
qf_lib/documents_utils/document_exporting/pdf_exporter.py
webclinic017/qf-lib
198
12724473
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
solutions/LeetCode/Python3/22.py
timxor/leetcode-journal
854
12724487
__________________________________________________________________________________________________ 36ms class Solution: def generateParenthesis(self, n: 'int') -> 'List[str]': if n == 0: return [''] ans = [] def backtrack(S = '',left = 0, right = 0): if len(S) == 2 * n: ...
pyretri/datasets/folder/folder_base.py
dongan-beta/PyRetri
1,063
12724532
<gh_stars>1000+ # -*- coding: utf-8 -*- import numpy as np from PIL import Image import pickle import os from abc import abstractmethod from ...utils import ModuleBase from typing import Dict, List class FolderBase(ModuleBase): """ The base class of folder function. """ default_hyper_params = dict(...
code_examples/cython_spring16/geometry_py.py
mikofski/thw-berkeley
106
12724564
<reponame>mikofski/thw-berkeley<gh_stars>100-1000 import math def sum_circle(data, x, y, r): """Sum array values that fall within the given circle. Parameters ---------- data : numpy.ndarray The array to sum. x, y, r : float The center and radius of circle, in array coordinates. ...
example_dialogs.py
timeopochin/picotui
739
12724587
from picotui.context import Context from picotui.dialogs import * with Context(): # Feel free to comment out extra dialogs to play with a particular # in detail d = DTextEntry(25, "Hello World", title="Wazzup?") res = d.result() d = DMultiEntry(25, 5, "Hello\nWorld".split("\n"), title="Comment:") ...
homura/vision/models/densenet.py
wangjunyan305/homura
102
12724628
<reponame>wangjunyan305/homura """ DenseNet for CIFAR dataset proposed in Gao et al. 2016 https://github.com/liuzhuang13/DenseNet """ import torch from torch import nn from torch.nn import functional as F from homura.vision.models import MODEL_REGISTRY __all__ = ["densenet40", "densenet100", "CIFARDenseNet"] _paddi...
models/ops.py
yhgon/tacotron
242
12724638
import tensorflow as tf from tensorflow.contrib.seq2seq.python.ops.helper import CustomHelper from tensorflow.contrib.rnn import * class InferenceHelper(CustomHelper): def _initialize_fn(self): # we always reconstruct the whole output finished = tf.tile([False], [self._batch_size]) next_in...
examples/plot_sars.py
skovic/SHARPpy
163
12724658
<reponame>skovic/SHARPpy<gh_stars>100-1000 """ Plotting data from the SARS database ==================================== """ import sharppy.sharptab as tab import sharppy.databases.sars as sars import numpy as np import os import matplotlib.pyplot as plt database_fn = os.path.join( os.path.dirname( sars.__file__ ), ...
GCC-paddle/gcc/tasks/__init__.py
S-HuaBomb/Contrib
243
12724659
from gcc.models.emb import ( FromNumpy, FromNumpyAlign, FromNumpyGraph, GraphWave, ProNE, Zero, ) def build_model(name, hidden_size, **model_args): return { "zero": Zero, "from_numpy": FromNumpy, "from_numpy_align": FromNumpyAlign, "from_numpy_graph": FromNu...
micro-benchmark/snippets/assignments/chained/main.py
WenJinfeng/PyCG
121
12724689
<filename>micro-benchmark/snippets/assignments/chained/main.py<gh_stars>100-1000 def func1(): pass def func2(): pass a = b = func1 b() a = b = func2 a()
notebook/pandas_ohlc_downsampling.py
vhn0912/python-snippets
174
12724711
<gh_stars>100-1000 import pandas as pd df = pd.read_csv('data/src/aapl_2015_2019.csv', index_col=0, parse_dates=True)['2017'] print(df) # open high low close volume # 2017-01-03 115.80 116.3300 114.760 116.15 28781865 # 2017-01-04 115.85 116.5100 115.750 116.02 21118116 # 2017-01...
tests/pki/test_models.py
pythonModule/commandment
138
12724716
<reponame>pythonModule/commandment import pytest import os.path import logging from cryptography import x509 from cryptography.hazmat.primitives.asymmetric import rsa from commandment.pki.models import RSAPrivateKey, CACertificate logger = logging.getLogger(__name__) class TestModels: def test_rsa_privatekey_fr...
models/data_manager.py
nawshad/multi-task-NLP
308
12724721
<reponame>nawshad/multi-task-NLP ''' Script to manage datasets for multiple tasks ''' from torch.utils.data import Dataset, DataLoader, BatchSampler from utils.data_utils import TaskType, ModelType import torch import random import logging import json logger = logging.getLogger("multi_task") class allTasksDataset(Data...
conanfile.py
dbacchet/entt
6,792
12724781
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.co...
components/espcoredump/corefile/riscv.py
cablelabs/esp-idf
8,747
12724822
# # Copyright 2021 Espressif Systems (Shanghai) 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 l...
DEPRECATED_PYTHON_SRC/component/hosts.py
17701253801/firefly-proxy
5,895
12724834
import os import codecs import json import collections from collections import defaultdict from gevent import socket from fnmatch import fnmatch if os.name == 'nt': import win_inet_pton socket.inet_pton = win_inet_pton.inet_pton socket.inet_ntop = win_inet_pton.inet_ntop from gsocks.smart_relay import For...
lib/oembed/utils.py
goztrk/django-htk
206
12724839
# Python Standard Library Imports import re # Third Party (PyPI) Imports import requests import rollbar import six.moves.urllib as urllib # HTK Imports from htk.lib.oembed.cachekeys import OembedResponseCache from htk.lib.oembed.constants import * from htk.utils.request import get_current_request def get_oembed_htm...
opts.py
Nitin-Mane/dense-ulearn-vos
157
12724853
""" Copyright (c) 2021 TU Darmstadt Author: <NAME> <<EMAIL>> License: Apache License 2.0 """ from __future__ import print_function import os import torch import argparse from core.config import cfg def add_global_arguments(parser): # # Model details # parser.add_argument("--snapshot-dir", type=str, ...
maro/cli/inspector/visualization.py
yangboz/maro
598
12724866
<reponame>yangboz/maro # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import argparse from maro.cli.inspector.cim_dashboard import start_cim_dashboard from maro.cli.inspector.citi_bike_dashboard import start_citi_bike_dashboard from maro.cli.inspector.params import GlobalScenarios if __name...
ajenti-core/aj/security/verifier.py
ajenti/ajen
3,777
12724876
from jadi import service import aj @service class ClientCertificateVerificator(): def __init__(self, context): self.context = context def verify(self, x509): serial = x509.get_serial_number() digest = x509.digest('sha1') # logging.debug('SSL verify: %s / %s' % (x509.get_subjec...
pandapower/test/loadflow/PF_Results.py
yougnen/pandapower
104
12724904
import numpy as np def get_PF_Results(): results=\ { 10: { 0: { 'delta' : { 'Yyn': np.array ([ #10,0,deltaYyn #BusTr_HV,Tr_LV,Load 1.0000001787261197, 0.9990664471050634, 0.9408623912831601, 0.9999997973033823, 0.9989329879720452, 0.9398981202882926...
samples/lightning/lit_mnist.py
elgalu/labml
463
12724927
<reponame>elgalu/labml """ Modified from https://colab.research.google.com/github/PytorchLightning/pytorch-lightning/blob/master/notebooks/01-mnist-hello-world.ipynb Added labml logger """ import pytorch_lightning as pl import torch from pytorch_lightning.metrics.functional import accuracy from torch import nn from to...
tests/modules/span_extractors/self_attentive_span_extractor_test.py
MSLars/allennlp
11,433
12724935
import numpy import torch from allennlp.modules.span_extractors import SpanExtractor, SelfAttentiveSpanExtractor from allennlp.common.params import Params class TestSelfAttentiveSpanExtractor: def test_locally_normalised_span_extractor_can_build_from_params(self): params = Params( { ...
tests/__init__.py
iiiusky/Sasila
327
12724938
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest2 as unittest all_suite = unittest.TestLoader().discover(os.path.dirname(__file__), "test_*.py")
test/mitmproxy/proxy/layers/test_socks5_fuzz.py
KarlParkinson/mitmproxy
24,939
12724966
from hypothesis import given from hypothesis.strategies import binary from mitmproxy import options from mitmproxy.connection import Client from mitmproxy.proxy.context import Context from mitmproxy.proxy.events import DataReceived from mitmproxy.proxy.layers.modes import Socks5Proxy opts = options.Options() tctx = C...
elliot/recommender/content_based/VSM/__init__.py
gategill/elliot
175
12724969
from .vector_space_model import VSM
tests/__init__.py
asmeurer/nikola
1,901
12724971
"""Tests for Nikola."""
components/isceobj/Util/geo/exceptions.py
vincentschut/isce2
1,133
12724976
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2012 California Institute of Technology. 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 th...
tools/gen_header_v3.py
Kill-Console/xresloader
219
12724987
<reponame>Kill-Console/xresloader<filename>tools/gen_header_v3.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import string import glob import sys from subprocess import Popen work_dir = os.getcwd() script_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(script_dir) os.chdir(sc...
Python/ch6-1_b.py
andjor/deep-learning-with-csharp-and-cntk
120
12725039
import time import datetime import os import sys import numpy as np use_cntk = True if use_cntk: try: base_directory = os.path.split(sys.executable)[0] os.environ['PATH'] += ';' + base_directory import cntk os.environ['KERAS_BACKEND'] = 'cntk' except ImportError: print('...
angrutils/expr.py
Ashaya123/angr-utils
226
12725040
# Expression evaluation routines import claripy def get_signed_range(se, expr): """ Calculate the range of the expression with signed boundaries """ size = expr.size() umin = umax = smin = smax = None if not sat_zero(se, expr): try: umin = se.min(expr, extra_constraints=[cl...
heath/main.py
121121321/chaoxing_auto_sign
287
12725048
# -*- coding: utf8 -*- import os import re import json import configparser import threading from datetime import datetime from urllib import parse from urllib.parse import quote import requests class HeathReport(object): def __init__(self, user): """ :params username: 手机号或学号 :params ...
doc/integrations/label-studioAPI/setup.py
novium258/cortx-1
552
12725066
<filename>doc/integrations/label-studioAPI/setup.py from setuptools import setup setup( name='Cortx S3-Label Studio Integration', version='1.0.0', packages=[ '' ], url='', license='MIT ', author='sumit', author_email='<EMAIL>', description='Cortx S3 integration with Label Studio, one of ...
Python3/862.py
rakhi2001/ecom7
854
12725086
<gh_stars>100-1000 __________________________________________________________________________________________________ sample 856 ms submission class Solution: def shortestSubarray(self, nums: List[int], k: int) -> int: NOT_FOUND = -1 if not nums: return NOT_FOUND ...
linformer_pytorch/linformer_pytorch.py
tatp22/linformer-pytorch
322
12725097
<filename>linformer_pytorch/linformer_pytorch.py import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.checkpoint import checkpoint def identity(x, *args, **kwargs): return x def get_act(activation): if activation == "gelu": return F.gelu if activation == "relu": ...
src/genie/libs/parser/iosxe/tests/ShowCdpNeighbors/cli/equal/device_output_5_expected.py
balmasea/genieparser
204
12725099
expected_output = { "cdp": { "index": { 1: { "capability": "R S C", "device_id": "Device_With_A_Particularly_Long_Name", "hold_time": 134, "local_interface": "GigabitEthernet1", "platform": "N9K-9000v", ...
LeetCode/python3/394.py
ZintrulCre/LeetCode_Archiver
279
12725105
class Solution: def decodeString(self, s: str) -> str: stack = [] stack.append([1, ""]) num = 0 for l in s: if l.isdigit(): num = num * 10 + ord(l) - ord('0') elif l == '[': stack.append([num, ""]) num = 0 ...
Algo and DSA/LeetCode-Solutions-master/Python/number-of-rectangles-that-can-form-the-largest-square.py
Sourav692/FAANG-Interview-Preparation
3,269
12725110
<filename>Algo and DSA/LeetCode-Solutions-master/Python/number-of-rectangles-that-can-form-the-largest-square.py # Time: O(n) # Space: O(1) class Solution(object): def countGoodRectangles(self, rectangles): """ :type rectangles: List[List[int]] :rtype: int """ result = mx =...
tools/SDKTool/src/ui/tree/ui_tree/over_node_info.py
Passer-D/GameAISDK
1,210
12725127
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright...
examples/multiline_plot.py
ATayls/DnaFeaturesViewer
391
12725130
"""In this example we plot a record fragment with sequence over multiple lines. """ from dna_features_viewer import BiopythonTranslator translator = BiopythonTranslator() graphic_record = translator.translate_record("example_sequence.gb") subrecord = graphic_record.crop((1700, 2000)) fig, axes = subrecord.plot_on_mult...
L1Trigger/GlobalTriggerAnalyzer/python/L1ExtraInputTagSet_cff.py
ckamtsikis/cmssw
852
12725147
# Set of input tags for L1Extra in agreement with L1Reco_cff # # <NAME> 2012-05-22 import FWCore.ParameterSet.Config as cms L1ExtraInputTagSet = cms.PSet( L1ExtraInputTags=cms.PSet( TagL1ExtraMuon=cms.InputTag("l1extraParticles"), TagL1ExtraIsoEG=cms.InputTag("l1extraParticles", "Isolated"),...
attic/iterables/CACM/less_more.py
matteoshen/example-code
5,651
12725166
<reponame>matteoshen/example-code """ <NAME> - The Curse of the Excluded Middle DOI:10.1145/2605176 CACM vol.57 no.06 """ def less_than_30(n): check = n < 30 print('%d < 30 : %s' % (n, check)) return check def more_than_20(n): check = n > 20 print('%d > 20 : %s' % (n, check)) return check l =...
src/quicknlp/metrics.py
jalajthanaki/quick-nlp
287
12725175
<reponame>jalajthanaki/quick-nlp import torch from fastai.core import to_np import numpy as np from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction def token_accuracy(preds, targs): preds = torch.max(preds, dim=-1)[1] return (preds[:-1] == targs.data).float().mean() def perplexity(preds, t...
modelvshuman/datasets/info_mappings.py
TizianThieringer/model-vs-human
158
12725346
from abc import ABC class ImagePathToInformationMapping(ABC): def __init__(self): pass def __call__(self, full_path): pass class ImageNetInfoMapping(ImagePathToInformationMapping): """ For ImageNet-like directory structures without sessions/conditions: .../{category}/{im...
etc/base_config.py
yandexdataschool/everware
130
12725350
# Basic configuration, you should not use this directly # instead checkout local_config.py or local_dockermacine_config.py # spawn with custom docker containers c.JupyterHub.spawner_class = 'everware.CustomDockerSpawner' c.Spawner.tls = False c.Spawner.debug = True c.Spawner.start_timeout = 1000 c.Spawner.http_time...
third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/models/testharness_results_unittest.py
wenfeifei/miniblink49
5,964
12725381
# 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 webkitpy.layout_tests.models import testharness_results class TestHarnessResultCheckerTest(unittest.TestCase): def test_is_testh...
src/oscar_accounts/management/commands/oscar_accounts_init.py
n8snyder/django-oscar-accounts
149
12725438
from django.core.management.base import BaseCommand from oscar_accounts.setup import create_default_accounts class Command(BaseCommand): help = "Initialize oscar accounts default structure" def handle(self, *args, **options): create_default_accounts()
utils/font_tool.py
gregbugaj/TextGenerator
166
12725462
<gh_stars>100-1000 from fontTools.fontBuilder import TTFont fonts = {} def check(char, font_path): if font_path in fonts: font = fonts.get(font_path) else: font = TTFont(font_path) fonts[font_path] = font utf8_char = char.encode("unicode_escape").decode('utf-8') if utf8_char....
lnbits/extensions/lnurlpos/migrations.py
blackcoffeexbt/lnbits-legend
258
12725469
async def m001_initial(db): """ Initial lnurlpos table. """ await db.execute( f""" CREATE TABLE lnurlpos.lnurlposs ( id TEXT NOT NULL PRIMARY KEY, key TEXT NOT NULL, title TEXT NOT NULL, wallet TEXT NOT NULL, currency TEXT NOT ...
Chapter 05/crack_zip.py
Prakshal2607/Effective-Python-Penetration-Testing
346
12725477
import zipfile filename = 'test.zip' dictionary = 'passwordlist.txt' password = None file_to_open = zipfile.ZipFile(filename) with open(dictionary, 'r') as f: for line in f.readlines(): password = line.strip('\n') try: file_to_open.extractall(pwd=password) password = '<PASSWORD>' % password print passwo...
notebook/random_random.py
vhn0912/python-snippets
174
12725509
import random print(random.random()) # 0.4496839011176701 random.seed(0) print(random.random()) # 0.8444218515250481 print(random.random()) # 0.7579544029403025 random.seed(0) print(random.random()) # 0.8444218515250481 print(random.random()) # 0.7579544029403025
dreamplace/ops/density_overflow/density_overflow.py
xiefei1026/DREAMPlace
323
12725524
## # @file density_overflow.py # @author <NAME> # @date Jun 2018 # @brief Compute density overflow # import math import torch from torch import nn from torch.autograd import Function from dreamplace.ops.density_map.density_map import DensityMap as DensityMap import pdb class DensityOverflow(DensityMap): "...
tests/deployment/sagemaker/sagemaker_moto/__init__.py
Shumpei-Kikuta/BentoML
3,451
12725594
<reponame>Shumpei-Kikuta/BentoML<gh_stars>1000+ from moto.core.models import base_decorator from tests.deployment.sagemaker.sagemaker_moto.model import sagemaker_backends moto_mock_sagemaker = base_decorator(sagemaker_backends)