code
stringlengths
1
199k
import json import numpy as np inputs = { 'xml_file_path' : "./data/Abl_Gef_Ima_copy/", 'section' : '280_BottomRead', 'ligand_order' : ['Gef-Ima','Gef-Ima','Gef-Ima','Gef-Ima'], 'Lstated' : np.array([20.0e-6,9.15e-6,4.18e-6,1.91e-6,0.875e-6,0.4e-6,0.183e-6,0.0837e-6,0.0383e-6,0.0175e-6,...
from __future__ import unicode_literals import logging import sys import yaml try: # pragma: no cover from collections import UserDict # noqa except ImportError: # pragma: no cover from UserDict...
'''Tests for firewall API. This is mostly copy from core-admin''' import datetime import unittest import qubesadmin.firewall import qubesadmin.tests class TestOption(qubesadmin.firewall.RuleChoice): opt1 = 'opt1' opt2 = 'opt2' another = 'another' class TC_00_RuleChoice(qubesadmin.tests.QubesTestCase): d...
""" Scikit learn interface for gensim for easy use of gensim with scikit-learn Follows scikit-learn API conventions """ import numpy as np from scipy import sparse from sklearn.base import TransformerMixin, BaseEstimator from sklearn.exceptions import NotFittedError from gensim import models from gensim import matutils...
'''Quick script to collect information about responders.''' __author__ = 'nomis52@gmail.com (Simon Newton)' import getopt import logging import pprint import sys import textwrap from ola import PidStore from ola.ClientWrapper import ClientWrapper from ola.OlaClient import OlaClient, RDMNack from ola.RDMAPI import RDMAP...
""" test the build system """ from rez.build_process_ import create_build_process from rez.build_system import create_build_system from rez.resolved_context import ResolvedContext from rez.exceptions import BuildError, BuildContextResolveError,\ PackageFamilyNotFoundError import unittest from rez.tests.util import ...
"""Recognizes simple heuristically delimited warnings.""" __metaclass__ = type __all__ = [ 'SimpleWarning', ] from flufl.bounce._detectors.simplematch import SimpleMatch from flufl.bounce._detectors.simplematch import _c from flufl.bounce.interfaces import NoPermanentFailures PATTERNS = [ # pop3.pta.lia.net...
import ufl import dolfin.cpp as cpp from . import svgtools def ufl_cell(self): return ufl.Cell(self.cell_name(), geometric_dimension=self.geometry().dim()) def ufl_coordinate_element(self): """Return the finite element of the coordinate vector field of this domain. """ cell = sel...
from datetime import datetime, timedelta import time, sys, requests, os, argparse from pprint import pprint from glob import glob from collections import OrderedDict class Zone: allZones = {} @classmethod def makeZone(cls, zoneId, *args): if zoneId in cls.allZones: return cls.allZones[zo...
from casadi import * import numpy as N n = 10 m = 8 x0 = N.random.rand(n,1)+0.1 A = N.random.randn(m,n) b = mul(A,x0) c = N.random.randn(n) x = ssym("x",n) ffcn = SXFunction([x],[inner_prod(c,x)]) gfcn = SXFunction([x],[mul(A,x)]) for solver in ['ipopt','ip_method']: if solver=='ipopt': # Solve with IPOPT nlp...
from studiovendor.Qt import QtWidgets from .groupitem import GroupItem class ItemDelegate(QtWidgets.QStyledItemDelegate): def __init__(self): """ This class is used to display data for the items in a ItemsWidget. """ QtWidgets.QStyledItemDelegate.__init__(self) self._itemsWid...
import datetime from PyQt5.QtWidgets import QTreeWidgetItem from TriblerGUI.utilities import prec_div class TransactionWidgetItem(QTreeWidgetItem): """ This class represents a widget that displays a transaction. """ def __init__(self, parent, transaction, asset1_prec, asset2_prec): QTreeWidgetIt...
import math h1 = [ 1, 2, 3, 4, 5, 6, 7, 8 ] h2 = [ 6, 5, 4, 3, 2, 1, 0, 0 ] h3 = [ 8, 7, 6, 5, 4, 3, 2, 1 ] h4 = [ 1, 2, 3, 4, 4, 3, 2, 1 ] h5 = [ 8, 8, 8, 8, 8, 8, 8, 8 ] h = [ h1, h2, h3, h4, h5 ] def mean(hist): mean = 0.0 for i in hist: mean += i mean/= len(hist) return mean def bhatta (hist...
""" Copyright (c) 2013-2014 Benedicte Ofstad Distributed under the GNU Lesser General Public License v3.0. For full terms see the file LICENSE.md. """ from numpy import array, dot, sqrt, set_printoptions, reshape, multiply, divide, add, subtract, diag import numpy as np from scipy import mat, linalg, double from read_i...
import time from functools import partial """ functions to iter over .fasta and .fastq files. and I believe fasta_iter and fastq_iter are faster than many iterators available. created: long time ago last modified: 2014.01.26 - use partial to read blocks from file """ def fasta_iter(f, blocksize=int(1e7)): """ f...
import retro import retro.actors from retro.actors import action import retro.assets import retro.scenes import retro.resources class Movement1(retro.actors.Drawable): def update(self): self.position = (self.position[0] + 1, self.position[1] + 1) return self.area def hit...
from __future__ import absolute_import from __future__ import print_function import math from .exceptions import * def format_option_for_cfour(opt, val): """Function to reformat value *val* for option *opt* from python into cfour-speak. Arrays are the primary target. """ text = '' # Transform list f...
from pyproj import Proj from pyproj import transform from shapely.geometry import Point from shapely.wkt import loads import datetime import logging import mapnik import osgeo.ogr import pkg_resources from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils impo...
import sys import os import re import logging import datetime import ConfigParser from deepmac_manager import dmManager from deepmac_record_class import dmRecord log = logging.getLogger('dm_import') handler = logging.StreamHandler() logformat = logging.Formatter("%(asctime)s - %(name)s %(levelname)s: %(message)s") hand...
import os import base64 from xml.etree.cElementTree import ElementTree from lazagne.config.module_info import ModuleInfo from lazagne.config import homes class Filezilla(ModuleInfo): def __init__(self): ModuleInfo.__init__(self, 'filezilla', 'sysadmin') def run(self): pwd_found = [] for ...
from django import forms from django.conf.urls import url, include from django.utils.translation import ugettext_lazy as _ from acceptable import AcceptableService service = AcceptableService('django_app') class TestForm(forms.Form): foo = forms.EmailField( required=True, label=_('foo'), hel...
from casadi import * import casadi from numpy import * import unittest import sys from math import isnan, isinf import argparse parser = argparse.ArgumentParser() parser.add_argument('--known_bugs', help='Run with known bugs', action='store_true') parser.add_argument('--ignore_memory_heavy', help='Skip those tests that...
from casadi import * import numpy as NP import matplotlib.pyplot as plt """ Example program demonstrating sensitivity analysis with sIPOPT from CasADi Test problem (from sIPOPT example collection) min (x1-1)^2 +(x2-2)^2 + (x3-3)^2 s.t. x1+2*x2+3*x3 = 0 @author Joel Andersson, K.U. Leuven 2012 """ x = ssym("...
"""An RFC 2821 smtp proxy. Usage: %(program)s [options] [localhost:localport [remotehost:remoteport]] Options: --nosetuid -n This program generally tries to setuid `nobody', unless this flag is set. The setuid call will fail if this program is not run as root (in which case, use this fl...
balance = 320000 annualInterestRate = 0.2 mir = annualInterestRate/12.0 lb = float("{0:.2f}".format(balance/12.0)) ub = float("{0:.2f}".format((balance * (1 + mir)**12)/12.0)) def cb(balance, fmp): b = balance for i in range(12): mub = b - fmp b = mub + (mir * mub) return float("{0:.2f}".for...
import os PROJECT_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..') DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_RO...
print "hola mundo"
import json import os import sys import datetime from unittest import TestCase file_ = os.path.abspath(__file__) tests_ = os.path.dirname(file_) products_ = os.path.dirname(tests_) shopify_ = os.path.dirname(products_) root = os.path.dirname(shopify_) sys.path.append(root) from shopify.products import Image class TestI...
import urllib.request import json import re from utils import IPgetter import logging import urllib.parse FORMAT = '[%(levelname)s] (%(threadName)-9s) %(message)s' logging.basicConfig(format=FORMAT) class Messages: def __init__(self,apikey, googleto, devices): self.mode = "Automate" self.headers = {...
import der, ecdsa class UnknownCurveError(Exception): pass def orderlen(order): return (1+len("%x"%order))//2 # bytes curves = [] class Curve: def __init__(self, name, curve, generator, oid): self.name = name self.curve = curve self.generator = generator self.order = generato...
from .broadcast_input_stream_configuration import BroadcastTsInputStreamConfiguration class BroadcastTsAudioStreamConfiguration(BroadcastTsInputStreamConfiguration): def __init__(self, stream_id, packet_identifier=None, start_with_discontinuity_indicator=None, align_pes=None, set_rai_on_au=None, us...
import fileinput from collections import defaultdict lines = list(map(lambda s: s.strip(), fileinput.input())) n, m = len(lines), len(lines[0]) def outside(i, j): return i < 0 or j < 0 or i >= n or j >= m def adj(i, j): yield i + 1, j yield i, j + 1 yield i - 1, j yield i, j - 1 def toi(i, j): r...
import logging import os import sys import warnings from django.utils.translation import ugettext_lazy as _ # noqa from openstack_dashboard import exceptions warnings.formatwarning = lambda message, category, *args, **kwargs: \ '%s: %s' % (category.__name__, message) ROOT_PATH = os.path.dirname(os.path.abspath(__f...
import blescan import sys import datetime import bluetooth._bluetooth as bluez def print_beacons(): dev_id = 0 try: sock = bluez.hci_open_dev(dev_id) except: print ("error accessing bluetooth device..."); sys.exit(1) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable...
from measures.generic.GenericMeasure import GenericMeasure import re import measures.generic.Units as Units class TableMessageEndToEndDelay(GenericMeasure): def __init__(self, period, simulationTime): GenericMeasure.__init__(self, '', period, simulationTime, Units.SECONDS) self.__receivedPattern = r...
"""A simple single thread WeChat client.""" import click import sys import time from logging import config, getLogger from pywxclient.core import Session, SyncClient, parse_message from pywxclient.core.exception import ( WaitScanQRCode, RequestError, APIResponseError, SessionExpiredError, AuthorizeTimeout, Unsu...
import traceback import logging from logging import * import sys from os import path import os import time from . import config if not os.path.exists("log"): os.makedirs("log") if not os.path.exists("config"): os.makedirs("config") exec(config.configDefaultDebug) exec(config.loadConfiguration("debug.cfg").read(...
import abc import base64 import contextlib import errno import functools import os import shutil from castellan import key_manager from oslo_concurrency import processutils from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import excutils from oslo_utils import fileutils from ...
""" Copyright [2009-2020] EMBL-European Bioinformatics Institute 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...
import unittest from chapter_02.src.answer_02 import get_kth_last from chapter_02.src.LinkedList import LinkedList class TestKthLast(unittest.TestCase): def test_empty_list(self): self.assertIs(get_kth_last(None, 7), None) self.assertIs(get_kth_last(LinkedList(), 33), None) def test_out_range(se...
import csv import logging import os import sys from itertools import islice from collections import defaultdict import xlrd from common.models import Publication, WebLink, WebResource from django.conf import settings from django.utils.text import slugify from django.core.management.base import BaseCommand, CommandError...
import time from networking_cisco.apps.saf.common import constants from networking_cisco.apps.saf.common import dfa_exceptions as dexc from networking_cisco.apps.saf.common import dfa_logger as logging from networking_cisco.apps.saf.common import utils LOG = logging.getLogger(__name__) class DfaFailureRecovery(object):...
import gym import logging import numpy as np from typing import Any, Dict import ray import ray.rllib.agents.impala.vtrace_torch as vtrace from ray.rllib.models.torch.torch_action_dist import TorchCategorical from ray.rllib.policy.policy import Policy from ray.rllib.policy.policy_template import build_policy_class from...
import unittest import numpy as np from spectralcluster import autotune from spectralcluster import configs from spectralcluster import constraint from spectralcluster import laplacian from spectralcluster import refinement from spectralcluster import spectral_clusterer from spectralcluster import utils RefinementName ...
"""Tests specific to Feature Columns integration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python import keras from tensorflow.python.data.ops import dataset_ops from tensorflow.python.feature_column import feature...
from __future__ import absolute_import import fcntl import logging import os import sys import yaml from django.conf import settings LOG = logging.getLogger(__name__) def include_constructor(loader, node): """Loads a yaml include file.""" LOG.debug("Loading YAML(include) content from %s." % node.value) cont...
import logging from xml.etree import ElementTree from nova import vendor from twisted.internet import defer from twisted.internet import reactor from nova import exception from nova import flags from nova import process from nova import test from nova import utils FLAGS = flags.FLAGS class ProcessTestCase(test.TrialTes...
from unittest import mock from osc_lib.command import command from osc_lib import exceptions from openstackclient.tests.unit import fakes as test_fakes from openstackclient.tests.unit import utils as test_utils class FakeCommand(command.Command): def take_action(self, parsed_args): pass class TestCommand(te...
'{<warning descr="Unresolved reference 'foo'">foo</warning>}'.format(**{"boo": 1})
"""Test util for Seeing More Tensorflow libraries.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import os import numpy as np import tensorflow as tf from typing import List, Tuple, Union from isl import data_provider from isl import uti...
""" Fetches the current price from the bitstamp ticker and stores it in the sqlite3 database. """ import client import rules import settings from datetime import datetime import sqlite3 import sys import time def main(): data = client.fetch_price() buy = data['buy'] sell = data['sell'] now = int(time.ti...
""" <Started> July 2013 <Author> Savvas Savvides <savvas@purdue.edu> <Purpose> This module contains the Trace object, which is used to capture all the extracted information from a trace file. Example using this module: import Trace trace = Trace.Trace(path_to_trace) print trace """ import os impor...
""" Module holds selenium stuff """ from abc import abstractmethod import os import time import shutil import sys import subprocess import urwid from bzt.engine import ScenarioExecutor, Scenario from bzt.utils import RequiredTool, shell_exec, shutdown_process, BetterDict, JavaVM from bzt.six import string_types, text_t...
from sdk.data.CANFrame import CANFrame from sdk.data.Mappable import Mappable class Request(Mappable): """ Request to device representation""" __slots__ = ('frame', 'wait_time') def __init__(self, frame, wait_time): """ :param CANFrame frame: :param int wait_time: """ ...
from usage.exc import UnknownFieldFunctionError from pkg_resources import iter_entry_points from usage.log import logging logger = logging.getLogger('fields') FIELD_FUNCTIONS = {} for entry_point in iter_entry_points(group='usage.fields'): try: FIELD_FUNCTIONS[entry_point.name] = entry_point.load() exce...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reddit', '0008_auto_20160619_2253'), ] operations = [ migrations.AlterField( model_name='subreddits', name='name', fi...
"""A Generic HTTP Server implementation designed to serve arbitrary files. Note: This server is only intended for winnforum testing purposes, do not use this in a production environment. Example usage: d = DatabaseServer('Test', 'localhost', 8000) d.setFileToServe('/allsitedata', 'allsitedata1') d.start() d.setFilesToS...
""" Server API Reference for Server API (REST/Json) OpenAPI spec version: 2.0.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os import re from six import iteritems from ..configuration import Configuration from ..api_client...
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
from django.shortcuts import render_to_response from catalogue.models import BookItem, BookCategory, BookAttribute, BookAttributeType from catalogue.entities import RU_ru from django.conf import settings def index(request): bookCategoryList = BookCategory.objects.filter(active=True).order_by('category_name') re...
"""Tests for building and repacking clients.""" import io import os from unittest import mock from absl import app from grr_response_client_builder import build_helpers from grr_response_core import config from grr_response_core.lib import config_parser from grr_response_core.lib.rdfvalues import client as rdf_client f...
"""Utilities for V2 control flow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import attr_value_pb2 from tensorflow.python.distribute import distribution_strategy_context from tensorflow.python.eager import context from t...
"""Contains tools that deliver information about the state of the database. Currently, these tools are made to be used with mysql_service benchmark but may be expanded in the future to support other benchmarks. Launch_mysql_service: Wrapper script to drive multiple runs of mysql_service. Launch_driver: Driver script th...
""" Copyright 2015 SYSTRAN Software, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by ap...
import logging from flask import Flask, Response, session, render_template, request, url_for, redirect, abort import json import urllib from markupsafe import Markup import time from flask import send_from_directory import os from flask_login import LoginManager, login_required, login_user, logout_user, current_user im...
import collections import copy import errno import functools import httplib import os import re try: from eventlet.green import socket from eventlet.green import ssl except ImportError: import socket import ssl import osprofiler.web try: import sendfile # noqa SENDFILE_SUPPORTED = True except I...
def action_extensions(base_actions, project_path=None): def echo(name, *args, **kwargs): print(name, args, kwargs) def verbose(name, ctx, args): print('Output from test-verbose') if args.verbose: print('Verbose mode on') # Add global options extensions = { 'gl...
import PyCA.Core as ca import PyCA.Common as common import PyCA.Display as display import numpy as np import matplotlib.pyplot as plt def ElastReg(I0Orig, I1Orig, scales = [1], nIters = [1000], maxPert = [0.2], fluidParams = [0.1, 0.1, 0.001], ...
import numpy as np from dataset import * def load_gt_roidb(dataset_name, image_set_name, root_path, dataset_path, result_path=None, flip=False): """ load ground truth roidb """ imdb = eval(dataset_name)(image_set_name, root_path, dataset_path, result_path) roidb = imdb.gt_roidb() if fl...
"""Haiku implementation of VQ-VAE https://arxiv.org/abs/1711.00937.""" import types from typing import Any, Optional from haiku._src import base from haiku._src import initializers from haiku._src import module from haiku._src import moving_averages import jax import jax.numpy as jnp hk = types.ModuleType("haiku") hk.g...
from functools import partial import six from cinderclient import exceptions as cinder_exc from oslo_config import cfg from oslo_log import log as logging from karbor.common import constants from karbor import exception from karbor.services.protection.client_factory import ClientFactory from karbor.services.protection ...
import unittest import numpy from pyscf import gto, scf, lib from pyscf import grad mol = gto.Mole() mol.verbose = 5 mol.output = '/dev/null' mol.atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ] mol.charge = -1 mol.spin = 1 mol.build() mol1 = gto.Mole() mol...
import os, unittest class Tests(): def suite(self): modules_to_test = [] test_dir = os.listdir('.') for test in test_dir: if test.startswith('test') and test.endswith('.py'): modules_to_test.append(test.rstrip('.py')) alltests = unittest.TestSuite() ...
import logging import requests import queue import threading import time import json import re from pprint import pformat import streamsx.topology.schema logger = logging.getLogger('streamsx.rest') def _exact_resource(json_rep, id=None): if id is not None: if not 'id' in json_rep: return False ...
import tensorflow.python.platform import numpy as np import tensorflow as tf import os NUM_LABELS = 2 # The number of labels. BATCH_SIZE = 100 # The number of training examples to use per training step. tf.app.flags.DEFINE_string('train', None, 'File containing the training data (labels &...
from connector import channel from google3.cloud.graphite.mmv2.services.google.identity_toolkit import ( oauth_idp_config_pb2, ) from google3.cloud.graphite.mmv2.services.google.identity_toolkit import ( oauth_idp_config_pb2_grpc, ) from typing import List class OAuthIdpConfig(object): def __init__( ...
import collections import typing from typing import Any, Callable, Iterable, Optional if typing.TYPE_CHECKING: # pragma: NO COVER from google.cloud.pubsub_v1 import subscriber class MessagesOnHold(object): """Tracks messages on hold by ordering key. Not thread-safe. """ def __init__(self): self...
"""Usage: boxplot.py --kind=KIND --os=OS --host=HOST Arguments: HOST Host name OS OS name KIND category or classifier Options: -h --help -o OS """ from __future__ import print_function from docopt import docopt import glob from cloudmesh_client.common.hostlist import Parameter import os.pa...
import asyncio import functools import importlib import inspect import logging from typing import Text, Dict, Optional, Any, List, Callable, Collection, Type from rasa.shared.exceptions import RasaException logger = logging.getLogger(__name__) def class_from_module_path( module_path: Text, lookup_path: Optional[Tex...
from girder.api import access from girder.api.describe import autoDescribeRoute, Description from girder.api.rest import boundHandler, filtermodel, RestException from girder.constants import AccessType from girder.plugins.worker import utils from . import constants @access.admin(scope=constants.TOKEN_SCOPE_AUTO_CREATE_...
from sqlalchemy.sql import operators from sqlalchemy import String from sqlalchemy.types import TypeDecorator, CHAR, VARCHAR, TEXT from sqlalchemy.dialects.postgresql import UUID import json import uuid __all__ = ['GUID', 'JSONDict', 'JSONSmallDict'] class GUID(TypeDecorator): """Platform-independent GUID type. ...
""" This module contains definitions for scorers. Highlights: - when implementing a stateful scorer you should inherit from Stateful - when using your scorer with programs such as Earley and Nederhof, remember to wrap it using StatefulScorerWrapper this will basically abstract away implementation detail...
import collections def _recursem(mapping): rv = {} for k, v in mapping.items(): if isinstance(v, TasksConfigBaseMapping): rv[k] = _recursem(v) elif isinstance(v, TasksConfigBaseSequence): rv[k] = _recursel(v) else: rv[k] = v return rv def _recursel...
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? ...
""" Smoke test using the samples. """ import unittest import os import six import sys import time import subprocess from requests import post import flask_ask launch = { "version": "1.0", "session": { "new": True, "sessionId": "amzn1.echo-api.session.0000000-0000-0000-0000-00000000000", "application": {...
import functools from oslo_log import log from oslo_service import periodic_task from zun.common import context from zun.compute.compute_node_tracker import ComputeNodeTracker from zun.container import driver from zun import objects LOG = log.getLogger(__name__) def set_context(func): @functools.wraps(func) def...
import openamAuth
__all__ = ['ThresholdRescaler', 'get_thresholds_from_file'] import numpy as np from ..utils import load_dictionary_from_file class ThresholdRescaler(object): def __init__(self, thresholds, n_classes=None): if isinstance(thresholds, float): self.thresholds = np.full(n_classes, thresholds) elif isinst...
from MAT.ReconciliationDocument import _getListValue, AnnotationEquivalenceClassifier, \ SPECIAL_VOTE_VALUES from MAT.Operation import OpArgument, Option class ReconciliationPhase(object): argList = [] def __init__(self, **kw): self.pData = {} # In general, adding votes is permitted. # But ...
""" Contains common layers """ from functools import partial import numpy as np import tensorflow as tf import tensorflow.keras.layers as K # pylint: disable=import-error from .layer import Layer, add_as_function from ..utils import get_num_channels, get_num_dims @add_as_function class Flatten2D: """ Flatten tensor...
''' ''' Test.Summary = ''' Test TLS protocol offering based on SNI ''' Test.SkipUnless( Condition.HasOpenSSLVersion("1.1.1") ) ts = Test.MakeATSProcess("ts", select_ports=True, enable_tls=True) server = Test.MakeOriginServer("server", ssl=True) request_foo_header = {"headers": "GET / HTTP/1.1\r\n\r\n", "timestamp"...
import os import mock import grpc from grpc.experimental import aio import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core imp...
import argparse import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template, request from xml_toolbox import XmlToolbox parser = argparse.ArgumentParser(description='Show transversal xml properties.') parser.add_argument('--debug', '-d', dest='debug', act...
import time import urllib import invoke_ourweather import json def timer_start(): start_time = time.time() return start_time def timer_check(time_passed, method_type): end_time = time.time() - time_passed if end_time > 60: response = "An Error has been encountered with " + method_type + " It has...
import functools import logging from django.utils.decorators import available_attrs import openstackx.admin import openstackx.api.exceptions as openstackx_exceptions import openstackx.extras from horizon.api.base import * LOG = logging.getLogger(__name__) def check_openstackx(f): """Decorator that adds extra info t...
from highton.call_mixins import Call from highton import fields class SearchCallMixin(Call): """ A mixin to search models """ SEARCH_OFFSET = 25 @classmethod def search(cls, term=None, page=0, **criteria): """ Search a list of the model If you use "term": - Return...
import argparse import googleapiclient from googleapiclient.discovery import build from googleapiclient.errors import HttpError from oauth2client.client import GoogleCredentials from datetime import datetime import json credentials = GoogleCredentials.get_application_default() bigquery_service = build('bigquery', 'v2',...
import json from pathlib import Path from . import constants def get_job_dir_component_path(job_dir=None, component_name=None): return Path(job_dir, constants.JOB_DIR_COMPONENT_PATHS[component_name]) def load_job_dir_component(job_dir=None, component_name=None): component_path = get_job_dir_component_path(job_d...
""" Unit tests for Spark ML Python APIs. """ import sys if sys.version_info[:2] <= (2, 6): try: import unittest2 as unittest except ImportError: sys.stderr.write('Please install unittest2 to test with Python 2.6 or earlier') sys.exit(1) else: import unittest from pyspark.tests import...
import hashlib import mock from neutron_lib import constants from neutron.plugins.common import utils from neutron.tests import base LONG_NAME1 = "A_REALLY_LONG_INTERFACE_NAME1" LONG_NAME2 = "A_REALLY_LONG_INTERFACE_NAME2" SHORT_NAME = "SHORT" MOCKED_HASH = "mockedhash" class MockSHA(object): def hexdigest(self): ...