content
string
from contextlib import redirect_stdout import io from unittest import TestCase from unittest.mock import patch from todone.backend import DatabaseError from todone.commands.setup import setup_db, version from todone import config, __version__ from todone.parser import exceptions as pe class TestVersion(TestCase): ...
# -*- coding: utf-8 -*- from django.contrib.sites.models import Site from django.conf import settings from cms.utils.moderator import page_moderator_state, I_APPROVE from cms.utils import get_language_from_request from django.shortcuts import render_to_response from django.template.context import RequestContext from cm...
#-*- coding: utf-8 -*- from django.core.files import File as DjangoFile from django.test.testcases import TestCase from filer.models import tools from filer.models.clipboardmodels import Clipboard from filer.models.foldermodels import Folder from filer.models.imagemodels import Image from filer.tests.helpers import cre...
import unittest from scrapy.http import Request from scrapy.item import BaseItem from scrapy.utils.spider import iterate_spider_output, iter_spider_classes from scrapy.contrib.spiders import CrawlSpider class MyBaseSpider(CrawlSpider): pass # abstract spider class MySpider1(MyBaseSpider): name = 'myspider1'...
from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu...
""" This module contains a base type which provides list-style mutations without specific data storage methods. See also http://www.aryehleib.com/MutableLists.html Author: Aryeh Leib Taurog. """ from django.utils.functional import total_ordering from django.utils import six from django.utils.six.moves import xrange ...
import json import base64 def request(url, user, passwd, data=None, method=None): if data: data = json.dumps(data) # NOTE: fetch_url uses a password manager, which follows the # standard request-then-challenge basic-auth semantics. However as # JIRA allows some unauthorised operations it doesn...
#!/usr/bin/env python '''Simple test with a blocking C++ method that should allow python threads to run.''' import unittest import threading from sample import Bucket class Unlocker(threading.Thread): def __init__(self, bucket): threading.Thread.__init__(self) self.bucket = bucket def ...
from django import forms from django.contrib.admin.util import (flatten_fieldsets, lookup_field, display_for_field, label_for_field, help_text_for_field) from django.contrib.admin.templatetags.admin_static import static from django.contrib.contenttypes.models import ContentType from django.core.exceptions import Ob...
import openerp.tests.common as test_common class TestPickingInvoicing(test_common.SingleTransactionCase): def setUp(self): super(TestPickingInvoicing, self).setUp() self.picking_model = self.env['stock.picking'] self.move_model = self.env['stock.move'] self.invoice_wizard = self.e...
from __future__ import unicode_literals from django.contrib import auth from django.contrib.auth.hashers import ( check_password, is_password_usable, make_password, ) from django.contrib.auth.signals import user_logged_in from django.contrib.contenttypes.models import ContentType from django.core import validators...
import errno import os import os.path import logging import time import hashlib import tempfile from contextlib import contextmanager from functools import wraps from path import Path def reducehashdict(dict, keys): """pull the given keys out of the dictionary, return the reduced dictionary and the sha1 hash ...
from flask import jsonify, request, current_app, url_for from . import api from ..models import User, Post @api.route('/users/<int:id>') def get_user(id): user = User.query.get_or_404(id) return jsonify(user.to_json()) @api.route('/users/<int:id>/posts/') def get_user_posts(id): user = User.query.get_or...
import os import time import platform from avocado import Test from avocado import skipIf from avocado.utils import archive, build, cpu, genio, linux_modules, process from avocado.utils.software_manager import SoftwareManager IS_POWER_NV = 'PowerNV' in genio.read_file('/proc/cpuinfo') class DBLIPIStrom(Test): "...
""" PostgreSQL database backend for Django. Requires psycopg 2: http://initd.org/projects/psycopg2 """ from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures from django.db.backends.postgresql.operations import DatabaseOperations as PostgresqlDatabaseOperations from django.utils.safestring import Sa...
"""Sparse Equations and Least Squares. The original Fortran code was written by C. C. Paige and M. A. Saunders as described in C. C. Paige and M. A. Saunders, LSQR: An algorithm for sparse linear equations and sparse least squares, TOMS 8(1), 43--71 (1982). C. C. Paige and M. A. Saunders, Algorithm 583; LSQR: Sparse...
# -*- coding: utf-8 -*- """Module handling report menus contents""" from contextlib import contextmanager from . import Report from cfme.fixtures import pytest_selenium as sel from cfme.intelligence.reports.ui_elements import FolderManager from cfme.web_ui import Region, BootstrapTreeview, Tree, accordion, form_button...
from ipalib import api, errors from ipalib import Str from ipalib import Object, Command from ipalib import _ from ipalib.plugable import Registry from ipapython.dn import DN __doc__ = _(""" Kerberos pkinit options Enable or disable anonymous pkinit using the principal WELLKNOWN/ANONYMOUS@REALM. The server must have ...
from pcs.lib.cib.resource import remote_node, guest_node from pcs.lib.xml_tools import get_root def get_existing_nodes_names(corosync_conf=None, cib=None): return __get_nodes_names(*__get_nodes(corosync_conf, cib)) def get_existing_nodes_names_addrs(corosync_conf=None, cib=None): corosync_nodes, remote_and_g...
""" Tests for analytics.distributions """ from django.test import TestCase from nose.tools import raises from student.models import CourseEnrollment from student.tests.factories import UserFactory from opaque_keys.edx.locations import SlashSeparatedCourseKey from instructor_analytics.distributions import profile_dist...
from __future__ import absolute_import, division, unicode_literals import os import flask from flask import Flask, Response from mo_hg.relay.cache import Cache from mo_json import value2json from mo_logs import Except, Log, constants, startup from pyLibrary.env.flask_wrappers import cors_wrapper APP_NAME = "HG Rela...
"""Runs a test repeatedly to measure its flakiness. The return code is non-zero if the failure rate is higher than the specified threshold, but is not 100%.""" import argparse import multiprocessing.dummy import subprocess import sys import time def load_options(): parser = argparse.ArgumentParser(description=__doc...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Lector: spellchecker.py Copyright (C) 2009, John Schember Modified for Lector by Zdenko Podobný This code is released under MIT licence """ import re from PyQt4.Qt import Qt, QAction from PyQt4.Qt import QSyntaxHighlighter, QTextCharFormat from PyQt4...
from autothreadharness.harness_case import HarnessCase import unittest class Leader_7_1_6(HarnessCase): role = HarnessCase.ROLE_LEADER case = '7 1 6' golden_devices_required = 4 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
"""Prepare Performance Test Bisect Tool This script is used by a try bot to create a working directory and sync an initial copy of the depot for use in bisecting performance regressions. An example usage: ./tools/prepare-bisect-perf-regressions.py --working_directory "~/builds" --output_buildbot_annotations Would...
"""Tests for classification of TarFileStrings.""" __author__ = 'Tarashish Mishra' import base64 import os import unittest from core.domain import fs_domain from extensions.rules import tar_file_string import utils class TarFileStringRuleUnitTests(unittest.TestCase): """Tests for rules operating on UnicodeStrin...
from __future__ import unicode_literals import frappe import json no_value_fields = ('Section Break', 'Column Break', 'HTML', 'Table', 'Button', 'Image', 'Fold', 'Heading') display_fieldtypes = ('Section Break', 'Column Break', 'HTML', 'Button', 'Image', 'Fold', 'Heading') default_fields = ('doctype','name','owner','...
import os import json import collections import pytest from . placebo_fixtures import placeboify, maybe_sleep from ansible.modules.cloud.amazon import data_pipeline from ansible.module_utils._text import to_text # test_api_gateway.py requires the `boto3` and `botocore` modules boto3 = pytest.importorskip('boto3') ...
# -- encoding: UTF-8 -- from hayes.analysis import AnalysisBase, builtin_simple_analyzer from hayes.utils import object_to_dict class DocumentIndex(object): name = None fields = {} enable_source = True enable_size = False enable_timestamp = False def get_model(self): # For Django compat. return None def g...
import multiprocessing import os import sys import mozlog import grouping_formatter here = os.path.split(__file__)[0] servo_root = os.path.abspath(os.path.join(here, "..", "..")) def wpt_path(*args): return os.path.join(here, *args) def servo_path(*args): return os.path.join(servo_root, *args) # Imports s...
# -*- coding: utf-8 -*- """Implemention of various Tractography methods these tools are meant to be paired with diffusion reconstruction methods from dipy.reconst This module uses the trackvis coordinate system, for more information about this coordinate system please see dipy.tracking.utils The following modules als...
# -*- coding: utf-8 -*- """ ===================================================================== Spectro-temporal receptive field (STRF) estimation on continuous data ===================================================================== This demonstrates how an encoding model can be fit with multiple continuous input...
import time from openerp.osv import osv from openerp.tools.translate import _ from openerp.report import report_sxw from common_report_header import common_report_header class partner_balance(report_sxw.rml_parse, common_report_header): def __init__(self, cr, uid, name, context=None): super(partner_balan...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleError from ansible.plugins.action import ActionBase from ansible.utils.vars import merge_hash class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): # individual m...
import time from openerp.report import report_sxw class pos_lines(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(pos_lines, self).__init__(cr, uid, name, context=context) self.total = 0.0 self.localcontext.update({ 'time': time, 'total_quan...
{ 'name': 'Expense Tracker', 'version': '2.0', 'category': 'Human Resources', 'sequence': 95, 'summary': 'Expenses Validation, Invoicing', 'description': """ Manage expenses by Employees ============================ This application allows you to manage your employees' daily expenses. It gives ...
from django.core.management.base import BaseCommand from optparse import make_option class Command(BaseCommand): """ Script Class. """ option_list = BaseCommand.option_list + ( make_option('--drop', '-d', dest='drop', action="store_tru...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import json from ansible.plugins.terminal import TerminalBase from ansible.errors import AnsibleConnectionFailure class TerminalModule(TerminalBase): terminal_stdout_re = [ re.compile(r"[\r\n]?[\w+\-\.:\/\...
import os from unittest import SkipTest from django.contrib.staticfiles.testing import StaticLiveServerCase from django.utils.module_loading import import_string from django.utils.translation import ugettext as _ class AdminSeleniumWebDriverTestCase(StaticLiveServerCase): available_apps = [ 'django.cont...
# Edge creation logic def add_edge(edge, i, j): if i < j: edge.add((i,j)) else: edge.add((j,i)) def srt2(i,j): if i > j: return j,i return i,j def add_all_redge(edge, pdb, res_table, oi, ai, oj, aj): mino = min(oi,oj) maxo = max(oi,oj) for i in reversed(range(len(re...
"""Class representing an X.509 certificate chain.""" from utils import cryptomath from X509 import X509 class X509CertChain: """This class represents a chain of X.509 certificates. @type x509List: list @ivar x509List: A list of L{tlslite.X509.X509} instances, starting with the end-entity certificate ...
""" LoginRadius BaseOAuth2 backend, docs at: http://psa.matiasaguirre.net/docs/backends/loginradius.html """ from social.backends.oauth import BaseOAuth2 class LoginRadiusAuth(BaseOAuth2): """LoginRadius BaseOAuth2 authentication backend.""" name = 'loginradius' ID_KEY = 'ID' ACCESS_TOKEN_URL = 'h...
# -*- coding: utf-8 -*- from sympy.physics.unitsystems.dimensions import Dimension, DimensionSystem from sympy.physics.unitsystems.units import Unit, UnitSystem from sympy.physics.unitsystems.quantities import Quantity from sympy.utilities.pytest import raises length = Dimension(name="length", symbol="L", length=1) m...
"""System tests for Google Cloud Build operators""" from tests.providers.google.cloud.operators.test_sftp_to_gcs_system_helper import SFTPtoGcsTestHelper from tests.providers.google.cloud.utils.gcp_authenticator import GCP_GCS_KEY from tests.test_utils.gcp_system_helpers import CLOUD_DAG_FOLDER, provide_gcp_context, s...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline ...
"""Utility to convert the output of batch prediction into a CSV submission. It converts the JSON files created by the command 'gcloud beta ml jobs submit prediction' into a CSV file ready for submission. """ import json import tensorflow as tf from builtins import range from tensorflow import app from tensorflow imp...
from itertools import product from lasagne.layers import get_output import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T def plot_loss(net): train_loss = [row['train_loss'] for row in net.train_history_] valid_loss = [row['valid_loss'] for row in net.train_history_] ...
import logging from django.conf import settings from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard import api LOG = logging.getLogger(__name__) # Predefined provider ...
#! /bin/env python # -*- coding: utf-8 -*- # Use when Calisphere Object URLs for a collection change, to generate # a redirect file mapping 'old' (on SOLR-PROD) to 'new' (on SOLR-TEST) URLs. # # This script takes a Collection ID and a 'match' field in SOLR (i.e. best # field to use for matching SOLR-PROD record to cor...
""" pdfpath.py Classes for representing path information in PDF documents. Path state command support. """ class Path: def __init__(self, subpaths, clipping, painting): self.subpaths = subpaths self.clipping = clipping self.painting = painting class Subpath: def __init__(self, con...
"""Support for Entropy Ops. See ${python/contrib.bayesflow.entropy}.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.contrib.bayesflow.python.ops.entropy_impl import * # pylint: en...
""" The Spatial Reference class, represensents OGR Spatial Reference objects. Example: >>> from django.contrib.gis.gdal import SpatialReference >>> srs = SpatialReference('WGS84') >>> print srs GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORI...
import sys import unittest try: import simplejson as json except ImportError: import json from libcloud.utils.py3 import httplib from libcloud.utils.py3 import urlparse from libcloud.utils.py3 import b from libcloud.utils.py3 import parse_qsl from libcloud.common.cloudstack import CloudStackConnection from l...
from itertools import chain from django.apps import apps from django.core.checks import Error def check_generic_foreign_keys(app_configs=None, **kwargs): from .fields import GenericForeignKey if app_configs is None: models = apps.get_models() else: models = chain.from_iterable(app_config...
""" ========================================================== Sample pipeline for text feature extraction and evaluation ========================================================== The dataset used in this example is the 20 newsgroups dataset which will be automatically downloaded and then cached and reused for the do...
""" ========================================= Image denoising using dictionary learning ========================================= An example comparing the effect of reconstructing noisy fragments of the Lena image using firstly online :ref:`DictionaryLearning` and various transform methods. The dictionary is fitted o...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, CloudStackException, cs_argument_spec, cs_requ...
from .utils import install_locale, get_home_pos install_locale('pronterface') import wx import sys import os import time import types import re import math import logging from printrun import gcoder from printrun.objectplater import make_plater, PlaterPanel from printrun.gl.libtatlin import actors import printrun.gui...
""" Directives for typically HTML-specific constructs. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import Directive from docutils.parsers.rst import states from docutils.transforms import components class MetaBody(states.SpecializedBody): class ...
import py import svntestbase from py.path import SvnAuth import time import sys svnbin = py.path.local.sysfind('svn') def make_repo_auth(repo, userdata): """ write config to repo user information in userdata is used for auth userdata has user names as keys, and a tuple (password, readwrite) as ...
''' Created on 04.05.2013 @author: capone ''' from crashtec.db.provider import routines as dbroutines from crashtec.db.schema.fields import PRIMARY_KEY_FIELD import dbmodel # Utility class which used to make hack with meta-classes. See results_metaclass() class Acceptor(object): def __init__(self, class_name)...
from __future__ import print_function from pyspark.sql import SparkSession from pyspark.ml.param import Params from pyspark.mllib.linalg import * import sys if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("PipSanityCheck")\ .getOrCreate() sc = spark.sparkContext ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' network ping sensor. ''' from ping import do_one as ping from whmonit.client.sensors import TaskSensorBase from whmonit.common.units import unit_reg class Sensor(TaskSensorBase): '''Generic 'ping' sensor.''' # W0232: Class has no __init__ method # R0201:...
import os import sys import json import doctest import unittest from test import test_support # import json with and without accelerations cjson = test_support.import_fresh_module('json', fresh=['_json']) pyjson = test_support.import_fresh_module('json', blocked=['_json']) # create two base classes that will be used...
from datetime import datetime from datetime import timedelta from mock import patch from mock import MagicMock from functional import actions from modules.um_assessments.model import AsmDateDAO from modules.um_assessments.service import AsmDates START = datetime.utcnow() - timedelta(days=1) END = datetime.utcnow()...
from openerp import models, api from collections import defaultdict class Picking(models.Model): _inherit = 'stock.picking' @api.model def _prepare_pack_ops(self, picking, quants, forced_qties): """Get the owner from the moves instead of the picking. The only case we need to fix is the ...
#!/usr/bin/python import sys import os import os.path import cStringIO import re def get_cur_dir(): path = sys.path[0] if os.path.isdir(path): return path elif os.path.isfile(path): return os.path.dirname(path) CUR_DIR = get_cur_dir() COCOS_ROOT = os.path.abspath(os.path.join(CUR_DIR, ".....
#! /usr/bin/env python """ Affine spatial transformation """ import numpy as np from numpy.linalg import inv import argparse, sys, csv, os, time def getArgs(): parser = argparse.ArgumentParser( description = """Affine spatial transformation""" ) parser.add_argument( "-c", "--controlPoints", type = str, re...
from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.scheduler import filters LOG = logging.getLogger(__name__) class ImagePropertiesFilter(filters.BaseHostFilter): """Filter compute nodes that satisfy instance image properties. The ImagePropertiesFilt...
import copy from keystone.common import sql from keystone import exception from keystone.openstack.common import timeutils from keystone import token class TokenModel(sql.ModelBase, sql.DictBase): __tablename__ = 'token' attributes = ['id', 'expires', 'user_id', 'trust_id'] id = sql.Column(sql.String(64)...
"""Support for RSS/Atom feeds.""" from datetime import datetime, timedelta from logging import getLogger from os.path import exists from threading import Lock import pickle import voluptuous as vol import feedparser from homeassistant.const import EVENT_HOMEASSISTANT_START, CONF_SCAN_INTERVAL from homeassistant.helpe...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import * from django.forms import CharField from django.forms import FileField from django.forms import FileInput from django.forms import Form from django.forms imp...
""" Represents a VPCSecurityGroupMembership """ class VPCSecurityGroupMembership(object): """ Represents VPC Security Group that this RDS database is a member of Properties reference available from the AWS documentation at http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/\ API_VpcSecurity...
"""Unit test for Google Test's break-on-failure mode. A user can ask Google Test to seg-fault when an assertion fails, using either the GTEST_BREAK_ON_FAILURE environment variable or the --gtest_break_on_failure flag. This script tests such functionality by invoking gtest_break_on_failure_unittest_ (a program written...
"""Tests for tensorflow.ctc_ops.ctc_decoder_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf def SimpleSparseTensorFrom(x): """Create a very simple SparseTensor with dimensions (batch, time). Args: ...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): depends_on = ( ('catalogue', '0001_initial'), ('order', '0001_initial'), ) def forwards(self, orm): # Adding model ...
""" Clickjacking Protection Middleware. This module provides a middleware that implements protection against a malicious site loading resources from your site in a hidden frame. """ from django.conf import settings class XFrameOptionsMiddleware(object): """ Middleware that sets the X-Frame-Options HTTP head...
"""Tool for helpers used in linux building process.""" import os import SCons.Defaults import subprocess def _OutputFromShellCommand(command): process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) return process.communicate()[0].strip() # This is a pure SCons helper function. def _InternalBui...
from __future__ import unicode_literals import unittest, frappe from frappe.test_runner import make_test_records make_test_records("User") make_test_records("Email Account") class TestEmail(unittest.TestCase): def setUp(self): frappe.db.sql("""delete from `tabEmail Unsubscribe`""") frappe.db.sql("""delete from ...
import re from django.contrib.auth.views import ( INTERNAL_RESET_SESSION_TOKEN, INTERNAL_RESET_URL_TOKEN, ) from django.test import Client def extract_token_from_url(url): token_search = re.search(r'/reset/.*/(.+?)/', url) if token_search: return token_search.group(1) class PasswordResetConfirm...
import os import re import sys import traceback import subprocess def check_output(*popenargs, **kwargs): process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: raise ValueError((retcode, output)) ...
""" Some priors for GPy. Author: Ilias Bilionis Date: 5/5/2015 """ __all__ = ['LogLogisticPrior', 'JeffreysPrior'] import GPy import numpy as np class LogLogisticPrior(GPy.priors.Prior): """ Log-Logistic prior suitable for lengthscale parameters. From Conti & O'Hagan (2010) """ ...
"""upgradewallet RPC functional test Test upgradewallet RPC. Download node binaries: test/get_previous_releases.py -b v0.19.1 v0.18.1 v0.17.2 v0.16.3 v0.15.2 Only v0.15.2 and v0.16.3 are required by this test. The others are used in feature_backwards_compatibility.py """ import os import shutil import struct from ...
# fiducialMon.py import time import RO.Wdg import Tkinter import TUI.Models import TUI.PlaySound class ScriptClass(object): def __init__(self, sr): # if True, run in debug-only mode (which doesn't DO anything) # if False, real time run sr.debug = False self.name="fiducialMon" ...
from nose.tools import * from framework.auth.core import Auth from framework.exceptions import PermissionsError from website import settings from website.addons.base import AddonConfig from website.addons.base import AddonOAuthNodeSettingsBase from website.addons.base import AddonOAuthUserSettingsBase from website.oa...
# -*- coding: utf-8 -*- # @Time : 2018/2/8 16:09 # @Author : play4fun # @File : Displaying a video feed with OpenCV and Tkinter.py # @Software: PyCharm """ Displaying a video feed with OpenCV and Tkinter.py: https://www.pyimagesearch.com/2016/05/30/displaying-a-video-feed-with-opencv-and-tkinter/ """ # import...
import collections import command import gitutil import os import re import sys import terminal def FindCheckPatch(): top_level = gitutil.GetTopLevel() try_list = [ os.getcwd(), os.path.join(os.getcwd(), '..', '..'), os.path.join(top_level, 'tools'), os.path.join(top_level, 'scr...
""" Copyright 2014 Google 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 applicable law or agreed to in...
import mxnet as mx import os import logging import argparse from math import ceil import sparse_sgd # symbol net def get_symbol(): data = mx.symbol.Variable('data') fc1 = mx.symbol.FullyConnected(data, name='fc1', num_hidden=128) act1 = mx.symbol.Activation(fc1, name='relu1', act_type="relu") fc2 = mx....
"""Tests for MultivariateNormal.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class MultivariateNormalTest(tf.test.TestCase): def testNonmatchingMuSigmaFails(self): with tf.Session(): mvn = tf....
from django.db import models from django.db import utils import datetime import hashlib import re class BadSequenceError(Exception): def __init__(self,why): self.why = why def __str__(self): return repr(self.why) class Giraffe_Mappable_Model(models.Model): """ This is an abstract cla...
import bzrlib.patiencediff # from bzrlib.textfile import check_text_lines def intersect(ra, rb): """Given two ranges return the range where they intersect or None. >>> intersect((0, 10), (0, 6)) (0, 6) >>> intersect((0, 10), (5, 15)) (5, 10) >>> intersect((0, 10), (10, 15)) >>> intersect(...
from tornado import gen from . import spotifyMix as spot from lib.database.auth import save_token from lib.basehandler import OAuthRequestHandler class SpotifyAuth(OAuthRequestHandler, spot.SpotifyOAuth2Mixin): scope = [ 'playlist-read-private', 'playlist-read-collaborative', 'user-follow...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.six import iteritems, string_types from ansible.module_utils.parsing.convert_bool import boolean from ansible.plugins.action import ActionBase from ansible.utils.vars import isidentifier class ActionModu...
from modules.OsmoseTranslation import T_ from .Analyser_Osmosis import Analyser_Osmosis sql10 = """ SELECT DISTINCT ON (highways.id) highways.id, ST_AsText(nodes.geom) FROM {0}highways AS motorways JOIN {1}highways AS highways ON highways.linestring && motorways.linestring AND highways.nodes && motorwa...
""" NSX data models. This module defines data models used by the VMware NSX plugin family. """ import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy import sql from neutron.db import model_base from neutron.db import models_v2 class TzNetworkBinding(model_base.BASEV2): """Represents a binding of ...
import cgi import json import os import traceback import urllib import urlparse from constants import content_types from pipes import Pipeline, template from ranges import RangeParser from request import Authentication from response import MultipartContent from utils import HTTPException __all__ = ["file_handler", "p...
import sys import os if(len(sys.argv) < 3): print print '\t'+sys.argv[0] + ' - Generate final byte for XOR LRC' print print 'Usage: ' + sys.argv[0] + ' <ID Byte1> <ID Byte2> ... <LRC>' print print '\tSpecifying the bytes of a UID with a known LRC will find the last byte value' print '\tneeded to generate that L...
#!/usr/bin/python3 -u # given an arbitrary piece of Python data, encode it in such a manner # that it can be later encoded into JSON. # http://json.org/ # # Format: # * None, int, float, str, bool - unchanged (long is removed in Python 3) # (json.dumps encodes these fine verbatim) # * list - ['LIST', ...
from __future__ import unicode_literals from calendar import timegm from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import Http404, HttpResponse from django.template import Templat...