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 |
|---|---|---|---|---|
lldb/packages/Python/lldbsuite/test/commands/command/script/callables.py | medismailben/llvm-project | 2,338 | 12621457 |
import lldb
# bunch of different kinds of python callables that should
# all work as commands.
def check(debugger, command, context, result, internal_dict):
if (not isinstance(debugger, lldb.SBDebugger) or
not isinstance(command, str) or
not isinstance(result, lldb.SBCommandReturnObject) or
... |
Packs/HealthCheck/Scripts/HealthCheckServerLog/HealthCheckServerLog.py | diCagri/content | 799 | 12621476 | import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
# noqa: F401
# noqa: F401
import re
def findOldestDate(incidentDate, newDate):
incidentDate = datetime.strptime(incidentDate, "%Y-%m-%d %H:%M:%S")
newDate = datetime.strptime(newDate, "%Y-%m-%d %H:%M:%S")
return min... |
extra_tests/snippets/os_info.py | dbrgn/RustPython | 11,058 | 12621483 | import os
assert os.name == 'posix' or os.name == 'nt'
|
release/stubs.min/Autodesk/Revit/DB/Structure/__init___parts/RebarContainerParameterManager.py | htlcnn/ironpython-stubs | 182 | 12621494 | <filename>release/stubs.min/Autodesk/Revit/DB/Structure/__init___parts/RebarContainerParameterManager.py
class RebarContainerParameterManager(object,IDisposable):
""" Provides implementation of RebarContainer parameters overrides. """
def AddOverride(self,paramId,value):
"""
AddOverride(self: RebarContainerPa... |
src/dialogs/folder.py | Sammmasqw/Facepager | 430 | 12621496 | <reponame>Sammmasqw/Facepager
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import QFileDialog, QCheckBox, QHBoxLayout, QLabel
class SelectFolderDialog(QFileDialog):
"""
Create a custom Folder Dialog with an option to import files as nodes
"""
def __init__(self,*args,... |
python-package/lightgbm/callback.py | PyVCEchecker/LightGBM | 5,753 | 12621514 | <reponame>PyVCEchecker/LightGBM
# coding: utf-8
"""Callbacks library."""
import collections
from functools import partial
from typing import Any, Callable, Dict, List, Tuple, Union
from .basic import _ConfigAliases, _log_info, _log_warning
_EvalResultTuple = Union[
List[Tuple[str, str, float, bool]],
List[Tup... |
my_projects/mechanism/Linkages_mechanism.py | cigar666/my_manim_projects | 159 | 12621525 | <gh_stars>100-1000
from manimlib.imports import *
from my_manim_projects.my_projects.mechanism.basic_component import *
class Four_bar_linkage(Scene):
def construct(self):
O1, O2 = LEFT * 2 + DOWN, RIGHT * 2. + DOWN
dot_O1 = Dot(O1, color=PINK)
dot_O2 = Dot(O2, color=PINK)
bar_1 ... |
var/spack/repos/builtin/packages/cmockery/package.py | kkauder/spack | 2,360 | 12621533 | <reponame>kkauder/spack<gh_stars>1000+
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Cmockery(AutotoolsPackage):
"""A lightweight librar... |
examples/ocr/v20181119/general_fast_ocr.py | snowxmas/tencentcloud-sdk-python | 465 | 12621534 | <gh_stars>100-1000
import os
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.... |
deep_architect/contrib/communicators/mpi_communicator.py | dapatil211/deep_architect | 272 | 12621548 | <filename>deep_architect/contrib/communicators/mpi_communicator.py
from mpi4py import MPI
from deep_architect.contrib.communicators.communicator import Communicator
"""
Tags for the requests used by the communicator
"""
READY_REQ = 0
MODEL_REQ = 1
RESULTS_REQ = 2
"""
Contains implementation for MPI based Communicator. ... |
Grand_Central_Robot_Xylophone/code.py | gamblor21/Adafruit_Learning_System_Guides | 665 | 12621552 | <filename>Grand_Central_Robot_Xylophone/code.py
# Adafruit Grand Central Robot Xylophone Demo Program
# <NAME> and <NAME> for Adafruit Industries
# MIT License
import time
import board
from digitalio import DigitalInOut, Direction
solenoid_count = 8 # Set the total number of solenoids used
start_pin = 2 # Star... |
.venv/lib/python3.8/site-packages/pandas/tests/frame/test_period.py | acrucetta/Chicago_COVI_WebApp | 115 | 12621567 | import numpy as np
from pandas import DataFrame, Index, PeriodIndex, period_range
import pandas._testing as tm
class TestPeriodIndex:
def test_as_frame_columns(self):
rng = period_range("1/1/2000", periods=5)
df = DataFrame(np.random.randn(10, 5), columns=rng)
ts = df[rng[0]]
tm.... |
selfdrive/dragonpilot/gpxd.py | kansakitw/dragonpilotamd | 251 | 12621577 | <reponame>kansakitw/dragonpilotamd
#!/usr/bin/env python3
# The MIT License
#
# Copyright (c) 2019-, <NAME>, dragonpilot community, and a number of other of contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software... |
tests/conftest.py | sdispater/poet | 367 | 12621579 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import os
import pytest
import tempfile
import shutil
from cleo.inputs.list_input import ListInput
from cleo.outputs.console_output import ConsoleOutput
from cleo.styles import CleoStyle
from poet.console import Application
from poet.console.commands.command import Command
... |
tests/test_server.py | pyGrowler/Growler | 806 | 12621609 | #
# tests/test_server.py
#
import pytest
import asyncio
import growler
@pytest.fixture
def app(event_loop):
app = growler.App(loop=event_loop)
return app
@pytest.fixture
def growler_server(app, event_loop, unused_tcp_port):
return app.create_server(host='127.0.0.1',
port=un... |
src/timeago/locales/pl.py | nmb10/timeago | 220 | 12621619 | <reponame>nmb10/timeago
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2018-11-11
@author: marcel-odya
'''
base = [
["właśnie teraz", "za chwilę"],
["%s sekund temu", "za %s sekund", "%s sekundy temu", "za %s sekundy"],
["minutę temu", "za minutę"],
["%s minut temu", "za %s minut", "%s m... |
RecoTracker/DeDx/python/dedxEstimatorsFromRefitter_cff.py | ckamtsikis/cmssw | 852 | 12621658 | <reponame>ckamtsikis/cmssw
import FWCore.ParameterSet.Config as cms
from RecoTracker.TrackProducer.TrackRefitter_cfi import *
RefitterForDeDx = TrackRefitter.clone(
TrajectoryInEvent = True
)
from RecoTracker.DeDx.dedxEstimators_cff import *
dedxHitInfo.tracks="RefitterForDeDx"
dedxHitInfo.trajectoryTrackAssoci... |
tools/sandbox/c7n_index/setup.py | al3pht/cloud-custodian | 2,415 | 12621687 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from setuptools import setup, find_packages
setup(
name="c7n_indexer",
version='0.0.2',
description="Cloud Custodian - Metrics/Resource Indexer",
classifiers=[
"Topic :: System :: Systems Administration",
"T... |
ocs_ci/utility/perf_dash/dashboard_api.py | srivickynesh/ocs-ci | 130 | 12621709 | <filename>ocs_ci/utility/perf_dash/dashboard_api.py
"""
API module to interact with the Performance Dashboard
In order to push results into the dashboard, and pulling data
from it to compare between results.
The DB structure is :
some tables which use for indexing values and all in the same structure:
... |
monero/daemon.py | successor1/wownero-python | 130 | 12621716 | import six
from .backends.jsonrpc import JSONRPCDaemon
class Daemon(object):
"""Monero daemon.
Provides interface to a daemon instance.
:param backend: a daemon backend
:param \\**kwargs: arguments to initialize a :class:`JSONRPCDaemon <monero.backends.jsonrpc.JSONRPCDaemon>`
... |
tests/common/test_run/ascend/transdata_matmul_run.py | tianjiashuo/akg | 286 | 12621741 | <gh_stars>100-1000
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
ide_server.py | vmr1532/Time2Code | 332 | 12621746 | <reponame>vmr1532/Time2Code
from flask import Flask, request, render_template, Markup
import requests
from urllib.parse import urlparse
import markdown
import os
import subprocess
import socket
app = Flask(__name__)
@app.route('/')
def time2code():
text = request.args.get('code')
lang = request.args.get('la... |
tests/rest_framework/__init__.py | A-Ashiq/django-filter | 2,512 | 12621769 | <reponame>A-Ashiq/django-filter<filename>tests/rest_framework/__init__.py
default_app_config = 'tests.rest_framework.apps.RestFrameworkTestConfig'
|
corehq/sql_proxy_accessors/migrations/0047_remove_get_case_models_functions.py | dimagilg/commcare-hq | 471 | 12621790 | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sql_proxy_accessors', '0046_get_ledger_values_for_cases_2'),
]
operations = [
migrations.RunSQL('DROP FUNCTION IF EXISTS get_case_transactions(TEXT)'),
migrations.Ru... |
migrations/versions/2191c871434_add_snapshot_model.py | vault-the/changes | 443 | 12621793 | """Add snapshot model
Revision ID: 2191c871434
Revises: 1<PASSWORD>
Create Date: 2014-07-17 17:21:42.915797
"""
# revision identifiers, used by Alembic.
revision = '2191c871434'
down_revision = '1<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'snapshot',
... |
Trakttv.bundle/Contents/Libraries/Shared/elapsed/__init__.py | disrupted/Trakttv.bundle | 1,346 | 12621813 | from elapsed.main import setup, reset, clock, format_report, print_report
__version__ = '1.0.0'
|
sonnet/src/parallel_linear_test.py | ScriptBox99/deepmind-sonnet | 10,287 | 12621815 | <filename>sonnet/src/parallel_linear_test.py<gh_stars>1000+
# Copyright 2019 The Sonnet 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.... |
src/sage/categories/graded_lie_algebras.py | bopopescu/sage | 1,742 | 12621821 | r"""
Graded Lie Algebras
AUTHORS:
- <NAME> (2018-08-16): initial version
"""
# ****************************************************************************
# Copyright (C) 2018 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Publ... |
Python/count_digit.py | OluSure/Hacktoberfest2021-1 | 215 | 12621822 | # python program to find how many digit in given integer numbers e.g. 123->3 , 737327->6 digit first we take log of base 10 then add 1.
from math import log,floor
print(floor(log(int(input()),10)+1))
|
tests/test_cfg.py | mohamedbakrey12/prpjectINDeepLearning | 122 | 12621846 | import os
import pytest
from hydra import compose, initialize
from omegaconf import DictConfig
config_files = [f.split('.')[0] for f in os.listdir('conf') if 'yaml' in f]
@pytest.mark.parametrize('config_name', config_files)
def test_cfg(config_name: str) -> None:
with initialize(config_path='../conf'):
... |
tensorflow/contrib/mpi_collectives/mpi_ops_test.py | tianyapiaozi/tensorflow | 848 | 12621855 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
testing/example_scripts/acceptance/fixture_mock_integration.py | markshao/pytest | 9,225 | 12621880 | <gh_stars>1000+
"""Reproduces issue #3774"""
from unittest import mock
import pytest
config = {"mykey": "ORIGINAL"}
@pytest.fixture(scope="function")
@mock.patch.dict(config, {"mykey": "MOCKED"})
def my_fixture():
return config["mykey"]
def test_foobar(my_fixture):
assert my_fixture == "MOCKED"
|
core/git_mixins/branches.py | timfjord/GitSavvy | 2,058 | 12621934 | from collections import namedtuple
import re
from GitSavvy.core.git_command import mixin_base
MYPY = False
if MYPY:
from typing import Dict, Iterable, Optional, Sequence
BRANCH_DESCRIPTION_RE = re.compile(r"^branch\.(.*?)\.description (.*)$")
Branch = namedtuple("Branch", (
"name",
"remote",
"name_... |
packages/engine/src/worker/runner/python/fbs/TaskID.py | mschrader15/hash | 219 | 12621939 | <gh_stars>100-1000
# automatically generated by the FlatBuffers compiler, do not modify
# namespace:
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class TaskId(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls):
return 16
# TaskId
def Init(s... |
tda/orders/__init__.py | zhangted/tda-api | 986 | 12621969 | from enum import Enum
from . import common
from . import equities
from . import generic
from . import options
import sys
assert sys.version_info[0] >= 3
__error_message = (
'EquityOrderBuilder has been deleted from the library. Please use ' +
'OrderBuilder and its associated templates instead. See he... |
release/stubs.min/Autodesk/Revit/DB/__init___parts/WorksharingUtils.py | htlcnn/ironpython-stubs | 182 | 12622027 | class WorksharingUtils(object,IDisposable):
""" A static class that contains utility functions related to worksharing. """
@staticmethod
def CheckoutElements(document,elementsToCheckout,options=None):
"""
CheckoutElements(document: Document,elementsToCheckout: ICollection[ElementId]) -> ICollection[ElementI... |
anchore/anchore-modules/queries/list-content-search-matches.py | berez23/anchore | 401 | 12622032 | <reponame>berez23/anchore
#!/usr/bin/env python
import sys
import os
import re
import json
import traceback
import anchore.anchore_utils
# main routine
try:
config = anchore.anchore_utils.init_query_cmdline(sys.argv, "params: <filename> <filename> ...\nhelp: use 'all' to show all content search match filenames"... |
tests/manage/z_cluster/nodes/test_worker_nodes_network_failures.py | annagitel/ocs-ci | 130 | 12622034 | <gh_stars>100-1000
import logging
import pytest
from concurrent.futures import ThreadPoolExecutor
from time import sleep
from ocs_ci.framework import config
from ocs_ci.framework.pytest_customization.marks import (
skipif_aws_i3,
skipif_vsphere_ipi,
skipif_ibm_power,
)
from ocs_ci.framework.testlib import ... |
src/gluonts/model/rotbaum/_model.py | Xiaoxiong-Liu/gluon-ts | 2,648 | 12622049 | <reponame>Xiaoxiong-Liu/gluon-ts
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/L... |
src/ralph/__main__.py | DoNnMyTh/ralph | 1,668 | 12622055 | #!/usr/bin/env python
import os
import sys
def main(settings_module='ralph.settings', force=False):
if force:
os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
else:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_module)
from django.core.management import execute_from_comma... |
tests/test_models/test_necks/test_necks.py | gopi231091/mmdetection3d | 217 | 12622071 | import pytest
import torch
from mmdet3d.models.builder import build_backbone, build_neck
def test_centerpoint_fpn():
second_cfg = dict(
type='SECOND',
in_channels=64,
out_channels=[64, 128, 256],
layer_nums=[3, 5, 5],
layer_strides=[2, 2, 2],
norm_cfg=dict(type='B... |
data structures/stack/python/stack.py | iabhimanyu/Algorithms | 715 | 12622096 | class Stack:
def __init__(self):
self.list = []
def push(self, element):
self.list.append(element)
def pop(self):
assert len(self.list) > 0, "Stack is empty"
return self.list.pop()
def isEmpty(self):
return len(self.list) == 0
|
bookwyrm/tests/models/test_fields.py | mouse-reeve/fedireads | 270 | 12622103 | """ testing models """
from io import BytesIO
from collections import namedtuple
from dataclasses import dataclass
import json
import pathlib
import re
from typing import List
from unittest.mock import patch
from PIL import Image
import responses
from django.core.exceptions import ValidationError
from django.core.fil... |
Attacks/AttackMethods/DEEPFOOL.py | jiannanWang/DEEPSEC | 178 | 12622106 | <filename>Attacks/AttackMethods/DEEPFOOL.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# References: S.-M. Moosavi-Dezfooli, et al., "Deepfool: A simple and accurate method to fool deep neural networks," in CVPR, 2016
# Reference Implementation from Authors: https://github.com/LTS4/DeepFool/tree/master/Python
# ***... |
server/api/blueprints/teacher.py | brayest/testcode | 652 | 12622118 | from datetime import datetime
from functools import wraps
import flask
import requests
from flask import Blueprint
from flask_babel import gettext
from flask_login import current_user, login_required, logout_user
from flask_weasyprint import HTML, render_pdf
from loguru import logger
from sqlalchemy import and_
from ... |
dfirtrack_main/views/company_views.py | thomas-kropeit/dfirtrack | 273 | 12622119 | from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateV... |
examples/python/contrasts.py | CCHiggins/statsmodels | 6,931 | 12622125 | <filename>examples/python/contrasts.py
#!/usr/bin/env python
# coding: utf-8
# DO NOT EDIT
# Autogenerated from the notebook contrasts.ipynb.
# Edit the notebook and then sync the output with this file.
#
# flake8: noqa
# DO NOT EDIT
# # Contrasts Overview
import numpy as np
import statsmodels.api as sm
# This docu... |
src/Entity/__init__.py | QWERTSKIHACK/peniot | 143 | 12622168 | """
This package contains the following entities:
1) Protocol
2) Attack Suite
3) Attack
4) Input Format
In this module, we have the backend entities to represent and structure our code
And these entities have the following relations in between: (Connection endpoints represent cardinality o... |
Clients/ParaView/Testing/Python/VolumeCellSelection.py | xj361685640/ParaView | 815 | 12622193 | from paraview.simple import *
from paraview import smtesting
import vtk
from paraview.vtk.vtkCommonCore import vtkCollection;
import vtk.vtkRenderingVolume
import os
paraview.simple._DisableFirstRenderCameraReset()
smtesting.ProcessCommandLineArguments()
smtesting.LoadServerManagerState(smtesting.StateXMLFileName)
v... |
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_partition_backfill.py | dbatten5/dagster | 4,606 | 12622199 | import os
from dagster.core.execution.backfill import BulkActionStatus
from dagster.seven import get_system_temp_directory
from dagster_graphql.client.query import LAUNCH_PARTITION_BACKFILL_MUTATION
from dagster_graphql.test.utils import (
execute_dagster_graphql,
execute_dagster_graphql_and_finish_runs,
i... |
addons/dropbox/settings/defaults.py | gaybro8777/osf.io | 628 | 12622215 | # OAuth app keys
DROPBOX_KEY = None
DROPBOX_SECRET = None
DROPBOX_AUTH_CSRF_TOKEN = 'dropbox-auth-csrf-token'
# Max file size permitted by frontend in megabytes
MAX_UPLOAD_SIZE = 150
|
tests/lazy/test_solve_lazy.py | rodluger/starry | 116 | 12622217 | # -*- coding: utf-8 -*-
"""
Linear solve / likelihood tests.
"""
import starry
import numpy as np
from scipy.linalg import cho_solve
from scipy.stats import multivariate_normal
import pytest
import itertools
@pytest.fixture(autouse=True)
def data():
# Instantiate a dipole map
map = starry.Map(ydeg=1, reflec... |
niftynet/engine/windows_aggregator_grid.py | tdml13/NiftyNet | 1,403 | 12622230 | <gh_stars>1000+
# -*- coding: utf-8 -*-
"""
windows aggregator decode sampling grid coordinates and image id from
batch data, forms image level output and write to hard drive.
"""
from __future__ import absolute_import, division, print_function
import os
from collections import OrderedDict
import numpy as np
import p... |
convoy/data.py | bureado/batch-shipyard | 279 | 12622234 | # Copyright (c) Microsoft Corporation
#
# All rights reserved.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights... |
common/dataset/__init__.py | AlexTaehwan/kgpolicy | 111 | 12622250 | from .preprocess import CKGData
|
tfjs_graph_converter/convert_fused_depthwise.py | httpsgithu/tfjs-to-tf | 114 | 12622271 | # SPDX-License-Identifier: MIT
# Copyright © 2020 <NAME>
"""Functions to rewrite FusedDepthwiseConv2d as native TensorFlow operations"""
import tfjs_graph_converter.graph_rewrite_util as util
from tfjs_graph_converter.graph_rewrite_util import generate_name_from
def _split_fused_depthwise(node: util.NodeDef,... |
redis/commands/json/__init__.py | utkarshgupta137/redis-py | 483 | 12622288 | <reponame>utkarshgupta137/redis-py<filename>redis/commands/json/__init__.py
from json import JSONDecodeError, JSONDecoder, JSONEncoder
import redis
from ..helpers import nativestr
from .commands import JSONCommands
from .decoders import bulk_of_jsons, decode_list
class JSON(JSONCommands):
"""
Create a clien... |
vivisect/tests/testreports.py | pombredanne/vivisect | 716 | 12622294 | import unittest
import vivisect.reports as v_reports
import vivisect.tests.helpers as helpers
class ReportsTest(unittest.TestCase):
'''
Test each of the base report modules.
'''
@classmethod
def setUpClass(cls):
cls.vw = helpers.getTestWorkspace('windows', 'i386', 'helloworld.exe')
d... |
more_autograding_examples/python_random_input_output/submissions/solution.py | elihschiff/Submitty | 411 | 12622335 | <filename>more_autograding_examples/python_random_input_output/submissions/solution.py<gh_stars>100-1000
import sys
def percent_change(old,new):
return int(100*(float(new)-old)/old)
def print_change(old1, new1, old2, new2):
p1 = percent_change(old1,new1)
p2 = percent_change(old2,new2)
print (p1, "vs",... |
settings.py | mdgrotheer/twitter-intelligence | 202 | 12622342 | GOOGLE_MAP_API_KEY = 'YOUR_API_KEY'
PORT = 5000
|
tests/unit/test_objector.py | nickatnight/praw | 2,360 | 12622359 | <filename>tests/unit/test_objector.py
import pytest
from praw.exceptions import ClientException, RedditAPIException
from . import UnitTest
class TestObjector(UnitTest):
def test_objectify_returns_None_for_None(self):
assert self.reddit._objector.objectify(None) is None
def test_parse_error(self):
... |
perma_web/perma/migrations/0008_auto_20160602_1911.py | rachelaus/perma | 317 | 12622362 | <reponame>rachelaus/perma<gh_stars>100-1000
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def set_registrar_status(apps, schema_editor):
Registrar = apps.get_model('perma', 'Registrar')
Registrar.objects.filter(is_approved=True).update(status='approv... |
annotation-vocab/tools/vocab_tester.py | ziransun/wpt | 2,479 | 12622364 |
# Author: <NAME> (<EMAIL>)
# License: Apache2
# Last Modified: 2016-09-02
from __future__ import print_function
import json
from rdflib import ConjunctiveGraph, URIRef
from pyld import jsonld
from pyld.jsonld import compact, expand, frame, from_rdf, to_rdf, JsonLdProcessor
import urllib
# Stop code from looking up ... |
lbry/wallet/server/db/__init__.py | nishp77/lbry-sdk | 4,996 | 12622370 | <filename>lbry/wallet/server/db/__init__.py
import enum
@enum.unique
class DB_PREFIXES(enum.Enum):
claim_to_support = b'K'
support_to_claim = b'L'
claim_to_txo = b'E'
txo_to_claim = b'G'
claim_to_channel = b'I'
channel_to_claim = b'J'
claim_short_id_prefix = b'F'
effective_amount = ... |
src/webdav/__init__.py | rbanffy/Zope | 289 | 12622381 | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
python/fcdd/runners/argparse_configs.py | kyungmin96/myfcdd | 152 | 12622388 | import os.path as pt
from argparse import ArgumentParser
import numpy as np
from fcdd.datasets import DS_CHOICES, PREPROC_CHOICES
from fcdd.datasets.noise_modes import MODES
from fcdd.models import choices
from fcdd.training.setup import OBJECTIVES, SUPERVISE_MODES
class DefaultConfig(object):
def __call__(self,... |
test/test_seed_schema.py | aviv-julienjehannet/GenSON | 377 | 12622396 | <reponame>aviv-julienjehannet/GenSON<filename>test/test_seed_schema.py
from . import base
class TestSeedTuple(base.SchemaNodeTestCase):
def test_tuple(self):
self.add_schema({'type': 'array', 'items': []})
self.add_object([None])
self.assertResult({'type': 'array', 'items': [{'type': 'nul... |
gunnery/account/urls.py | timgates42/gunnery | 314 | 12622425 | from django.conf.urls import patterns, url
from views import modal_permissions, profile_page
urlpatterns = patterns('',
url(r'^account/profile/(?P<user_id>[\d]+)/$', profile_page, name='profile'),
url(r'^account/login/$', 'django.contrib.auth.views.login', {'template_name': 'page/login.html'}),
url(r'^ac... |
brainstorm/hooks.py | PyCN/brainstorm | 1,473 | 12622435 | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
import math
import signal
import sys
from collections import OrderedDict
import h5py
import numpy as np
from six import string_types
from brainstorm.describable import Describable
from brainstorm import optional
fr... |
src/encoded/tests/test_schema_computational_model.py | procha2/encoded | 102 | 12622443 | import pytest
def test_unique_software(testapp, computational_model_unique_software):
res = testapp.post_json('/computational_model', computational_model_unique_software, expect_errors=True)
assert res.status_code == 201
def test_non_unique_software(testapp, computational_model_non_unique_software):
res ... |
qttbx/viewers/chimerax.py | dperl-sol/cctbx_project | 155 | 12622454 | <reponame>dperl-sol/cctbx_project
"""
Interface for ChimeraX using ISOLDE REST API client
https://www.cgl.ucsf.edu/chimerax/
https://isolde.cimr.cam.ac.uk/what-isolde/
"""
from __future__ import absolute_import, division, print_function
import os
import subprocess
import sys
import tempfile
from libtbx.utils impor... |
RecoParticleFlow/PFClusterProducer/python/particleFlowZeroSuppressionECAL_cff.py | ckamtsikis/cmssw | 852 | 12622467 | import FWCore.ParameterSet.Config as cms
pfZeroSuppressionThresholds_EB = [0.080]*170
pfZeroSuppressionThresholds_EEminus = [0.300]*39
pfZeroSuppressionThresholds_EEplus = pfZeroSuppressionThresholds_EEminus
#
# These are expected to be adjusted soon, while the thresholds for older setups will remain unchanged.
#
_pf... |
python/mleap/sklearn/base.py | neilsummers/mleap | 1,401 | 12622517 | <filename>python/mleap/sklearn/base.py
#
# 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, Versio... |
ppci/lang/python/python2ir.py | kl4w3i/ppci | 161 | 12622525 | <reponame>kl4w3i/ppci
""" Python to IR compilation.
"""
import logging
import ast
import contextlib
import inspect
from ... import ir, irutils
from ...common import SourceLocation, CompilerError
from ...binutils import debuginfo
def python_to_ir(f, imports=None):
"""Compile a piece of python code to an ir modul... |
api/utils/local.py | wkma/bk-sops | 881 | 12622544 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 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... |
learntools/sql/ex5.py | roannav/learntools | 359 | 12622562 | <reponame>roannav/learntools<filename>learntools/sql/ex5.py
from google.cloud import bigquery
from learntools.core import *
# Setup (4.57s on Kaggle)
client = bigquery.Client()
# (3) YearDistrib
rides_per_year_query = """
SELECT EXTRACT(YEAR FROM trip_start_timestamp) AS year,
... |
selfdrive/can/packer.py | BoneE562/openpilot | 114 | 12622589 | # pylint: skip-file
import os
import subprocess
can_dir = os.path.dirname(os.path.abspath(__file__))
subprocess.check_call(["make", "packer_impl.so"], cwd=can_dir)
from selfdrive.can.packer_impl import CANPacker
assert CANPacker
|
app/demo/countries/migrations/0016_person_smart.py | sesostris/django-material-admin | 270 | 12622590 | # Generated by Django 3.0 on 2019-12-12 20:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('countries', '0015_auto_20190719_1539'),
]
operations = [
migrations.AddField(
model_name='person',
name='smart',
... |
text_extensions_for_pandas/io/conll.py | CODAIT/text-extensions-for-pandas | 193 | 12622592 | <filename>text_extensions_for_pandas/io/conll.py
#
# Copyright (c) 2020 IBM Corp.
# 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... |
prepare_dataset.py | scripples/scripp_gpt-2 | 105 | 12622618 | #!/usr/bin/env python3
# Usage:
# PYTHONPATH=src ./encode.py <file|directory|glob> /path/to/output.npz
# PYTHONPATH=src ./train --dataset /path/to/output.npz
import argparse
import numpy as np
import sys
import tqdm
from ftfy import fix_text
import tflex_utils
parser = argparse.ArgumentParser(
description='Us... |
benchmark_scripts/train.py | qq456cvb/KeypointNet | 117 | 12622627 | import os
import hydra
import torch
import logging
logger = logging.getLogger(__name__)
import omegaconf
import importlib
from tqdm import tqdm
from utils import AverageMeter, ModelWrapper
import dataset
import utils
def train(cfg):
KeypointDataset = getattr(dataset, 'Keypoint{}Dataset'.format(cfg.task.capitaliz... |
tools/rename.py | gatehouse/cppcms | 388 | 12622632 | <reponame>gatehouse/cppcms
#!/usr/bin/env python
#
# Copyright <NAME> 2009. Use, modification and
# distribution is subject to the Boost Software License, Version
# 1.0. (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
import re
import sys
import os
import os.path
import Str... |
slackbot/management/commands/sendtestslack.py | mepsd/CLAC | 126 | 12622634 | <filename>slackbot/management/commands/sendtestslack.py
import djclick as click
from django.conf import settings
from django.core.management.base import CommandError
from slackbot.bot import sendmsg
from calc.site_utils import absolutify_url
@click.command()
def command() -> None:
url = absolutify_url('/')
... |
zincbase/web/__init__.py | complexdb/zincbase | 174 | 12622638 | class GraphCaster:
def __init__(self, redis_address='redis://'):
"""Create a graph cast, so that a KB can be displayed
on localhost:5000. It won't work if you installed basic
Zincbase -- try `pip install zincbase[web]`.
:param str redis_address: URL of the redis instance
the ... |
ParlAI/tests/test_params.py | UmaTaru/run | 163 | 12622648 | #!/usr/bin/env python
# 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.
"""Test ParlaiParser and other opt/params.py code."""
import os
import json
import unittest
from parlai.core.params impo... |
crfnet/model/losses_neural_filter.py | XiaoJake/CameraRadarFusionNet | 256 | 12622681 |
##### NEURAL FILTER LOSSES #####
import tensorflow as tf
def binary_focal_loss(loss_fn, threshold=0.5, alpha=0.2, gamma=2.0):
"""
Compared to focal loss, the binary focal loss
:param alpha: Scale the focal weight with alpha.
:param gamma: Take the power of the focal weight with gamma.
"""
... |
sdk/agrifood/azure-agrifood-farming/azure/agrifood/farming/operations/_planting_data_operations.py | rsdoherty/azure-sdk-for-python | 2,728 | 12622685 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
translators/objects/archive_assembly.py | Mango-3/blenderseed | 256 | 12622706 | #
# This source file is part of appleseed.
# Visit http://appleseedhq.net/ for additional information and resources.
#
# This software is released under the MIT license.
#
# Copyright (c) 2019 <NAME>, The appleseedhq Organization
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this... |
modules/ssl/update_policies.py | kulikjak/httpd | 2,529 | 12622710 | <gh_stars>1000+
#!/usr/bin/env python
import json
import os
import sys
from httplib import HTTPSConnection
# The location were Mozilla defines the *current* TLS Security in JSON format
#
MOZ_TLS_CONF_SERVER = "statics.tls.security.mozilla.org"
MOZ_TLS_CONF_PATH = "/server-side-tls-conf.json"
MOZ_TLS_CONF_URL = ... |
test/native/test_query.py | hugovk/pg8000 | 337 | 12622815 | import pytest
from pg8000.native import DatabaseError, to_statement
# Tests relating to the basic operation of the database driver, driven by the
# pg8000 custom interface.
@pytest.fixture
def db_table(request, con):
con.run(
"CREATE TEMPORARY TABLE t1 (f1 int primary key, "
"f2 bigint not null... |
tests/test_pyenv_feature_help.py | jmscraig/pyenv-win | 1,454 | 12622821 | <reponame>jmscraig/pyenv-win
from test_pyenv import TestPyenvBase
from test_pyenv_helpers import run_pyenv_test
class TestPyenvFeatureGlobal(TestPyenvBase):
def test_help(self, setup):
def commands(ctx):
stdout, stderr = ctx.pyenv("help")
stdout = "\r\n".join(stdout.splitlines()[:2... |
brew/selection/pruning/base.py | va26/brew | 344 | 12622839 | <gh_stars>100-1000
class Prunner(object):
def __init__(self):
pass
def fit(self, ensemble, X, y):
return self
def get(self, p=0.1):
return self.ensemble[:int(p * len(self.ensemble))]
|
sktime_dl/utils/__init__.py | talhaanwarch/sktime-dl | 510 | 12622843 | __all__ = [
"check_and_clean_data",
"check_and_clean_validation_data",
"check_is_fitted",
"save_trained_model"
]
from sktime_dl.utils._data import check_and_clean_data
from sktime_dl.utils._data import check_and_clean_validation_data
from sktime_dl.utils._models import check_is_fitted
from sktime_dl.ut... |
predict.py | mariomeissner/lightning-transformers | 451 | 12622865 | <gh_stars>100-1000
"""The shell entry point `$ pl-transformers-predict` is also available."""
import hydra
from omegaconf import DictConfig
from lightning_transformers.cli.predict import main
@hydra.main(config_path="./conf", config_name="config")
def hydra_entry(cfg: DictConfig) -> None:
main(cfg)
if __name__... |
slac_tf/slac/agents/slac/ablation_model_distribution_network.py | alfaevc/vlRLstack | 147 | 12622884 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import gin
import numpy as np
from slac.agents.slac.model_distribution_network import Bernoulli
from slac.agents.slac.model_distribution_network import Compressor
from slac.agents.slac.model_d... |
00Python/day07/basic01.py | HaoZhang95/PythonAndMachineLearning | 937 | 12622885 |
"""
缺省函数,就是参数可以有默认值,跟kotlin一样
返回值也可以简写,省略 -> int:
"""
def print_info(name, age=20):
print("姓名:%s, 年龄:%s" % (name, age))
print_info("张三", 28)
print_info("李四")
"""
元组[]不定长参数,参数的数量不确定, 调用类似于位置参数
参数名之前加上*表示这个星号表明参数的类型为元祖,但是传入实参的时候不需要中括号[]
"""
def my_func01(*args):
print(type(args))
print(args... |
src/scholarutil.py | moorage/synthetic-computer-vision | 940 | 12622956 | import sys, pickle, os, time, yaml
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(cur_dir, 'scholar_py'))
import scholar
cache_file = os.path.join(cur_dir, 'papers.pkl')
yaml_cache_file = os.path.join(cur_dir, 'papers_cache.yml')
def get_paper_data(querier, paper):
if type(paper... |
Tools/smoke.py | isabella232/MissilesPerfectMaster | 158 | 12622971 | <gh_stars>100-1000
import sys
import os
import math
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFilter
def crop(src_pixels, dst_pixels, x, y, w, h, dx, dy):
for ky in range(h):
for kx in range(w):
p = src_pixels[x+kx, y+ky];
dst_pixels[dx+kx, ... |
pytorchvideo/data/encoded_video_decord.py | kevinmtian/pytorchvideo | 2,391 | 12622976 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import math
from typing import BinaryIO, Dict, Optional, TypeVar
import torch
from .utils import thwc_to_cthw
from .video import Video
logger = logging.getLogger(__name__)
try:
import decord
except ImportError:
_HAS_DEC... |
Dynamic Programming/Editing Distance/python/editing_distance.py | iabhimanyu/Algorithms | 715 | 12622990 | # Uses python2
def edit_distance(s, t):
m, n = len(s), len(t)
dp = [[0]*(n + 1) for i in xrange(m + 1)]
for i in xrange(m + 1):
for j in xrange(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif s[i - 1] == t[j - 1]:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.