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
sampleproject/demoapp/urls.py
ms-boom/django-easy-select2
186
11042544
<gh_stars>100-1000 from django.urls import path from .views import NoteCreateView, NoteEditView, NoteListView urlpatterns = [ path('', NoteListView.as_view(), name='note-list'), path('create', NoteCreateView.as_view(), name='note-create'), path('<pk>/edit', NoteEditView.as_view(), name='note-edit'), ]
neutronclient/tests/unit/osc/v2/logging/fakes.py
casual-lemon/python-neutronclient
120
11042547
# Copyright 2017 FUJITSU LIMITED # 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 b...
libs/rpy2-2.9.3/rpy/robjects/tests/testVector.py
walbaum1994/python-ml-course
655
11042551
<reponame>walbaum1994/python-ml-course<filename>libs/rpy2-2.9.3/rpy/robjects/tests/testVector.py import unittest import rpy2.robjects as robjects ri = robjects.rinterface import array, time, sys import time import datetime import rpy2.rlike.container as rlc from collections import OrderedDict if sys.version_info[0] ==...
easyquotation/timekline.py
rayshifu/easyquotation
3,630
11042557
# coding:utf8 """ # pylint: disable=line-too-long url = "http://data.gtimg.cn/flashdata/hushen/minute/sz000001.js?maxage=110&0.28163905744440854" """ import re from . import basequotation, helpers class TimeKline(basequotation.BaseQuotation): """腾讯免费行情获取""" max_num = 1 @property def stock_api(self)...
test/examples/python3/typical_class.py
EraYaN/transpyle
107
11042583
class MyTypicalClass: def __init__(self, arg1: int, arg2: int): self.arg1 = arg1 self.arg2 = arg2 def check(self) -> bool: return self.arg1 == self.arg2 def do_sth(self, my_arg: int) -> None: if my_arg < 0: print('negative') elif my_arg > 0: ...
tests/vfs/vshadow_file_entry.py
dfjxs/dfvfs
176
11042593
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the file entry implementation using pyvshadow.""" import unittest from dfvfs.lib import definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from dfvfs.vfs import vshadow_file_entry from dfvfs.vfs import vshadow_f...
slowfast/datasets/frame_loader.py
dylan-campbell/Motionformer
153
11042616
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import os import torch from . import utils as utils from .decoder import get_start_end_idx def temporal_sampling( num_frames, start_idx, end_idx, num_samples, start_frame=0 ): """ Given the start and end frame ...
synapse/lib/scrape.py
vertexproject/synapse
216
11042620
<reponame>vertexproject/synapse import logging import collections import idna import regex import unicodedata import synapse.data as s_data import synapse.lib.crypto.coin as s_coin logger = logging.getLogger(__name__) tldlist = list(s_data.get('iana.tlds')) tldlist.sort(key=lambda x: len(x)) tldlist.reverse() t...
tcconfig/_shaping_rule_finder.py
personalcomputer/tcconfig
644
11042637
""" .. codeauthor:: <NAME> <<EMAIL>> """ from simplesqlite.query import And, Where from ._const import Tc, TrafficDirection from ._network import is_anywhere_network from .parser._model import Filter, Qdisc from .parser.shaping_rule import TcShapingRuleParser class TcShapingRuleFinder: @property def _parse...
Python/Interfacing_C_C++_Fortran/Ctypes/stats.py
Gjacquenot/training-material
115
11042659
#!/usr/bin/env python from ctypes import Structure, cdll, c_double, c_int import os class Stats(Structure): _fields_ = [ ('mean', c_double), ('stddev', c_double), ('n', c_int) ] _stats = None def get_stats(n): global _stats if _stats is None: lib = cdll.LoadLibrary...
tests/test_scheduler_base.py
FingerCrunch/scrapy
41,267
11042662
from typing import Dict, Optional from unittest import TestCase from urllib.parse import urljoin, urlparse from testfixtures import LogCapture from twisted.internet import defer from twisted.trial.unittest import TestCase as TwistedTestCase from scrapy.core.scheduler import BaseScheduler from scrapy.crawler import Cr...
modules/templates/locations/PE/config.py
whanderley/eden
205
11042695
<reponame>whanderley/eden # -*- coding: utf-8 -*- from gluon import current def config(settings): """ Template settings for Peru - designed to be used in a Cascade with an application template """ #T = current.T # Pre-Populate settings.base.prepopulate.append("locations/PE") ...
scripts/imitation/visualize.py
kvas7andy/ngsim_env
127
11042735
<reponame>kvas7andy/ngsim_env<gh_stars>100-1000 import matplotlib matplotlib.use('agg') import pylab as plt import numpy as np import os import sys import utils import visualize_utils file_name_id = "" if len(sys.argv) > 1: file_name_id = str(sys.argv[1]) model_labels = [ 'singleagent_def_1_fine', 'singl...
cockpit/instruments/performance_gauge.py
wx-b/cockpit
367
11042798
"""Performance Gauge.""" import warnings import seaborn as sns from cockpit.instruments.utils_instruments import ( _add_last_value_to_legend, check_data, create_basic_plot, ) def performance_gauge(self, fig, gridspec): """Plotting train/valid accuracy vs. epoch and mini-batch loss vs. iteration. ...
styleframe/command_line/tests/__init__.py
Jacaranda-Health/StyleFrame
308
11042857
import styleframe as sf import os tests_commandline_dir = os.path.join(os.path.dirname(sf.__file__), 'command_line', 'tests') TEST_JSON_FILE = os.path.join(tests_commandline_dir, 'test_json.json') TEST_JSON_STRING_FILE = os.path.join(tests_comma...
saleor/payment/migrations/0012_transaction_customer_id.py
elwoodxblues/saleor
15,337
11042930
<reponame>elwoodxblues/saleor<filename>saleor/payment/migrations/0012_transaction_customer_id.py<gh_stars>1000+ # Generated by Django 2.2.2 on 2019-06-28 12:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("payment", "0011_auto_20190516_0901")] operations ...
src/utils/save_img.py
ShanzhiGu/EverybodyDanceNow_reproduce_pytorch
544
11042931
<gh_stars>100-1000 import numpy as np import cv2 def main(): vc = cv2.VideoCapture(0) if vc.isOpened(): is_capturing, _ = vc.read() else: is_capturing = False cnt = 0 while is_capturing: is_capturing, img = vc.read() # img = img[:, 80:80+480] cv2.imwrite('.....
django_sharding_library/decorators.py
waveaccounting/django-sharding
212
11042936
from six import iteritems from django.conf import settings from django.apps import apps from django_sharding_library.constants import Backends from django_sharding_library.exceptions import NonExistentDatabaseException, ShardedModelInitializationException from django_sharding_library.fields import ShardedIDFieldMixin...
lizard_ext/lizardoutside.py
jackhj000/lizard
1,255
11042970
<filename>lizard_ext/lizardoutside.py<gh_stars>1000+ ''' This is an extension of lizard, that counts the complexity outside functions ''' class LizardExtension(object): # pylint: disable=R0903 def __call__(self, tokens, reader): for token in tokens: yield token # adding the global ps...
tests/test_aocd.py
azuline/advent-of-code-data
255
11042971
<reponame>azuline/advent-of-code-data import aocd import pytest def test_get_data_imported_from_class(): from aocd import get_data assert aocd._module.get_data is get_data def test_get_data_via_import(mocker): fake_stack = [("~/2017/q23.py",)] mocker.patch("aocd.get.traceback.extract_stack", return...
tools/extract_font_charset.py
KoryakovDmitry/synthtiger
153
11043007
<filename>tools/extract_font_charset.py """ SynthTIGER Copyright (c) 2021-present NAVER Corp. MIT license """ import argparse import os import pprint import time import traceback import unicodedata from concurrent.futures import ProcessPoolExecutor, as_completed from fontTools.ttLib import TTFont from pygame import f...
scripts/ch2_hyperplane.py
mathkann/understanding-random-forests
353
11043057
<filename>scripts/ch2_hyperplane.py import numpy as np import pylab as pl from sklearn import svm blue = (0, 0, 1.0) red = (1.0, 0, 0) gray = (0.7, 0.7, 0.7) # we create 40 separable points X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] Y = [0] * 20 + [1] * 20 # fit the model clf = svm.S...
tests/test__not_implemented.py
ehiggs-deliverect/mongomock
574
11043091
import unittest import mongomock class NotImplementedTests(unittest.TestCase): def tearDown(self): mongomock.warn_on_feature('session') def test_raises(self): collection = mongomock.MongoClient().db.collection with self.assertRaises(NotImplementedError): collection.inser...
stocklook/patterns/insidebars.py
zbarge/stocklook
149
11043095
from stocklook.patterns.pattern import Pattern class InsideBars(Pattern): @property def mother_candle(self): return self.data[-1] @property def high(self): return self.mother_candle[1] @property def low(self): return self.mother_candle[2] def __repr__(self): ...
sdk/storage/azure-storage-queue/azure/storage/queue/aio/__init__.py
rsdoherty/azure-sdk-for-python
2,728
11043100
<gh_stars>1000+ # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ---------------------------------------------------------------------...
paas-ce/paas/paas/saas/migrations/0002_auto_20161025_2016.py
renmcc/bk-PaaS
767
11043121
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
lightreid/optim/lr_scheduler/__init__.py
nataliamiccini/light-reid
296
11043126
from .warmup_steplr import WarmupMultiStepLR from .decayed_cosinelr import DelayedCosineAnnealingLR from .warmup_cosinelr import WarmupCosineAnnealingLR
AssetStudio/pkg.py
kakacoding/pkg-doctor
128
11043173
# -*- en coding: utf-8 -*- from __future__ import unicode_literals import sys import csv import json from io import open from os import path from collections import OrderedDict if sys.version_info.major < 3: reload(sys) sys.setdefaultencoding('utf8') markdeep_head = """ <meta charset="utf-8" emacsmode="-*- m...
src/sage/schemes/jacobians/all.py
fchapoton/sage
1,742
11043186
#from abstract_jacobian import is_Jacobian, Jacobian
tern/analyze/default/container/run.py
shrikanta8/tern
325
11043191
# -*- coding: utf-8 -*- # # Copyright (c) 2019-2021 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause """ Run analysis on a container image """ import logging from tern.utils import constants from tern.utils import rootfs from tern.report import report from tern.report import formats from ter...
api/v2/serializers/summaries/credential.py
simpsonw/atmosphere
197
11043215
from core.models import Credential from rest_framework import serializers class CredentialSummarySerializer(serializers.ModelSerializer): class Meta: model = Credential fields = ( 'id', 'key', 'clean_value', )
sympy/run_test.py
nikicc/anaconda-recipes
642
11043233
import sympy from sympy import Rational a = Rational(14, 4) assert str(a) == '7/2'
setup.py
wis/gdom
1,323
11043241
from setuptools import setup, find_packages setup( name='gdom', version='1.0.0', download_url='https://github.com/syrusakbary/gdom/archive/master.zip', packages=find_packages(), author='<NAME>', author_email='<EMAIL>', description='DOM Traversing and Scraping using GraphQL', long_descri...
test/__init__.py
Havaldar/pyABC
144
11043245
<reponame>Havaldar/pyABC """Unit tests for pyABC."""
Data Structures and Algorithms Nanodegree/P4 - Route Planner/student_code.py
vkbhandare/Udacity-1
149
11043263
<reponame>vkbhandare/Udacity-1<gh_stars>100-1000 import math from queue import PriorityQueue def shortest_path(graph, start, goal): pathQueue = PriorityQueue() pathQueue.put(start, 0) prev = {start: None} score = {start: 0} while not pathQueue.empty(): curr = pathQueue.get() ...
tests/test_style/test_palettes.py
mmorrison1670/yellowbrick
3,662
11043276
# tests.test_style.test_palettes # Tests the palettes module of the yellowbrick library. # # Author: <NAME> <<EMAIL>> # Created: Tue Oct 04 16:21:58 2016 -0400 # # Copyright (C) 2016 The scikit-yb developers # For license information, see LICENSE.txt # # ID: test_palettes.py [c6aff34] <EMAIL> $ """ Tests the palett...
tests/forte/data/readers/ontonotes_reader_test.py
jzpang/forte
163
11043317
# Copyright 2019 The Forte 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 applicable ...
build/scripts/gen_swiftc_output_map.py
HeyLey/catboost
6,989
11043333
import json import sys def just_do_it(args): source_root, build_root, out_file, srcs = args[0], args[1], args[2], args[3:] assert(len(srcs)) result_obj = {} for src in srcs: result_obj[src] = {'object': src.replace(source_root, build_root) + '.o'} with open(out_file, 'w') as of: of...
2013/Round B/Problem A/A-solution.py
prashantsingh2408/Google-Kick-Start
237
11043342
from itertools import product T = int(input()) for x in range(1, T + 1): N = int(input()) matrix = [] uniques = set(range(1, N ** 2 + 1)) valid = True for row_index in range(N ** 2): row = list(map(int, input().split())) matrix.append(row) if valid and set(row) != uniques: ...
tests/e2e/scale/conftest.py
annagitel/ocs-ci
130
11043354
<reponame>annagitel/ocs-ci<gh_stars>100-1000 import logging from ocs_ci.framework import config from ocs_ci.ocs import constants log = logging.getLogger(__name__) def pytest_collection_modifyitems(items): """ A pytest hook to skip tests from summary report Args: items: list of collected tests ...
tacker/tests/functional/vnfm/test_vnfm_param.py
takahashi-tsc/tacker
116
11043382
# Copyright 2015 Brocade Communications System, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
wyze_sdk/models/events/__init__.py
RebelTat/wyze-sdk
132
11043398
from __future__ import annotations import logging from datetime import datetime from enum import Enum from typing import Optional, Sequence, Set, Tuple, Union from wyze_sdk.models import (JsonObject, epoch_to_datetime, show_unknown_key_warning) class EventAlarmType(Enum): """ Se...
tests/test_version.py
chrononyan/ok
148
11043405
<reponame>chrononyan/ok<gh_stars>100-1000 import datetime import json from server.models import db, Assignment, Backup, Course, User, Version from server.utils import encode_id from server.forms import VersionForm from tests import OkTestCase class TestVersion(OkTestCase): def setUp(self): super().setUp(...
src/nlpia/book/examples/ch05u01_your_first_neuron.py
byukan/nlpia
532
11043453
<reponame>byukan/nlpia # ch05m01_your_first_neuron.py import numpy as np from keras.layers import Dense, Activation from keras.models import Sequential # OR logic gate inputs and output. # x_train is sample data (input features) # y_train the expected outcome for example x_train = np.array([[0, 0], ...
scripts/visual_feature_layer.py
peaceofmind123/esrgan_modified
137
11043454
<reponame>peaceofmind123/esrgan_modified # Copyright 2021 Dakewe Biotech Corporation. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/li...
MicroTokenizer/tokenizers/dag_tokenizer.py
howl-anderson/MicroTokenizer
136
11043490
<reponame>howl-anderson/MicroTokenizer<gh_stars>100-1000 from typing import Dict, List from MicroTokenizer import get_dict_file from MicroTokenizer.data_structures.dictionary import DictionaryData from MicroTokenizer.data_structures.non_recursive_algorithm import NonRecursiveAlgorithm from MicroTokenizer.data_structur...
benchmark/deepspeed/pretrain_gpt2_moe.py
yf225/alpa
114
11043498
<gh_stars>100-1000 # coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. 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/LICENS...
awswrangler/dynamodb/__init__.py
isichei/aws-data-wrangler
2,695
11043534
<reponame>isichei/aws-data-wrangler """Amazon DynamoDB Write Module.""" from awswrangler.dynamodb._delete import delete_items from awswrangler.dynamodb._utils import get_table from awswrangler.dynamodb._write import put_csv, put_df, put_items, put_json __all__ = ["delete_items", "get_table", "put_csv", "put_df", "put...
src/robusta/core/reporting/callbacks.py
kandahk/robusta
273
11043561
import time from pydantic import BaseModel from robusta.core.reporting.action_requests import ( sign_action_request, ExternalActionRequest, ActionRequestBody, ) from . import CallbackChoice from ..playbooks.actions_registry import Action class ExternalActionRequestBuilder(BaseModel): @classmethod ...
tests/build/test_helpers.py
zyfra/ebonite
270
11043564
import pytest from ebonite.build.helpers import validate_kwargs class A: @validate_kwargs def method1(self, a, b, **kwargs): return a, b @validate_kwargs(allowed=['c']) def method2(self, a, b, **kwargs): return a, b, kwargs.get('c') def test_validate_kwargs(): a = A() asse...
test/fixtures/code/input/example.py
kokizzu/src2png
2,431
11043601
<gh_stars>1000+ # -*- coding: utf-8 -*- from flask import ( Blueprint, render_template, session, g, flash, request, redirect, url_for, current_app ) from accounts.models import User from accounts.forms import ( LoginForm, SignupForm, SignupConfirmForm, RecoverPasswordForm, RecoverPasswordConfirmForm ) f...
Custom/events/AutomaticPreviewJobSubmission/AutomaticPreviewJobSubmission.py
ThinkboxSoftware/Deadline
113
11043678
from Deadline.Events import * from Deadline.Scripting import * ################################################################################## ## This is the function that Deadline calls to get an instance of the ## main DeadlineEventListener class. ##################################################################...
leetcode.com/python/1315_Sum_of_Nodes_with_Even_Valued_Grandparent.py
mamane19/coding-interview-gym
713
11043706
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # Top-Down class Solution(object): def sumEvenGrandparent(self, root): """ :type root: TreeNode ...
tests/test_convert.py
SliverChen/py3dtiles
183
11043720
<filename>tests/test_convert.py # -*- coding: utf-8 -*- import os from pytest import approx, raises import shutil from py3dtiles import convert_to_ecef from py3dtiles.convert import convert, SrsInMissingException def test_convert_to_ecef(): # results tested with gdaltransform [x, y, z] = convert_to_ecef(-75....
tests/osc/test_osc_OscMessage.py
butayama/supriya
191
11043742
import uqbar.strings import supriya def test(): osc_message = supriya.osc.OscMessage( "/foo", 1, 2.5, supriya.osc.OscBundle( contents=( supriya.osc.OscMessage("/bar", "baz", 3.0), supriya.osc.OscMessage("/ffff", False, True, None), ...
v2/auart_hd.py
Dilepa/micropython-async
443
11043755
<reponame>Dilepa/micropython-async<gh_stars>100-1000 # auart_hd.py # Author: <NAME> # Copyright <NAME> 2018 Released under the MIT license # Demo of running a half-duplex protocol to a device. The device never sends # unsolicited messages. An example is a communications device which responds # to AT commands. # The ma...
examples/logdna_example.py
ChihweiLHBird/sanic
4,959
11043768
import logging import socket from os import getenv from platform import node from uuid import getnode as get_mac from logdna import LogDNAHandler from sanic import Sanic from sanic.response import json from sanic.request import Request log = logging.getLogger('logdna') log.setLevel(logging.INFO) def get_my_ip_addr...
angr/engines/soot/statements/identity.py
Kyle-Kyle/angr
6,132
11043796
import logging from .base import SimSootStmt l = logging.getLogger('angr.engines.soot.statements.identity') class SimSootStmt_Identity(SimSootStmt): def _execute(self): dst = self._translate_value(self.stmt.left_op) src_expr = self._translate_expr(self.stmt.right_op) src_val = src_expr....
nncf/common/tensor_statistics/reduction.py
MaximProshin/nncf
136
11043799
""" Copyright (c) 2022 Intel 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 applicable law or agreed to in writin...
pyscript/metrics/__init__.py
takuto0831/Competition-utils
105
11043800
<filename>pyscript/metrics/__init__.py from .base import * from .regression import * from .classification import *
python/163_Missing_Ranges.py
dvlpsh/leetcode-1
4,416
11043811
class Solution(object): def findMissingRanges(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: List[str] """ ranges = [] prev = lower - 1 for i in range(len(nums) + 1): if i == len(nums)...
examples/textArea.py
tgolsson/appJar
666
11043823
import sys sys.path.append("../") from appJar import gui def press(btn=None): if btn == "CLEAR": app.clearTextArea("t1", callFunction=app.getCheckBox("CALL")) elif btn == "SET": app.setTextArea("t1", app.getEntry("text"), callFunction=app.getCheckBox("CALL"), end=app.getCheckBox("END")) els...
test_project/test_app/forms.py
kadamsagar039/python-sonar
530
11043827
from django import forms from .models import Data class NameForm(forms.Form): name = forms.CharField(max_length=255) class DataForm(forms.ModelForm): class Meta: model = Data fields = ['name']
src/tests/files_test.py
swellander/tryceratops
269
11043833
import ast import os from tryceratops.files.parser import parse_file from tryceratops.filters import IgnoreViolation def get_full_path(filename: str): ref_dir = f"{os.path.dirname(__file__)}/samples/ignore_comments/" path = f"{ref_dir}{filename}.py" return path def test_parse_ignore_line(): filenam...
vegans/utils/architectures/mnist.py
unit8co/vegans
459
11043862
import pickle import numpy as np import torch.nn as nn from vegans.utils.utils import get_input_dim from vegans.utils.layers import LayerReshape, LayerPrintSize, LayerInception, LayerResidualConvBlock def preprocess_mnist(torch_data, normalize=True, pad=None): """Load the mnist data from root. Parameters ...
mmsr/models/archs/ref_restoration_arch.py
yumingj/C2-Matching
111
11043889
<filename>mmsr/models/archs/ref_restoration_arch.py import mmsr.models.archs.arch_util as arch_util import torch import torch.nn as nn import torch.nn.functional as F from mmsr.models.archs.DCNv2.dcn_v2 import DCN_sep_pre_multi_offset as DynAgg class ContentExtractor(nn.Module): def __init__(self, in_nc=3, out_n...
mead/api_examples/preproc_tlm.py
shar999/mead-baseline
241
11043900
import glob import gzip import sys import argparse import baseline from baseline.vectorizers import BPEVectorizer1D, WordpieceVectorizer1D from mead.api_examples.preproc_utils import * from eight_mile.utils import ( write_yaml, ) from typing import Optional import numpy as np import os try: import jsonlines ...
chaospy/distributions/sampler/latin_hypercube.py
utsekaj42/chaospy
333
11043913
<filename>chaospy/distributions/sampler/latin_hypercube.py """ Create Latin Hyper-cube samples. Example usage ------------- Normal usage:: >>> chaospy.create_latin_hypercube_samples(order=4, dim=2).round(4) array([[0.6634, 0.2788, 0.9876, 0.1205], [0.4681, 0.0531, 0.5102, 0.8493]]) """ import numpy...
tbx/taxonomy/admin.py
torchbox/wagtail-torchbox
103
11043937
from django.conf.urls import url from django.contrib.admin.utils import quote from django.core.exceptions import PermissionDenied from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from wagtail.contrib.modeladmin.helpers import ButtonHelper from wagtail.contrib.model...
scripts/utils/hdr.py
efedo/renderer
1,857
11043955
import math import re # # standard conversions # def _float_to_rgbe(rv, gv, bv): assert isinstance(rv, float) # red value assert isinstance(gv, float) # green value assert isinstance(bv, float) # blue value max_v = max(rv, gv, bv) if max_v < 1e-32: rm = 0 # red mantissa gm =...
tests/test_0120-autograd-support.py
BioGeek/awkward-1.0
519
11043972
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE from __future__ import absolute_import import pytest # noqa: F401 import numpy as np # noqa: F401 import awkward as ak # noqa: F401 autograd = pytest.importorskip("autograd") def tanh(x): y = np.exp(-2.0 * x) return ...
app/state/sessions.py
cmyui/gulag
187
11043980
from typing import TYPE_CHECKING from app.objects.collections import Channels from app.objects.collections import Clans from app.objects.collections import MapPools from app.objects.collections import Matches from app.objects.collections import Players if TYPE_CHECKING: from app.objects.achievement import Achieve...
evaluation/webnlg-automatic-evaluation/evaluation.py
sedrickkeh/dart
107
11044022
from benchmark_reader import Benchmark from collections import defaultdict from unidecode import unidecode import re import os from natsort import natsorted import sys categories = ['Astronaut', 'Airport', 'Monument', 'University', 'Food', 'SportsTe...
datasets/refresd/refresd.py
zidingz/datasets
10,608
11044037
# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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/lice...
pychromecast/models.py
strunker/pychromecast
1,874
11044072
""" Chromecast types """ import asyncio from collections import namedtuple import zeroconf ZEROCONF_ERRORS = (IOError, asyncio.TimeoutError) if hasattr(zeroconf, "EventLoopBlocked"): # Added in zeroconf 0.37.0 ZEROCONF_ERRORS = (*ZEROCONF_ERRORS, zeroconf.EventLoopBlocked) CastInfo = namedtuple( "CastInf...
bookwyrm/migrations/0019_auto_20201130_1939.py
mouse-reeve/fedireads
270
11044073
# Generated by Django 3.0.7 on 2020-11-30 19:39 import bookwyrm.models.fields from django.db import migrations def update_notnull(app_registry, schema_editor): db_alias = schema_editor.connection.alias users = app_registry.get_model("bookwyrm", "User") for user in users.objects.using(db_alias): i...
tests/cpydiff/types_tuple_subscrstep.py
learnforpractice/micropython-cpp
13,648
11044109
<reponame>learnforpractice/micropython-cpp<filename>tests/cpydiff/types_tuple_subscrstep.py """ categories: Types,tuple description: Tuple load with step != 1 not implemented cause: Unknown workaround: Unknown """ print((1, 2, 3, 4)[0:4:2])
data_process/gen_label.py
dreamerlin/MVFNet
102
11044122
"""Generate list of train/val set for multiple video datasets""" import argparse import json import os import os.path as osp import shutil def parse_args(): """Build file label list""" parser = argparse.ArgumentParser(description='Build file label list') parser.add_argument('data_path', type=str, ...
components/iscesys/Traits/Datetime.py
vincentschut/isce2
1,133
11044131
<reponame>vincentschut/isce2 #!/usr/bin/env python3 import datetime as DT dtformat = "%Y-%m-%d %H:%M:%S.%f" dtformat1 = "%Y-%m-%d %H:%M:%S" class datetimeType(DT.datetime): ''' Override inbuilt datetime.datetime to add functionality. ''' def __new__(self, *args, **kwargs): ''' Overri...
tars/deployment/mixins.py
js882829/tars
371
11044132
<reponame>js882829/tars<filename>tars/deployment/mixins.py import logging import operator import time from django.db import transaction from django.contrib.auth.models import User as django_user from constance import config from roll_engine.utils.log import get_logger from django.test import RequestFactory from rest_...
packages/cq-treesitter-engine/test/data/class.py
pozymasika/cq
114
11044169
import mycats class Cat(object): def __init__(self, name): self.name = name def meow(self): print 'Im a talking cat' pickles = Cat('pickles') pickles.meow()
scale.app/scripts/sloc.py
f4rsh/SCALe
239
11044184
#!/usr/bin/env python # Copyright (c) 2007-2018 Carnegie Mellon University. All Rights Reserved. # See COPYRIGHT file for details. import sys import argparse import re parser = argparse.ArgumentParser(description="Converts program code into 'significant' code, sans comments & whitespace", epilog=''' Takes program c...
clif/testing/python/slots_test.py
wangxf123456/clif
966
11044190
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
python/RawNet2_modified/utils.py
ishine/RawNet
199
11044193
<gh_stars>100-1000 import os import zipfile import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn def keras_lr_decay(step, decay=0.0001): return 1.0 / (1.0 + decay * step) def init_weights(m): print(m) if isinstance(m, nn.Linear): torch.nn.init.xavier_uniform(m.we...
scrapera/image/duckduckgo.py
Baras64/Scrapera
300
11044239
<gh_stars>100-1000 import asyncio import json import os import random import re import urllib.parse import uuid import warnings import aiofiles import aiohttp from bs4 import BeautifulSoup class DuckDuckGoScraper: def __init__(self): self.headers = {"accept": "text/html,application/xhtml+xml,application/x...
nautobot/core/management/commands/generate_secret_key.py
psmware-ltd/nautobot
384
11044256
from django.core.management.base import BaseCommand from django.core.management.utils import get_random_secret_key class Command(BaseCommand): help = "Generates a new SECRET_KEY that can be used in a project settings file." requires_system_checks = False def handle(self, *args, **options): retur...
qcengine/programs/gamess/__init__.py
jhrmnn/QCEngine
105
11044276
<reponame>jhrmnn/QCEngine from .runner import GAMESSHarness
utils/speech/compute_cmvn_stats.py
didichuxing/delta
1,442
11044294
#!/usr/bin/env python3 # Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. # 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://ww...
attacks/lcg/truncated_state_recovery.py
jvdsn/crypto-attacks
139
11044319
from sage.all import QQ from sage.all import ZZ from sage.all import matrix from sage.all import vector def attack(y, k, s, m, a, c): """ Recovers the states associated with the outputs from a truncated linear congruential generator. More information: <NAME> al., "Reconstructing Truncated Integer Variable...
notMNIST/notMNIST.py
shekkizh/TensorflowProjects
204
11044349
<filename>notMNIST/notMNIST.py __author__ = 'Charlie' import read_notMNIST import numpy as np import os, sys, inspect import tensorflow as tf from six.moves import range utils_path = os.path.realpath( os.path.abspath(os.path.join(os.path.split(inspect.getfile(inspect.currentframe()))[0], ".."))) if utils_path not ...
extra_tests/snippets/funky_syntax.py
dbrgn/RustPython
11,058
11044535
<reponame>dbrgn/RustPython<gh_stars>1000+ import traceback a = 2 b = 2 + 4 if a < 5 else 'boe' assert b == 6 c = 2 + 4 if a > 5 else 'boe' assert c == 'boe' d = lambda x, y: x > y assert d(5, 4) e = lambda x: 1 if x else 0 assert e(True) == 1 assert e(False) == 0 try: a = "aaaa" + \ "bbbb" 1/0 except ZeroDivisi...
carla/evaluation/process_nans.py
jayanthyetukuri/CARLA
140
11044587
<reponame>jayanthyetukuri/CARLA from typing import Tuple import pandas as pd def remove_nans( factuals: pd.DataFrame, counterfactuals: pd.DataFrame ) -> Tuple[pd.DataFrame, pd.DataFrame]: """ Parameters ---------- factuals: Has to be the same shape as counterfactuals counterfactuals: Has to ...
accelerator/examples/build_dsexample-iterate.py
eBay/accelerator
143
11044614
from .printer import prt description = "Dataset: Iterate" def main(urd): prt.source(__file__) prt() prt('Run a method that creates a dataset.') job = urd.build('dsexample_createdataset') prt() prt('Iterate and merge the number column of the dataset.') job = urd.build('dsexample_iterateandmerge', source=job) ...
pycoin/coins/groestlcoin/hash.py
jaschadub/pycoin
1,210
11044615
<gh_stars>1000+ import hashlib from pycoin.encoding.hexbytes import bytes_as_revhex def sha256(data): return bytes_as_revhex(hashlib.sha256(data).digest()) def groestlHash(data): """Groestl-512 compound hash.""" try: import groestlcoin_hash except ImportError: t = 'Groestlcoin requi...
framework/Optimizers/acceptanceConditions/AcceptanceCondition.py
rinelson456/raven
159
11044658
<filename>framework/Optimizers/acceptanceConditions/AcceptanceCondition.py # Copyright 2017 Battelle Energy Alliance, 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...
tests/por.py
sublee/hangulize
145
11044680
<reponame>sublee/hangulize<filename>tests/por.py # -*- coding: utf-8 -*- from tests import HangulizeTestCase from hangulize.langs.por import Portuguese class PortugueseTestCase(HangulizeTestCase): """ http://korean.go.kr/09_new/dic/rule/rule_foreign_0219.jsp """ lang = Portuguese() def test_1s...
tests/bitcoin/test_script_interpreter.py
febuiles/two1-python
415
11044683
import pytest from two1.bitcoin.hash import Hash from two1.bitcoin.exceptions import ScriptInterpreterError from two1.bitcoin.script import Script from two1.bitcoin.script_interpreter import ScriptInterpreter from two1.bitcoin.txn import Transaction from two1.bitcoin.txn import TransactionInput from two1.bitcoin.txn i...
python/pong.py
arganoid/allegro5
1,538
11044685
#!/usr/bin/env python3 """ Allegro Python port game example Original Author: <NAME> """ from allegro import * from random import randint, random import os examples_data = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "examples/data")) class Pallet: def __init__(self, x, y, w, h, speed...
amazon_problems/problem_7.py
loftwah/Daily-Coding-Problem
129
11044686
<filename>amazon_problems/problem_7.py<gh_stars>100-1000 """This problem was asked by Amazon. Given a string s and an integer k, break up the string into multiple texts such that each text has a length of k or less. You must break it up so that words don't break across lines. If there's no way to break the text up, ...
home-assistant/custom_components/ai_thermostat/models/utils.py
denysdovhan/smart-home
128
11044688
import asyncio import logging from datetime import datetime, timedelta from custom_components.ai_thermostat.helpers import convert_decimal, set_trv_values _LOGGER = logging.getLogger(__name__) def mode_remap(hvac_mode, modes): if modes is None: return hvac_mode if modes.get(hvac_mode) is not None: return mode...