code stringlengths 1 199k |
|---|
import os
import sys
from string import digits
from pysec import chain
from pysec.io import fd
if __name__ == '__main__':
path = os.path.abspath(sys.argv[1])
with fd.File.open(path, fd.FO_READEX) as txt:
for line in txt.lines() | chain.contains(*digits) | chain.to_erepr:
print line |
from glob import glob
import os
pkgs = os.path.join(os.environ["ROOT"], "pkgs")
pkg_dir = glob(os.path.join(pkgs, "conda-build-test-ignore-prefix-files-1.0-0"))[0]
info_dir = os.path.join(pkg_dir, 'info')
assert os.path.isdir(info_dir)
assert not os.path.isfile(os.path.join(info_dir, "has_prefix")) |
import argparse
import os
import warnings
import numpy
import chainer
from chainer import training
from chainer.training import extensions
from net import Discriminator
from net import Generator
from updater import DCGANUpdater
from visualize import out_generated_image
def main():
parser = argparse.ArgumentParser(d... |
import PartyCatchActivityToonSD
from pandac.PandaModules import Vec4
from direct.directnotify import DirectNotifyGlobal
from direct.interval.IntervalGlobal import Sequence, Parallel, Wait, Func
from direct.interval.IntervalGlobal import LerpColorScaleInterval
from direct.interval.IntervalGlobal import WaitInterval, Act... |
import mock
from tests.compat import unittest
from tests.utils import make_api_result
import evelink.parsing.industry_jobs as evelink_ij
class IndustryJobsTestCase(unittest.TestCase):
def test_parse_industry_jobs(self):
api_result, _, _ = make_api_result("char/industry_jobs.xml")
result = evelink_ij... |
import sys
"""
reimplementation of calculate_checksum() from
netgear libacos_shared.so
binary MD5: 660c1e24aa32c4e096541e6147c8b56e libacos_shared.so
"""
class LibAcosChecksum(object):
def __init__(self,data,data_len,checksum_offset=-1):
self.dword_623A0=0
self.dword_623A4=0
fake_checksum="... |
__all__ = ['MayaParser', 'MayaParserFilter', 'MayaParserTextureFilter', 'MayaParserTextureEditFilter', 'MayaParserReferenceFilter']
from cStringIO import StringIO
from maya_app import Maya
from pyasm.application.common import TacticException
import string, re, os, shutil
class MayaParser(object):
'''class to read a... |
debug = False
import os
import Queue
import socket
import random
from pprint import pprint
from BTL.platform import bttime
import BTL.stackthreading as threading
from BTL.HostIP import get_host_ip, get_host_ips
from BTL.exceptions import str_exc
if os.name == 'nt':
from BTL import win32icmp
def daemon_thread(target... |
""" Utility functions and classes for pdfssa4met.
Created on Mar 1, 2010
@author: John Harrison
"""
class ConfigError(Exception):
def __init__(self, msg):
self.msg = msg
class UsageError(Exception):
def __init__(self, msg):
self.msg = msg
def mean(mylist):
""" Calculate the mean average of t... |
import orange
data = orange.ExampleTable("lenses")
age, prescr, astigm, tears, y = data.domain.variables
print "\n\nPreprocessor_removeDuplicates\n"
print "Before removal\n"
data2 = orange.Preprocessor_ignore(data, attributes = [age])
for ex in data2:
print ex
print "After removal\n"
data2, weightID = orange.Prepro... |
from cgi import parse_qs
import requests
import datetime
import os
import os.path
import redis
import json
REDIS = redis.Redis()
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'application/json'), ('Access-Control-Allow-Origin', '*')])
parameters = parse_qs(environ.get('QUERY_STRIN... |
from . import model |
"""Helpers for device automations."""
import asyncio
from functools import wraps
import logging
from types import ModuleType
from typing import Any, List, MutableMapping
import voluptuous as vol
import voluptuous_serialize
from homeassistant.components import websocket_api
from homeassistant.const import CONF_DEVICE_ID... |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
ht... |
import logging
import math
import time
from django.utils import timezone
from modularodm import Q
from oauthlib.oauth2 import OAuth2Error
from dateutil.relativedelta import relativedelta
from framework.celery_tasks import app as celery_app
from scripts import utils as scripts_utils
from website.app import init_app
from... |
"""Tests for an actual dns resolution."""
import logging
import unittest
import grpc
import six
from tests.unit import test_common
from tests.unit.framework.common import test_constants
_METHOD = '/ANY/METHOD'
_REQUEST = b'\x00\x00\x00'
_RESPONSE = _REQUEST
class GenericHandler(grpc.GenericRpcHandler):
def service(... |
"""Tests for signature_def_util.py.
- Tests adding a SignatureDef to TFLite metadata.
"""
import tensorflow as tf
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.lite.tools.signature import signature_def_utils
class SignatureDefUtilsTest(tf.test.TestCase):
def testAddSignatureDefToFlatbufferMet... |
from __future__ import absolute_import
from splunklib.six.moves import zip
def xml_compare(expected, found):
"""Checks equality of two ``ElementTree`` objects.
:param expected: An ``ElementTree`` object.
:param found: An ``ElementTree`` object.
:return: ``Boolean``, whether the two objects are equal.
... |
"""Config flow to configure the Luftdaten component."""
from collections import OrderedDict
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
CONF_MONITORED_CONDITIONS, CONF_SCAN_INTERVAL,
CONF_SENSORS, CONF_SHOW_ON_MAP)
from homeassistant.core import callback
f... |
from __future__ import unicode_literals
import unittest
import datetime
import json
import mock
from django.test import TestCase
from django.db.models import Q
from wagtail.tests.search import models
from .test_backends import BackendTests
class TestElasticSearchBackend(BackendTests, TestCase):
backend_path = 'wagt... |
from django.core import exceptions
from oscar.apps.offer.models import Range, Condition, Benefit
def _class_path(klass):
return '%s.%s' % (klass.__module__, klass.__name__)
def create_range(range_class):
"""
Create a custom range instance
"""
if not hasattr(range_class, 'name'):
raise except... |
"""
>>> bisect_in([], 1)
False
>>> import array
>>> import random
>>> SIZE = 10
>>> my_array = array.array('l', range(0, SIZE, 2))
>>> random.seed(42)
>>> for i in range(SIZE):
... print(i, bisect_in(my_array, i))
0 True
1 False
2 True
3 False
4 True
5 Fal... |
import re
try:
s = set()
del s
except NameError:
from Set import Set as set
from ply import lex
from sherrors import *
class NeedMore(Exception):
pass
def is_blank(c):
return c in (' ', '\t')
_RE_DIGITS = re.compile(r'^\d+$')
def are_digits(s):
return _RE_DIGITS.search(s) is not None
_OPERATORS ... |
"""
This module contains a Loader class which provides two methods
sync_entity() and sync_nnr() to load data entities and many to
many relationships into database.
It will check if some entity or relationship exists in db, and
call create/update/delete for entity and add/remove for relationship
to make records in db ar... |
import re
import crypt
from rhn.UserDictCase import UserDictCase
from spacewalk.common.rhnLog import log_debug, log_error
from spacewalk.common.rhnConfig import CFG
from spacewalk.common.rhnException import rhnFault, rhnException
from spacewalk.common.rhnTranslate import _
import rhnSQL
import rhnSession
class User:
... |
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import difflib
import threading
import time
import traceback
from thread import error as threadError
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from ... |
import inspect
import os
import subprocess
import socket
import sys
import time
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"..")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
import mosq_test
rc = 1
keepalive = 60... |
"""
Functions that can are used to modify XBlock fragments for use in the LMS and Studio
"""
import datetime
import json
import logging
import static_replace
import uuid
import markupsafe
from lxml import html, etree
from contracts import contract
from django.conf import settings
from django.utils.timezone import UTC
f... |
from argparse import ArgumentParser
from typing import Any
from django.core.management.base import BaseCommand, CommandError
from zerver.lib.actions import do_delete_old_unclaimed_attachments
from zerver.models import get_old_unclaimed_attachments
class Command(BaseCommand):
help = """Remove unclaimed attachments f... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import codecs
import os.path
import time
from unittest import skipIf
from pants_test.backend.jvm.tasks.missing_jvm_check import is_missing_jvm
from pants_test.pants_run... |
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def pro_substring_check():
#words are from https://raw.githubusercontent.com/dwyl/english-words/master/words.txt
path = "/Users/ludirehak/Downloads/words.txt"
for parse_type in ('string', 'enum'):
frame = h2o.H2OFrame.from_python... |
import Orange
data = Orange.data.Table("voting")
classifier = Orange.classification.LogisticRegressionLearner(data)
c_values = data.domain.class_var.values
for d in data[5:8]:
c = classifier(d)
print("{}, originally {}".format(c_values[int(classifier(d)[0])],
d.get_class())) |
from __future__ import absolute_import, print_function
import itertools
from django import template
from sentry import status_checks
register = template.Library()
@register.inclusion_tag('sentry/partial/system-status.html', takes_context=True)
def show_system_status(context):
problems = list(itertools.chain.from_it... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('customuser', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='CustomUser',
name='attachment',
field... |
"""This takes two command-line arguments:
INFILE raw linked ELF file name
OUTFILE output file name
It makes a copy of INFILE, and changes the ELF PHDR in place in the copy.
Then it moves the copy to OUTFILE.
nacl_helper_bootstrap's large (~1G) bss segment could cause the ker... |
import unittest
import textwrap
from test import support, mock_socket
import socket
import io
import smtpd
import asyncore
class DummyServer(smtpd.SMTPServer):
def __init__(self, *args, **kwargs):
smtpd.SMTPServer.__init__(self, *args, **kwargs)
self.messages = []
if self._decode_data:
... |
from datetime import datetime
import django
from django.core.exceptions import ImproperlyConfigured
from actstream.signals import action
from actstream.registry import register, unregister
from actstream.models import Action, actor_stream, model_stream
from actstream.tests.base import render, ActivityBaseTestCase
from ... |
try:
import uhashlib as hashlib
except ImportError:
try:
import hashlib
except ImportError:
# This is neither uPy, nor cPy, so must be uPy with
# uhashlib module disabled.
print("SKIP")
raise SystemExit
h = hashlib.sha256()
print(h.digest())
h = hashlib.sha256()
h.upd... |
from subspace import *
if __name__ == '__main__':
scenario = hallway_one_way(-5,0)
print scenario
scenarioFile = open("hallway-one-way-space.xml","w")
scenarioFile.write(scenario.getTextPretty()) |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: meraki_content_filtering
short_description: Edit Meraki MX content filtering policies
ve... |
my_dict = dict()
my_dict
class MyClass():
pass
my_instance = MyClass()
same_instance = my_instance
same_instance |
"""Unit tests for settings.py."""
from third_party_auth import provider, settings
from third_party_auth.tests import testutil
from util.enterprise_helpers import enterprise_enabled
import unittest
_ORIGINAL_AUTHENTICATION_BACKENDS = ('first_authentication_backend',)
_ORIGINAL_INSTALLED_APPS = ('first_installed_app',)
_... |
"""Coverage.py's main entrypoint."""
import os
import sys
bundled_coverage_path = os.getenv('BUNDLED_COVERAGE_PATH')
if bundled_coverage_path:
sys_path_backup = sys.path
sys.path = [p for p in sys.path if p != bundled_coverage_path]
from coverage.cmdline import main
sys.path = sys_path_backup
else:
... |
"""TensorFlow Eager execution prototype.
EXPERIMENTAL: APIs here are unstable and likely to change without notice.
To use, at program startup, call `tfe.enable_eager_execution()`.
@@metrics
@@list_devices
@@num_gpus
@@py_func
@@defun
@@implicit_gradients
@@implicit_value_and_gradients
@@gradients_function
@@value_and_g... |
"""Tests for tensorflow_lite_support.metadata.metadata."""
import enum
import os
from absl.testing import parameterized
import six
import tensorflow as tf
import flatbuffers
from tensorflow.python.platform import resource_loader
from tensorflow_lite_support.metadata import metadata_schema_py_generated as _metadata_fb
f... |
"""The Python implementation of the GRPC interoperability test client."""
import argparse
from oauth2client import client as oauth2client_client
from grpc.early_adopter import implementations
from grpc_interop import methods
from grpc_interop import resources
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
def _args():
parser = a... |
"""Management commands used by django-watson."""
from __future__ import unicode_literals |
import subprocess
import os
import argparse
if not os.path.exists('.pypt/gh-token'):
print("To use this script, you must create a GitHub token first.")
print("Get a token here: https://github.com/settings/tokens")
print("Then, put it in a file named .pypt/gh-token")
exit(1)
parser = argparse.ArgumentPar... |
import unittest
from test import test_support
import socket
import urllib
import sys
import os
import time
mimetools = test_support.import_module("mimetools", deprecated=True)
def _open_with_retry(func, host, *args, **kwargs):
# Connecting to remote hosts is flaky. Make it more robust
# by retrying the connect... |
try:
from lxml import etree as tree
class CustomResolver(tree.Resolver):
def resolve(self, url, id, context):
if 'custom-entities.ent' in url:
return self.resolve_filename('man/custom-entities.ent', context)
_parser = tree.XMLParser()
_parser.resolvers.add(CustomResol... |
"""
Tests for the MapAnnotation and related base types
introduced in 5.1.
"""
import library as lib
import pytest
import omero
from omero_model_ExperimenterGroupI import ExperimenterGroupI
from omero_model_MapAnnotationI import MapAnnotationI
from omero.rtypes import rbool, rstring
from omero.rtypes import unwrap
from ... |
"""
View yappi profiling data.
Usage: $0 <filename>
"""
import sys
import yappi
def main(args):
filename = args[0]
stats = yappi.YFuncStats()
stats.add(filename)
stats.print_all()
if __name__ == '__main__':
main(sys.argv[1:]) |
"""Tests for qutebrowser.misc.autoupdate."""
import pytest
from PyQt5.QtCore import QUrl
from qutebrowser.misc import autoupdate, httpclient
INVALID_JSON = ['{"invalid": { "json"}', '{"wrong": "keys"}']
class HTTPGetStub(httpclient.HTTPClient):
"""A stub class for HTTPClient.
Attributes:
url: the last u... |
'''
these tables are generated from the STM32 datasheets for the STM32H743bi
'''
build = {
"CHIBIOS_STARTUP_MK" : "os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32h7xx.mk",
"CHIBIOS_PLATFORM_MK" : "os/hal/ports/STM32/STM32H7xx/platform.mk"
}
mcu = {
# location of MCU serial number
'UDID_STAR... |
'''
This decoder stacks on top of the 'onewire_link' PD and decodes the
1-Wire protocol (network layer).
The 1-Wire protocol enables bidirectional communication over a single wire
(and ground) between a single master and one or multiple slaves. The protocol
is layered:
- Link layer (reset, presence detection, reading/... |
import mock
from oslo_utils import uuidutils
from neutron.agent.common import config as agent_config
from neutron.agent.l3 import router_info
from neutron.agent.linux import ip_lib
from neutron.common import constants as l3_constants
from neutron.common import exceptions as n_exc
from neutron.tests import base
_uuid = ... |
"""
Basic data classes for representing context free grammars. A
X{grammar} specifies which trees can represent the structure of a
given text. Each of these trees is called a X{parse tree} for the
text (or simply a X{parse}). In a X{context free} grammar, the set of
parse trees for any piece of a text can depend onl... |
"""Tests for tensorflow.python.framework.errors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import warnings
import tensorflow as tf
from tensorflow.core.lib.core import error_codes_pb2
class ErrorsTest(tf.test.TestCas... |
import logging
from django.template import defaultfilters
from django.utils.translation import ugettext_lazy as _
from horizon import messages
from horizon import tables
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
ENABLE = 0
DISABLE = 1
class CreateUserLink(tables.LinkAction):
name = "crea... |
from __future__ import unicode_literals
from django.apps import apps
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.core.exceptions import ImproperlyConfigured
from django.dispatch import receiver
from django.test import TestCase, override_settings
... |
"""unit testing code for database connection objects
"""
import os
import shutil
import tempfile
import traceback
import unittest
import doctest
from rdkit import RDConfig
from rdkit.Dbase import StorageUtils
class TestCase(unittest.TestCase):
def testDoctest(self):
if RDConfig.useSqlLite:
fd, tempName = te... |
import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import (
FXA_OAUTH_ENDPOINT,
FXA_PROFILE_ENDPOINT,
FirefoxAccountsProvider,
)
class FirefoxAccountsOAuth2Adapter(OAuth2Adapter):
provider_id = Firef... |
import sys
import os
from setuptools import setup
version = "1.1"
doc_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "docs")
index_filename = os.path.join(doc_dir, "index.txt")
news_filename = os.path.join(doc_dir, "news.txt")
long_description = """
The main website for pip is `www.pip-installer.org
<ht... |
'''
This is the gr-fcd package. This package provides a GNU Radio
source block for the FunCube Dongle hardware.
'''
from fcd_swig import * |
"""The Search integration."""
from collections import defaultdict, deque
import logging
import voluptuous as vol
from homeassistant.components import automation, group, script, websocket_api
from homeassistant.components.homeassistant import scene
from homeassistant.core import HomeAssistant, callback, split_entity_id
... |
import numpy as np
import pytest
from sklearn.base import clone
from sklearn.base import ClassifierMixin
from sklearn.base import is_classifier
from sklearn.datasets import make_classification
from sklearn.datasets import make_regression
from sklearn.datasets import load_iris, load_diabetes
from sklearn.impute import S... |
from __future__ import print_function
import sys
class Plot(object):
# Generated using
# http://tools.medialab.sciences-po.fr/iwanthue/
COLORS = ["#CD54D0",
"#79D94C",
"#7470CD",
"#D2D251",
"#863D79",
"#76DDA6",
"#D4467B",
... |
from sympy.vector.basisdependent import (BasisDependent, BasisDependentAdd,
BasisDependentMul, BasisDependentZero)
from sympy.core import S, Pow
from sympy.core.expr import AtomicExpr
from sympy import ImmutableMatrix as Matrix
import sympy.vector
class Dyadic(BasisDependent):
... |
from . import account_payment
from . import payment_line
from . import payment_mode
from . import account_move_reconcile |
"""Tests for tensorflow.python.framework.sparse_tensor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
f... |
"""Extracts archives."""
import hashlib
import optparse
import os
import os.path
import tarfile
import shutil
import sys
import zipfile
def CheckedJoin(output, path):
"""
CheckedJoin returns os.path.join(output, path). It does sanity checks to
ensure the resulting path is under output, but shouldn't be used on un... |
"""A base class to provide a model and corresponding input data for testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class ModelAndInput(object):
"""Base class to provide model and its corresponding inputs."""
def get_model(self):
"""Return... |
from urllib import unquote
from urlparse import urlparse
try:
from urlparse import parse_qsl
except ImportError: # pragma: no cover
from cgi import parse_qsl # noqa
from . import kwdict
def _parse_url(url):
scheme = urlparse(url).scheme
schemeless = url[len(scheme) + 3:]
# parse with HTTP URL sema... |
from django.db import connections
from django.db.models.query import QuerySet, Q, ValuesQuerySet, ValuesListQuerySet
from django.contrib.gis.db.models import aggregates
from django.contrib.gis.db.models.fields import get_srid_info, GeometryField, PointField, LineStringField
from django.contrib.gis.db.models.sql import ... |
"""The tests for generic camera component."""
import asyncio
from unittest import mock
from homeassistant.bootstrap import setup_component
@asyncio.coroutine
def test_fetching_url(aioclient_mock, hass, test_client):
"""Test that it fetches the given url."""
aioclient_mock.get('http://example.com', text='hello w... |
"""
Provide API-callable functions for knowledge base management (using kb's).
"""
import os
import re
from invenio import bibknowledge_dblayer
from invenio.jsonutils import json
from invenio.bibformat_config import CFG_BIBFORMAT_ELEMENTS_PATH
from invenio.config import CFG_WEBDIR
processor_type = 0
try:
from lxml... |
from odoo.tests.common import TransactionCase
class TestResourceCommon(TransactionCase):
def _define_calendar(self, name, attendances, tz):
return self.env['resource.calendar'].create({
'name': name,
'tz': tz,
'attendance_ids': [
(0, 0, {
... |
from weboob.capabilities.base import NotLoaded, NotAvailable
from .iformatter import IFormatter
__all__ = ['MultilineFormatter']
class MultilineFormatter(IFormatter):
def __init__(self, key_value_separator=u': ', after_item=u'\n'):
IFormatter.__init__(self)
self.key_value_separator = key_value_separ... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'BlogPost.site'
db.add_column('blog_blogpost', 'site', self.gf('django.db.models.fields.related.ForeignKey')(default=1, ... |
"""Manages and runs tests from the current working directory.
This will traverse the current working directory and look for python files that
contain subclasses of SpirvTest.
If a class has an @inside_spirv_testsuite decorator, an instance of that
class will be created and serve as a test case in that testsuite. The t... |
from itertools import product
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_almost_equal
from scipy import linalg
import pytest
from sklearn import neighbors, manifold
from sklearn.manifold._locally_linear import barycenter_kneighbors_graph
from sklearn.utils._testing import ignore_warn... |
import numpy as np
import operator
from . import (linear_sum_assignment, OptimizeResult)
from ._optimize import _check_unknown_options
from scipy._lib._util import check_random_state
import itertools
QUADRATIC_ASSIGNMENT_METHODS = ['faq', '2opt']
def quadratic_assignment(A, B, method="faq", options=None):
r"""
... |
import re
import fnmatch
import sys
import subprocess
import datetime
import os
EXCLUDE = [
# auto generated:
'src/qt/bitcoinstrings.cpp',
'src/chainparamsseeds.h',
# other external copyrights:
'src/reverse_iterator.h',
'src/test/fuzz/FuzzedDataProvider.h',
'src/tinyformat.h',
'src/bench... |
import sys
sys.path.append('../../..')
import oosmos
oosmos.cWindows.Clean() |
"""
Package resource API
--------------------
A resource is a logical file contained within a package, or a logical
subdirectory thereof. The package resource API expects resource names
to have their path parts separated with ``/``, *not* whatever the local
path separator is. Do not use os.path operations to manipula... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import dec, run_module_suite
from scipy._lib._testutils import xslow
from scipy.special._testutils import MissingModule, check_version
from scipy.special._mptestutils import (
Arg, IntArg, mp_assert_allclose, asse... |
"""
***************************************************************************
QtPrintSupport.py
---------------------
Date : November 2015
Copyright : (C) 2015 by Matthias Kuhn
Email : matthias at opengis dot ch
********************************************... |
from oslo.config import cfg
from neutron.extensions import portbindings
eswitch_opts = [
cfg.StrOpt('vnic_type',
default=portbindings.VIF_TYPE_MLNX_DIRECT,
help=_("Type of VM network interface: mlnx_direct or "
"hostdev")),
cfg.BoolOpt('apply_profile_patch',
... |
"""Tests for JIT compilation on the CPU and GPU devices."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from tensorflow.compiler.tests import test_utils
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.prot... |
import nest
import unittest
from math import exp
@nest.check_stack
class VogelsSprekelerConnectionTestCase(unittest.TestCase):
"""Check vogels_sprekeler_synapse model properties."""
def setUp(self):
"""Set up the test."""
nest.set_verbosity('M_WARNING')
nest.ResetKernel()
# setti... |
import json
import re
import sys
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.six import binary_type, text_type
from ansible.module_utils._text import to_native
class ConfigProxy(object):
def __init__(self, actual, client, attribute_values_dict, readwrite_attrs, transforms={}, reado... |
import sys
from os.path import abspath, dirname, join
sys.setrecursionlimit(2000)
sys.path.insert(1, dirname(dirname(abspath(__file__))))
sys.path.append(abspath(join(dirname(__file__), "_ext")))
needs_sphinx = '1.3' # Actually 1.3.4, but micro versions aren't supported here.
extensions = [
"djangodocs",
"sphi... |
import logging
from airflow.exceptions import AirflowException
from airflow.models import DagBag
_log = logging.getLogger(__name__)
def get_task_instance(dag_id, task_id, execution_date):
"""Return the task object identified by the given dag_id and task_id."""
dagbag = DagBag()
# Check DAG exists.
if da... |
"""Map Z-Wave nodes and values to Home Assistant entities."""
import openzwavemqtt.const as const_ozw
from openzwavemqtt.const import CommandClass, ValueGenre, ValueIndex, ValueType
from . import const
DISCOVERY_SCHEMAS = (
{ # Binary sensors
const.DISC_COMPONENT: "binary_sensor",
const.DISC_VALUES... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Profile.send_emails'
db.add_column('profile_profile', 'send_emails', self.gf('django.db.models.fields.BooleanField')(de... |
class NoUniqueMatch(RuntimeError):
"""There was more than one extension, or none, that matched the query."""
class NoMatches(NoUniqueMatch):
"""There were no extensions with the driver name found."""
class MultipleMatches(NoUniqueMatch):
"""There were multiple matches for the given name.""" |
from openerp import models, api
class WizLockLot(models.TransientModel):
_name = 'wiz.lock.lot'
@api.multi
def action_lock_lots(self):
lot_obj = self.env['stock.production.lot']
active_ids = self._context['active_ids']
lot_obj.browse(active_ids).button_lock()
@api.multi
def a... |
"""
celery.events.state
~~~~~~~~~~~~~~~~~~~
This module implements a datastructure used to keep
track of the state of a cluster of workers and the tasks
it is working on (by consuming events).
For every event consumed the state is updated,
so the state represents the state of the cluster
... |
import re
foo = 42
re.compile(rf'.*{foo}.*') |
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def delete_old_scheduled_jobs(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""Delete any old scheduled jobs, to handle changes in the for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.