repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
Bjay1435/capstone | refs/heads/master | rootfs/usr/lib/python3.4/distutils/command/build_scripts.py | 92 | """distutils.command.build_scripts
Implements the Distutils 'build_scripts' command."""
import os, re
from stat import ST_MODE
from distutils import sysconfig
from distutils.core import Command
from distutils.dep_util import newer
from distutils.util import convert_path, Mixin2to3
from distutils import log
import tokenize
# check if Python is called on the first line with this expression
first_line_re = re.compile(b'^#!.*python[0-9.]*([ \t].*)?$')
class build_scripts(Command):
description = "\"build\" scripts (copy and fixup #! line)"
user_options = [
('build-dir=', 'd', "directory to \"build\" (copy) to"),
('force', 'f', "forcibly build everything (ignore file timestamps"),
('executable=', 'e', "specify final destination interpreter path"),
]
boolean_options = ['force']
def initialize_options(self):
self.build_dir = None
self.scripts = None
self.force = None
self.executable = None
self.outfiles = None
def finalize_options(self):
self.set_undefined_options('build',
('build_scripts', 'build_dir'),
('force', 'force'),
('executable', 'executable'))
self.scripts = self.distribution.scripts
def get_source_files(self):
return self.scripts
def run(self):
if not self.scripts:
return
self.copy_scripts()
def copy_scripts(self):
"""Copy each script listed in 'self.scripts'; if it's marked as a
Python script in the Unix way (first line matches 'first_line_re',
ie. starts with "\#!" and contains "python"), then adjust the first
line to refer to the current Python interpreter as we copy.
"""
self.mkpath(self.build_dir)
outfiles = []
updated_files = []
for script in self.scripts:
adjust = False
script = convert_path(script)
outfile = os.path.join(self.build_dir, os.path.basename(script))
outfiles.append(outfile)
if not self.force and not newer(script, outfile):
log.debug("not copying %s (up-to-date)", script)
continue
# Always open the file, but ignore failures in dry-run mode --
# that way, we'll get accurate feedback if we can read the
# script.
try:
f = open(script, "rb")
except OSError:
if not self.dry_run:
raise
f = None
else:
encoding, lines = tokenize.detect_encoding(f.readline)
f.seek(0)
first_line = f.readline()
if not first_line:
self.warn("%s is an empty file (skipping)" % script)
continue
match = first_line_re.match(first_line)
if match:
adjust = True
post_interp = match.group(1) or b''
if adjust:
log.info("copying and adjusting %s -> %s", script,
self.build_dir)
updated_files.append(outfile)
if not self.dry_run:
if not sysconfig.python_build:
executable = self.executable
else:
executable = os.path.join(
sysconfig.get_config_var("BINDIR"),
"python%s%s" % (sysconfig.get_config_var("VERSION"),
sysconfig.get_config_var("EXE")))
executable = os.fsencode(executable)
shebang = b"#!" + executable + post_interp + b"\n"
# Python parser starts to read a script using UTF-8 until
# it gets a #coding:xxx cookie. The shebang has to be the
# first line of a file, the #coding:xxx cookie cannot be
# written before. So the shebang has to be decodable from
# UTF-8.
try:
shebang.decode('utf-8')
except UnicodeDecodeError:
raise ValueError(
"The shebang ({!r}) is not decodable "
"from utf-8".format(shebang))
# If the script is encoded to a custom encoding (use a
# #coding:xxx cookie), the shebang has to be decodable from
# the script encoding too.
try:
shebang.decode(encoding)
except UnicodeDecodeError:
raise ValueError(
"The shebang ({!r}) is not decodable "
"from the script encoding ({})"
.format(shebang, encoding))
with open(outfile, "wb") as outf:
outf.write(shebang)
outf.writelines(f.readlines())
if f:
f.close()
else:
if f:
f.close()
updated_files.append(outfile)
self.copy_file(script, outfile)
if os.name == 'posix':
for file in outfiles:
if self.dry_run:
log.info("changing mode of %s", file)
else:
oldmode = os.stat(file)[ST_MODE] & 0o7777
newmode = (oldmode | 0o555) & 0o7777
if newmode != oldmode:
log.info("changing mode of %s from %o to %o",
file, oldmode, newmode)
os.chmod(file, newmode)
# XXX should we modify self.outfiles?
return outfiles, updated_files
class build_scripts_2to3(build_scripts, Mixin2to3):
def copy_scripts(self):
outfiles, updated_files = build_scripts.copy_scripts(self)
if not self.dry_run:
self.run_2to3(updated_files)
return outfiles, updated_files
|
wolfram74/numerical_methods_iserles_notes | refs/heads/master | venv/lib/python2.7/site-packages/IPython/kernel/zmq/heartbeat.py | 2 | """The client and server for a basic ping-pong style heartbeat.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import errno
import os
import socket
from threading import Thread
import zmq
from IPython.utils.localinterfaces import localhost
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
class Heartbeat(Thread):
"A simple ping-pong style heartbeat that runs in a thread."
def __init__(self, context, addr=None):
if addr is None:
addr = ('tcp', localhost(), 0)
Thread.__init__(self)
self.context = context
self.transport, self.ip, self.port = addr
if self.port == 0:
if addr[0] == 'tcp':
s = socket.socket()
# '*' means all interfaces to 0MQ, which is '' to socket.socket
s.bind(('' if self.ip == '*' else self.ip, 0))
self.port = s.getsockname()[1]
s.close()
elif addr[0] == 'ipc':
self.port = 1
while os.path.exists("%s-%s" % (self.ip, self.port)):
self.port = self.port + 1
else:
raise ValueError("Unrecognized zmq transport: %s" % addr[0])
self.addr = (self.ip, self.port)
self.daemon = True
def run(self):
self.socket = self.context.socket(zmq.ROUTER)
self.socket.linger = 1000
c = ':' if self.transport == 'tcp' else '-'
self.socket.bind('%s://%s' % (self.transport, self.ip) + c + str(self.port))
while True:
try:
zmq.device(zmq.QUEUE, self.socket, self.socket)
except zmq.ZMQError as e:
if e.errno == errno.EINTR:
continue
else:
raise
else:
break
|
GiovanniConserva/TestDeploy | refs/heads/master | venv/Lib/site-packages/binstar_client/commands/whoami.py | 1 | '''
Print the information of the current user
'''
from __future__ import unicode_literals
from binstar_client import errors
from binstar_client.utils import get_server_api
from binstar_client.utils.pprint import pprint_user
import logging
log = logging.getLogger('binstar.whoami')
def main(args):
aserver_api = get_server_api(args.token, args.site, args.log_level)
try:
user = aserver_api.user()
except errors.Unauthorized as err:
log.debug(err)
log.info('Anonymous User')
return 1
pprint_user(user)
def add_parser(subparsers):
subparser = subparsers.add_parser('whoami',
help='Print the information of the current user',
description=__doc__)
subparser.set_defaults(main=main)
|
ali-filth/android_kernel_samsung_msm8226 | refs/heads/cm-11.0 | tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Util.py | 12527 | # Util.py - Python extension for perf script, miscellaneous utility code
#
# Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com>
#
# This software may be distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
import errno, os
FUTEX_WAIT = 0
FUTEX_WAKE = 1
FUTEX_PRIVATE_FLAG = 128
FUTEX_CLOCK_REALTIME = 256
FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME)
NSECS_PER_SEC = 1000000000
def avg(total, n):
return total / n
def nsecs(secs, nsecs):
return secs * NSECS_PER_SEC + nsecs
def nsecs_secs(nsecs):
return nsecs / NSECS_PER_SEC
def nsecs_nsecs(nsecs):
return nsecs % NSECS_PER_SEC
def nsecs_str(nsecs):
str = "%5u.%09u" % (nsecs_secs(nsecs), nsecs_nsecs(nsecs)),
return str
def add_stats(dict, key, value):
if not dict.has_key(key):
dict[key] = (value, value, value, 1)
else:
min, max, avg, count = dict[key]
if value < min:
min = value
if value > max:
max = value
avg = (avg + value) / 2
dict[key] = (min, max, avg, count + 1)
def clear_term():
print("\x1b[H\x1b[2J")
audit_package_warned = False
try:
import audit
machine_to_id = {
'x86_64': audit.MACH_86_64,
'alpha' : audit.MACH_ALPHA,
'ia64' : audit.MACH_IA64,
'ppc' : audit.MACH_PPC,
'ppc64' : audit.MACH_PPC64,
's390' : audit.MACH_S390,
's390x' : audit.MACH_S390X,
'i386' : audit.MACH_X86,
'i586' : audit.MACH_X86,
'i686' : audit.MACH_X86,
}
try:
machine_to_id['armeb'] = audit.MACH_ARMEB
except:
pass
machine_id = machine_to_id[os.uname()[4]]
except:
if not audit_package_warned:
audit_package_warned = True
print "Install the audit-libs-python package to get syscall names"
def syscall_name(id):
try:
return audit.audit_syscall_to_name(id, machine_id)
except:
return str(id)
def strerror(nr):
try:
return errno.errorcode[abs(nr)]
except:
return "Unknown %d errno" % nr
|
RobertWalsh/zBar | refs/heads/master | python/examples/read_one.py | 38 | #!/usr/bin/python
from sys import argv
import zbar
# create a Processor
proc = zbar.Processor()
# configure the Processor
proc.parse_config('enable')
# initialize the Processor
device = '/dev/video0'
if len(argv) > 1:
device = argv[1]
proc.init(device)
# enable the preview window
proc.visible = True
# read at least one barcode (or until window closed)
proc.process_one()
# hide the preview window
proc.visible = False
# extract results
for symbol in proc.results:
# do something useful with results
print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
|
laenderoliveira/exerclivropy | refs/heads/master | cap08/listagem-08-09.py | 1 | def fatorial(x):
fat = 1
while x > 1:
fat *= x
x -= 1
return fat
print(fatorial(0)) |
geimer/easybuild-easyblocks | refs/heads/master | easybuild/easyblocks/generic/toolchain.py | 4 | ##
# Copyright 2009-2013 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (http://www.herculesstichting.be/in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for installing compiler toolchains, implemented as an easyblock
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
"""
from easybuild.framework.easyblock import EasyBlock
class Toolchain(EasyBlock):
"""
Compiler toolchain: generate module file only, nothing to build/install
"""
def configure_step(self):
"""Do nothing."""
pass
def build_step(self):
"""Do nothing."""
pass
def install_step(self):
"""Do nothing."""
pass
def sanity_check_step(self):
"""
As a toolchain doesn't install anything really, this is always OK
"""
pass
|
SPKian/Testing | refs/heads/master | erpnext/patches/v5_0/newsletter.py | 60 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
import frappe.permissions
def execute():
frappe.reload_doc("core", "doctype", "block_module")
frappe.reload_doctype("User")
frappe.reload_doctype("Lead")
frappe.reload_doctype("Contact")
frappe.reload_doc('crm', 'doctype', 'newsletter_list')
frappe.reload_doc('crm', 'doctype', 'newsletter_list_subscriber')
frappe.reload_doc('crm', 'doctype', 'newsletter')
frappe.permissions.reset_perms("Newsletter")
if not frappe.db.exists("Role", "Newsletter Manager"):
frappe.get_doc({"doctype": "Role", "role": "Newsletter Manager"}).insert()
for userrole in frappe.get_all("UserRole", "parent", {"role": "Sales Manager"}):
if frappe.db.exists("User", userrole.parent):
user = frappe.get_doc("User", userrole.parent)
user.append("user_roles", {
"doctype": "UserRole",
"role": "Newsletter Manager"
})
user.flags.ignore_mandatory = True
user.save()
# create default lists
general = frappe.new_doc("Newsletter List")
general.title = "General"
general.insert()
general.import_from("Lead")
general.import_from("Contact")
|
nrwahl2/ansible | refs/heads/devel | lib/ansible/module_utils/cnos_devicerules.py | 87 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by
# Ansible still belong to the author of the module, and may assign their
# own license to the complete work.
#
# Copyright (C) 2017 Lenovo, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Contains device rule and methods
# Lenovo Networking
def getRuleString(deviceType, variableId):
retVal = variableId + ":"
if(deviceType == 'g8272_cnos'):
if variableId in g8272_cnos:
retVal = retVal + g8272_cnos[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
elif(deviceType == 'g8296_cnos'):
if variableId in g8296_cnos:
retVal = retVal + g8296_cnos[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
elif(deviceType == 'g8332_cnos'):
if variableId in g8332_cnos:
retVal = retVal + g8332_cnos[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
elif(deviceType == 'NE1072T'):
if variableId in NE1072T:
retVal = retVal + NE1072T[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
elif(deviceType == 'NE1032'):
if variableId in NE1032:
retVal = retVal + NE1032[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
elif(deviceType == 'NE1032T'):
if variableId in NE1032T:
retVal = retVal + NE1032T[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
elif(deviceType == 'NE10032'):
if variableId in NE10032:
retVal = retVal + NE10032[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
elif(deviceType == 'NE2572'):
if variableId in NE2572:
retVal = retVal + NE2572[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
else:
if variableId in default_cnos:
retVal = retVal + default_cnos[variableId]
else:
retVal = "The variable " + variableId + " is not supported"
return retVal
# EOM
default_cnos = {
'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-64',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-32',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-32',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,\
interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,\
trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,\
input,output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,\
vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:1000,10000,100000,25000,40000,50000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
NE2572 = {
'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-64',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-54',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-54',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,input,\
output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:10000,100000,25000,40000,50000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
NE1032T = {
'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-64',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-32',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-32',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,input,\
output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:1000,10000,100000,25000,40000,50000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
NE1032 = {
'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-64',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-32',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-32',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,input,\
output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:1000,10000,100000,25000,40000,50000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
NE1072T = {
'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-64',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-54',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-54',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,input,\
output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:1000,10000,100000,25000,40000,50000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
NE10032 = {
'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-64',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-32',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-32',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,input,\
output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:10000,100000,25000,40000,50000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
g8272_cnos = {'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-64',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-54',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-54',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,input,\
output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:1000,10000,40000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
g8296_cnos = {'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-128',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-96',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-96',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,\
arp,dhcp,ospf,port,port-unreachable,redirects,router,\
unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,\
input,output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:1000,10000,40000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
g8332_cnos = {'vlan_id': 'INTEGER_VALUE:1-3999',
'vlan_id_range': 'INTEGER_VALUE_RANGE:1-3999',
'vlan_name': 'TEXT:',
'vlan_flood': 'TEXT_OPTIONS:ipv4,ipv6',
'vlan_state': 'TEXT_OPTIONS:active,suspend',
'vlan_last_member_query_interval': 'INTEGER_VALUE:1-25',
'vlan_querier': 'IPV4Address:',
'vlan_querier_timeout': 'INTEGER_VALUE:1-65535',
'vlan_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_query_max_response_time': 'INTEGER_VALUE:1-25',
'vlan_report_suppression': 'INTEGER_VALUE:1-25',
'vlan_robustness_variable': 'INTEGER_VALUE:1-7',
'vlan_startup_query_count': 'INTEGER_VALUE:1-10',
'vlan_startup_query_interval': 'INTEGER_VALUE:1-18000',
'vlan_snooping_version': 'INTEGER_VALUE:2-3',
'vlan_access_map_name': 'TEXT: ',
'vlan_ethernet_interface': 'TEXT:',
'vlan_portagg_number': 'INTEGER_VALUE:1-4096',
'vlan_accessmap_action': 'TEXT_OPTIONS:drop,forward,redirect',
'vlan_dot1q_tag': 'MATCH_TEXT_OR_EMPTY:egress-only',
'vlan_filter_name': 'TEXT:',
'vlag_auto_recovery': 'INTEGER_VALUE:240-3600',
'vlag_config_consistency': 'TEXT_OPTIONS:disable,strict',
'vlag_instance': 'INTEGER_VALUE:1-128',
'vlag_port_aggregation': 'INTEGER_VALUE:1-4096',
'vlag_priority': 'INTEGER_VALUE:0-65535',
'vlag_startup_delay': 'INTEGER_VALUE:0-3600',
'vlag_tier_id': 'INTEGER_VALUE:1-512',
'vlag_hlthchk_options': 'TEXT_OPTIONS:keepalive-attempts,\
keepalive-interval,peer-ip,retry-interval',
'vlag_keepalive_attempts': 'INTEGER_VALUE:1-24',
'vlag_keepalive_interval': 'INTEGER_VALUE:2-300',
'vlag_retry_interval': 'INTEGER_VALUE:1-300',
'vlag_peerip': 'IPV4Address:',
'vlag_peerip_vrf': 'TEXT_OPTIONS:default,management',
'bgp_as_number': 'NO_VALIDATION:1-4294967295',
'bgp_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_bgp_local_count': 'INTEGER_VALUE:2-64',
'cluster_id_as_ip': 'IPV4Address:',
'cluster_id_as_number': 'NO_VALIDATION:1-4294967295',
'confederation_identifier': 'INTEGER_VALUE:1-65535',
'condeferation_peers_as': 'INTEGER_VALUE:1-65535',
'stalepath_delay_value': 'INTEGER_VALUE:1-3600',
'maxas_limit_as': 'INTEGER_VALUE:1-2000',
'neighbor_ipaddress': 'IPV4Address:',
'neighbor_as': 'NO_VALIDATION:1-4294967295',
'router_id': 'IPV4Address:',
'bgp_keepalive_interval': 'INTEGER_VALUE:0-3600',
'bgp_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_aggregate_prefix': 'IPV4AddressWithMask:',
'addrfamily_routemap_name': 'TEXT:',
'reachability_half_life': 'INTEGER_VALUE:1-45',
'start_reuse_route_value': 'INTEGER_VALUE:1-20000',
'start_suppress_route_value': 'INTEGER_VALUE:1-20000',
'max_duration_to_suppress_route': 'INTEGER_VALUE:1-255',
'unreachability_halftime_for_penalty': 'INTEGER_VALUE:1-45',
'distance_external_AS': 'INTEGER_VALUE:1-255',
'distance_internal_AS': 'INTEGER_VALUE:1-255',
'distance_local_routes': 'INTEGER_VALUE:1-255',
'maxpath_option': 'TEXT_OPTIONS:ebgp,ibgp',
'maxpath_numbers': 'INTEGER_VALUE:2-32',
'network_ip_prefix_with_mask': 'IPV4AddressWithMask:',
'network_ip_prefix_value': 'IPV4Address:',
'network_ip_prefix_mask': 'IPV4Address:',
'nexthop_crtitical_delay': 'NO_VALIDATION:1-4294967295',
'nexthop_noncrtitical_delay': 'NO_VALIDATION:1-4294967295',
'addrfamily_redistribute_option': 'TEXT_OPTIONS:direct,ospf,\
static',
'bgp_neighbor_af_occurances': 'INTEGER_VALUE:1-10',
'bgp_neighbor_af_filtername': 'TEXT:',
'bgp_neighbor_af_maxprefix': 'INTEGER_VALUE:1-15870',
'bgp_neighbor_af_prefixname': 'TEXT:',
'bgp_neighbor_af_routemap': 'TEXT:',
'bgp_neighbor_address_family': 'TEXT_OPTIONS:ipv4,ipv6',
'bgp_neighbor_connection_retrytime': 'INTEGER_VALUE:1-65535',
'bgp_neighbor_description': 'TEXT:',
'bgp_neighbor_maxhopcount': 'INTEGER_VALUE:1-255',
'bgp_neighbor_local_as': 'NO_VALIDATION:1-4294967295',
'bgp_neighbor_maxpeers': 'INTEGER_VALUE:1-96',
'bgp_neighbor_password': 'TEXT:',
'bgp_neighbor_timers_Keepalive': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_timers_holdtime': 'INTEGER_VALUE:0-3600',
'bgp_neighbor_ttl_hops': 'INTEGER_VALUE:1-254',
'bgp_neighbor_update_options': 'TEXT_OPTIONS:ethernet,loopback,\
vlan',
'bgp_neighbor_update_ethernet': 'TEXT:',
'bgp_neighbor_update_loopback': 'INTEGER_VALUE:0-7',
'bgp_neighbor_update_vlan': 'INTEGER_VALUE:1-4094',
'bgp_neighbor_weight': 'INTEGER_VALUE:0-65535',
'ethernet_interface_value': 'INTEGER_VALUE:1-32',
'ethernet_interface_range': 'INTEGER_VALUE_RANGE:1-32',
'ethernet_interface_string': 'TEXT:',
'loopback_interface_value': 'INTEGER_VALUE:0-7',
'mgmt_interface_value': 'INTEGER_VALUE:0-0',
'vlan_interface_value': 'INTEGER_VALUE:1-4094',
'portchannel_interface_value': 'INTEGER_VALUE:1-4096',
'portchannel_interface_range': 'INTEGER_VALUE_RANGE:1-4096',
'portchannel_interface_string': 'TEXT:',
'aggregation_group_no': 'INTEGER_VALUE:1-4096',
'aggregation_group_mode': 'TEXT_OPTIONS:active,on,passive',
'bfd_options': 'TEXT_OPTIONS:authentication,echo,interval,ipv4,\
ipv6,neighbor',
'bfd_interval': 'INTEGER_VALUE:50-999',
'bfd_minrx': 'INTEGER_VALUE:50-999',
'bfd_ multiplier': 'INTEGER_VALUE:3-50',
'bfd_ipv4_options': 'TEXT_OPTIONS:authentication,echo,interval',
'bfd_auth_options': 'TEXT_OPTIONS:keyed-md5,keyed-sha1,\
meticulous-keyed-md5,meticulous-keyed-sha1,simple',
'bfd_key_options': 'TEXT_OPTIONS:key-chain,key-id',
'bfd_key_chain': 'TEXT:',
'bfd_key_id': 'INTEGER_VALUE:0-255',
'bfd_key_name': 'TEXT:',
'bfd_neighbor_ip': 'TEXT:',
'bfd_neighbor_options': 'TEXT_OPTIONS:admin-down,multihop,\
non-persistent',
'bfd_access_vlan': 'INTEGER_VALUE:1-3999',
'bfd_bridgeport_mode': 'TEXT_OPTIONS:access,dot1q-tunnel,trunk',
'trunk_options': 'TEXT_OPTIONS:allowed,native',
'trunk_vlanid': 'INTEGER_VALUE:1-3999',
'portCh_description': 'TEXT:',
'duplex_option': 'TEXT_OPTIONS:auto,full,half',
'flowcontrol_options': 'TEXT_OPTIONS:receive,send',
'portchannel_ip_options': 'TEXT_OPTIONS:access-group,address,arp,\
dhcp,ospf,port,port-unreachable,redirects,router,unreachables',
'accessgroup_name': 'TEXT:',
'portchannel_ipv4': 'IPV4Address:',
'portchannel_ipv4_mask': 'TEXT:',
'arp_ipaddress': 'IPV4Address:',
'arp_macaddress': 'TEXT:',
'arp_timeout_value': 'INTEGER_VALUE:60-28800',
'relay_ipaddress': 'IPV4Address:',
'ip_ospf_options': 'TEXT_OPTIONS:authentication,\
authentication-key,bfd,cost,database-filter,dead-interval,\
hello-interval,message-digest-key,mtu,mtu-ignore,network,\
passive-interface,priority,retransmit-interval,shutdown,\
transmit-delay',
'ospf_id_decimal_value': 'NO_VALIDATION:1-4294967295',
'ospf_id_ipaddres_value': 'IPV4Address:',
'lacp_options': 'TEXT_OPTIONS:port-priority,suspend-individual,\
timeout',
'port_priority': 'INTEGER_VALUE:1-65535',
'lldp_options': 'TEXT_OPTIONS:receive,tlv-select,transmit,\
trap-notification',
'lldp_tlv_options': 'TEXT_OPTIONS:link-aggregation,\
mac-phy-status,management-address,max-frame-size,\
port-description,port-protocol-vlan,port-vlan,power-mdi,\
protocol-identity,system-capabilities,system-description,\
system-name,vid-management,vlan-name',
'load_interval_delay': 'INTEGER_VALUE:30-300',
'load_interval_counter': 'INTEGER_VALUE:1-3',
'mac_accessgroup_name': 'TEXT:',
'mac_address': 'TEXT:',
'microburst_threshold': 'NO_VALIDATION:1-4294967295',
'mtu_value': 'INTEGER_VALUE:64-9216',
'service_instance': 'NO_VALIDATION:1-4294967295',
'service_policy_options': 'TEXT_OPTIONS:copp-system-policy,\
input,output,type',
'service_policy_name': 'TEXT:',
'spanning_tree_options': 'TEXT_OPTIONS:bpdufilter,bpduguard,\
cost,disable,enable,guard,link-type,mst,port,port-priority,vlan',
'spanning_tree_cost': 'NO_VALIDATION:1-200000000',
'spanning_tree_interfacerange': 'INTEGER_VALUE_RANGE:1-3999',
'spanning_tree_portpriority': 'TEXT_OPTIONS:0,32,64,96,128,160,\
192,224',
'portchannel_ipv6_neighbor_mac': 'TEXT:',
'portchannel_ipv6_neighbor_address': 'IPV6Address:',
'portchannel_ipv6_linklocal': 'IPV6Address:',
'portchannel_ipv6_dhcp_vlan': 'INTEGER_VALUE:1-4094',
'portchannel_ipv6_dhcp_ethernet': 'TEXT:',
'portchannel_ipv6_dhcp': 'IPV6Address:',
'portchannel_ipv6_address': 'IPV6Address:',
'portchannel_ipv6_options': 'TEXT_OPTIONS:address,dhcp,\
link-local,nd,neighbor',
'interface_speed': 'TEXT_OPTIONS:1000,10000,40000,50000,auto',
'stormcontrol_options': 'TEXT_OPTIONS:broadcast,multicast,\
unicast',
'stormcontrol_level': 'FLOAT:',
'portchannel_dot1q_tag': 'TEXT_OPTIONS:disable,enable,\
egress-only',
'vrrp_id': 'INTEGER_VALUE:1-255',
}
|
dahlstrom-g/intellij-community | refs/heads/master | python/testData/refactoring/changeSignature/positionalOnlyMarkerPropagatesExistingParameterSignatureDefaultToCall.before.py | 10 | def func(a=None, b=None):
pass
func(b=1)
func()
|
Archcady/mbed-os | refs/heads/master | TESTS/netsocket/host_tests/udp_shotgun.py | 39 | """
mbed SDK
Copyright (c) 2011-2013 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import socket
import json
import random
import itertools
import time
from sys import stdout
from threading import Thread
from SocketServer import BaseRequestHandler, UDPServer
from mbed_host_tests import BaseHostTest, event_callback
class UDPEchoClientHandler(BaseRequestHandler):
def handle(self):
""" UDP packet handler. Responds with multiple simultaneous packets
"""
data, sock = self.request
pattern = [ord(d) << 4 for d in data]
# Each byte in request indicates size of packet to recieve
# Each packet size is shifted over by 4 to fit in a byte, which
# avoids any issues with endianess or decoding
for packet in pattern:
data = [random.randint(0, 255) for _ in range(packet-1)]
data.append(reduce(lambda a,b: a^b, data))
data = ''.join(map(chr, data))
sock.sendto(data, self.client_address)
# Sleep a tiny bit to compensate for local network
time.sleep(0.01)
class UDPEchoClientTest(BaseHostTest):
def __init__(self):
"""
Initialise test parameters.
:return:
"""
BaseHostTest.__init__(self)
self.SERVER_IP = None # Will be determined after knowing the target IP
self.SERVER_PORT = 0 # Let TCPServer choose an arbitrary port
self.server = None
self.server_thread = None
self.target_ip = None
@staticmethod
def find_interface_to_target_addr(target_ip):
"""
Finds IP address of the interface through which it is connected to the target.
:return:
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((target_ip, 0)) # Target IP, any port
except socket.error:
s.connect((target_ip, 8000)) # Target IP, 'random' port
ip = s.getsockname()[0]
s.close()
return ip
def setup_udp_server(self):
"""
sets up a UDP server for target to connect and send test data.
:return:
"""
# !NOTE: There should mechanism to assert in the host test
if self.SERVER_IP is None:
self.log("setup_udp_server() called before determining server IP!")
self.notify_complete(False)
# Returning none will suppress host test from printing success code
self.server = UDPServer((self.SERVER_IP, self.SERVER_PORT), UDPEchoClientHandler)
ip, port = self.server.server_address
self.SERVER_PORT = port
self.server.allow_reuse_address = True
self.log("HOST: Listening for UDP packets: " + self.SERVER_IP + ":" + str(self.SERVER_PORT))
self.server_thread = Thread(target=UDPEchoClientTest.server_thread_func, args=(self,))
self.server_thread.start()
@staticmethod
def server_thread_func(this):
"""
Thread function to run TCP server forever.
:param this:
:return:
"""
this.server.serve_forever()
@event_callback("target_ip")
def _callback_target_ip(self, key, value, timestamp):
"""
Callback to handle reception of target's IP address.
:param key:
:param value:
:param timestamp:
:return:
"""
self.target_ip = value
self.SERVER_IP = self.find_interface_to_target_addr(self.target_ip)
self.setup_udp_server()
@event_callback("host_ip")
def _callback_host_ip(self, key, value, timestamp):
"""
Callback for request for host IP Addr
"""
self.send_kv("host_ip", self.SERVER_IP)
@event_callback("host_port")
def _callback_host_port(self, key, value, timestamp):
"""
Callback for request for host port
"""
self.send_kv("host_port", self.SERVER_PORT)
def teardown(self):
if self.server:
self.server.shutdown()
self.server_thread.join()
|
Maistho/CouchPotatoServer | refs/heads/master | libs/qbittorrent/client.py | 2 | import requests
import json
class LoginRequired(Exception):
def __str__(self):
return 'Please login first.'
class QBittorrentClient(object):
"""class to interact with qBittorrent WEB API"""
def __init__(self, url):
if not url.endswith('/'):
url += '/'
self.url = url
session = requests.Session()
check_prefs = session.get(url+'query/preferences')
if check_prefs.status_code == 200:
self._is_authenticated = True
self.session = session
else:
self._is_authenticated = False
def _get(self, endpoint, **kwargs):
"""
Method to perform GET request on the API.
:param endpoint: Endpoint of the API.
:param kwargs: Other keyword arguments for requests.
:return: Response of the GET request.
"""
return self._request(endpoint, 'get', **kwargs)
def _post(self, endpoint, data, **kwargs):
"""
Method to perform POST request on the API.
:param endpoint: Endpoint of the API.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments for requests.
:return: Response of the POST request.
"""
return self._request(endpoint, 'post', data, **kwargs)
def _request(self, endpoint, method, data=None, **kwargs):
"""
Method to hanle both GET and POST requests.
:param endpoint: Endpoint of the API.
:param method: Method of HTTP request.
:param data: POST DATA for the request.
:param kwargs: Other keyword arguments.
:return: Response for the request.
"""
final_url = self.url + endpoint
if not self._is_authenticated:
raise LoginRequired
rq = self.session
if method == 'get':
request = rq.get(final_url, **kwargs)
else:
request = rq.post(final_url, data, **kwargs)
request.raise_for_status()
if len(request.text) == 0:
data = json.loads('{}')
else:
try:
data = json.loads(request.text)
except ValueError:
data = request.text
return data
def login(self, username, password):
"""
Method to authenticate the qBittorrent Client.
Declares a class attribute named ``session`` which
stores the authenticated session if the login is correct.
Else, shows the login error.
:param username: Username.
:param password: Password.
:return: Response to login request to the API.
"""
self.session = requests.Session()
login = self.session.post(self.url+'login',
data={'username': username,
'password': password})
if login.text == 'Ok.':
self._is_authenticated = True
else:
return login.text
def logout(self):
"""
Logout the current session.
"""
response = self._get('logout')
self._is_authenticated = False
return response
@property
def qbittorrent_version(self):
"""
Get qBittorrent version.
"""
return self._get('version/qbittorrent')
@property
def api_version(self):
"""
Get WEB API version.
"""
return self._get('version/api')
@property
def api_min_version(self):
"""
Get minimum WEB API version.
"""
return self._get('version/api_min')
def shutdown(self):
"""
Shutdown qBittorrent.
"""
return self._get('command/shutdown')
def torrents(self, status='active', label='', sort='priority',
reverse=False, limit=10, offset=0):
"""
Returns a list of torrents matching the supplied filters.
:param status: Current status of the torrents.
:param label: Fetch all torrents with the supplied label.
:param sort: Sort torrents by.
:param reverse: Enable reverse sorting.
:param limit: Limit the number of torrents returned.
:param offset: Set offset (if less than 0, offset from end).
:return: list() of torrent with matching filter.
"""
STATUS_LIST = ['all', 'downloading', 'completed',
'paused', 'active', 'inactive']
if status not in STATUS_LIST:
raise ValueError("Invalid status.")
params = {
'filter': status,
'label': label,
'sort': sort,
'reverse': reverse,
'limit': limit,
'offset': offset
}
return self._get('query/torrents', params=params)
def get_torrent(self, infohash):
"""
Get details of the torrent.
:param infohash: INFO HASH of the torrent.
"""
return self._get('query/propertiesGeneral/' + infohash.lower())
def get_torrent_trackers(self, infohash):
"""
Get trackers for the torrent.
:param infohash: INFO HASH of the torrent.
"""
return self._get('query/propertiesTrackers/' + infohash.lower())
def get_torrent_webseeds(self, infohash):
"""
Get webseeds for the torrent.
:param infohash: INFO HASH of the torrent.
"""
return self._get('query/propertiesWebSeeds/' + infohash.lower())
def get_torrent_files(self, infohash):
"""
Get list of files for the torrent.
:param infohash: INFO HASH of the torrent.
"""
return self._get('query/propertiesFiles/' + infohash.lower())
@property
def global_transfer_info(self):
"""
Get JSON data of the global transfer info of qBittorrent.
"""
return self._get('query/transferInfo')
@property
def preferences(self):
"""
Get the current qBittorrent preferences.
Can also be used to assign individual preferences.
For setting multiple preferences at once,
see ``set_preferences`` method.
Note: Even if this is a ``property``,
to fetch the current preferences dict, you are required
to call it like a bound method.
Wrong::
qb.preferences
Right::
qb.preferences()
"""
prefs = self._get('query/preferences')
class Proxy(Client):
"""
Proxy class to to allow assignment of individual preferences.
this class overrides some methods to ease things.
Because of this, settings can be assigned like::
In [5]: prefs = qb.preferences()
In [6]: prefs['autorun_enabled']
Out[6]: True
In [7]: prefs['autorun_enabled'] = False
In [8]: prefs['autorun_enabled']
Out[8]: False
"""
def __init__(self, url, prefs, auth, session):
super(Proxy, self).__init__(url)
self.prefs = prefs
self._is_authenticated = auth
self.session = session
def __getitem__(self, key):
return self.prefs[key]
def __setitem__(self, key, value):
kwargs = {key: value}
return self.set_preferences(**kwargs)
def __call__(self):
return self.prefs
return Proxy(self.url, prefs, self._is_authenticated, self.session)
def sync(self, rid=0):
"""
Sync the torrents by supplied LAST RESPONSE ID.
Read more @ http://git.io/vEgXr
:param rid: Response ID of last request.
"""
return self._get('sync/maindata', params={'rid': rid})
def download_from_link(self, link,
save_path=None, label=''):
"""
Download torrent using a link.
:param link: URL Link or list of.
:param save_path: Path to download the torrent.
:param label: Label of the torrent(s).
:return: Empty JSON data.
"""
if not isinstance(link, list):
link = [link]
data = {'urls': link}
if save_path:
data.update({'savepath': save_path})
if label:
data.update({'label': label})
return self._post('command/download', data=data)
def download_from_file(self, file_buffer,
save_path=None, label=''):
"""
Download torrent using a file.
:param file_buffer: Single file() buffer or list of.
:param save_path: Path to download the torrent.
:param label: Label of the torrent(s).
:return: Empty JSON data.
"""
if isinstance(file_buffer, list):
torrent_files = {}
for i, f in enumerate(file_buffer):
torrent_files.update({'torrents%s' % i: f})
print torrent_files
else:
torrent_files = {'torrents': file_buffer}
data = {}
if save_path:
data.update({'savepath': save_path})
if label:
data.update({'label': label})
return self._post('command/upload', data=data, files=torrent_files)
def add_trackers(self, infohash, trackers):
"""
Add trackers to a torrent.
:param infohash: INFO HASH of torrent.
:param trackers: Trackers.
"""
data = {'hash': infohash.lower(),
'urls': trackers}
return self._post('command/addTrackers', data=data)
@staticmethod
def process_infohash_list(infohash_list):
"""
Method to convert the infohash_list to qBittorrent API friendly values.
:param infohash_list: List of infohash.
"""
if isinstance(infohash_list, list):
data = {'hashes': '|'.join([h.lower() for h in infohash_list])}
else:
data = {'hashes': infohash_list.lower()}
return data
def pause(self, infohash):
"""
Pause a torrent.
:param infohash: INFO HASH of torrent.
"""
return self._post('command/pause', data={'hash': infohash.lower()})
def pause_all(self):
"""
Pause all torrents.
"""
return self._get('command/pauseAll')
def pause_multiple(self, infohash_list):
"""
Pause multiple torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/pauseAll', data=data)
def resume(self, infohash):
"""
Resume a paused torrent.
:param infohash: INFO HASH of torrent.
"""
return self._post('command/resume', data={'hash': infohash.lower()})
def resume_all(self):
"""
Resume all torrents.
"""
return self._get('command/resumeAll')
def resume_multiple(self, infohash_list):
"""
Resume multiple paused torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/resumeAll', data=data)
def delete(self, infohash_list):
"""
Delete torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/delete', data=data)
def delete_permanently(self, infohash_list):
"""
Permanently delete torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/deletePerm', data=data)
def recheck(self, infohash_list):
"""
Recheck torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/recheck', data=data)
def increase_priority(self, infohash_list):
"""
Increase priority of torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/increasePrio', data=data)
def decrease_priority(self, infohash_list):
"""
Decrease priority of torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/decreasePrio', data=data)
def set_max_priority(self, infohash_list):
"""
Set torrents to maximum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/topPrio', data=data)
def set_min_priority(self, infohash_list):
"""
Set torrents to minimum priority level.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/bottomPrio', data=data)
def set_file_priority(self, infohash, file_id, priority):
"""
Set file of a torrent to a supplied priority level.
:param infohash: INFO HASH of torrent.
:param file_id: ID of the file to set priority.
:param priority: Priority level of the file.
"""
if priority not in [0, 1, 2, 7]:
raise ValueError("Invalid priority, refer WEB-UI docs for info.")
elif not isinstance(file_id, int):
raise TypeError("File ID must be an int")
data = {'hash': infohash.lower(),
'id': file_id,
'priority': priority}
return self._post('command/setFilePrio', data=data)
# Get-set global download and upload speed limits.
def get_global_download_limit(self):
"""
Get global download speed limit.
"""
return self._get('command/getGlobalDlLimit')
def set_global_download_limit(self, limit):
"""
Set global download speed limit.
:param limit: Speed limit in bytes.
"""
return self._post('command/setGlobalDlLimit', data={'limit': limit})
global_download_limit = property(get_global_download_limit,
set_global_download_limit)
def get_global_upload_limit(self):
"""
Get global upload speed limit.
"""
return self._get('command/getGlobalUpLimit')
def set_global_upload_limit(self, limit):
"""
Set global upload speed limit.
:param limit: Speed limit in bytes.
"""
return self._post('command/setGlobalUpLimit', data={'limit': limit})
global_upload_limit = property(get_global_upload_limit,
set_global_upload_limit)
# Get-set download and upload speed limits of the torrents.
def get_torrent_download_limit(self, infohash_list):
"""
Get download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/getTorrentsDlLimit', data=data)
def set_torrent_download_limit(self, infohash_list, limit):
"""
Set download speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes.
"""
data = self.process_infohash_list(infohash_list)
data.update({'limit': limit})
return self._post('command/setTorrentsDlLimit', data=data)
def get_torrent_upload_limit(self, infohash_list):
"""
Get upoload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/getTorrentsUpLimit', data=data)
def set_torrent_upload_limit(self, infohash_list, limit):
"""
Set upload speed limit of the supplied torrents.
:param infohash_list: Single or list() of infohashes.
:param limit: Speed limit in bytes.
"""
data = self.process_infohash_list(infohash_list)
data.update({'limit': limit})
return self._post('command/setTorrentsUpLimit', data=data)
# setting preferences
def set_preferences(self, **kwargs):
"""
Set preferences of qBittorrent.
Read all possible preferences @ http://git.io/vEgDQ
:param kwargs: set preferences in kwargs form.
"""
json_data = "json={}".format(json.dumps(kwargs))
headers = {'content-type': 'application/x-www-form-urlencoded'}
return self._post('command/setPreferences', data=json_data,
headers=headers)
def get_alternative_speed_status(self):
"""
Get Alternative speed limits. (1/0)
"""
return self._get('command/alternativeSpeedLimitsEnabled')
alternative_speed_status = property(get_alternative_speed_status)
def toggle_alternative_speed(self):
"""
Toggle alternative speed limits.
"""
return self._get('command/toggleAlternativeSpeedLimits')
def toggle_sequential_download(self, infohash_list):
"""
Toggle sequential download in supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/toggleSequentialDownload', data=data)
def toggle_first_last_piece_priority(self, infohash_list):
"""
Toggle first/last piece priority of supplied torrents.
:param infohash_list: Single or list() of infohashes.
"""
data = self.process_infohash_list(infohash_list)
return self._post('command/toggleFirstLastPiecePrio', data=data)
def force_start(self, infohash_list, value=True):
"""
Force start selected torrents.
:param infohash_list: Single or list() of infohashes.
:param value: Force start value (bool)
"""
data = self.process_infohash_list(infohash_list)
data.update({'value': json.dumps(value)})
return self._post('command/setForceStart', data=data)
|
icomfort/cobbler | refs/heads/master | cobbler/item_profile.py | 2 | """
A Cobbler Profile. A profile is a reference to a distribution, possibly some kernel options, possibly some Virt options, and some kickstart data.
Copyright 2006-2009, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
import utils
import item
import time
from cexceptions import *
from utils import _
# this datastructure is described in great detail in item_distro.py -- read the comments there.
FIELDS = [
["name","",None,"Name",True,"Ex: F10-i386-webserver",0,"str"],
["uid","","","",False,"",0,"str"],
["owners","SETTINGS:default_ownership","SETTINGS:default_ownership","Owners",True,"Owners list for authz_ownership (space delimited)",0,"list"],
["distro",None,'<<inherit>>',"Distribution",True,"Parent distribution",[],"str"],
["parent",'','',"Parent Profile",True,"",[],"str"],
["enable_menu","SETTINGS:enable_menu",'<<inherit>>',"Enable PXE Menu?",True,"Show this profile in the PXE menu?",0,"bool"],
["kickstart","SETTINGS:default_kickstart",'<<inherit>>',"Kickstart",True,"Path to kickstart template",0,"str"],
["kernel_options",{},'<<inherit>>',"Kernel Options",True,"Ex: selinux=permissive",0,"dict"],
["kernel_options_post",{},'<<inherit>>',"Kernel Options (Post Install)",True,"Ex: clocksource=pit noapic",0,"dict"],
["ks_meta",{},'<<inherit>>',"Kickstart Metadata",True,"Ex: dog=fang agent=86",0,"dict"],
["repos",[],'<<inherit>>',"Repos",True,"Repos to auto-assign to this profile",[],"list"],
["comment","","","Comment",True,"Free form text description",0,"str"],
["virt_auto_boot","SETTINGS:virt_auto_boot",'<<inherit>>',"Virt Auto Boot",True,"Auto boot this VM?",0,"bool"],
["virt_cpus",1,'<<inherit>>',"Virt CPUs",True,"integer",0,"int"],
["virt_file_size","SETTINGS:default_virt_file_size",'<<inherit>>',"Virt File Size(GB)",True,"",0,"int"],
["virt_ram","SETTINGS:default_virt_ram",'<<inherit>>',"Virt RAM (MB)",True,"",0,"int"],
["depth",1,1,"",False,"",0,"int"],
["virt_type","SETTINGS:default_virt_type",'<<inherit>>',"Virt Type",True,"Virtualization technology to use",["xenpv","xenfv","qemu", "vmware"],"str"],
["virt_path","",'<<inherit>>',"Virt Path",True,"Ex: /directory OR VolGroup00",0,"str"],
["virt_bridge","SETTINGS:default_virt_bridge",'<<inherit>>',"Virt Bridge",True,"",0,"str"],
["dhcp_tag","default",'<<inherit>>',"DHCP Tag",True,"See manpage or leave blank",0,"str"],
["server","<<inherit>>",'<<inherit>>',"Server Override",True,"See manpage or leave blank",0,"str"],
["ctime",0,0,"",False,"",0,"int"],
["mtime",0,0,"",False,"",0,"int"],
["name_servers","SETTINGS:default_name_servers",[],"Name Servers",True,"space delimited",0,"list"],
["name_servers_search","SETTINGS:default_name_servers_search",[],"Name Servers Search Path",True,"space delimited",0,"list"],
["mgmt_classes",[],'<<inherit>>',"Management Classes",True,"For external configuration management",0,"list"],
["mgmt_parameters","<<inherit>>","<<inherit>>","Management Parameters",True,"Parameters which will be handed to your management application (Must be valid YAML dictionary)", 0,"str"],
["fetchable_files",{},'<<inherit>>',"Fetchable Files",True,"Templates for tftp or wget",0,"dict"],
["template_files",{},'<<inherit>>',"Template Files",True,"File mappings for built-in config management",0,"dict"],
["redhat_management_key","<<inherit>>","<<inherit>>","Red Hat Management Key",True,"Registration key for RHN, Spacewalk, or Satellite",0,"str"],
["redhat_management_server","<<inherit>>","<<inherit>>","Red Hat Management Server",True,"Address of Spacewalk or Satellite Server",0,"str"],
["template_remote_kickstarts", "SETTINGS:template_remote_kickstarts", "SETTINGS:template_remote_kickstarts", "", False, "", 0, "bool"]
]
class Profile(item.Item):
TYPE_NAME = _("profile")
COLLECTION_TYPE = "profile"
def make_clone(self):
ds = self.to_datastruct()
cloned = Profile(self.config)
cloned.from_datastruct(ds)
return cloned
def get_fields(self):
return FIELDS
def set_parent(self,parent_name):
"""
Instead of a --distro, set the parent of this object to another profile
and use the values from the parent instead of this one where the values
for this profile aren't filled in, and blend them together where they
are hashes. Basically this enables profile inheritance. To use this,
the object MUST have been constructed with is_subobject=True or the
default values for everything will be screwed up and this will likely NOT
work. So, API users -- make sure you pass is_subobject=True into the
constructor when using this.
"""
old_parent = self.get_parent()
if isinstance(old_parent, item.Item):
old_parent.children.pop(self.name, 'pass')
if parent_name is None or parent_name == '':
self.parent = ''
return True
if parent_name == self.name:
# check must be done in two places as set_parent could be called before/after
# set_name...
raise CX(_("self parentage is weird"))
found = self.config.profiles().find(name=parent_name)
if found is None:
raise CX(_("profile %s not found, inheritance not possible") % parent_name)
self.parent = parent_name
self.depth = found.depth + 1
parent = self.get_parent()
if isinstance(parent, item.Item):
parent.children[self.name] = self
return True
def set_distro(self,distro_name):
"""
Sets the distro. This must be the name of an existing
Distro object in the Distros collection.
"""
d = self.config.distros().find(name=distro_name)
if d is not None:
old_parent = self.get_parent()
if isinstance(old_parent, item.Item):
old_parent.children.pop(self.name, 'pass')
self.distro = distro_name
self.depth = d.depth +1 # reset depth if previously a subprofile and now top-level
d.children[self.name] = self
return True
raise CX(_("distribution not found"))
def set_redhat_management_key(self,key):
return utils.set_redhat_management_key(self,key)
def set_redhat_management_server(self,server):
return utils.set_redhat_management_server(self,server)
def set_name_servers(self,data):
# FIXME: move to utils since shared with system
if data == "<<inherit>>":
data = []
data = utils.input_string_or_list(data)
self.name_servers = data
return True
def set_name_servers_search(self,data):
if data == "<<inherit>>":
data = []
data = utils.input_string_or_list(data)
self.name_servers_search = data
return True
def set_enable_menu(self,enable_menu):
"""
Sets whether or not the profile will be listed in the default
PXE boot menu. This is pretty forgiving for YAML's sake.
"""
self.enable_menu = utils.input_boolean(enable_menu)
return True
def set_template_remote_kickstarts(self, template):
"""
Sets whether or not the server is configured to template remote
kickstarts.
"""
self.template_remote_kickstarts = utils.input_boolean(template)
return True
def set_dhcp_tag(self,dhcp_tag):
if dhcp_tag is None:
dhcp_tag = ""
self.dhcp_tag = dhcp_tag
return True
def set_server(self,server):
if server is None or server == "":
server = "<<inherit>>"
self.server = server
return True
def set_kickstart(self,kickstart):
"""
Sets the kickstart. This must be a NFS, HTTP, or FTP URL.
Or filesystem path. Minor checking of the URL is performed here.
"""
if kickstart == "" or kickstart is None:
self.kickstart = ""
return True
if kickstart == "<<inherit>>":
self.kickstart = kickstart
return True
if utils.find_kickstart(kickstart):
self.kickstart = kickstart
return True
raise CX(_("kickstart not found: %s") % kickstart)
def set_virt_auto_boot(self,num):
return utils.set_virt_auto_boot(self,num)
def set_virt_cpus(self,num):
return utils.set_virt_cpus(self,num)
def set_virt_file_size(self,num):
return utils.set_virt_file_size(self,num)
def set_virt_ram(self,num):
return utils.set_virt_ram(self,num)
def set_virt_type(self,vtype):
return utils.set_virt_type(self,vtype)
def set_virt_bridge(self,vbridge):
return utils.set_virt_bridge(self,vbridge)
def set_virt_path(self,path):
return utils.set_virt_path(self,path)
def set_repos(self,repos,bypass_check=False):
return utils.set_repos(self,repos,bypass_check)
def get_parent(self):
"""
Return object next highest up the tree.
"""
if self.parent is None or self.parent == '':
if self.distro is None:
return None
result = self.config.distros().find(name=self.distro)
else:
result = self.config.profiles().find(name=self.parent)
return result
def check_if_valid(self):
if self.name is None or self.name == "":
raise CX("name is required")
distro = self.get_conceptual_parent()
if distro is None:
raise CX("Error with profile %s - distro is required" % (self.name))
|
mlperf/training_results_v0.7 | refs/heads/master | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/topi/python/topi/tag.py | 2 | # 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 file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Namespace of all tag system in tvm
Each operator can be tagged by a tag, which indicate its type.
Generic categories
- tag.ELEMWISE="elemwise":
Elementwise operator, for example :code:`out[i, j] = input[i, j]`
- tag.BROADCAST="broadcast":
Broadcasting operator, can always map output axis to the input in order.
for example :code:`out[i, ax1, j, ax2] = input[i, j]`.
Note that the axis need to be in order so transpose is not a bcast operator.
If an input of broadcast operator has same shape as output,
we can ensure that it is elementwise relation.
- tag.INJECTIVE="injective":
Injective operator, can always injectively map output axis to a single input axis.
All injective operator can still be safely fused similar to ewise to reduction.
- tag.COMM_REDUCE="comm_reduce":
Communicative reduction operator
- If an op does not belong to these generic categories, it should have a special tag.
Note
----
When we add a new topi operator, the op need to be tagged as generic as possible.
We can also compose tags like "injective,pad" to give generic and specific information.
When we use composed tags, we must always put generic tag in the first location.
"""
ELEMWISE = "elemwise"
BROADCAST = "broadcast"
INJECTIVE = "injective"
COMM_REDUCE = "comm_reduce"
COMM_REDUCE_IDX = "comm_reduce_idx"
def is_broadcast(tag):
"""Check if a tag is bcast
Parameters
----------
tag : str
The input tag
Returns
-------
ret : bool
Whether a tag is broadcast
"""
if tag in (ELEMWISE, BROADCAST):
return True
return tag.startswith(ELEMWISE) or tag.startswith(BROADCAST)
def is_injective(tag):
"""Check if a tag is injective
Parameters
----------
tag : str
The input tag
Returns
-------
ret : bool
Whether a tag is injective
"""
if tag in (ELEMWISE, BROADCAST, INJECTIVE):
return True
return (tag.startswith(ELEMWISE) or
tag.startswith(BROADCAST) or
tag.startswith(INJECTIVE))
|
t0in4/django | refs/heads/master | tests/migrations/test_migrations_squashed_erroneous/7_auto.py | 770 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("migrations", "6_auto")]
operations = [
migrations.RunPython(migrations.RunPython.noop)
]
|
larsmans/scipy | refs/heads/master | scipy/special/basic.py | 4 | #
# Author: Travis Oliphant, 2002
#
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
import math
from scipy._lib.six import xrange
from numpy import (pi, asarray, floor, isscalar, iscomplex, real, imag, sqrt,
where, mgrid, sin, place, issubdtype, extract,
less, inexact, nan, zeros, atleast_1d, sinc)
from ._ufuncs import (ellipkm1, mathieu_a, mathieu_b, iv, jv, gamma, psi, zeta,
hankel1, hankel2, yv, kv, gammaln, ndtri,
errprint, poch, binom, hyp0f1)
from . import specfun
from . import orthogonal
__all__ = ['agm', 'ai_zeros', 'assoc_laguerre', 'bei_zeros', 'beip_zeros',
'ber_zeros', 'bernoulli', 'berp_zeros', 'bessel_diff_formula',
'bi_zeros', 'clpmn', 'comb', 'digamma', 'diric', 'ellipk',
'erf_zeros', 'erfcinv', 'erfinv', 'errprint', 'euler', 'factorial',
'factorialk', 'factorial2', 'fresnel_zeros',
'fresnelc_zeros', 'fresnels_zeros', 'gamma', 'gammaln', 'h1vp',
'h2vp', 'hankel1', 'hankel2', 'hyp0f1', 'iv', 'ivp', 'jn_zeros',
'jnjnp_zeros', 'jnp_zeros', 'jnyn_zeros', 'jv', 'jvp', 'kei_zeros',
'keip_zeros', 'kelvin_zeros', 'ker_zeros', 'kerp_zeros', 'kv',
'kvp', 'lmbda', 'lpmn', 'lpn', 'lqmn', 'lqn', 'mathieu_a',
'mathieu_b', 'mathieu_even_coef', 'mathieu_odd_coef', 'ndtri',
'obl_cv_seq', 'pbdn_seq', 'pbdv_seq', 'pbvv_seq', 'perm',
'polygamma', 'pro_cv_seq', 'psi', 'riccati_jn', 'riccati_yn',
'sinc', 'sph_in', 'sph_inkn',
'sph_jn', 'sph_jnyn', 'sph_kn', 'sph_yn', 'y0_zeros', 'y1_zeros',
'y1p_zeros', 'yn_zeros', 'ynp_zeros', 'yv', 'yvp', 'zeta',
'SpecialFunctionWarning']
class SpecialFunctionWarning(Warning):
"""Warning that can be issued with ``errprint(True)``"""
pass
warnings.simplefilter("always", category=SpecialFunctionWarning)
def diric(x, n):
"""Periodic sinc function, also called the Dirichlet function.
The Dirichlet function is defined as::
diric(x) = sin(x * n/2) / (n * sin(x / 2)),
where `n` is a positive integer.
Parameters
----------
x : array_like
Input data
n : int
Integer defining the periodicity.
Returns
-------
diric : ndarray
Examples
--------
>>> from scipy import special
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-8*np.pi, 8*np.pi, num=201)
>>> plt.figure(figsize=(8, 8));
>>> for idx, n in enumerate([2, 3, 4, 9]):
... plt.subplot(2, 2, idx+1)
... plt.plot(x, special.diric(x, n))
... plt.title('diric, n={}'.format(n))
>>> plt.show()
The following example demonstrates that `diric` gives the magnitudes
(modulo the sign and scaling) of the Fourier coefficients of a
rectangular pulse.
Suppress output of values that are effectively 0:
>>> np.set_printoptions(suppress=True)
Create a signal `x` of length `m` with `k` ones:
>>> m = 8
>>> k = 3
>>> x = np.zeros(m)
>>> x[:k] = 1
Use the FFT to compute the Fourier transform of `x`, and
inspect the magnitudes of the coefficients:
>>> np.abs(np.fft.fft(x))
array([ 3. , 2.41421356, 1. , 0.41421356, 1. ,
0.41421356, 1. , 2.41421356])
Now find the same values (up to sign) using `diric`. We multiply
by `k` to account for the different scaling conventions of
`numpy.fft.fft` and `diric`:
>>> theta = np.linspace(0, 2*np.pi, m, endpoint=False)
>>> k * special.diric(theta, k)
array([ 3. , 2.41421356, 1. , -0.41421356, -1. ,
-0.41421356, 1. , 2.41421356])
"""
x, n = asarray(x), asarray(n)
n = asarray(n + (x-x))
x = asarray(x + (n-n))
if issubdtype(x.dtype, inexact):
ytype = x.dtype
else:
ytype = float
y = zeros(x.shape, ytype)
# empirical minval for 32, 64 or 128 bit float computations
# where sin(x/2) < minval, result is fixed at +1 or -1
if np.finfo(ytype).eps < 1e-18:
minval = 1e-11
elif np.finfo(ytype).eps < 1e-15:
minval = 1e-7
else:
minval = 1e-3
mask1 = (n <= 0) | (n != floor(n))
place(y, mask1, nan)
x = x / 2
denom = sin(x)
mask2 = (1-mask1) & (abs(denom) < minval)
xsub = extract(mask2, x)
nsub = extract(mask2, n)
zsub = xsub / pi
place(y, mask2, pow(-1, np.round(zsub)*(nsub-1)))
mask = (1-mask1) & (1-mask2)
xsub = extract(mask, x)
nsub = extract(mask, n)
dsub = extract(mask, denom)
place(y, mask, sin(nsub*xsub)/(nsub*dsub))
return y
def jnjnp_zeros(nt):
"""Compute zeros of integer-order Bessel functions Jn and Jn'.
Results are arranged in order of the magnitudes of the zeros.
Parameters
----------
nt : int
Number (<=1200) of zeros to compute
Returns
-------
zo[l-1] : ndarray
Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
n[l-1] : ndarray
Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
m[l-1] : ndarray
Serial number of the zeros of Jn(x) or Jn'(x) associated
with lth zero. Of length `nt`.
t[l-1] : ndarray
0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
length `nt`.
See Also
--------
jn_zeros, jnp_zeros : to get separated arrays of zeros.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
raise ValueError("Number must be integer <= 1200.")
nt = int(nt)
n, m, t, zo = specfun.jdzo(nt)
return zo[1:nt+1], n[:nt], m[:nt], t[:nt]
def jnyn_zeros(n, nt):
"""Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
Returns 4 arrays of length `nt`, corresponding to the first `nt` zeros of
Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively.
Parameters
----------
n : int
Order of the Bessel functions
nt : int
Number (<=1200) of zeros to compute
See jn_zeros, jnp_zeros, yn_zeros, ynp_zeros to get separate arrays.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(nt) and isscalar(n)):
raise ValueError("Arguments must be scalars.")
if (floor(n) != n) or (floor(nt) != nt):
raise ValueError("Arguments must be integers.")
if (nt <= 0):
raise ValueError("nt > 0")
return specfun.jyzo(abs(n), nt)
def jn_zeros(n, nt):
"""Compute zeros of integer-order Bessel function Jn(x).
Parameters
----------
n : int
Order of Bessel function
nt : int
Number of zeros to return
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
return jnyn_zeros(n, nt)[0]
def jnp_zeros(n, nt):
"""Compute zeros of integer-order Bessel function derivative Jn'(x).
Parameters
----------
n : int
Order of Bessel function
nt : int
Number of zeros to return
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
return jnyn_zeros(n, nt)[1]
def yn_zeros(n, nt):
"""Compute zeros of integer-order Bessel function Yn(x).
Parameters
----------
n : int
Order of Bessel function
nt : int
Number of zeros to return
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
return jnyn_zeros(n, nt)[2]
def ynp_zeros(n, nt):
"""Compute zeros of integer-order Bessel function derivative Yn'(x).
Parameters
----------
n : int
Order of Bessel function
nt : int
Number of zeros to return
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
return jnyn_zeros(n, nt)[3]
def y0_zeros(nt, complex=False):
"""Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0.
Parameters
----------
nt : int
Number of zeros to return
complex : bool, default False
Set to False to return only the real zeros; set to True to return only
the complex zeros with negative real part and positive imaginary part.
Note that the complex conjugates of the latter are also zeros of the
function, but are not returned by this routine.
Returns
-------
z0n : ndarray
Location of nth zero of Y0(z)
y0pz0n : ndarray
Value of derivative Y0'(z0) for nth zero
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("Arguments must be scalar positive integer.")
kf = 0
kc = not complex
return specfun.cyzo(nt, kf, kc)
def y1_zeros(nt, complex=False):
"""Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1.
Parameters
----------
nt : int
Number of zeros to return
complex : bool, default False
Set to False to return only the real zeros; set to True to return only
the complex zeros with negative real part and positive imaginary part.
Note that the complex conjugates of the latter are also zeros of the
function, but are not returned by this routine.
Returns
-------
z1n : ndarray
Location of nth zero of Y1(z)
y1pz1n : ndarray
Value of derivative Y1'(z1) for nth zero
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("Arguments must be scalar positive integer.")
kf = 1
kc = not complex
return specfun.cyzo(nt, kf, kc)
def y1p_zeros(nt, complex=False):
"""Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
The values are given by Y1(z1) at each z1 where Y1'(z1)=0.
Parameters
----------
nt : int
Number of zeros to return
complex : bool, default False
Set to False to return only the real zeros; set to True to return only
the complex zeros with negative real part and positive imaginary part.
Note that the complex conjugates of the latter are also zeros of the
function, but are not returned by this routine.
Returns
-------
z1pn : ndarray
Location of nth zero of Y1'(z)
y1z1pn : ndarray
Value of derivative Y1(z1) for nth zero
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("Arguments must be scalar positive integer.")
kf = 2
kc = not complex
return specfun.cyzo(nt, kf, kc)
def _bessel_diff_formula(v, z, n, L, phase):
# from AMS55.
# L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1
# L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1
# For K, you can pull out the exp((v-k)*pi*i) into the caller
v = asarray(v)
p = 1.0
s = L(v-n, z)
for i in xrange(1, n+1):
p = phase * (p * (n-i+1)) / i # = choose(k, i)
s += p*L(v-n + i*2, z)
return s / (2.**n)
bessel_diff_formula = np.deprecate(_bessel_diff_formula,
message="bessel_diff_formula is a private function, do not use it!")
def jvp(v, z, n=1):
"""Compute nth derivative of Bessel function Jv(z) with respect to `z`.
Parameters
----------
v : float
Order of Bessel function
z : complex
Argument at which to evaluate the derivative
n : int, default 1
Order of derivative
Notes
-----
The derivative is computed using the relation DLFM 10.6.7 [2]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.6.E7
"""
if not isinstance(n, int) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if n == 0:
return jv(v, z)
else:
return _bessel_diff_formula(v, z, n, jv, -1)
def yvp(v, z, n=1):
"""Compute nth derivative of Bessel function Yv(z) with respect to `z`.
Parameters
----------
v : float
Order of Bessel function
z : complex
Argument at which to evaluate the derivative
n : int, default 1
Order of derivative
Notes
-----
The derivative is computed using the relation DLFM 10.6.7 [2]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.6.E7
"""
if not isinstance(n, int) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if n == 0:
return yv(v, z)
else:
return _bessel_diff_formula(v, z, n, yv, -1)
def kvp(v, z, n=1):
"""Compute nth derivative of real-order modified Bessel function Kv(z)
Kv(z) is the modified Bessel function of the second kind.
Derivative is calculated with respect to `z`.
Parameters
----------
v : array_like of float
Order of Bessel function
z : array_like of complex
Argument at which to evaluate the derivative
n : int
Order of derivative. Default is first derivative.
Returns
-------
out : ndarray
The results
Examples
--------
Calculate multiple values at order 5:
>>> from scipy.special import kvp
>>> kvp(5, (1, 2, 3+5j))
array([-1849.0354+0.j , -25.7735+0.j , -0.0307+0.0875j])
Calculate for a single value at multiple orders:
>>> kvp((4, 4.5, 5), 1)
array([ -184.0309, -568.9585, -1849.0354])
Notes
-----
The derivative is computed using the relation DLFM 10.29.5 [2]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 6.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.29.E5
"""
if not isinstance(n, int) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if n == 0:
return kv(v, z)
else:
return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1)
def ivp(v, z, n=1):
"""Compute nth derivative of modified Bessel function Iv(z) with respect
to `z`.
Parameters
----------
v : array_like of float
Order of Bessel function
z : array_like of complex
Argument at which to evaluate the derivative
n : int, default 1
Order of derivative
Notes
-----
The derivative is computed using the relation DLFM 10.29.5 [2]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 6.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.29.E5
"""
if not isinstance(n, int) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if n == 0:
return iv(v, z)
else:
return _bessel_diff_formula(v, z, n, iv, 1)
def h1vp(v, z, n=1):
"""Compute nth derivative of Hankel function H1v(z) with respect to `z`.
Parameters
----------
v : float
Order of Hankel function
z : complex
Argument at which to evaluate the derivative
n : int, default 1
Order of derivative
Notes
-----
The derivative is computed using the relation DLFM 10.6.7 [2]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.6.E7
"""
if not isinstance(n, int) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if n == 0:
return hankel1(v, z)
else:
return _bessel_diff_formula(v, z, n, hankel1, -1)
def h2vp(v, z, n=1):
"""Compute nth derivative of Hankel function H2v(z) with respect to `z`.
Parameters
----------
v : float
Order of Hankel function
z : complex
Argument at which to evaluate the derivative
n : int, default 1
Order of derivative
Notes
-----
The derivative is computed using the relation DLFM 10.6.7 [2]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 5.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.6.E7
"""
if not isinstance(n, int) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if n == 0:
return hankel2(v, z)
else:
return _bessel_diff_formula(v, z, n, hankel2, -1)
@np.deprecate(message="scipy.special.sph_jn is deprecated in scipy 0.18.0. "
"Use scipy.special.spherical_jn instead. "
"Note that the new function has a different signature.")
def sph_jn(n, z):
"""Compute spherical Bessel function jn(z) and derivative.
This function computes the value and first derivative of jn(z) for all
orders up to and including n.
Parameters
----------
n : int
Maximum order of jn to compute
z : complex
Argument at which to evaluate
Returns
-------
jn : ndarray
Value of j0(z), ..., jn(z)
jnp : ndarray
First derivative j0'(z), ..., jn'(z)
See also
--------
spherical_jn
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 8.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z):
nm, jn, jnp, yn, ynp = specfun.csphjy(n1, z)
else:
nm, jn, jnp = specfun.sphj(n1, z)
return jn[:(n+1)], jnp[:(n+1)]
@np.deprecate(message="scipy.special.sph_yn is deprecated in scipy 0.18.0. "
"Use scipy.special.spherical_yn instead. "
"Note that the new function has a different signature.")
def sph_yn(n, z):
"""Compute spherical Bessel function yn(z) and derivative.
This function computes the value and first derivative of yn(z) for all
orders up to and including n.
Parameters
----------
n : int
Maximum order of yn to compute
z : complex
Argument at which to evaluate
Returns
-------
yn : ndarray
Value of y0(z), ..., yn(z)
ynp : ndarray
First derivative y0'(z), ..., yn'(z)
See also
--------
spherical_yn
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 8.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z) or less(z, 0):
nm, jn, jnp, yn, ynp = specfun.csphjy(n1, z)
else:
nm, yn, ynp = specfun.sphy(n1, z)
return yn[:(n+1)], ynp[:(n+1)]
@np.deprecate(message="scipy.special.sph_jnyn is deprecated in scipy 0.18.0. "
"Use scipy.special.spherical_jn and "
"scipy.special.spherical_yn instead. "
"Note that the new function has a different signature.")
def sph_jnyn(n, z):
"""Compute spherical Bessel functions jn(z) and yn(z) and derivatives.
This function computes the value and first derivative of jn(z) and yn(z)
for all orders up to and including n.
Parameters
----------
n : int
Maximum order of jn and yn to compute
z : complex
Argument at which to evaluate
Returns
-------
jn : ndarray
Value of j0(z), ..., jn(z)
jnp : ndarray
First derivative j0'(z), ..., jn'(z)
yn : ndarray
Value of y0(z), ..., yn(z)
ynp : ndarray
First derivative y0'(z), ..., yn'(z)
See also
--------
spherical_jn
spherical_yn
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 8.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z) or less(z, 0):
nm, jn, jnp, yn, ynp = specfun.csphjy(n1, z)
else:
nm, yn, ynp = specfun.sphy(n1, z)
nm, jn, jnp = specfun.sphj(n1, z)
return jn[:(n+1)], jnp[:(n+1)], yn[:(n+1)], ynp[:(n+1)]
@np.deprecate(message="scipy.special.sph_in is deprecated in scipy 0.18.0. "
"Use scipy.special.spherical_in instead. "
"Note that the new function has a different signature.")
def sph_in(n, z):
"""Compute spherical Bessel function in(z) and derivative.
This function computes the value and first derivative of in(z) for all
orders up to and including n.
Parameters
----------
n : int
Maximum order of in to compute
z : complex
Argument at which to evaluate
Returns
-------
in : ndarray
Value of i0(z), ..., in(z)
inp : ndarray
First derivative i0'(z), ..., in'(z)
See also
--------
spherical_in
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 8.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z):
nm, In, Inp, kn, knp = specfun.csphik(n1, z)
else:
nm, In, Inp = specfun.sphi(n1, z)
return In[:(n+1)], Inp[:(n+1)]
@np.deprecate(message="scipy.special.sph_kn is deprecated in scipy 0.18.0. "
"Use scipy.special.spherical_kn instead. "
"Note that the new function has a different signature.")
def sph_kn(n, z):
"""Compute spherical Bessel function kn(z) and derivative.
This function computes the value and first derivative of kn(z) for all
orders up to and including n.
Parameters
----------
n : int
Maximum order of kn to compute
z : complex
Argument at which to evaluate
Returns
-------
kn : ndarray
Value of k0(z), ..., kn(z)
knp : ndarray
First derivative k0'(z), ..., kn'(z)
See also
--------
spherical_kn
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 8.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z) or less(z, 0):
nm, In, Inp, kn, knp = specfun.csphik(n1, z)
else:
nm, kn, knp = specfun.sphk(n1, z)
return kn[:(n+1)], knp[:(n+1)]
@np.deprecate(message="scipy.special.sph_inkn is deprecated in scipy 0.18.0. "
"Use scipy.special.spherical_in and "
"scipy.special.spherical_kn instead. "
"Note that the new function has a different signature.")
def sph_inkn(n, z):
"""Compute spherical Bessel functions in(z), kn(z), and derivatives.
This function computes the value and first derivative of in(z) and kn(z)
for all orders up to and including n.
Parameters
----------
n : int
Maximum order of in and kn to compute
z : complex
Argument at which to evaluate
Returns
-------
in : ndarray
Value of i0(z), ..., in(z)
inp : ndarray
First derivative i0'(z), ..., in'(z)
kn : ndarray
Value of k0(z), ..., kn(z)
knp : ndarray
First derivative k0'(z), ..., kn'(z)
See also
--------
spherical_in
spherical_kn
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 8.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z) or less(z, 0):
nm, In, Inp, kn, knp = specfun.csphik(n1, z)
else:
nm, In, Inp = specfun.sphi(n1, z)
nm, kn, knp = specfun.sphk(n1, z)
return In[:(n+1)], Inp[:(n+1)], kn[:(n+1)], knp[:(n+1)]
def riccati_jn(n, x):
r"""Compute Ricatti-Bessel function of the first kind and its derivative.
The Ricatti-Bessel function of the first kind is defined as :math:`x
j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first
kind of order :math:`n`.
This function computes the value and first derivative of the
Ricatti-Bessel function for all orders up to and including `n`.
Parameters
----------
n : int
Maximum order of function to compute
x : float
Argument at which to evaluate
Returns
-------
jn : ndarray
Value of j0(x), ..., jn(x)
jnp : ndarray
First derivative j0'(x), ..., jn'(x)
Notes
-----
The computation is carried out via backward recurrence, using the
relation DLMF 10.51.1 [2]_.
Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
Jin [1]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.51.E1
"""
if not (isscalar(n) and isscalar(x)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n == 0):
n1 = 1
else:
n1 = n
nm, jn, jnp = specfun.rctj(n1, x)
return jn[:(n+1)], jnp[:(n+1)]
def riccati_yn(n, x):
"""Compute Ricatti-Bessel function of the second kind and its derivative.
The Ricatti-Bessel function of the second kind is defined as :math:`x
y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second
kind of order :math:`n`.
This function computes the value and first derivative of the function for
all orders up to and including `n`.
Parameters
----------
n : int
Maximum order of function to compute
x : float
Argument at which to evaluate
Returns
-------
yn : ndarray
Value of y0(x), ..., yn(x)
ynp : ndarray
First derivative y0'(x), ..., yn'(x)
Notes
-----
The computation is carried out via ascending recurrence, using the
relation DLMF 10.51.1 [2]_.
Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
Jin [1]_.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions.
http://dlmf.nist.gov/10.51.E1
"""
if not (isscalar(n) and isscalar(x)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n == 0):
n1 = 1
else:
n1 = n
nm, jn, jnp = specfun.rcty(n1, x)
return jn[:(n+1)], jnp[:(n+1)]
def erfinv(y):
"""Inverse function for erf.
"""
return ndtri((y+1)/2.0)/sqrt(2)
def erfcinv(y):
"""Inverse function for erfc.
"""
return -ndtri(0.5*y)/sqrt(2)
def erf_zeros(nt):
"""Compute nt complex zeros of error function erf(z).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
raise ValueError("Argument must be positive scalar integer.")
return specfun.cerzo(nt)
def fresnelc_zeros(nt):
"""Compute nt complex zeros of cosine Fresnel integral C(z).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
raise ValueError("Argument must be positive scalar integer.")
return specfun.fcszo(1, nt)
def fresnels_zeros(nt):
"""Compute nt complex zeros of sine Fresnel integral S(z).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
raise ValueError("Argument must be positive scalar integer.")
return specfun.fcszo(2, nt)
def fresnel_zeros(nt):
"""Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
raise ValueError("Argument must be positive scalar integer.")
return specfun.fcszo(2, nt), specfun.fcszo(1, nt)
def assoc_laguerre(x, n, k=0.0):
"""Compute nth-order generalized (associated) Laguerre polynomial.
The polynomial :math:`L^(alpha)_n(x)` is orthogonal over ``[0, inf)``,
with weighting function ``exp(-x) * x**alpha`` with ``alpha > -1``.
Notes
-----
`assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with
reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
"""
return orthogonal.eval_genlaguerre(n, k, x)
digamma = psi
def polygamma(n, x):
"""Polygamma function n.
This is the nth derivative of the digamma (psi) function.
Parameters
----------
n : array_like of int
The order of the derivative of `psi`.
x : array_like
Where to evaluate the polygamma function.
Returns
-------
polygamma : ndarray
The result.
Examples
--------
>>> from scipy import special
>>> x = [2, 3, 25.5]
>>> special.polygamma(1, x)
array([ 0.64493407, 0.39493407, 0.03999467])
>>> special.polygamma(0, x) == special.psi(x)
array([ True, True, True], dtype=bool)
"""
n, x = asarray(n), asarray(x)
fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x)
return where(n == 0, psi(x), fac2)
def mathieu_even_coef(m, q):
r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
The Fourier series of the even solutions of the Mathieu differential
equation are of the form
.. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz
.. math:: \mathrm{ce}_{2n+1}(z, q) = \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z
This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even
input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input
m=2n+1.
Parameters
----------
m : int
Order of Mathieu functions. Must be non-negative.
q : float (>=0)
Parameter of Mathieu functions. Must be non-negative.
Returns
-------
Ak : ndarray
Even or odd Fourier coefficients, corresponding to even or odd m.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/28.4#i
"""
if not (isscalar(m) and isscalar(q)):
raise ValueError("m and q must be scalars.")
if (q < 0):
raise ValueError("q >=0")
if (m != floor(m)) or (m < 0):
raise ValueError("m must be an integer >=0.")
if (q <= 1):
qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
else:
qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
km = int(qm + 0.5*m)
if km > 251:
print("Warning, too many predicted coefficients.")
kd = 1
m = int(floor(m))
if m % 2:
kd = 2
a = mathieu_a(m, q)
fc = specfun.fcoef(kd, m, q, a)
return fc[:km]
def mathieu_odd_coef(m, q):
r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
The Fourier series of the odd solutions of the Mathieu differential
equation are of the form
.. math:: \mathrm{se}_{2n+1}(z, q) = \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
.. math:: \mathrm{se}_{2n+2}(z, q) = \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
input m=2n+1.
Parameters
----------
m : int
Order of Mathieu functions. Must be non-negative.
q : float (>=0)
Parameter of Mathieu functions. Must be non-negative.
Returns
-------
Bk : ndarray
Even or odd Fourier coefficients, corresponding to even or odd m.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(m) and isscalar(q)):
raise ValueError("m and q must be scalars.")
if (q < 0):
raise ValueError("q >=0")
if (m != floor(m)) or (m <= 0):
raise ValueError("m must be an integer > 0")
if (q <= 1):
qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
else:
qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
km = int(qm + 0.5*m)
if km > 251:
print("Warning, too many predicted coefficients.")
kd = 4
m = int(floor(m))
if m % 2:
kd = 3
b = mathieu_b(m, q)
fc = specfun.fcoef(kd, m, q, b)
return fc[:km]
def lpmn(m, n, z):
"""Associated Legendre function of the first kind, Pmn(z).
Computes the associated Legendre function of the first kind of order m and
degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
This function takes a real argument ``z``. For complex arguments ``z``
use clpmn instead.
Parameters
----------
m : int
``|m| <= n``; the order of the Legendre function.
n : int
where ``n >= 0``; the degree of the Legendre function. Often
called ``l`` (lower case L) in descriptions of the associated
Legendre function
z : float
Input value.
Returns
-------
Pmn_z : (m+1, n+1) array
Values for all orders 0..m and degrees 0..n
Pmn_d_z : (m+1, n+1) array
Derivatives for all orders 0..m and degrees 0..n
See Also
--------
clpmn: associated Legendre functions of the first kind for complex z
Notes
-----
In the interval (-1, 1), Ferrer's function of the first kind is
returned. The phase convention used for the intervals (1, inf)
and (-inf, -1) is such that the result is always real.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/14.3
"""
if not isscalar(m) or (abs(m) > n):
raise ValueError("m must be <= n.")
if not isscalar(n) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if not isscalar(z):
raise ValueError("z must be scalar.")
if iscomplex(z):
raise ValueError("Argument must be real. Use clpmn instead.")
if (m < 0):
mp = -m
mf, nf = mgrid[0:mp+1, 0:n+1]
sv = errprint(0)
if abs(z) < 1:
# Ferrer function; DLMF 14.9.3
fixarr = where(mf > nf, 0.0,
(-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
else:
# Match to clpmn; DLMF 14.9.13
fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
sv = errprint(sv)
else:
mp = m
p, pd = specfun.lpmn(mp, n, z)
if (m < 0):
p = p * fixarr
pd = pd * fixarr
return p, pd
def clpmn(m, n, z, type=3):
"""Associated Legendre function of the first kind, Pmn(z).
Computes the associated Legendre function of the first kind of order m and
degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
Parameters
----------
m : int
``|m| <= n``; the order of the Legendre function.
n : int
where ``n >= 0``; the degree of the Legendre function. Often
called ``l`` (lower case L) in descriptions of the associated
Legendre function
z : float or complex
Input value.
type : int, optional
takes values 2 or 3
2: cut on the real axis ``|x| > 1``
3: cut on the real axis ``-1 < x < 1`` (default)
Returns
-------
Pmn_z : (m+1, n+1) array
Values for all orders ``0..m`` and degrees ``0..n``
Pmn_d_z : (m+1, n+1) array
Derivatives for all orders ``0..m`` and degrees ``0..n``
See Also
--------
lpmn: associated Legendre functions of the first kind for real z
Notes
-----
By default, i.e. for ``type=3``, phase conventions are chosen according
to [1]_ such that the function is analytic. The cut lies on the interval
(-1, 1). Approaching the cut from above or below in general yields a phase
factor with respect to Ferrer's function of the first kind
(cf. `lpmn`).
For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values
on the interval (-1, 1) in the complex plane yields Ferrer's function
of the first kind.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
.. [2] NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/14.21
"""
if not isscalar(m) or (abs(m) > n):
raise ValueError("m must be <= n.")
if not isscalar(n) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if not isscalar(z):
raise ValueError("z must be scalar.")
if not(type == 2 or type == 3):
raise ValueError("type must be either 2 or 3.")
if (m < 0):
mp = -m
mf, nf = mgrid[0:mp+1, 0:n+1]
sv = errprint(0)
if type == 2:
fixarr = where(mf > nf, 0.0,
(-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1))
else:
fixarr = where(mf > nf, 0.0, gamma(nf-mf+1) / gamma(nf+mf+1))
sv = errprint(sv)
else:
mp = m
p, pd = specfun.clpmn(mp, n, real(z), imag(z), type)
if (m < 0):
p = p * fixarr
pd = pd * fixarr
return p, pd
def lqmn(m, n, z):
"""Associated Legendre function of the second kind, Qmn(z).
Computes the associated Legendre function of the second kind of order m and
degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
Parameters
----------
m : int
``|m| <= n``; the order of the Legendre function.
n : int
where ``n >= 0``; the degree of the Legendre function. Often
called ``l`` (lower case L) in descriptions of the associated
Legendre function
z : complex
Input value.
Returns
-------
Qmn_z : (m+1, n+1) array
Values for all orders 0..m and degrees 0..n
Qmn_d_z : (m+1, n+1) array
Derivatives for all orders 0..m and degrees 0..n
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(m) or (m < 0):
raise ValueError("m must be a non-negative integer.")
if not isscalar(n) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if not isscalar(z):
raise ValueError("z must be scalar.")
m = int(m)
n = int(n)
# Ensure neither m nor n == 0
mm = max(1, m)
nn = max(1, n)
if iscomplex(z):
q, qd = specfun.clqmn(mm, nn, z)
else:
q, qd = specfun.lqmn(mm, nn, z)
return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)]
def bernoulli(n):
"""Bernoulli numbers B0..Bn (inclusive).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(n) or (n < 0):
raise ValueError("n must be a non-negative integer.")
n = int(n)
if (n < 2):
n1 = 2
else:
n1 = n
return specfun.bernob(int(n1))[:(n+1)]
def euler(n):
"""Euler numbers E0..En (inclusive).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(n) or (n < 0):
raise ValueError("n must be a non-negative integer.")
n = int(n)
if (n < 2):
n1 = 2
else:
n1 = n
return specfun.eulerb(n1)[:(n+1)]
def lpn(n, z):
"""Legendre functions of the first kind, Pn(z).
Compute sequence of Legendre functions of the first kind (polynomials),
Pn(z) and derivatives for all degrees from 0 to n (inclusive).
See also special.legendre for polynomial class.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z):
pn, pd = specfun.clpn(n1, z)
else:
pn, pd = specfun.lpn(n1, z)
return pn[:(n+1)], pd[:(n+1)]
def lqn(n, z):
"""Legendre functions of the second kind, Qn(z).
Compute sequence of Legendre functions of the second kind, Qn(z) and
derivatives for all degrees from 0 to n (inclusive).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (n != floor(n)) or (n < 0):
raise ValueError("n must be a non-negative integer.")
if (n < 1):
n1 = 1
else:
n1 = n
if iscomplex(z):
qn, qd = specfun.clqn(n1, z)
else:
qn, qd = specfun.lqnb(n1, z)
return qn[:(n+1)], qd[:(n+1)]
def ai_zeros(nt):
"""
Compute `nt` zeros and values of the Airy function Ai and its derivative.
Computes the first `nt` zeros, `a`, of the Airy function Ai(x);
first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x);
the corresponding values Ai(a');
and the corresponding values Ai'(a).
Parameters
----------
nt : int
Number of zeros to compute
Returns
-------
a : ndarray
First `nt` zeros of Ai(x)
ap : ndarray
First `nt` zeros of Ai'(x)
ai : ndarray
Values of Ai(x) evaluated at first `nt` zeros of Ai'(x)
aip : ndarray
Values of Ai'(x) evaluated at first `nt` zeros of Ai(x)
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
kf = 1
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be a positive integer scalar.")
return specfun.airyzo(nt, kf)
def bi_zeros(nt):
"""
Compute `nt` zeros and values of the Airy function Bi and its derivative.
Computes the first `nt` zeros, b, of the Airy function Bi(x);
first `nt` zeros, b', of the derivative of the Airy function Bi'(x);
the corresponding values Bi(b');
and the corresponding values Bi'(b).
Parameters
----------
nt : int
Number of zeros to compute
Returns
-------
b : ndarray
First `nt` zeros of Bi(x)
bp : ndarray
First `nt` zeros of Bi'(x)
bi : ndarray
Values of Bi(x) evaluated at first `nt` zeros of Bi'(x)
bip : ndarray
Values of Bi'(x) evaluated at first `nt` zeros of Bi(x)
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
kf = 2
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be a positive integer scalar.")
return specfun.airyzo(nt, kf)
def lmbda(v, x):
r"""Jahnke-Emden Lambda function, Lambdav(x).
This function is defined as [2]_,
.. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v},
where :math:`\Gamma` is the gamma function and :math:`J_v` is the
Bessel function of the first kind.
Parameters
----------
v : float
Order of the Lambda function
x : float
Value at which to evaluate the function and derivatives
Returns
-------
vl : ndarray
Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
dl : ndarray
Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
.. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and
Curves" (4th ed.), Dover, 1945
"""
if not (isscalar(v) and isscalar(x)):
raise ValueError("arguments must be scalars.")
if (v < 0):
raise ValueError("argument must be > 0.")
n = int(v)
v0 = v - n
if (n < 1):
n1 = 1
else:
n1 = n
v1 = n1 + v0
if (v != floor(v)):
vm, vl, dl = specfun.lamv(v1, x)
else:
vm, vl, dl = specfun.lamn(v1, x)
return vl[:(n+1)], dl[:(n+1)]
def pbdv_seq(v, x):
"""Parabolic cylinder functions Dv(x) and derivatives.
Parameters
----------
v : float
Order of the parabolic cylinder function
x : float
Value at which to evaluate the function and derivatives
Returns
-------
dv : ndarray
Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
dp : ndarray
Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 13.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(v) and isscalar(x)):
raise ValueError("arguments must be scalars.")
n = int(v)
v0 = v-n
if (n < 1):
n1 = 1
else:
n1 = n
v1 = n1 + v0
dv, dp, pdf, pdd = specfun.pbdv(v1, x)
return dv[:n1+1], dp[:n1+1]
def pbvv_seq(v, x):
"""Parabolic cylinder functions Vv(x) and derivatives.
Parameters
----------
v : float
Order of the parabolic cylinder function
x : float
Value at which to evaluate the function and derivatives
Returns
-------
dv : ndarray
Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
dp : ndarray
Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 13.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(v) and isscalar(x)):
raise ValueError("arguments must be scalars.")
n = int(v)
v0 = v-n
if (n <= 1):
n1 = 1
else:
n1 = n
v1 = n1 + v0
dv, dp, pdf, pdd = specfun.pbvv(v1, x)
return dv[:n1+1], dp[:n1+1]
def pbdn_seq(n, z):
"""Parabolic cylinder functions Dn(z) and derivatives.
Parameters
----------
n : int
Order of the parabolic cylinder function
z : complex
Value at which to evaluate the function and derivatives
Returns
-------
dv : ndarray
Values of D_i(z), for i=0, ..., i=n.
dp : ndarray
Derivatives D_i'(z), for i=0, ..., i=n.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996, chapter 13.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(n) and isscalar(z)):
raise ValueError("arguments must be scalars.")
if (floor(n) != n):
raise ValueError("n must be an integer.")
if (abs(n) <= 1):
n1 = 1
else:
n1 = n
cpb, cpd = specfun.cpbdn(n1, z)
return cpb[:n1+1], cpd[:n1+1]
def ber_zeros(nt):
"""Compute nt zeros of the Kelvin function ber(x).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 1)
def bei_zeros(nt):
"""Compute nt zeros of the Kelvin function bei(x).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 2)
def ker_zeros(nt):
"""Compute nt zeros of the Kelvin function ker(x).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 3)
def kei_zeros(nt):
"""Compute nt zeros of the Kelvin function kei(x).
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 4)
def berp_zeros(nt):
"""Compute nt zeros of the Kelvin function ber'(x).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 5)
def beip_zeros(nt):
"""Compute nt zeros of the Kelvin function bei'(x).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 6)
def kerp_zeros(nt):
"""Compute nt zeros of the Kelvin function ker'(x).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 7)
def keip_zeros(nt):
"""Compute nt zeros of the Kelvin function kei'(x).
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return specfun.klvnzo(nt, 8)
def kelvin_zeros(nt):
"""Compute nt zeros of all Kelvin functions.
Returned in a length-8 tuple of arrays of length nt. The tuple contains
the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei').
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
raise ValueError("nt must be positive integer scalar.")
return (specfun.klvnzo(nt, 1),
specfun.klvnzo(nt, 2),
specfun.klvnzo(nt, 3),
specfun.klvnzo(nt, 4),
specfun.klvnzo(nt, 5),
specfun.klvnzo(nt, 6),
specfun.klvnzo(nt, 7),
specfun.klvnzo(nt, 8))
def pro_cv_seq(m, n, c):
"""Characteristic values for prolate spheroidal wave functions.
Compute a sequence of characteristic values for the prolate
spheroidal wave functions for mode m and n'=m..n and spheroidal
parameter c.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(m) and isscalar(n) and isscalar(c)):
raise ValueError("Arguments must be scalars.")
if (n != floor(n)) or (m != floor(m)):
raise ValueError("Modes must be integers.")
if (n-m > 199):
raise ValueError("Difference between n and m is too large.")
maxL = n-m+1
return specfun.segv(m, n, c, 1)[1][:maxL]
def obl_cv_seq(m, n, c):
"""Characteristic values for oblate spheroidal wave functions.
Compute a sequence of characteristic values for the oblate
spheroidal wave functions for mode m and n'=m..n and spheroidal
parameter c.
References
----------
.. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
Functions", John Wiley and Sons, 1996.
http://jin.ece.illinois.edu/specfunc.html
"""
if not (isscalar(m) and isscalar(n) and isscalar(c)):
raise ValueError("Arguments must be scalars.")
if (n != floor(n)) or (m != floor(m)):
raise ValueError("Modes must be integers.")
if (n-m > 199):
raise ValueError("Difference between n and m is too large.")
maxL = n-m+1
return specfun.segv(m, n, c, -1)[1][:maxL]
def ellipk(m):
"""Complete elliptic integral of the first kind.
This function is defined as
.. math:: K(m) = \\int_0^{\\pi/2} [1 - m \\sin(t)^2]^{-1/2} dt
Parameters
----------
m : array_like
The parameter of the elliptic integral.
Returns
-------
K : array_like
Value of the elliptic integral.
Notes
-----
For more precision around point m = 1, use `ellipkm1`, which this
function calls.
See Also
--------
ellipkm1 : Complete elliptic integral of the first kind around m = 1
ellipkinc : Incomplete elliptic integral of the first kind
ellipe : Complete elliptic integral of the second kind
ellipeinc : Incomplete elliptic integral of the second kind
"""
return ellipkm1(1 - asarray(m))
def agm(a, b):
"""Arithmetic, Geometric Mean.
Start with a_0=a and b_0=b and iteratively compute
a_{n+1} = (a_n+b_n)/2
b_{n+1} = sqrt(a_n*b_n)
until a_n=b_n. The result is agm(a, b)
agm(a, b)=agm(b, a)
agm(a, a) = a
min(a, b) < agm(a, b) < max(a, b)
"""
s = a + b + 0.0
return (pi / 4) * s / ellipkm1(4 * a * b / s ** 2)
def comb(N, k, exact=False, repetition=False):
"""The number of combinations of N things taken k at a time.
This is often expressed as "N choose k".
Parameters
----------
N : int, ndarray
Number of things.
k : int, ndarray
Number of elements taken.
exact : bool, optional
If `exact` is False, then floating point precision is used, otherwise
exact long integer is computed.
repetition : bool, optional
If `repetition` is True, then the number of combinations with
repetition is computed.
Returns
-------
val : int, ndarray
The total number of combinations.
Notes
-----
- Array arguments accepted only for exact=False case.
- If k > N, N < 0, or k < 0, then a 0 is returned.
Examples
--------
>>> from scipy.special import comb
>>> k = np.array([3, 4])
>>> n = np.array([10, 10])
>>> comb(n, k, exact=False)
array([ 120., 210.])
>>> comb(10, 3, exact=True)
120L
>>> comb(10, 3, exact=True, repetition=True)
220L
"""
if repetition:
return comb(N + k - 1, k, exact)
if exact:
N = int(N)
k = int(k)
if (k > N) or (N < 0) or (k < 0):
return 0
val = 1
for j in xrange(min(k, N-k)):
val = (val*(N-j))//(j+1)
return val
else:
k, N = asarray(k), asarray(N)
cond = (k <= N) & (N >= 0) & (k >= 0)
vals = binom(N, k)
if isinstance(vals, np.ndarray):
vals[~cond] = 0
elif not cond:
vals = np.float64(0)
return vals
def perm(N, k, exact=False):
"""Permutations of N things taken k at a time, i.e., k-permutations of N.
It's also known as "partial permutations".
Parameters
----------
N : int, ndarray
Number of things.
k : int, ndarray
Number of elements taken.
exact : bool, optional
If `exact` is False, then floating point precision is used, otherwise
exact long integer is computed.
Returns
-------
val : int, ndarray
The number of k-permutations of N.
Notes
-----
- Array arguments accepted only for exact=False case.
- If k > N, N < 0, or k < 0, then a 0 is returned.
Examples
--------
>>> from scipy.special import perm
>>> k = np.array([3, 4])
>>> n = np.array([10, 10])
>>> perm(n, k)
array([ 720., 5040.])
>>> perm(10, 3, exact=True)
720
"""
if exact:
if (k > N) or (N < 0) or (k < 0):
return 0
val = 1
for i in xrange(N - k + 1, N + 1):
val *= i
return val
else:
k, N = asarray(k), asarray(N)
cond = (k <= N) & (N >= 0) & (k >= 0)
vals = poch(N - k + 1, k)
if isinstance(vals, np.ndarray):
vals[~cond] = 0
elif not cond:
vals = np.float64(0)
return vals
def factorial(n, exact=False):
"""The factorial function, n! = special.gamma(n+1).
If exact is 0, then floating point precision is used, otherwise
exact long integer is computed.
- Array argument accepted only for exact=False case.
- If n<0, the return value is 0.
Parameters
----------
n : int or array_like of ints
Calculate ``n!``. Arrays are only supported with `exact` set
to False. If ``n < 0``, the return value is 0.
exact : bool, optional
The result can be approximated rapidly using the gamma-formula
above. If `exact` is set to True, calculate the
answer exactly using integer arithmetic. Default is False.
Returns
-------
nf : float or int
Factorial of `n`, as an integer or a float depending on `exact`.
Examples
--------
>>> from scipy.special import factorial
>>> arr = np.array([3, 4, 5])
>>> factorial(arr, exact=False)
array([ 6., 24., 120.])
>>> factorial(5, exact=True)
120L
"""
if exact:
return math.factorial(n)
else:
n = asarray(n)
vals = gamma(n+1)
return where(n >= 0, vals, 0)
def factorial2(n, exact=False):
"""Double factorial.
This is the factorial with every second value skipped. E.g., ``7!! = 7 * 5
* 3 * 1``. It can be approximated numerically as::
n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi) n odd
= 2**(n/2) * (n/2)! n even
Parameters
----------
n : int or array_like
Calculate ``n!!``. Arrays are only supported with `exact` set
to False. If ``n < 0``, the return value is 0.
exact : bool, optional
The result can be approximated rapidly using the gamma-formula
above (default). If `exact` is set to True, calculate the
answer exactly using integer arithmetic.
Returns
-------
nff : float or int
Double factorial of `n`, as an int or a float depending on
`exact`.
Examples
--------
>>> from scipy.special import factorial2
>>> factorial2(7, exact=False)
array(105.00000000000001)
>>> factorial2(7, exact=True)
105L
"""
if exact:
if n < -1:
return 0
if n <= 0:
return 1
val = 1
for k in xrange(n, 0, -2):
val *= k
return val
else:
n = asarray(n)
vals = zeros(n.shape, 'd')
cond1 = (n % 2) & (n >= -1)
cond2 = (1-(n % 2)) & (n >= -1)
oddn = extract(cond1, n)
evenn = extract(cond2, n)
nd2o = oddn / 2.0
nd2e = evenn / 2.0
place(vals, cond1, gamma(nd2o + 1) / sqrt(pi) * pow(2.0, nd2o + 0.5))
place(vals, cond2, gamma(nd2e + 1) * pow(2.0, nd2e))
return vals
def factorialk(n, k, exact=True):
"""Multifactorial of n of order k, n(!!...!).
This is the multifactorial of n skipping k values. For example,
factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
In particular, for any integer ``n``, we have
factorialk(n, 1) = factorial(n)
factorialk(n, 2) = factorial2(n)
Parameters
----------
n : int
Calculate multifactorial. If `n` < 0, the return value is 0.
k : int
Order of multifactorial.
exact : bool, optional
If exact is set to True, calculate the answer exactly using
integer arithmetic.
Returns
-------
val : int
Multifactorial of `n`.
Raises
------
NotImplementedError
Raises when exact is False
Examples
--------
>>> from scipy.special import factorialk
>>> factorialk(5, 1, exact=True)
120L
>>> factorialk(5, 3, exact=True)
10L
"""
if exact:
if n < 1-k:
return 0
if n <= 0:
return 1
val = 1
for j in xrange(n, 0, -k):
val = val*j
return val
else:
raise NotImplementedError
|
Jaccorot/python | refs/heads/master | horx/0009/run.py | 40 | #!/usr/bin/env python3
import re
import requests
r = requests.get('https://github.com')
matches = re.findall('(?:https?|ftp)://[^\s/$\.?#].[^\s]+', r.text)
for i in range(0, len(matches)):
print('matche >>>: {} \n'.format(matches[i]))
|
aspose-pdf/Aspose.Pdf-for-Cloud | refs/heads/master | SDKs/Aspose.Pdf-Cloud-SDK-for-Python/asposepdfcloud/models/ResponseMessage.py | 27 | #!/usr/bin/env python
class ResponseMessage(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'Code': 'int',
'Message': 'str'
}
self.attributeMap = {
'Code': 'Code','Message': 'Message'}
self.Code = None # int
self.Message = None # str
|
pelson/pelican-plugins | refs/heads/master | representative_image/__init__.py | 65 | from .representative_image import *
|
rasika-amaratissa/xhtml2pdf | refs/heads/master | demo/tgpisa/tgpisa/model.py | 169 | from turbogears.database import PackageHub
# import some basic SQLObject classes for declaring the data model
# (see http://www.sqlobject.org/SQLObject.html#declaring-the-class)
from sqlobject import SQLObject, SQLObjectNotFound, RelatedJoin
# import some datatypes for table columns from SQLObject
# (see http://www.sqlobject.org/SQLObject.html#column-types for more)
from sqlobject import StringCol, UnicodeCol, IntCol, DateTimeCol
__connection__ = hub = PackageHub('tgpisa')
# your data model
# class YourDataClass(SQLObject):
# pass
|
hulkamania/lockdown | refs/heads/master | src/daemonize.py | 1 | import os
import sys
class Daemonize:
''' Generic class for creating a daemon
http://code.activestate.com/recipes/578072-generic-way-to-create-a-daemonized-process-in-pyth/
'''
def daemonize(self):
try:
#this process would create a parent and a child
pid = os.fork()
if pid > 0:
# take care of the first parent
sys.exit(0)
except OSError, err:
sys.stderr.write("Fork 1 has failed --> %d--[%s]\n" % (err.errno, err.strerror))
sys.exit(1)
#change to root
os.chdir('/')
#detach from terminal
os.setsid()
# file to be created ?
os.umask(0)
try:
# this process creates a parent and a child
pid = os.fork()
if pid > 0:
print "Daemon process pid %d" % pid
#bam
sys.exit(0)
except OSError, err:
sys.stderr.write("Fork 2 has failed --> %d--[%s]\n" % (err.errno, err.strerror))
sys.exit(1)
sys.stdout.flush()
sys.stderr.flush()
def start_daemon(self):
self.daemonize()
self.run_daemon()
def run_daemon(self):
''' override this function
'''
pass
|
cupy/cupy | refs/heads/master | tests/cupyx_tests/scipy_tests/sparse_tests/__init__.py | 2 | import pytest
import cupy
if cupy.cuda.runtime.is_hip:
pytest.skip('HIP sparse support is not yet ready',
allow_module_level=True)
|
mchaperc/web_search | refs/heads/master | constants.py | 1 | links = [
"https://www.news.ycombinator.com",
"https://www.bloomberg.com/",
] |
sukiand/idapython | refs/heads/master | pywraps/deploy_all.py | 16 | # Please use the same tag for the same .i file
# That means if many insertions are going to happen in one
# given .i file then don't use more than code marking tag
print "\n-------- DEPLOY started --------------------------------------------------\n"
deploys = {
"idaapi (common functions, notifywhen)" : {
"tag" : "py_idaapi",
"src" : ["py_cvt.hpp", "py_idaapi.hpp", "py_idaapi.py", "py_notifywhen.hpp", "py_notifywhen.py"],
"tgt" : "../swig/idaapi.i"
},
"View (common)" : {
"tag" : "py_view_base",
"src" : ["py_view_base.hpp", "py_view_base.py"],
"tgt" : "../swig/view.i"
},
"IDAView" : {
"tag" : "py_idaview",
"src" : ["py_idaview.hpp", "py_idaview.py"],
"tgt" : "../swig/view.i"
},
"Graph" : {
"tag" : "py_graph",
"src" : ["py_graph.hpp", "py_graph.py"],
"tgt" : "../swig/graph.i"
},
"custview" : {
"tag" : "py_custviewer",
"src" : ["py_custview.py","py_custview.hpp"],
"tgt" : "../swig/kernwin.i"
},
"plgform" : {
"tag" : "py_plgform",
"src" : ["py_plgform.hpp","py_plgform.py"],
"tgt" : "../swig/kernwin.i"
},
"expr" : {
"tag" : "py_expr",
"src" : ["py_expr.hpp","py_expr.py"],
"tgt" : "../swig/expr.i"
},
"cli" : {
"tag" : "py_cli",
"src" : ["py_cli.py","py_cli.hpp"],
"tgt" : "../swig/kernwin.i"
},
"Loader" : {
"tag" : "py_loader",
"src" : ["py_loader.hpp"],
"tgt" : "../swig/loader.i"
},
"kernwin, choose2, askusingform" : {
"tag" : "py_kernwin",
"src" : ["py_kernwin.hpp","py_kernwin.py","py_choose.hpp","py_choose2.hpp","py_choose2.py","py_askusingform.hpp","py_askusingform.py"],
"tgt" : "../swig/kernwin.i"
},
"idd" : {
"tag" : "py_idd",
"src" : ["py_dbg.hpp","py_appcall.py"],
"tgt" : "../swig/idd.i"
},
"idd (python)" : {
"tag" : "py_idd_2",
"src" : ["py_dbg.py"],
"tgt" : "../swig/idd.i"
},
"nalt" : {
"tag" : "py_nalt",
"src" : ["py_nalt.hpp","py_nalt.py"],
"tgt" : "../swig/nalt.i"
},
"dbg" : {
"tag" : "py_dbg",
"src" : ["py_dbg.hpp"],
"tgt" : "../swig/dbg.i"
},
"linput/diskio" : {
"tag" : "py_diskio",
"src" : ["py_linput.hpp","py_diskio.hpp","py_diskio.py"],
"tgt" : "../swig/diskio.i"
},
"name" : {
"tag" : "py_name",
"src" : ["py_name.hpp","py_name.py"],
"tgt" : "../swig/name.i"
},
"qfile" : {
"tag" : "py_qfile",
"src" : ["py_qfile.hpp"],
"tgt" : "../swig/fpro.i"
},
"bytes" : {
"tag" : "py_bytes",
"src" : ["py_bytes.hpp","py_custdata.py","py_custdata.hpp"],
"tgt" : "../swig/bytes.i"
},
"typeinf" : {
"tag" : "py_typeinf",
"src" : ["py_typeinf.hpp","py_typeinf.py"],
"tgt" : "../swig/typeinf.i"
},
"gdl" : {
"tag" : "py_gdl",
"src" : ["py_gdl.py"],
"tgt" : "../swig/gdl.i"
},
"ua" : {
"tag" : "py_ua",
"src" : ["py_ua.hpp","py_ua.py"],
"tgt" : "../swig/ua.i"
},
"idp" : {
"tag" : "py_idp",
"src" : ["py_idp.hpp"],
"tgt" : "../swig/idp.i"
},
"lines" : {
"tag" : "py_lines",
"src" : ["py_lines.hpp","py_lines.py"],
"tgt" : "../swig/lines.i"
},
"registry" : {
"tag" : "py_registry",
"src" : ["py_registry.hpp"],
"tgt" : "../swig/registry.i"
},
"pc_win32_appcall" : {
"tag" : "appcalltest",
"src" : ["py_appcall.py"],
"tgt" : "../../../tests/input/pc_win32_appcall.pe.hints"
},
"ex_custdata example" : {
"tag" : "ex_custdata",
"src" : ["../examples/ex_custdata.py"],
"tgt" : "../../../tests/input/pc_win32_custdata1.pe.hints"
},
"ex_choose2" : {
"tag" : "py_choose2ex1",
"src" : ["py_choose2.py"],
"tgt" : "../examples/ex_choose2.py"
},
"ex_formchooser" : {
"tag" : "ex_formchooser",
"src" : ["py_askusingform.py"],
"tgt" : "../../formchooser/formchooser.py"
},
"ex_askusingform" : {
"tag" : "ex_askusingform",
"src" : ["py_askusingform.py"],
"tgt" : "../examples/ex_askusingform.py"
},
"ex_cli example" : {
"tag" : "ex_cli_ex1",
"src" : ["py_cli.py"],
"tgt" : "../examples/ex_cli.py"
},
"ex_expr example" : {
"tag" : "ex_expr",
"src" : ["py_expr.py"],
"tgt" : "../examples/ex_expr.py"
},
"ex_custview.py example" : {
"tag" : "py_custviewerex1",
"src" : ["py_custview.py"],
"tgt" : "../examples/ex_custview.py"
}
}
import deploy
for name in deploys:
data = deploys[name]
print "Deploying %s" % name
deploy.deploy(data["tag"], data["src"], data["tgt"])
|
ice9js/servo | refs/heads/master | components/script/dom/bindings/codegen/parser/tests/test_arraybuffer.py | 158 | import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
interface TestArrayBuffer {
attribute ArrayBuffer bufferAttr;
void bufferMethod(ArrayBuffer arg1, ArrayBuffer? arg2, ArrayBuffer[] arg3, sequence<ArrayBuffer> arg4);
attribute ArrayBufferView viewAttr;
void viewMethod(ArrayBufferView arg1, ArrayBufferView? arg2, ArrayBufferView[] arg3, sequence<ArrayBufferView> arg4);
attribute Int8Array int8ArrayAttr;
void int8ArrayMethod(Int8Array arg1, Int8Array? arg2, Int8Array[] arg3, sequence<Int8Array> arg4);
attribute Uint8Array uint8ArrayAttr;
void uint8ArrayMethod(Uint8Array arg1, Uint8Array? arg2, Uint8Array[] arg3, sequence<Uint8Array> arg4);
attribute Uint8ClampedArray uint8ClampedArrayAttr;
void uint8ClampedArrayMethod(Uint8ClampedArray arg1, Uint8ClampedArray? arg2, Uint8ClampedArray[] arg3, sequence<Uint8ClampedArray> arg4);
attribute Int16Array int16ArrayAttr;
void int16ArrayMethod(Int16Array arg1, Int16Array? arg2, Int16Array[] arg3, sequence<Int16Array> arg4);
attribute Uint16Array uint16ArrayAttr;
void uint16ArrayMethod(Uint16Array arg1, Uint16Array? arg2, Uint16Array[] arg3, sequence<Uint16Array> arg4);
attribute Int32Array int32ArrayAttr;
void int32ArrayMethod(Int32Array arg1, Int32Array? arg2, Int32Array[] arg3, sequence<Int32Array> arg4);
attribute Uint32Array uint32ArrayAttr;
void uint32ArrayMethod(Uint32Array arg1, Uint32Array? arg2, Uint32Array[] arg3, sequence<Uint32Array> arg4);
attribute Float32Array float32ArrayAttr;
void float32ArrayMethod(Float32Array arg1, Float32Array? arg2, Float32Array[] arg3, sequence<Float32Array> arg4);
attribute Float64Array float64ArrayAttr;
void float64ArrayMethod(Float64Array arg1, Float64Array? arg2, Float64Array[] arg3, sequence<Float64Array> arg4);
};
""")
results = parser.finish()
iface = results[0]
harness.ok(True, "TestArrayBuffer interface parsed without error")
harness.check(len(iface.members), 22, "Interface should have twenty two members")
members = iface.members
def checkStuff(attr, method, t):
harness.ok(isinstance(attr, WebIDL.IDLAttribute), "Expect an IDLAttribute")
harness.ok(isinstance(method, WebIDL.IDLMethod), "Expect an IDLMethod")
harness.check(str(attr.type), t, "Expect an ArrayBuffer type")
harness.ok(attr.type.isSpiderMonkeyInterface(), "Should test as a js interface")
(retType, arguments) = method.signatures()[0]
harness.ok(retType.isVoid(), "Should have a void return type")
harness.check(len(arguments), 4, "Expect 4 arguments")
harness.check(str(arguments[0].type), t, "Expect an ArrayBuffer type")
harness.ok(arguments[0].type.isSpiderMonkeyInterface(), "Should test as a js interface")
harness.check(str(arguments[1].type), t + "OrNull", "Expect an ArrayBuffer type")
harness.ok(arguments[1].type.inner.isSpiderMonkeyInterface(), "Should test as a js interface")
harness.check(str(arguments[2].type), t + "Array", "Expect an ArrayBuffer type")
harness.ok(arguments[2].type.inner.isSpiderMonkeyInterface(), "Should test as a js interface")
harness.check(str(arguments[3].type), t + "Sequence", "Expect an ArrayBuffer type")
harness.ok(arguments[3].type.inner.isSpiderMonkeyInterface(), "Should test as a js interface")
checkStuff(members[0], members[1], "ArrayBuffer")
checkStuff(members[2], members[3], "ArrayBufferView")
checkStuff(members[4], members[5], "Int8Array")
checkStuff(members[6], members[7], "Uint8Array")
checkStuff(members[8], members[9], "Uint8ClampedArray")
checkStuff(members[10], members[11], "Int16Array")
checkStuff(members[12], members[13], "Uint16Array")
checkStuff(members[14], members[15], "Int32Array")
checkStuff(members[16], members[17], "Uint32Array")
checkStuff(members[18], members[19], "Float32Array")
checkStuff(members[20], members[21], "Float64Array")
|
haoyuchen1992/osf.io | refs/heads/develop | tests/test_share.py | 39 | import xml
from mock import patch
from nose.tools import * # flake8: noqa (PEP8 asserts)
from tests.base import OsfTestCase
from website.search import util
from website.search import share_search
STANDARD_RETURN_VALUE = {
'hits': {
'hits': [{
"_score": 1,
"_type": "squaredcircle",
"_id": "1164135",
"_source": {
"description": "Jobbers and society.",
"contributors": [{
"name": "Zachary Ryder",
"givenName": "Zachary",
"familyName": "Ryder",
"additionalNames": ["Woo Woo Woo"],
"email": "",
"sameAs": []
}],
"title": "Am I Still Employed",
"providerUpdatedDateTime": "2014-11-24T00:00:00",
"uris": {
"canonicalUri": "http://squaredcircle.com/zackryder/woowoowoo",
"objectUris": ["10.123/wrestlingDOIs"]
},
"tags": ['woo', 'woo', 'woo'],
},
"_index": "share"
}, {
"_score": 1,
"_type": "squaredcircle",
"_id": "1164539",
"_source": {
"description": "Unlocking the universe with the Cosmic Key",
"contributors": [{
"name": "Star Dust",
"givenName": "Star",
"familyName": "Dust",
}],
"providerUpdatedDateTime": "2014-11-27T00:00:00",
"uris": {
"canonicalUri": "http://squaredcircle.com/stardust/hisssssss"
},
"tags": ['cody', 'is', 'noone']
},
"_index": "share"
}],
'total': 2
}
}
class TestShareSearch(OsfTestCase):
@patch.object(share_search.share_es, 'search')
def test_share_search(self, mock_search):
mock_search.return_value = {
'hits': {
'hits': {},
'total': 0
}
}
self.app.get('/api/v1/share/search/', params={
'q': '*',
'from': '1',
'size:': '20',
'sort': 'date',
'v': '1'
})
assert_is(mock_search.called, True)
@patch.object(share_search.share_es, 'count')
def test_share_count(self, mock_count):
mock_count.return_value = {'count': 0}
self.app.get('/api/v1/share/search/', params={
'q': '*',
'from': '1',
'size:': '20',
'sort': 'date',
'count': True,
'v': '1'
})
assert_is(mock_count.called, True)
def test_share_count_cleans_query(self):
cleaned_query = share_search.clean_count_query({
'aggs': {
'sourceAgg': {
'terms': {
'field': '_type',
'min_doc_count': 0,
'size': 0
}
}
},
'aggregations': {
'sourceAgg': {
'terms': {
'field': '_type',
'min_doc_count': 0,
'size': 0
}
}
},
'from': 0,
'query':
{
'match_all': {}
},
'size': 10
})
assert_equals(cleaned_query.keys(), ['query'])
@patch.object(share_search.share_es, 'search')
def test_share_providers(self, mock_search):
mock_search.return_value = {
'hits': {
'hits': {},
'total': 0
}
}
self.app.get('/api/v1/share/providers/')
assert_is(mock_search.called, True)
@patch.object(share_search.share_es, 'search')
def test_share_stats(self, mock_search):
mock_search.return_value = {
'hits': {
'hits': {},
'total': 0
},
'aggregations': {
'date_chunks': {
'buckets': [{
'articles_over_time': {
'buckets': []
},
'key': 'test',
'doc_count': 0
}]
},
'sources': {
'buckets': [{
'key': 'test',
'doc_count': 0
}]
},
'earlier_documents': {
'sources': {
'buckets': [{
'key': 'test',
'doc_count': 0
}]
}
}
}
}
self.app.get('/api/v1/share/stats/')
assert_is(mock_search.called, True)
class TestShareAtom(OsfTestCase):
@patch.object(share_search.share_es, 'search')
def test_atom_returns_200(self, mock_search):
mock_search.return_value = STANDARD_RETURN_VALUE
response = self.app.get('/share/atom/')
assert_equal(response.status, '200 OK')
@patch.object(share_search.share_es, 'search')
def test_atom_renders_xml(self, mock_search):
mock_search.return_value = STANDARD_RETURN_VALUE
response = self.app.get('/share/atom/')
xml_content = response.xml
assert isinstance(xml_content, xml.etree.ElementTree.Element)
@patch.object(share_search.share_es, 'search')
def test_atom_head_tag(self, mock_search):
mock_search.return_value = STANDARD_RETURN_VALUE
response = self.app.get('/share/atom/')
xml_content = response.xml
assert_equal(xml_content.tag, '{http://www.w3.org/2005/Atom}feed')
@patch.object(share_search.share_es, 'search')
def test_first_link_rel_self(self, mock_search):
mock_search.return_value = STANDARD_RETURN_VALUE
response = self.app.get('/share/atom/')
xml_content = response.xml
rel = xml_content.find('{http://www.w3.org/2005/Atom}link')
assert_equal(rel.attrib['rel'], 'self')
@patch.object(share_search.share_es, 'search')
def test_page_5_has_correct_links(self, mock_search):
mock_search.return_value = STANDARD_RETURN_VALUE
response = self.app.get('/share/atom/', params={
'page': 5
})
links = response.xml.findall('{http://www.w3.org/2005/Atom}link')
assert_equal(len(links), 4)
attribs = [link.attrib for link in links]
assert_equal(attribs[1]['href'][-7:], '?page=1')
assert_equal(attribs[1]['rel'], 'first')
assert_equal(attribs[2]['href'][-7:], '?page=6')
assert_equal(attribs[2]['rel'], 'next')
assert_equal(attribs[3]['href'][-7:], '?page=4')
assert_equal(attribs[3]['rel'], 'previous')
@patch.object(share_search.share_es, 'search')
def test_title_updates_with_query(self, mock_search):
mock_search.return_value = STANDARD_RETURN_VALUE
response = self.app.get('/share/atom/', params={
'q': 'cats'
})
title = response.xml.find('{http://www.w3.org/2005/Atom}title')
assert_equal(title.text, 'SHARE: Atom Feed for query: "cats"')
def test_illegal_unicode_sub(self):
illegal_str = u'\u0000\u0008\u000b\u000c\u000e\u001f\ufffe\uffffHello'
illegal_str += unichr(0xd800) + unichr(0xdbff) + ' World'
assert_equal(util.html_and_illegal_unicode_replace(illegal_str), 'Hello World')
assert_equal(util.html_and_illegal_unicode_replace(''), '')
assert_equal(util.html_and_illegal_unicode_replace(None), None)
assert_equal(util.html_and_illegal_unicode_replace('WOOOooooOOo'), 'WOOOooooOOo')
def test_html_tag_sub(self):
html_str = "<p><b>RKO</b> outta <i>NOWHERE</i>!!!</p>"
assert_equal(util.html_and_illegal_unicode_replace(html_str), 'RKO outta NOWHERE!!!')
@patch.object(share_search.share_es, 'search')
def test_atom_returns_correct_number(self, mock_search):
mock_search.return_value = STANDARD_RETURN_VALUE
response = self.app.get('/share/atom/')
entries = response.xml.findall('{http://www.w3.org/2005/Atom}entry')
assert_equal(len(entries), STANDARD_RETURN_VALUE['hits']['total'])
def test_compute_start_non_number(self):
page = 'cow'
size = 250
result = util.compute_start(page, size)
assert_equal(result, 0)
def test_compute_start_negative(self):
page = -10
size = 250
result = util.compute_start(page, size)
assert_equal(result, 0)
def test_compute_start_normal(self):
page = 50
size = 10
result = util.compute_start(page, size)
assert_equal(result, 490)
|
mccarrmb/moztrap | refs/heads/master | moztrap/view/manage/runs/forms.py | 3 | """
Management forms for runs.
"""
import floppyforms.__future__ as forms
from django.core.exceptions import ValidationError
from moztrap import model
from moztrap.view.lists import filters
from moztrap.view.utils import mtforms
class RunForm(mtforms.NonFieldErrorsClassFormMixin, mtforms.MTModelForm):
"""Base form for adding/editing runs."""
suites = mtforms.MTMultipleChoiceField(
required=False,
widget=mtforms.FilteredSelectMultiple(
choice_template="manage/run/suite_select/_suite_select_item.html",
listordering_template=(
"manage/run/suite_select/_suite_select_listordering.html"),
filters=[
filters.KeywordFilter("name"),
filters.ModelFilter(
"author", queryset=model.User.objects.all()),
],
)
)
productversion = mtforms.MTModelChoiceField(
queryset=model.ProductVersion.objects.all(),
choice_attrs=mtforms.product_id_attrs,
)
build = forms.CharField(max_length=200, required=False)
is_series = forms.BooleanField(required=False)
class Meta:
model = model.Run
fields = [
"productversion",
"name",
"description",
"is_series",
"build",
"start",
"end",
"is_series",
]
widgets = {
"name": forms.TextInput,
"description": mtforms.BareTextarea,
"build": forms.TextInput,
"is_series": forms.CheckboxInput,
"start": forms.DateInput,
"end": forms.DateInput,
}
def clean_suites(self):
"""
Make sure all the ids for the suites are valid and populate
self.cleaned_data with the real objects.
If these are not ids, then they are read-only strings of the title
and therefore don't need to be validated. So first verify they're
all ints.
"""
try:
suites = dict((unicode(x.id), x) for x in
model.Suite.objects.filter(pk__in=self.cleaned_data["suites"]))
try:
return [suites[x] for x in self.cleaned_data["suites"]]
except KeyError as e:
raise ValidationError("Not a valid suite for this run.")
except ValueError:
# some of the values weren't ints, and therefore this is
# from the read-only list of suites. so return None so that we
# don't try to remove and re-add them.
if "suites" in self.changed_data: # pragma: no cover
self.changed_data.remove("suites")
return None
def clean_build(self):
"""If this is a series, then null out the build field."""
if self.cleaned_data["is_series"]:
return None
def save(self, user=None):
"""Save and return run, with suite associations."""
user = user or self.user
run = super(RunForm, self).save(user=user)
if "suites" in self.changed_data:
# if this is empty, then don't make any changes, because
# either there are no suites, or this came from the read
# only suite list.
run.runsuites.all().delete(permanent=True)
for i, suite in enumerate(self.cleaned_data["suites"]):
model.RunSuite.objects.create(
run=run, suite=suite, order=i, user=user)
return run
class AddRunForm(RunForm):
"""Form for adding a run."""
def __init__(self, *args, **kwargs):
"""Initialize AddRunForm; default to being a series."""
super(AddRunForm, self).__init__(*args, **kwargs)
isf = self.fields["is_series"]
isf.initial = True
class EditRunForm(RunForm):
"""Form for editing a run."""
def __init__(self, *args, **kwargs):
"""Initialize EditRunForm; no changing product version of active run."""
super(EditRunForm, self).__init__(*args, **kwargs)
pvf = self.fields["productversion"]
sf = self.fields["suites"]
isf = self.fields["is_series"]
self.initial["suites"] = list(
self.instance.suites.values_list(
"name", flat=True).order_by("runsuites__order"))
if self.instance.status == model.Run.STATUS.active:
# can't change the product version of an active run.
pvf.queryset = pvf.queryset.filter(
pk=self.instance.productversion_id)
pvf.readonly = True
# can't change being a series in an active run
isf.readonly = True
# can't change suites of an active run either
sf.readonly = True
else:
# regardless, can't switch to different product entirely
pvf.queryset = pvf.queryset.filter(
product=self.instance.productversion.product_id)
# ajax populates available and included suites on page load
|
TAMU-CPT/galaxy-tools | refs/heads/master | tools/util/compare_codons.py | 1 | #!/usr/bin/env python
import argparse
import numpy as np
import itertools
import pygal
from Bio.Seq import Seq
from Bio.Alphabet import IUPAC
from pygal.style import LightSolarizedStyle
def tntable(table=11):
codons = itertools.product("ACTG", repeat=3)
_table = {}
translation = {}
for x in ["".join(y) for y in codons]:
aa = str(Seq(x, IUPAC.IUPACUnambiguousDNA()).translate(table=table)).upper()
translation[x] = aa
try:
_table[aa][x] = {}
except:
_table[aa] = {x: {}}
return _table, translation
def custom_sort(table, sort="default"):
if sort == "default":
kv = []
# Like a normal sort, except send * to end
def protein_sort(x):
return 1000 if x == "*" else ord(x)
for aa in sorted(table.keys(), key=protein_sort):
for codon in sorted(table[aa].keys()):
kv.append((aa, codon))
return kv
elif sort in ("ref", "comp"):
kv = custom_sort(table, sort="default")
def protein_sort(x):
-1 * table.get(x[0], {}).get(x[1], {}).get(sort, 0)
return sorted(kv, key=protein_sort)
def main(reference, comparison, sort_order="default", ref_title=None, cmp_title=None):
ref_data = np.genfromtxt(reference, dtype=None, delimiter="\t", names=True)
comp_data = np.genfromtxt(comparison, dtype=None, delimiter="\t", names=True)
table, translation = tntable()
ref_sum = sum(zip(*ref_data)[1])
for codon in ref_data:
# AAA \t N
# N -> AAA = 32
nt = codon[0].upper()
aa = translation[nt]
table[aa][nt]["ref"] = float(codon[1]) / ref_sum
comp_sum = sum(zip(*comp_data)[1])
for codon in comp_data:
nt = codon[0].upper()
if "nt" in translation:
aa = translation[nt]
table[aa][nt]["comp"] = float(codon[1]) / comp_sum
keys = []
ref_flat = []
comp_flat = []
for (x, y) in custom_sort(table, sort=sort_order):
keys.append("%s (%s)" % (x, y))
ref_val = table.get(x, {}).get(y, {}).get("ref", None)
comp_val = table.get(x, {}).get(y, {}).get("comp", None)
ref_flat.append({"value": ref_val, "label": str(ref_val)})
comp_flat.append({"value": comp_val, "label": str(comp_val)})
bar_chart = pygal.Bar(
width=1500,
height=400,
x_label_rotation=90,
style=LightSolarizedStyle,
delete=False,
)
bar_chart.title = "Codon Usage Frequency Comparison"
bar_chart.x_labels = keys
bar_chart.add(ref_title, ref_flat)
bar_chart.add(cmp_title, comp_flat)
print bar_chart.render()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Plot comparison of codon usage", epilog=""
)
parser.add_argument("reference", type=argparse.FileType("r"), help="Reference Data")
parser.add_argument(
"comparison", type=argparse.FileType("r"), help="Data to compare"
)
parser.add_argument(
"--sort_order",
choices=["default", "comp", "ref"],
help="Sort order for final plot",
default="default",
)
parser.add_argument("--ref_title", help="Reference title")
parser.add_argument("--cmp_title", help="Comparison title")
args = parser.parse_args()
main(**vars(args))
|
pabloborrego93/edx-platform | refs/heads/master | lms/djangoapps/edxnotes/decorators.py | 72 | """
Decorators related to edXNotes.
"""
import json
from django.conf import settings
from edxnotes.helpers import (
get_edxnotes_id_token,
get_public_endpoint,
get_token_url,
generate_uid,
is_feature_enabled,
)
from edxmako.shortcuts import render_to_string
def edxnotes(cls):
"""
Decorator that makes components annotatable.
"""
original_get_html = cls.get_html
def get_html(self, *args, **kwargs):
"""
Returns raw html for the component.
"""
is_studio = getattr(self.system, "is_author_mode", False)
course = self.descriptor.runtime.modulestore.get_course(self.runtime.course_id)
# Must be disabled:
# - in Studio;
# - when Harvard Annotation Tool is enabled for the course;
# - when the feature flag or `edxnotes` setting of the course is set to False.
if is_studio or not is_feature_enabled(course):
return original_get_html(self, *args, **kwargs)
else:
return render_to_string("edxnotes_wrapper.html", {
"content": original_get_html(self, *args, **kwargs),
"uid": generate_uid(),
"edxnotes_visibility": json.dumps(
getattr(self, 'edxnotes_visibility', course.edxnotes_visibility)
),
"params": {
# Use camelCase to name keys.
"usageId": unicode(self.scope_ids.usage_id).encode("utf-8"),
"courseId": unicode(self.runtime.course_id).encode("utf-8"),
"token": get_edxnotes_id_token(self.runtime.get_real_user(self.runtime.anonymous_student_id)),
"tokenUrl": get_token_url(self.runtime.course_id),
"endpoint": get_public_endpoint(),
"debug": settings.DEBUG,
"eventStringLimit": settings.TRACK_MAX_EVENT / 6,
},
})
cls.get_html = get_html
return cls
|
Tejal011089/fbd_erpnext | refs/heads/develop | erpnext/setup/utils.py | 18 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, throw
from frappe.utils import flt
def get_company_currency(company):
currency = frappe.db.get_value("Company", company, "default_currency", cache=True)
if not currency:
currency = frappe.db.get_default("currency")
if not currency:
throw(_('Please specify Default Currency in Company Master and Global Defaults'))
return currency
def get_root_of(doctype):
"""Get root element of a DocType with a tree structure"""
result = frappe.db.sql_list("""select name from `tab%s`
where lft=1 and rgt=(select max(rgt) from `tab%s` where docstatus < 2)""" %
(doctype, doctype))
return result[0] if result else None
def get_ancestors_of(doctype, name):
"""Get ancestor elements of a DocType with a tree structure"""
lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
result = frappe.db.sql_list("""select name from `tab%s`
where lft<%s and rgt>%s order by lft desc""" % (doctype, "%s", "%s"), (lft, rgt))
return result or []
def before_tests():
frappe.clear_cache()
# complete setup if missing
from erpnext.setup.page.setup_wizard.setup_wizard import setup_account
if not frappe.get_list("Company"):
setup_account({
"currency" :"USD",
"first_name" :"Test",
"last_name" :"User",
"company_name" :"Wind Power LLC",
"timezone" :"America/New_York",
"company_abbr" :"WP",
"industry" :"Manufacturing",
"country" :"United States",
"fy_start_date" :"2014-01-01",
"fy_end_date" :"2014-12-31",
"language" :"english",
"company_tagline" :"Testing",
"email" :"test@erpnext.com",
"password" :"test",
"chart_of_accounts" : "Standard"
})
frappe.db.sql("delete from `tabLeave Allocation`")
frappe.db.sql("delete from `tabLeave Application`")
frappe.db.sql("delete from `tabSalary Slip`")
frappe.db.sql("delete from `tabItem Price`")
frappe.db.commit()
@frappe.whitelist()
def get_exchange_rate(from_currency, to_currency):
try:
cache = frappe.cache()
key = "currency_exchange_rate:{0}:{1}".format(from_currency, to_currency)
value = cache.get(key)
if not value:
import requests
response = requests.get("http://api.fixer.io/latest", params={
"base": from_currency,
"symbols": to_currency
})
# expire in 24 hours
response.raise_for_status()
value = response.json()["rates"][to_currency]
cache.setex(key, value, 24 * 60 * 60)
return flt(value)
except:
exchange = "%s-%s" % (from_currency, to_currency)
return flt(frappe.db.get_value("Currency Exchange", exchange, "exchange_rate"))
|
naojsoft/ginga | refs/heads/master | ginga/misc/Settings.py | 3 | #
# Settings.py -- Simple class to manage stateful user preferences.
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os
import re
import ast
import numpy as np
from . import Callback
from . import Bunch
unset_value = "^^UNSET^^"
regex_assign = re.compile(r'^([a-zA-Z_]\w*)\s*=\s*(\S.*)$')
regex_array = re.compile(r'^\s*array\((\[.*\])\s*(,\s*dtype=(.+)\s*)?\)\s*$',
flags=re.DOTALL)
class SettingError(Exception):
pass
class Setting(Callback.Callbacks):
def __init__(self, value=unset_value, name=None, logger=None,
check_fn=None):
Callback.Callbacks.__init__(self)
self.value = value
self._unset = np.isscalar(value) and value == unset_value
self.name = name
self.logger = logger
if check_fn is None:
check_fn = self._check_none
self.check_fn = check_fn
# For callbacks
for name in ('set', ):
self.enable_callback(name)
def _check_none(self, value):
return value
def set(self, value, callback=True):
self.value = self.check_fn(value)
if callback:
self.make_callback('set', value)
def get(self, *args):
if self._unset:
if len(args) == 0:
raise KeyError("setting['%s'] value is not set!" % (
self.name))
else:
if len(args) != 1:
raise SettingError("Illegal parameter use to get(): %s" % (
str(args)))
return args[0]
return self.value
def __repr__(self):
return repr(self.value)
def __str__(self):
return str(self.value)
class SettingGroup(object):
def __init__(self, name=None, logger=None, preffile=None):
self.name = name
self.logger = logger
self.preffile = preffile
# TODO: add group change callback?
self.group = Bunch.Bunch()
self._group_b = Bunch.Bunch()
def add_settings(self, **kwdargs):
for key, value in kwdargs.items():
if key not in self.group:
setting = Setting(value=value, name=key,
logger=self.logger)
self._mk_add_callback(key, setting)
self.group[key] = setting
# add to backup group
if key not in self._group_b:
self._group_b[key] = setting
def get_setting(self, key):
return self.group[key]
def keys(self):
return self.group.keys()
def _mk_add_callback(self, key, setting):
setting._add_callback = setting.add_callback
def _add_callback(*args, **kwargs):
self.group[key]._add_callback(*args, **kwargs)
self._group_b[key]._add_callback(*args, **kwargs)
setting.add_callback = _add_callback
def share_settings(self, other, keylist=None, include_callbacks=True,
callback=True):
"""Sharing settings with `other`
"""
if keylist is None:
keylist = self.group.keys()
if include_callbacks:
for key in keylist:
oset, mset = other.group[key], self.group[key]
other.group[key] = mset
oset.merge_callbacks_to(mset)
if callback:
# make callbacks only after all items are set in the group
# TODO: only make callbacks for values that changed?
for key in keylist:
other.group[key].make_callback('set', other.group[key].value)
def unshare_settings(self, keylist=None, callback=True):
if keylist is None:
keylist = self._group_b.keys()
for key in keylist:
# copy value from current setting, while restoring old setting
if self.group[key] is not self._group_b[key]:
value = self.group[key].value
self.group[key] = self._group_b[key]
self.group[key].set(value, callback=False)
if callback:
# make callbacks only after all items are set in the group
# TODO: only make callbacks for values that changed?
for key in keylist:
self.group[key].make_callback('set', self.group[key].value)
def copy_settings(self, other, keylist=None, include_callbacks=False,
callback=True):
if keylist is None:
keylist = self.group.keys()
d = {key: self.get(key) for key in keylist}
if include_callbacks:
for key in keylist:
oset, mset = other.group[key], self.group[key]
mset.merge_callbacks_to(oset)
other.set_dict(d, callback=callback)
def setdefault(self, key, value):
if key in self.group:
return self.group[key].get(value)
else:
d = {key: value}
self.add_settings(**d)
return self.group[key].get(value)
def add_defaults(self, **kwdargs):
for key, value in kwdargs.items():
self.setdefault(key, value)
def set_defaults(self, **kwdargs):
return self.add_defaults(**kwdargs)
def get(self, *args):
key = args[0]
if len(args) == 1:
return self.group[key].get()
else:
if key in self.group:
return self.group[key].get(*args[1:])
if len(args) > 2:
raise SettingError("Illegal parameter use to get(): %s" % (
str(args)))
return args[1]
def get_dict(self, keylist=None):
if keylist is None:
keylist = self.group.keys()
return dict([[name, self.group[name].value]
for name in keylist])
def set_dict(self, d, callback=True):
for key, value in d.items():
if key not in self.group:
self.setdefault(key, value)
else:
self.group[key].set(value, callback=False)
if callback:
# make callbacks only after all items are set in the group
for key, value in d.items():
self.group[key].make_callback('set', value)
def set(self, callback=True, **kwdargs):
self.set_dict(kwdargs, callback=callback)
def __getitem__(self, key):
return self.group[key].value
def __setitem__(self, key, value):
self.group[key].set(value)
# TODO: Should deprecate this and encourage __contains__ like Python dict
def has_key(self, key):
return key in self.group
def __contains__(self, key):
return key in self.group
def clear_callbacks(self, keylist=None):
if keylist is None:
keylist = self.group.keys()
for key in keylist:
self.group[key].clear_callback('set')
def load(self, onError='raise', buf=None):
try:
if buf is None:
with open(self.preffile, 'r') as in_f:
buf = in_f.read()
d = dict(list(eval_assignments(make_assignments(strip_comments(
buf.split('\n'))))))
self.set_dict(d)
except Exception as e:
errmsg = "Error loading settings file (%s): %s" % (
self.preffile, str(e))
if onError == 'silent':
pass
elif onError == 'warn':
self.logger.warning(errmsg)
else:
raise SettingError(errmsg)
def _check(self, d):
if isinstance(d, dict):
for key, value in d.items():
d[key] = self._check(value)
return d
try:
if np.isnan(d):
return 0.0
elif np.isinf(d):
return 0.0
except Exception:
pass
return d
def _save(self, out_f, keys, d):
for key in keys:
val_s = repr(d[key])
out_f.write("%s = %s\n" % (key, val_s))
def save(self, keylist=None, output=None):
d = self.get_dict(keylist=keylist)
# sanitize data -- hard to parse NaN or Inf
self._check(d)
try:
# sort keys for easy reading/editing
keys = list(d.keys())
keys.sort()
if output is None:
output = self.preffile
if isinstance(output, str):
with open(output, 'w') as out_f:
self._save(out_f, keys, d)
else:
self._save(output, keys, d)
except Exception as e:
errmsg = "Error writing settings output: %s" % (str(e))
self.logger.error(errmsg)
########################################################
### NON-PEP8 PREDECESSORS: TO BE DEPRECATED
addSettings = add_settings
getSetting = get_setting
shareSettings = share_settings
copySettings = copy_settings
addDefaults = add_defaults
setDefaults = set_defaults
getDict = get_dict
setDict = set_dict
class Preferences(object):
def __init__(self, basefolder=None, logger=None):
self.folder = basefolder
self.logger = logger
self.settings = Bunch.Bunch(caseless=True)
def set_defaults(self, category, **kwdargs):
self.settings[category].add_defaults(**kwdargs)
def get_settings(self, category):
return self.settings[category]
def remove_settings(self, category):
del self.settings[category]
def get_dict_category(self, category):
return self.settings[category].get_dict()
def create_category(self, category):
if category not in self.settings:
suffix = '.cfg'
path = os.path.join(self.folder, category + suffix)
self.settings[category] = SettingGroup(logger=self.logger,
name=category,
preffile=path)
return self.settings[category]
def get_base_folder(self):
return self.folder
def get_dict(self):
return dict([[name, self.settings[name].get_dict()] for name in
self.settings.keys()])
########################################################
### NON-PEP8 PREDECESSORS: TO BE DEPRECATED
setDefaults = set_defaults
getSettings = get_settings
createCategory = create_category
get_baseFolder = get_base_folder
getDict = get_dict
def strip_comments(lines):
"""Strips all blank lines and comments from `lines`.
Parameters
----------
lines : iterable of str
The input file, stripped into lines
Returns
-------
results : iterable of (int, str)
An iterable containing tuples of (line number, text)
"""
for line_no, line in enumerate(lines):
line = line.strip()
if len(line) == 0 or line.startswith('#'):
continue
yield (line_no, line)
def make_assignments(results):
"""Makes line_no, kwd, value string triples.
Parameters
----------
results: iterable of (int, str)
Output of `strip_comments()`
Returns
-------
results: iterable of (int, str, str)
An iterable containing tuples of (line_number, kwd, val_str)
"""
building = False
kwd, vals, n = None, [], 0
for line_no, line in results:
match = regex_assign.match(line)
if match:
if building:
yield n, kwd, ' '.join(vals)
building = True
n = line_no
kwd, val = match.groups()
vals = [val]
else:
if building:
vals.append(line)
else:
raise Exception("Unexpected syntax on line {}: {}".format(line_no, line))
if len(vals) > 0:
yield n, kwd, ' '.join(vals)
def eval_assignments(results):
"""Makes kwd, value pairs.
Parameters
----------
results: iterable of (int, str, str)
Output of `make_assignments()`
Returns
-------
results: iterable of (str, val)
An iterable containing tuples of (kwd, val)
"""
for line_no, kwd, val_s in results:
match = regex_array.match(val_s)
if match:
data, _x, dtype = match.groups()
# special case for parsing numpy arrays
val = np.asarray(ast.literal_eval(data), dtype=dtype)
else:
val = ast.literal_eval(val_s)
yield kwd, val
|
ncclient/ncclient | refs/heads/master | ncclient/operations/retrieve.py | 3 | # Copyright 2009 Shikhar Bhushan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ncclient.operations.errors import OperationError
from ncclient.operations.rpc import RPC, RPCReply
from ncclient.xml_ import *
from lxml import etree
from ncclient.operations import util
class WithDefaultsError(OperationError):
"""Invalid 'with-defaults' mode or capability URI"""
class GetReply(RPCReply):
"""Adds attributes for the *data* element to `RPCReply`."""
def _parsing_hook(self, root):
self._data = None
if not self._errors:
self._data = root.find(qualify("data"))
@property
def data_ele(self):
"*data* element as an :class:`~xml.etree.ElementTree.Element`"
if not self._parsed:
self.parse()
return self._data
@property
def data_xml(self):
"*data* element as an XML string"
if not self._parsed:
self.parse()
return to_xml(self._data)
data = data_ele
"Same as :attr:`data_ele`"
class GetSchemaReply(GetReply):
"""Reply for GetSchema called with specific parsing hook."""
def _parsing_hook(self, root):
self._data = None
if not self._errors:
self._data = root.find(qualify("data", NETCONF_MONITORING_NS)).text
class Get(RPC):
"The *get* RPC."
REPLY_CLS = GetReply
"See :class:`GetReply`."
def request(self, filter=None, with_defaults=None):
"""Retrieve running configuration and device state information.
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
*with_defaults* defines an explicit method of retrieving default values from the configuration (see :rfc:`6243`)
:seealso: :ref:`filter_params`
"""
node = new_ele("get")
if filter is not None:
node.append(util.build_filter(filter))
if with_defaults is not None:
self._assert(":with-defaults")
_append_with_defaults_mode(
node,
with_defaults,
self._session.server_capabilities,
)
return self._request(node)
def _append_with_defaults_mode(node, mode, capabilities):
_validate_with_defaults_mode(mode, capabilities)
with_defaults_element = sub_ele_ns(
node,
"with-defaults",
NETCONF_WITH_DEFAULTS_NS,
)
with_defaults_element.text = mode
def _validate_with_defaults_mode(mode, capabilities):
valid_modes = _get_valid_with_defaults_modes(capabilities)
if mode.strip().lower() not in valid_modes:
raise WithDefaultsError(
"Invalid 'with-defaults' mode '{provided}'; the server only "
"supports the following: {options}".format(
provided=mode,
options=', '.join(valid_modes)
)
)
def _get_valid_with_defaults_modes(capabilities):
"""Reference: https://tools.ietf.org/html/rfc6243#section-4.3"""
capability = capabilities[":with-defaults"]
try:
valid_modes = [capability.parameters["basic-mode"]]
except KeyError:
raise WithDefaultsError(
"Invalid 'with-defaults' capability URI advertised by the server; "
"missing 'basic-mode' parameter"
)
try:
also_supported = capability.parameters["also-supported"]
except KeyError:
return valid_modes
valid_modes.extend(also_supported.split(","))
return valid_modes
class GetConfig(RPC):
"""The *get-config* RPC."""
REPLY_CLS = GetReply
"""See :class:`GetReply`."""
def request(self, source, filter=None, with_defaults=None):
"""Retrieve all or part of a specified configuration.
*source* name of the configuration datastore being queried
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
*with_defaults* defines an explicit method of retrieving default values from the configuration (see :rfc:`6243`)
:seealso: :ref:`filter_params`"""
node = new_ele("get-config")
node.append(util.datastore_or_url("source", source, self._assert))
if filter is not None:
node.append(util.build_filter(filter))
if with_defaults is not None:
self._assert(":with-defaults")
_append_with_defaults_mode(
node,
with_defaults,
self._session.server_capabilities,
)
return self._request(node)
class GetSchema(RPC):
"""The *get-schema* RPC."""
REPLY_CLS = GetSchemaReply
"""See :class:`GetReply`."""
def request(self, identifier, version=None, format=None):
"""Retrieve a named schema, with optional revision and type.
*identifier* name of the schema to be retrieved
*version* version of schema to get
*format* format of the schema to be retrieved, yang is the default
:seealso: :ref:`filter_params`"""
self._huge_tree = True
node = etree.Element(qualify("get-schema",NETCONF_MONITORING_NS))
if identifier is not None:
elem = etree.Element(qualify("identifier",NETCONF_MONITORING_NS))
elem.text = identifier
node.append(elem)
if version is not None:
elem = etree.Element(qualify("version",NETCONF_MONITORING_NS))
elem.text = version
node.append(elem)
if format is not None:
elem = etree.Element(qualify("format",NETCONF_MONITORING_NS))
elem.text = format
node.append(elem)
return self._request(node)
class Dispatch(RPC):
"""Generic retrieving wrapper"""
REPLY_CLS = RPCReply
"""See :class:`RPCReply`."""
def request(self, rpc_command, source=None, filter=None):
"""
*rpc_command* specifies rpc command to be dispatched either in plain text or in xml element format (depending on command)
*source* name of the configuration datastore being queried
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
:seealso: :ref:`filter_params`
Examples of usage::
dispatch('clear-arp-table')
or dispatch element like ::
xsd_fetch = new_ele('get-xnm-information')
sub_ele(xsd_fetch, 'type').text="xml-schema"
sub_ele(xsd_fetch, 'namespace').text="junos-configuration"
dispatch(xsd_fetch)
"""
if etree.iselement(rpc_command):
node = rpc_command
else:
node = new_ele(rpc_command)
if source is not None:
node.append(util.datastore_or_url("source", source, self._assert))
if filter is not None:
node.append(util.build_filter(filter))
return self._request(node)
|
TeachCraft/TeachCraft-Examples | refs/heads/master | examples/mcpi_import_3d_model.py | 1 | # These two lines are because of the folder the demos are located in, and aren't normally necessary
import os.path, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
#Example Source from: https://github.com/martinohanlon/minecraft-renderObjv2
#from minecraftstuff import MinecraftDrawing
import mcpi.minecraft as minecraft
import mcpi.block as block
import time
import datetime
# class to create 3d filled polygons
class MinecraftDrawing:
def __init__(self, mc):
self.mc = mc
# draw point
def drawPoint3d(self, x, y, z, blockType, blockData=None):
self.mc.setBlock(x,y,z,blockType,blockData)
#print("x = " + str(x) + ", y = " + str(y) + ", z = " + str(z))
# draws a face, when passed a collection of vertices which make up a polyhedron
def drawFace(self, vertices, blockType, blockData=None):
# get the edges of the face
edgesVertices = []
# persist first vertex
firstVertex = vertices[0]
# loop through vertices and get edges
vertexCount = 0
for vertex in vertices:
vertexCount+=1
if vertexCount > 1:
# got 2 vertices, get the points for the edge
edgesVertices = edgesVertices + self.getLine(lastVertex.x, lastVertex.y, lastVertex.z, vertex.x, vertex.y, vertex.z)
#print("x = " + str(lastVertex.x) + ", y = " + str(lastVertex.y) + ", z = " + str(lastVertex.z) + " x2 = " + str(vertex.x) + ", y2 = " + str(vertex.y) + ", z2 = " + str(vertex.z))
# persist the last vertex found
lastVertex = vertex
# get edge between the last and first vertices
edgesVertices = edgesVertices + self.getLine(lastVertex.x, lastVertex.y, lastVertex.z, firstVertex.x, firstVertex.y, firstVertex.z)
# sort edges vertices
def keyX( point ): return point.x
def keyY( point ): return point.y
def keyZ( point ): return point.z
edgesVertices.sort( key=keyZ )
edgesVertices.sort( key=keyY )
edgesVertices.sort( key=keyX )
# not very performant but wont have gaps between in complex models
for vertex in edgesVertices:
vertexCount+=1
# got 2 vertices, draw lines between them
if (vertexCount > 1):
self.drawLine(lastVertex.x, lastVertex.y, lastVertex.z, vertex.x, vertex.y, vertex.z, blockType, blockData)
#print("x = " + str(lastVertex.x) + ", y = " + str(lastVertex.y) + ", z = " + str(lastVertex.z) + " x2 = " + str(vertex.x) + ", y2 = " + str(vertex.y) + ", z2 = " + str(vertex.z))
# persist the last vertex found
lastVertex = vertex
# draw's all the points in a collection of vertices with a block
def drawVertices(self, vertices, blockType, blockData=None):
for vertex in vertices:
self.drawPoint3d(vertex.x, vertex.y, vertex.z, blockType, blockData)
# draw line
def drawLine(self, x1, y1, z1, x2, y2, z2, blockType, blockData):
self.drawVertices(self.getLine(x1, y1, z1, x2, y2, z2), blockType, blockData)
# returns points on a line
def getLine(self, x1, y1, z1, x2, y2, z2):
# return maximum of 2 values
def MAX(a,b):
if a > b: return a
else: return b
# return step
def ZSGN(a):
if a < 0: return -1
elif a > 0: return 1
elif a == 0: return 0
# list for vertices
vertices = []
# if the 2 points are the same, return single vertice
if (x1 == x2 and y1 == y2 and z1 == z2):
vertices.append(minecraft.Vec3(x1, y1, z1))
# else get all points in edge
else:
dx = x2 - x1
dy = y2 - y1
dz = z2 - z1
ax = abs(dx) << 1
ay = abs(dy) << 1
az = abs(dz) << 1
sx = ZSGN(dx)
sy = ZSGN(dy)
sz = ZSGN(dz)
x = x1
y = y1
z = z1
# x dominant
if (ax >= MAX(ay, az)):
yd = ay - (ax >> 1)
zd = az - (ax >> 1)
loop = True
while(loop):
vertices.append(minecraft.Vec3(x, y, z))
if (x == x2):
loop = False
if (yd >= 0):
y += sy
yd -= ax
if (zd >= 0):
z += sz
zd -= ax
x += sx
yd += ay
zd += az
# y dominant
elif (ay >= MAX(ax, az)):
xd = ax - (ay >> 1)
zd = az - (ay >> 1)
loop = True
while(loop):
vertices.append(minecraft.Vec3(x, y, z))
if (y == y2):
loop=False
if (xd >= 0):
x += sx
xd -= ay
if (zd >= 0):
z += sz
zd -= ay
y += sy
xd += ax
zd += az
# z dominant
elif(az >= MAX(ax, ay)):
xd = ax - (az >> 1)
yd = ay - (az >> 1)
loop = True
while(loop):
vertices.append(minecraft.Vec3(x, y, z))
if (z == z2):
loop=False
if (xd >= 0):
x += sx
xd -= az
if (yd >= 0):
y += sy
yd -= az
z += sz
xd += ax
yd += ay
return vertices
def load_obj(filename, defaultBlock, materials) :
V = [] #vertex
T = [] #texcoords
N = [] #normals
F = [] #face indexies
MF = [] #materials to faces
currentMaterial = defaultBlock
fh = open(filename)
for line in fh :
if line[0] == '#' : continue
line = line.strip().split(' ')
if line[0] == 'v' : #vertex
V.append(line[1:])
elif line[0] == 'vt' : #tex-coord
T.append(line[1:])
elif line[0] == 'vn' : #normal vector
N.append(line[1:])
elif line[0] == 'f' : #face
face = line[1:]
for i in range(0, len(face)) :
face[i] = face[i].split('/')
# OBJ indexies are 1 based not 0 based hence the -1
# convert indexies to integer
for j in range(0, len(face[i])) :
if face[i][j] != "":
face[i][j] = int(face[i][j]) - 1
#append the material currently in use to the face
F.append(face)
MF.append(currentMaterial)
elif line[0] == 'usemtl': # material
usemtl = line[1]
if (usemtl in materials.keys()):
currentMaterial = materials[usemtl]
else:
currentMaterial = defaultBlock
print("Warning: Couldn't find '" + str(usemtl) + "' in materials using default")
return V, T, N, F, MF
# strips the x,y,z co-ords from a vertex line, scales appropriately, rounds and converts to int
def getVertexXYZ(vertexLine, scale, startCoord, swapYZ):
# convert, round and scale
x = int((float(vertexLine[0]) * scale) + 0.5)
y = int((float(vertexLine[1]) * scale) + 0.5)
z = int((float(vertexLine[2]) * scale) + 0.5)
# add startCoord to x,y,z
x = x + startCoord.x
y = y + startCoord.y
z = z + startCoord.z
# swap y and z coord if needed
if swapYZ == True:
swap = y
y = z
z = swap
return x, y, z
# main program
if __name__ == "__main__":
print(datetime.datetime.now())
# Connect to minecraft server 127.0.0.1 as player 'steve'
mc = minecraft.Minecraft.create(address="127.0.0.1", name="steve")
#Create minecraft drawing class
mcDrawing = MinecraftDrawing(mc)
"""
Load objfile and set constants
COORDSSCALE = factor to scale the co-ords by
STARTCOORD = where to start the model, the relative position 0
CLEARAREA1/2 = 2 points the program should clear an area in between to put the model in
SWAPYZ = True to sway the Y and Z dimension
MATERIALS = a dictionary object which maps materials in the obj file to blocks in minecraft
DEFAULTBLOCK = the default type of block to build the model in, used if a material cant be found
"""
what_to_build = "shuttle" #Valid values: shuttle, skyscraper, or farmhouse
if what_to_build == "shuttle":
COORDSSCALE = 6
#Build model 20 blocks above player
pos = mc.player.getTilePos()
STARTCOORD = minecraft.Vec3(pos.x,pos.z,pos.y+20)
SWAPYZ = True
#Note: Y and Z are swapped in this 3d model compared to the MC universe
DEFAULTBLOCK = [block.WOOL.id,0]
MATERIALS = {"glass": [block.GLASS.id, 0],
"bone": [block.WOOL.id, 0],
"fldkdkgrey": [block.WOOL.id, 7],
"redbrick": [block.WOOL.id, 14],
"black": [block.WOOL.id, 15],
"brass": [block.WOOL.id, 1],
"dkdkgrey": [block.WOOL.id, 7]}
vertices,textures,normals,faces,materials = load_obj("resources/shuttle.obj", DEFAULTBLOCK, MATERIALS)
if what_to_build == "skyscraper":
COORDSSCALE = 1.4
#Build model 20 blocks to size of player
pos = mc.player.getTilePos()
STARTCOORD = minecraft.Vec3(pos.x,pos.y,pos.z+20)
SWAPYZ = False
DEFAULTBLOCK = [block.IRON_BLOCK, 0]
MATERIALS = {"glass": [block.GLASS.id, 0],
"bone": [block.WOOL.id, 0],
"fldkdkgrey": [block.WOOL.id, 7],
"redbrick": [block.WOOL.id, 14],
"black": [block.WOOL.id, 15],
"brass": [block.WOOL.id, 1],
"dkdkgrey": [block.WOOL.id, 7]}
MATERIALS = {
"brass": [block.WOOL.id, 1],
"bone": [block.WOOL.id, 0],
"black": [block.WOOL.id, 15],
"bluteal": [block.IRON_BLOCK, 0],
"tan": [24, 2],
"blutan": [42, 0],
"brown": [5, 1],
"ltbrown": [5, 3],
}
vertices,textures,normals,faces,materials = load_obj("resources/skyscraper.obj", DEFAULTBLOCK, MATERIALS)
if what_to_build == "farmhouse":
COORDSSCALE = 1
#Build model 20 blocks to size of player
pos = mc.player.getTilePos()
STARTCOORD = minecraft.Vec3(pos.x,pos.y,pos.z+20)
DEFAULTBLOCK = [block.IRON_BLOCK, 0]
MATERIALS = {}
SWAPYZ = False
vertices,textures,normals,faces,materials = load_obj("resources/farmhouse.obj", DEFAULTBLOCK, MATERIALS)
print("obj file loaded")
#Post a message to the minecraft chat window
mc.postToChat("Started 3d render...")
faceCount = 0
# loop through faces
for face in faces:
faceVertices = []
# loop through vertex's in face and call drawFace function
for vertex in face:
#strip co-ords from vertex line
vertexX, vertexY, vertexZ = getVertexXYZ(vertices[vertex[0]], COORDSSCALE, STARTCOORD, SWAPYZ)
faceVertices.append(minecraft.Vec3(vertexX,vertexY,vertexZ))
# draw the face
mcDrawing.drawFace(faceVertices, materials[faceCount][0], materials[faceCount][1])
faceCount = faceCount + 1
mc.postToChat("Model complete.")
print(datetime.datetime.now())
|
Qalthos/ansible | refs/heads/devel | test/units/modules/cloud/misc/virt_net/conftest.py | 38 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import pytest
from ansible.modules.cloud.misc import virt_net
from units.compat import mock
virt_net.libvirt = None
virt_net.HAS_VIRT = True
class DummyNetwork():
def __init__(self, name, isActive=True):
self._name = name
self._isActive = isActive
def name(self):
return self._name
def isActive(self):
return self._isActive
class DummyLibvirtConn():
def __init__(self):
self._network = [
DummyNetwork("inactive_net", isActive=False),
DummyNetwork("active_net", isActive=True)]
def listNetworks(self):
return [i.name() for i in self._network]
def networkLookupByName(self, name):
for i in self._network:
if i.name() == name:
return i
def listDefinedNetworks(self):
return []
class DummyLibvirt():
VIR_ERR_NETWORK_EXIST = 'VIR_ERR_NETWORK_EXIST'
@classmethod
def open(cls, uri):
return DummyLibvirtConn()
class libvirtError(Exception):
def __init__(self):
self.error_code
def get_error_code(self):
return self.error_code
@pytest.fixture
def dummy_libvirt(monkeypatch):
monkeypatch.setattr(virt_net, 'libvirt', DummyLibvirt)
return DummyLibvirt
@pytest.fixture
def virt_net_obj(dummy_libvirt):
return virt_net.VirtNetwork('qemu:///nowhere', mock.MagicMock())
|
fldc/CouchPotatoServer | refs/heads/custom | libs/chardet/charsetgroupprober.py | 2928 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from . import constants
import sys
from .charsetprober import CharSetProber
class CharSetGroupProber(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mActiveNum = 0
self._mProbers = []
self._mBestGuessProber = None
def reset(self):
CharSetProber.reset(self)
self._mActiveNum = 0
for prober in self._mProbers:
if prober:
prober.reset()
prober.active = True
self._mActiveNum += 1
self._mBestGuessProber = None
def get_charset_name(self):
if not self._mBestGuessProber:
self.get_confidence()
if not self._mBestGuessProber:
return None
# self._mBestGuessProber = self._mProbers[0]
return self._mBestGuessProber.get_charset_name()
def feed(self, aBuf):
for prober in self._mProbers:
if not prober:
continue
if not prober.active:
continue
st = prober.feed(aBuf)
if not st:
continue
if st == constants.eFoundIt:
self._mBestGuessProber = prober
return self.get_state()
elif st == constants.eNotMe:
prober.active = False
self._mActiveNum -= 1
if self._mActiveNum <= 0:
self._mState = constants.eNotMe
return self.get_state()
return self.get_state()
def get_confidence(self):
st = self.get_state()
if st == constants.eFoundIt:
return 0.99
elif st == constants.eNotMe:
return 0.01
bestConf = 0.0
self._mBestGuessProber = None
for prober in self._mProbers:
if not prober:
continue
if not prober.active:
if constants._debug:
sys.stderr.write(prober.get_charset_name()
+ ' not active\n')
continue
cf = prober.get_confidence()
if constants._debug:
sys.stderr.write('%s confidence = %s\n' %
(prober.get_charset_name(), cf))
if bestConf < cf:
bestConf = cf
self._mBestGuessProber = prober
if not self._mBestGuessProber:
return 0.0
return bestConf
# else:
# self._mBestGuessProber = self._mProbers[0]
# return self._mBestGuessProber.get_confidence()
|
okuta/chainer | refs/heads/master | tests/chainer_tests/test_backprop.py | 6 | import unittest
import mock
import numpy as np
import pytest
import chainer
from chainer.backends import cuda
from chainer import testing
from chainer.testing import attr
import chainerx
class TestBackward(unittest.TestCase):
def test_no_output(self):
chainer.backward([])
chainer.backward([], [])
def check_multiple_output_1arg(self, xp, skip_retain_grad_test=False):
x = chainer.Variable(xp.array([1, 2], np.float32))
h = x * 2
y0 = h * 3
y1 = h * 4
y0.grad = xp.array([1, 10], np.float32)
y1.grad = xp.array([100, 1000], np.float32)
chainer.backward([y0, y1])
testing.assert_allclose(x.grad, np.array([806, 8060], np.float32))
if skip_retain_grad_test:
return
assert y0.grad is None
assert y1.grad is None
def check_multiple_output_2args(self, xp, skip_retain_grad_test=False):
x = chainer.Variable(xp.array([1, 2], np.float32))
h = x * 2
y0 = h * 3
y1 = h * 4
gy0 = chainer.Variable(xp.array([1, 10], np.float32))
gy1 = chainer.Variable(xp.array([100, 1000], np.float32))
chainer.backward([y0, y1], [gy0, gy1])
testing.assert_allclose(x.grad, np.array([806, 8060], np.float32))
if skip_retain_grad_test:
return
assert y0.grad is None
assert y1.grad is None
def test_multiple_output_cpu(self):
self.check_multiple_output_1arg(np)
self.check_multiple_output_2args(np)
@attr.gpu
def test_multiple_output_gpu(self):
self.check_multiple_output_1arg(cuda.cupy)
self.check_multiple_output_2args(cuda.cupy)
@attr.chainerx
def test_multiple_output_chainerx_partially_ok(self):
self.check_multiple_output_1arg(
chainerx, skip_retain_grad_test=True)
self.check_multiple_output_2args(
chainerx, skip_retain_grad_test=True)
# TODO(kataoka): Variable.backward with ChainerX backend unexpectedly
# behaves like retain_grad=True
@pytest.mark.xfail(strict=True)
@attr.chainerx
def test_multiple_output_1arg_chainerx(self):
self.check_multiple_output_1arg(chainerx)
# TODO(kataoka): Variable.backward with ChainerX backend unexpectedly
# behaves like retain_grad=True
@pytest.mark.xfail(strict=True)
@attr.chainerx
def test_multiple_output_2args_chainerx(self):
self.check_multiple_output_2args(chainerx)
def test_multiple_output_call_count(self):
x = chainer.Variable(np.array([1, 2], np.float32))
f = chainer.FunctionNode()
f.forward = mock.MagicMock(
side_effect=lambda xs: tuple(x * 2 for x in xs))
f.backward = mock.MagicMock(
side_effect=lambda _, gys: tuple(gy * 2 for gy in gys))
h, = f.apply((x,))
y0 = h * 3
y1 = h * 4
y0.grad = np.array([1, 10], np.float32)
y1.grad = np.array([100, 1000], np.float32)
chainer.backward([y0, y1])
testing.assert_allclose(x.grad, np.array([806, 8060], np.float32))
assert f.backward.call_count == 1
def test_warn_no_grad(self):
x = chainer.Variable(np.array(4, np.float32))
x.grad = np.array(3, np.float32)
y = x * 2
with testing.assert_warns(RuntimeWarning):
chainer.backward([y])
testing.assert_allclose(x.grad, np.array(3, np.float32))
assert y.grad is None
def test_duplicate_outputs(self):
x = chainer.Variable(np.array(0, np.float32))
y = chainer.functions.identity(x)
y.grad = np.array(3, np.float32)
with testing.assert_warns(RuntimeWarning):
chainer.backward([y, y])
# 6 might be expected, but y.grad is used only once
testing.assert_allclose(x.grad, np.array(3, np.float32))
# see also test_function_node.TestGradTypeCheck
class TestBackwardTypeCheck(unittest.TestCase):
def _rand(self):
return np.random.uniform(-1, 1, (2, 3)).astype(np.float32)
def test_type_check(self):
x = chainer.Variable(self._rand())
y = x * x
y.grad = self._rand()
gy = chainer.Variable(self._rand())
with self.assertRaises(TypeError):
chainer.backward(y)
with self.assertRaises(TypeError):
chainer.backward([y], gy)
chainer.backward([y])
chainer.backward([y], [gy])
# see also test_function_node.TestGradValueCheck
class TestBackwardValueCheck(unittest.TestCase):
def test_length_check(self):
x = chainer.Variable(np.array(3, np.float32))
y = chainer.functions.identity(x)
gy = chainer.Variable(np.array(7, np.float32))
with self.assertRaises(ValueError):
chainer.backward([y], [])
with self.assertRaises(ValueError):
chainer.backward([y], [gy, gy])
with self.assertRaises(ValueError):
chainer.backward([], [gy])
with self.assertRaises(ValueError):
chainer.backward([y, y], [gy])
chainer.backward([y], [gy])
testing.run_module(__name__, __file__)
|
peeyush-tm/check_mk | refs/heads/nocout | livestatus/api/python/example.py | 6 | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import os, sys
import livestatus
try:
omd_root = os.getenv("OMD_ROOT")
socket_path = "unix:" + omd_root + "/tmp/run/live"
except:
sys.stderr.write("This example is indented to run in an OMD site\n")
sys.stderr.write("Please change socket_path in this example, if you are\n")
sys.stderr.write("not using OMD.\n")
sys.exit(1)
try:
# Make a single connection for each query
print "\nPerformance:"
for key, value in livestatus.SingleSiteConnection(socket_path).query_row_assoc("GET status").items():
print "%-30s: %s" % (key, value)
print "\nHosts:"
hosts = livestatus.SingleSiteConnection(socket_path).query_table("GET hosts\nColumns: name alias address")
for name, alias, address in hosts:
print "%-16s %-16s %s" % (name, address, alias)
# Do several queries in one connection
conn = livestatus.SingleSiteConnection(socket_path)
num_up = conn.query_value("GET hosts\nStats: hard_state = 0")
print "\nHosts up: %d" % num_up
stats = conn.query_row(
"GET services\n"
"Stats: state = 0\n"
"Stats: state = 1\n"
"Stats: state = 2\n"
"Stats: state = 3\n")
print "Service stats: %d/%d/%d/%d" % tuple(stats)
print "List of commands: %s" % \
", ".join(conn.query_column("GET commands\nColumns: name"))
print "Query error:"
conn.query_value("GET hosts\nColumns: hirni")
except Exception, e: # livestatus.MKLivestatusException, e:
print "Livestatus error: %s" % str(e)
|
neerajvashistha/pa-dude | refs/heads/master | lib/python2.7/site-packages/numpy/distutils/command/config.py | 75 | # Added Fortran compiler support to config. Currently useful only for
# try_compile call. try_run works but is untested for most of Fortran
# compilers (they must define linker_exe first).
# Pearu Peterson
from __future__ import division, absolute_import, print_function
import os, signal
import warnings
import sys
from distutils.command.config import config as old_config
from distutils.command.config import LANG_EXT
from distutils import log
from distutils.file_util import copy_file
from distutils.ccompiler import CompileError, LinkError
import distutils
from numpy.distutils.exec_command import exec_command
from numpy.distutils.mingw32ccompiler import generate_manifest
from numpy.distutils.command.autodist import (check_gcc_function_attribute,
check_gcc_variable_attribute,
check_inline,
check_restrict,
check_compiler_gcc4)
from numpy.distutils.compat import get_exception
LANG_EXT['f77'] = '.f'
LANG_EXT['f90'] = '.f90'
class config(old_config):
old_config.user_options += [
('fcompiler=', None, "specify the Fortran compiler type"),
]
def initialize_options(self):
self.fcompiler = None
old_config.initialize_options(self)
def _check_compiler (self):
old_config._check_compiler(self)
from numpy.distutils.fcompiler import FCompiler, new_fcompiler
if sys.platform == 'win32' and (self.compiler.compiler_type in
('msvc', 'intelw', 'intelemw')):
# XXX: hack to circumvent a python 2.6 bug with msvc9compiler:
# initialize call query_vcvarsall, which throws an IOError, and
# causes an error along the way without much information. We try to
# catch it here, hoping it is early enough, and print an helpful
# message instead of Error: None.
if not self.compiler.initialized:
try:
self.compiler.initialize()
except IOError:
e = get_exception()
msg = """\
Could not initialize compiler instance: do you have Visual Studio
installed? If you are trying to build with MinGW, please use "python setup.py
build -c mingw32" instead. If you have Visual Studio installed, check it is
correctly installed, and the right version (VS 2008 for python 2.6, 2.7 and 3.2,
VS 2010 for >= 3.3).
Original exception was: %s, and the Compiler class was %s
============================================================================""" \
% (e, self.compiler.__class__.__name__)
print ("""\
============================================================================""")
raise distutils.errors.DistutilsPlatformError(msg)
# After MSVC is initialized, add an explicit /MANIFEST to linker
# flags. See issues gh-4245 and gh-4101 for details. Also
# relevant are issues 4431 and 16296 on the Python bug tracker.
from distutils import msvc9compiler
if msvc9compiler.get_build_version() >= 10:
for ldflags in [self.compiler.ldflags_shared,
self.compiler.ldflags_shared_debug]:
if '/MANIFEST' not in ldflags:
ldflags.append('/MANIFEST')
if not isinstance(self.fcompiler, FCompiler):
self.fcompiler = new_fcompiler(compiler=self.fcompiler,
dry_run=self.dry_run, force=1,
c_compiler=self.compiler)
if self.fcompiler is not None:
self.fcompiler.customize(self.distribution)
if self.fcompiler.get_version():
self.fcompiler.customize_cmd(self)
self.fcompiler.show_customization()
def _wrap_method(self, mth, lang, args):
from distutils.ccompiler import CompileError
from distutils.errors import DistutilsExecError
save_compiler = self.compiler
if lang in ['f77', 'f90']:
self.compiler = self.fcompiler
try:
ret = mth(*((self,)+args))
except (DistutilsExecError, CompileError):
msg = str(get_exception())
self.compiler = save_compiler
raise CompileError
self.compiler = save_compiler
return ret
def _compile (self, body, headers, include_dirs, lang):
return self._wrap_method(old_config._compile, lang,
(body, headers, include_dirs, lang))
def _link (self, body,
headers, include_dirs,
libraries, library_dirs, lang):
if self.compiler.compiler_type=='msvc':
libraries = (libraries or [])[:]
library_dirs = (library_dirs or [])[:]
if lang in ['f77', 'f90']:
lang = 'c' # always use system linker when using MSVC compiler
if self.fcompiler:
for d in self.fcompiler.library_dirs or []:
# correct path when compiling in Cygwin but with
# normal Win Python
if d.startswith('/usr/lib'):
s, o = exec_command(['cygpath', '-w', d],
use_tee=False)
if not s: d = o
library_dirs.append(d)
for libname in self.fcompiler.libraries or []:
if libname not in libraries:
libraries.append(libname)
for libname in libraries:
if libname.startswith('msvc'): continue
fileexists = False
for libdir in library_dirs or []:
libfile = os.path.join(libdir, '%s.lib' % (libname))
if os.path.isfile(libfile):
fileexists = True
break
if fileexists: continue
# make g77-compiled static libs available to MSVC
fileexists = False
for libdir in library_dirs:
libfile = os.path.join(libdir, 'lib%s.a' % (libname))
if os.path.isfile(libfile):
# copy libname.a file to name.lib so that MSVC linker
# can find it
libfile2 = os.path.join(libdir, '%s.lib' % (libname))
copy_file(libfile, libfile2)
self.temp_files.append(libfile2)
fileexists = True
break
if fileexists: continue
log.warn('could not find library %r in directories %s' \
% (libname, library_dirs))
elif self.compiler.compiler_type == 'mingw32':
generate_manifest(self)
return self._wrap_method(old_config._link, lang,
(body, headers, include_dirs,
libraries, library_dirs, lang))
def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'):
self._check_compiler()
return self.try_compile(
"/* we need a dummy line to make distutils happy */",
[header], include_dirs)
def check_decl(self, symbol,
headers=None, include_dirs=None):
self._check_compiler()
body = """
int main(void)
{
#ifndef %s
(void) %s;
#endif
;
return 0;
}""" % (symbol, symbol)
return self.try_compile(body, headers, include_dirs)
def check_macro_true(self, symbol,
headers=None, include_dirs=None):
self._check_compiler()
body = """
int main(void)
{
#if %s
#else
#error false or undefined macro
#endif
;
return 0;
}""" % (symbol,)
return self.try_compile(body, headers, include_dirs)
def check_type(self, type_name, headers=None, include_dirs=None,
library_dirs=None):
"""Check type availability. Return True if the type can be compiled,
False otherwise"""
self._check_compiler()
# First check the type can be compiled
body = r"""
int main(void) {
if ((%(name)s *) 0)
return 0;
if (sizeof (%(name)s))
return 0;
}
""" % {'name': type_name}
st = False
try:
try:
self._compile(body % {'type': type_name},
headers, include_dirs, 'c')
st = True
except distutils.errors.CompileError:
st = False
finally:
self._clean()
return st
def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None):
"""Check size of a given type."""
self._check_compiler()
# First check the type can be compiled
body = r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)];
test_array [0] = 0
;
return 0;
}
"""
self._compile(body % {'type': type_name},
headers, include_dirs, 'c')
self._clean()
if expected:
body = r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)];
test_array [0] = 0
;
return 0;
}
"""
for size in expected:
try:
self._compile(body % {'type': type_name, 'size': size},
headers, include_dirs, 'c')
self._clean()
return size
except CompileError:
pass
# this fails to *compile* if size > sizeof(type)
body = r"""
typedef %(type)s npy_check_sizeof_type;
int main (void)
{
static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)];
test_array [0] = 0
;
return 0;
}
"""
# The principle is simple: we first find low and high bounds of size
# for the type, where low/high are looked up on a log scale. Then, we
# do a binary search to find the exact size between low and high
low = 0
mid = 0
while True:
try:
self._compile(body % {'type': type_name, 'size': mid},
headers, include_dirs, 'c')
self._clean()
break
except CompileError:
#log.info("failure to test for bound %d" % mid)
low = mid + 1
mid = 2 * mid + 1
high = mid
# Binary search:
while low != high:
mid = (high - low) // 2 + low
try:
self._compile(body % {'type': type_name, 'size': mid},
headers, include_dirs, 'c')
self._clean()
high = mid
except CompileError:
low = mid + 1
return low
def check_func(self, func,
headers=None, include_dirs=None,
libraries=None, library_dirs=None,
decl=False, call=False, call_args=None):
# clean up distutils's config a bit: add void to main(), and
# return a value.
self._check_compiler()
body = []
if decl:
if type(decl) == str:
body.append(decl)
else:
body.append("int %s (void);" % func)
# Handle MSVC intrinsics: force MS compiler to make a function call.
# Useful to test for some functions when built with optimization on, to
# avoid build error because the intrinsic and our 'fake' test
# declaration do not match.
body.append("#ifdef _MSC_VER")
body.append("#pragma function(%s)" % func)
body.append("#endif")
body.append("int main (void) {")
if call:
if call_args is None:
call_args = ''
body.append(" %s(%s);" % (func, call_args))
else:
body.append(" %s;" % func)
body.append(" return 0;")
body.append("}")
body = '\n'.join(body) + "\n"
return self.try_link(body, headers, include_dirs,
libraries, library_dirs)
def check_funcs_once(self, funcs,
headers=None, include_dirs=None,
libraries=None, library_dirs=None,
decl=False, call=False, call_args=None):
"""Check a list of functions at once.
This is useful to speed up things, since all the functions in the funcs
list will be put in one compilation unit.
Arguments
---------
funcs : seq
list of functions to test
include_dirs : seq
list of header paths
libraries : seq
list of libraries to link the code snippet to
libraru_dirs : seq
list of library paths
decl : dict
for every (key, value), the declaration in the value will be
used for function in key. If a function is not in the
dictionay, no declaration will be used.
call : dict
for every item (f, value), if the value is True, a call will be
done to the function f.
"""
self._check_compiler()
body = []
if decl:
for f, v in decl.items():
if v:
body.append("int %s (void);" % f)
# Handle MS intrinsics. See check_func for more info.
body.append("#ifdef _MSC_VER")
for func in funcs:
body.append("#pragma function(%s)" % func)
body.append("#endif")
body.append("int main (void) {")
if call:
for f in funcs:
if f in call and call[f]:
if not (call_args and f in call_args and call_args[f]):
args = ''
else:
args = call_args[f]
body.append(" %s(%s);" % (f, args))
else:
body.append(" %s;" % f)
else:
for f in funcs:
body.append(" %s;" % f)
body.append(" return 0;")
body.append("}")
body = '\n'.join(body) + "\n"
return self.try_link(body, headers, include_dirs,
libraries, library_dirs)
def check_inline(self):
"""Return the inline keyword recognized by the compiler, empty string
otherwise."""
return check_inline(self)
def check_restrict(self):
"""Return the restrict keyword recognized by the compiler, empty string
otherwise."""
return check_restrict(self)
def check_compiler_gcc4(self):
"""Return True if the C compiler is gcc >= 4."""
return check_compiler_gcc4(self)
def check_gcc_function_attribute(self, attribute, name):
return check_gcc_function_attribute(self, attribute, name)
def check_gcc_variable_attribute(self, attribute):
return check_gcc_variable_attribute(self, attribute)
class GrabStdout(object):
def __init__(self):
self.sys_stdout = sys.stdout
self.data = ''
sys.stdout = self
def write (self, data):
self.sys_stdout.write(data)
self.data += data
def flush (self):
self.sys_stdout.flush()
def restore(self):
sys.stdout = self.sys_stdout
|
MotorolaMobilityLLC/external-chromium_org | refs/heads/kitkat-mr1-release-falcon-gpe | tools/deep_memory_profiler/lib/pageframe.py | 123 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import re
import struct
LOGGER = logging.getLogger('dmprof')
class PageFrame(object):
"""Represents a pageframe and maybe its shared count."""
def __init__(self, pfn, size, pagecount, start_truncated, end_truncated):
self._pfn = pfn
self._size = size
self._pagecount = pagecount
self._start_truncated = start_truncated
self._end_truncated = end_truncated
def __str__(self):
result = str()
if self._start_truncated:
result += '<'
result += '%06x#%d' % (self._pfn, self._pagecount)
if self._end_truncated:
result += '>'
return result
def __repr__(self):
return str(self)
@staticmethod
def parse(encoded_pfn, size):
start = 0
end = len(encoded_pfn)
end_truncated = False
if encoded_pfn.endswith('>'):
end = len(encoded_pfn) - 1
end_truncated = True
pagecount_found = encoded_pfn.find('#')
pagecount = None
if pagecount_found >= 0:
encoded_pagecount = 'AAA' + encoded_pfn[pagecount_found+1 : end]
pagecount = struct.unpack(
'>I', '\x00' + encoded_pagecount.decode('base64'))[0]
end = pagecount_found
start_truncated = False
if encoded_pfn.startswith('<'):
start = 1
start_truncated = True
pfn = struct.unpack(
'>I', '\x00' + (encoded_pfn[start:end]).decode('base64'))[0]
return PageFrame(pfn, size, pagecount, start_truncated, end_truncated)
@property
def pfn(self):
return self._pfn
@property
def size(self):
return self._size
def set_size(self, size):
self._size = size
@property
def pagecount(self):
return self._pagecount
@property
def start_truncated(self):
return self._start_truncated
@property
def end_truncated(self):
return self._end_truncated
class PFNCounts(object):
"""Represents counts of PFNs in a process."""
_PATH_PATTERN = re.compile(r'^(.*)\.([0-9]+)\.([0-9]+)\.heap$')
def __init__(self, path, modified_time):
matched = self._PATH_PATTERN.match(path)
if matched:
self._pid = int(matched.group(2))
else:
self._pid = 0
self._command_line = ''
self._pagesize = 4096
self._path = path
self._pfn_meta = ''
self._pfnset = {}
self._reason = ''
self._time = modified_time
@staticmethod
def load(path, log_header='Loading PFNs from a heap profile dump: '):
pfnset = PFNCounts(path, float(os.stat(path).st_mtime))
LOGGER.info('%s%s' % (log_header, path))
with open(path, 'r') as pfnset_f:
pfnset.load_file(pfnset_f)
return pfnset
@property
def path(self):
return self._path
@property
def pid(self):
return self._pid
@property
def time(self):
return self._time
@property
def reason(self):
return self._reason
@property
def iter_pfn(self):
for pfn, count in self._pfnset.iteritems():
yield pfn, count
def load_file(self, pfnset_f):
prev_pfn_end_truncated = None
for line in pfnset_f:
line = line.strip()
if line.startswith('GLOBAL_STATS:') or line.startswith('STACKTRACES:'):
break
elif line.startswith('PF: '):
for encoded_pfn in line[3:].split():
page_frame = PageFrame.parse(encoded_pfn, self._pagesize)
if page_frame.start_truncated and (
not prev_pfn_end_truncated or
prev_pfn_end_truncated != page_frame.pfn):
LOGGER.error('Broken page frame number: %s.' % encoded_pfn)
self._pfnset[page_frame.pfn] = self._pfnset.get(page_frame.pfn, 0) + 1
if page_frame.end_truncated:
prev_pfn_end_truncated = page_frame.pfn
else:
prev_pfn_end_truncated = None
elif line.startswith('PageSize: '):
self._pagesize = int(line[10:])
elif line.startswith('PFN: '):
self._pfn_meta = line[5:]
elif line.startswith('PageFrame: '):
self._pfn_meta = line[11:]
elif line.startswith('Time: '):
self._time = float(line[6:])
elif line.startswith('CommandLine: '):
self._command_line = line[13:]
elif line.startswith('Reason: '):
self._reason = line[8:]
|
SNoiraud/gramps | refs/heads/master | gramps/gui/merge/mergefamily.py | 4 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2010 Michiel D. Nauta
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Provide merge capabilities for families.
"""
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
from gramps.gen.display.name import displayer as name_displayer
from gramps.gen.const import URL_MANUAL_SECT3
from ..display import display_help
from gramps.gen.errors import MergeError
from ..dialog import ErrorDialog
from ..managedwindow import ManagedWindow
from gramps.gen.merge import MergePersonQuery, MergeFamilyQuery
#-------------------------------------------------------------------------
#
# Gramps constants
#
#-------------------------------------------------------------------------
WIKI_HELP_PAGE = URL_MANUAL_SECT3
WIKI_HELP_SEC = _('Merge_Families', 'manual')
_GLADE_FILE = 'mergefamily.glade'
#-------------------------------------------------------------------------
#
# MergeFamily
#
#-------------------------------------------------------------------------
class MergeFamily(ManagedWindow):
"""
Merges two families into a single family. Displays a dialog box that allows
the families to be combined into one.
"""
def __init__(self, dbstate, uistate, track, handle1, handle2):
ManagedWindow.__init__(self, uistate, track, self.__class__)
self.database = dbstate.db
self.fy1 = self.database.get_family_from_handle(handle1)
self.fy2 = self.database.get_family_from_handle(handle2)
self.define_glade('mergefamily', _GLADE_FILE)
self.set_window(self._gladeobj.toplevel,
self.get_widget("family_title"),
_("Merge Families"))
self.setup_configs('interface.merge-family', 500, 250)
# Detailed selection widgets
father1 = self.fy1.get_father_handle()
father2 = self.fy2.get_father_handle()
if father1:
father1 = self.database.get_person_from_handle(father1)
if father2:
father2 = self.database.get_person_from_handle(father2)
father_id1 = father1.get_gramps_id() if father1 else ""
father_id2 = father2.get_gramps_id() if father2 else ""
father1 = name_displayer.display(father1) if father1 else ""
father2 = name_displayer.display(father2) if father2 else ""
entry1 = self.get_widget("father1")
entry2 = self.get_widget("father2")
entry1.set_text("%s [%s]" % (father1, father_id1))
entry2.set_text("%s [%s]" % (father2, father_id2))
deactivate = False
if father_id1 == "" and father_id2 == "":
deactivate = True
elif father_id2 == "":
self.get_widget("father_btn1").set_active(True)
deactivate = True
elif father_id1 == "":
self.get_widget("father_btn2").set_active(True)
deactivate = True
elif entry1.get_text() == entry2.get_text():
deactivate = True
if deactivate:
for widget_name in ('father1', 'father2', 'father_btn1',
'father_btn2'):
self.get_widget(widget_name).set_sensitive(False)
mother1 = self.fy1.get_mother_handle()
mother2 = self.fy2.get_mother_handle()
if mother1:
mother1 = self.database.get_person_from_handle(mother1)
if mother2:
mother2 = self.database.get_person_from_handle(mother2)
mother_id1 = mother1.get_gramps_id() if mother1 else ""
mother_id2 = mother2.get_gramps_id() if mother2 else ""
mother1 = name_displayer.display(mother1) if mother1 else ""
mother2 = name_displayer.display(mother2) if mother2 else ""
entry1 = self.get_widget("mother1")
entry2 = self.get_widget("mother2")
entry1.set_text("%s [%s]" % (mother1, mother_id1))
entry2.set_text("%s [%s]" % (mother2, mother_id2))
deactivate = False
if mother_id1 == "" and mother_id2 == "":
deactivate = True
elif mother_id1 == "":
self.get_widget("mother_btn2").set_active(True)
deactivate = True
elif mother_id2 == "":
self.get_widget("mother_btn1").set_active(True)
deactivate = True
elif entry1.get_text() == entry2.get_text():
deactivate = True
if deactivate:
for widget_name in ('mother1', 'mother2', 'mother_btn1',
'mother_btn2'):
self.get_widget(widget_name).set_sensitive(False)
entry1 = self.get_widget("rel1")
entry2 = self.get_widget("rel2")
entry1.set_text(str(self.fy1.get_relationship()))
entry2.set_text(str(self.fy2.get_relationship()))
if entry1.get_text() == entry2.get_text():
for widget_name in ('rel1', 'rel2', 'rel_btn1', 'rel_btn2'):
self.get_widget(widget_name).set_sensitive(False)
gramps1 = self.fy1.get_gramps_id()
gramps2 = self.fy2.get_gramps_id()
entry1 = self.get_widget("gramps1")
entry2 = self.get_widget("gramps2")
entry1.set_text(gramps1)
entry2.set_text(gramps2)
if entry1.get_text() == entry2.get_text():
for widget_name in ('gramps1', 'gramps2', 'gramps_btn1',
'gramps_btn2'):
self.get_widget(widget_name).set_sensitive(False)
# Main window widgets that determine which handle survives
rbutton1 = self.get_widget("handle_btn1")
rbutton_label1 = self.get_widget("label_handle_btn1")
rbutton_label2 = self.get_widget("label_handle_btn2")
add = _("and")
rbutton_label1.set_label("%s %s %s [%s]" %(father1, add, mother1, gramps1))
rbutton_label2.set_label("%s %s %s [%s]" %(father2, add, mother2, gramps2))
rbutton1.connect("toggled", self.on_handle1_toggled)
self.connect_button("family_help", self.cb_help)
self.connect_button("family_ok", self.cb_merge)
self.connect_button("family_cancel", self.close)
self.show()
def on_handle1_toggled(self, obj):
"""Preferred family changes"""
if obj.get_active():
father1_text = self.get_widget("father1").get_text()
if (father1_text != " []" or
self.get_widget("father2").get_text() == " []"):
self.get_widget("father_btn1").set_active(True)
mother1_text = self.get_widget("mother1").get_text()
if (mother1_text != " []" or
self.get_widget("mother2").get_text() == " []"):
self.get_widget("mother_btn1").set_active(True)
self.get_widget("rel_btn1").set_active(True)
self.get_widget("gramps_btn1").set_active(True)
else:
father2_text = self.get_widget("father2").get_text()
if (father2_text != " []" or
self.get_widget("father1").get_text() == " []"):
self.get_widget("father_btn2").set_active(True)
mother2_text = self.get_widget("mother2").get_text()
if (mother2_text != " []" or
self.get_widget("mother1").get_text() == " []"):
self.get_widget("mother_btn2").set_active(True)
self.get_widget("rel_btn2").set_active(True)
self.get_widget("gramps_btn2").set_active(True)
def cb_help(self, obj):
"""Display the relevant portion of the Gramps manual"""
display_help(webpage = WIKI_HELP_PAGE, section = WIKI_HELP_SEC)
def cb_merge(self, obj):
"""
Perform the merge of the families when the merge button is clicked.
"""
self.uistate.set_busy_cursor(True)
use_handle1 = self.get_widget("handle_btn1").get_active()
if use_handle1:
phoenix = self.fy1
titanic = self.fy2
else:
phoenix = self.fy2
titanic = self.fy1
phoenix_fh = phoenix.get_father_handle()
phoenix_mh = phoenix.get_mother_handle()
if self.get_widget("father_btn1").get_active() ^ use_handle1:
phoenix_fh = titanic.get_father_handle()
if self.get_widget("mother_btn1").get_active() ^ use_handle1:
phoenix_mh = titanic.get_mother_handle()
if self.get_widget("rel_btn1").get_active() ^ use_handle1:
phoenix.set_relationship(titanic.get_relationship())
if self.get_widget("gramps_btn1").get_active() ^ use_handle1:
phoenix.set_gramps_id(titanic.get_gramps_id())
try:
query = MergeFamilyQuery(self.database, phoenix, titanic,
phoenix_fh, phoenix_mh)
query.execute()
# Add the selected handle to history so that when merge is complete,
# phoenix is the selected row.
self.uistate.set_active(phoenix.get_handle(), 'Family')
except MergeError as err:
ErrorDialog(_("Cannot merge people"), str(err),
parent=self.window)
self.uistate.set_busy_cursor(False)
self.close()
|
shakamunyi/neutron-vrrp | refs/heads/master | neutron/plugins/mlnx/db/__init__.py | 69 | # Copyright 2013 Mellanox Technologies, 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
damdam-s/OCB | refs/heads/8.0 | addons/l10n_ae/__init__.py | 669 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Tech Receptives (<http://techreceptives.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
ping/youtube-dl | refs/heads/master | youtube_dl/extractor/weibo.py | 12 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
import json
import random
import re
from ..compat import (
compat_parse_qs,
compat_str,
)
from ..utils import (
js_to_json,
strip_jsonp,
urlencode_postdata,
)
class WeiboIE(InfoExtractor):
_VALID_URL = r'https?://weibo\.com/[0-9]+/(?P<id>[a-zA-Z0-9]+)'
_TEST = {
'url': 'https://weibo.com/6275294458/Fp6RGfbff?type=comment',
'info_dict': {
'id': 'Fp6RGfbff',
'ext': 'mp4',
'title': 'You should have servants to massage you,... 来自Hosico_猫 - 微博',
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
# to get Referer url for genvisitor
webpage, urlh = self._download_webpage_handle(url, video_id)
visitor_url = urlh.geturl()
if 'passport.weibo.com' in visitor_url:
# first visit
visitor_data = self._download_json(
'https://passport.weibo.com/visitor/genvisitor', video_id,
note='Generating first-visit data',
transform_source=strip_jsonp,
headers={'Referer': visitor_url},
data=urlencode_postdata({
'cb': 'gen_callback',
'fp': json.dumps({
'os': '2',
'browser': 'Gecko57,0,0,0',
'fonts': 'undefined',
'screenInfo': '1440*900*24',
'plugins': '',
}),
}))
tid = visitor_data['data']['tid']
cnfd = '%03d' % visitor_data['data']['confidence']
self._download_webpage(
'https://passport.weibo.com/visitor/visitor', video_id,
note='Running first-visit callback',
query={
'a': 'incarnate',
't': tid,
'w': 2,
'c': cnfd,
'cb': 'cross_domain',
'from': 'weibo',
'_rand': random.random(),
})
webpage = self._download_webpage(
url, video_id, note='Revisiting webpage')
title = self._html_search_regex(
r'<title>(.+?)</title>', webpage, 'title')
video_formats = compat_parse_qs(self._search_regex(
r'video-sources=\\\"(.+?)\"', webpage, 'video_sources'))
formats = []
supported_resolutions = (480, 720)
for res in supported_resolutions:
vid_urls = video_formats.get(compat_str(res))
if not vid_urls or not isinstance(vid_urls, list):
continue
vid_url = vid_urls[0]
formats.append({
'url': vid_url,
'height': res,
})
self._sort_formats(formats)
uploader = self._og_search_property(
'nick-name', webpage, 'uploader', default=None)
return {
'id': video_id,
'title': title,
'uploader': uploader,
'formats': formats
}
class WeiboMobileIE(InfoExtractor):
_VALID_URL = r'https?://m\.weibo\.cn/status/(?P<id>[0-9]+)(\?.+)?'
_TEST = {
'url': 'https://m.weibo.cn/status/4189191225395228?wm=3333_2001&sourcetype=weixin&featurecode=newtitle&from=singlemessage&isappinstalled=0',
'info_dict': {
'id': '4189191225395228',
'ext': 'mp4',
'title': '午睡当然是要甜甜蜜蜜的啦',
'uploader': '柴犬柴犬'
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
# to get Referer url for genvisitor
webpage = self._download_webpage(url, video_id, note='visit the page')
weibo_info = self._parse_json(self._search_regex(
r'var\s+\$render_data\s*=\s*\[({.*})\]\[0\]\s*\|\|\s*{};',
webpage, 'js_code', flags=re.DOTALL),
video_id, transform_source=js_to_json)
status_data = weibo_info.get('status', {})
page_info = status_data.get('page_info')
title = status_data['status_title']
uploader = status_data.get('user', {}).get('screen_name')
return {
'id': video_id,
'title': title,
'uploader': uploader,
'url': page_info['media_info']['stream_url']
}
|
wooga/airflow | refs/heads/master | airflow/providers/apache/spark/operators/__init__.py | 5130 | #
# 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 file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
|
MarcoFalke/bitcoin | refs/heads/master | test/functional/wallet_encryption.py | 8 | #!/usr/bin/env python3
# Copyright (c) 2016-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Wallet encryption"""
import time
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_raises_rpc_error,
assert_greater_than,
assert_greater_than_or_equal,
)
class WalletEncryptionTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def run_test(self):
passphrase = "WalletPassphrase"
passphrase2 = "SecondWalletPassphrase"
# Make sure the wallet isn't encrypted first
msg = "test message"
address = self.nodes[0].getnewaddress(address_type='legacy')
sig = self.nodes[0].signmessage(address, msg)
assert self.nodes[0].verifymessage(address, sig, msg)
assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrase was called", self.nodes[0].walletpassphrase, 'ff', 1)
assert_raises_rpc_error(-15, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.", self.nodes[0].walletpassphrasechange, 'ff', 'ff')
# Encrypt the wallet
assert_raises_rpc_error(-8, "passphrase can not be empty", self.nodes[0].encryptwallet, '')
self.nodes[0].encryptwallet(passphrase)
# Test that the wallet is encrypted
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)
assert_raises_rpc_error(-15, "Error: running with an encrypted wallet, but encryptwallet was called.", self.nodes[0].encryptwallet, 'ff')
assert_raises_rpc_error(-8, "passphrase can not be empty", self.nodes[0].walletpassphrase, '', 1)
assert_raises_rpc_error(-8, "passphrase can not be empty", self.nodes[0].walletpassphrasechange, '', 'ff')
# Check that walletpassphrase works
self.nodes[0].walletpassphrase(passphrase, 2)
sig = self.nodes[0].signmessage(address, msg)
assert self.nodes[0].verifymessage(address, sig, msg)
# Check that the timeout is right
time.sleep(3)
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)
# Test wrong passphrase
assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase + "wrong", 10)
# Test walletlock
self.nodes[0].walletpassphrase(passphrase, 84600)
sig = self.nodes[0].signmessage(address, msg)
assert self.nodes[0].verifymessage(address, sig, msg)
self.nodes[0].walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].signmessage, address, msg)
# Test passphrase changes
self.nodes[0].walletpassphrasechange(passphrase, passphrase2)
assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase, 10)
self.nodes[0].walletpassphrase(passphrase2, 10)
sig = self.nodes[0].signmessage(address, msg)
assert self.nodes[0].verifymessage(address, sig, msg)
self.nodes[0].walletlock()
# Test timeout bounds
assert_raises_rpc_error(-8, "Timeout cannot be negative.", self.nodes[0].walletpassphrase, passphrase2, -10)
self.log.info('Check a timeout less than the limit')
MAX_VALUE = 100000000
expected_time = int(time.time()) + MAX_VALUE - 600
self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE - 600)
# give buffer for walletpassphrase, since it iterates over all crypted keys
expected_time_with_buffer = time.time() + MAX_VALUE - 600
actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
assert_greater_than_or_equal(actual_time, expected_time)
assert_greater_than(expected_time_with_buffer, actual_time)
self.log.info('Check a timeout greater than the limit')
expected_time = int(time.time()) + MAX_VALUE - 1
self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE + 1000)
expected_time_with_buffer = time.time() + MAX_VALUE
actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
assert_greater_than_or_equal(actual_time, expected_time)
assert_greater_than(expected_time_with_buffer, actual_time)
if __name__ == '__main__':
WalletEncryptionTest().main()
|
oscarsjogren/dlw | refs/heads/master | dlw/cost.py | 1 | from __future__ import division
import numpy as np
from abc import ABCMeta, abstractmethod
from storage_tree import BigStorageTree
class Cost(object):
"""Abstract Cost class for the EZ-Climate model."""
__metaclass__ = ABCMeta
@abstractmethod
def cost(self):
pass
@abstractmethod
def price(self):
pass
class DLWCost(Cost):
"""Class to evaluate the cost curve for the EZ-Climate model.
Parameters
----------
tree : `TreeModel` object
tree structure used
emit_at_0 : float
initial GHG emission level
g : float
intital scale of the cost function
a : float
curvature of the cost function
join_price : float
price at which the cost curve is extended
max_price : float
price at which carbon dioxide can be removed from atmosphere in unlimited scale
tech_const : float
determines the degree of exogenous technological improvement over time. A number
of 1.0 implies 1 percent per yer lower cost
tech_scale : float
determines the sensitivity of technological change to previous mitigation
cons_at_0 : float
intital consumption. Default $30460bn based on US 2010 values.
Attributes
----------
tree : `TreeModel` object
tree structure used
g : float
intital scale of the cost function
a : float
curvature of the cost function
max_price : float
price at which carbon dioxide can be removed from atmosphere in unlimited scale
tech_const : float
determines the degree of exogenous technological improvement over time. A number
of 1.0 implies 1 percent per yer lower cost
tech_scale : float
determines the sensitivity of technological change to previous mitigation
cons_at_0 : float
intital consumption. Default $30460bn based on US 2010 values.
cbs_level : float
cbs_deriv :float
cbs_b : float
cbs_k : float
cons_per_ton : float
"""
def __init__(self, tree, emit_at_0, g, a, join_price, max_price,
tech_const, tech_scale, cons_at_0):
self.tree = tree
self.g = g
self.a = a
self.max_price = max_price
self.tech_const = tech_const
self.tech_scale = tech_scale
self.cbs_level = (join_price / (g * a))**(1.0 / (a - 1.0))
self.cbs_deriv = self.cbs_level / (join_price * (a - 1.0))
self.cbs_b = self.cbs_deriv * (max_price - join_price) / self.cbs_level
self.cbs_k = self.cbs_level * (max_price - join_price)**self.cbs_b
self.cons_per_ton = cons_at_0 / emit_at_0
def cost(self, period, mitigation, ave_mitigation):
"""Calculates the mitigation cost for the period. For details about the cost function
see DLW-paper.
Parameters
----------
period : int
period in tree for which mitigation cost is calculated
mitigation : ndarray
current mitigation values for period
ave_mitigation : ndarray
average mitigation up to this period for all nodes in the period
Returns
-------
ndarray
cost
"""
years = self.tree.decision_times[period]
tech_term = (1.0 - ((self.tech_const + self.tech_scale*ave_mitigation) / 100.0))**years
cbs = self.g * (mitigation**self.a)
bool_arr = (mitigation < self.cbs_level).astype(int)
if np.all(bool_arr):
c = (cbs * tech_term) / self.cons_per_ton
else:
base_cbs = self.g * self.cbs_level**self.a
bool_arr2 = (mitigation > self.cbs_level).astype(int)
extension = ((mitigation-self.cbs_level) * self.max_price
- self.cbs_b*mitigation * (self.cbs_k/mitigation)**(1.0/self.cbs_b) / (self.cbs_b-1.0)
+ self.cbs_b*self.cbs_level * (self.cbs_k/self.cbs_level)**(1.0/self.cbs_b) / (self.cbs_b-1.0))
c = (cbs * bool_arr + (base_cbs + extension)*bool_arr2) * tech_term / self.cons_per_ton
return c
def price(self, years, mitigation, ave_mitigation):
"""Inverse of the cost function. Gives emissions price for any given
degree of mitigation, average_mitigation, and horizon.
Parameters
----------
years : int y
years of technological change so far
mitigation : float
mitigation value in node
ave_mitigation : float
average mitigation up to this period
Returns
-------
float
the price.
"""
tech_term = (1.0 - ((self.tech_const + self.tech_scale*ave_mitigation) / 100))**years
if mitigation < self.cbs_level:
return self.g * self.a * (mitigation**(self.a-1.0)) * tech_term
else:
return (self.max_price - (self.cbs_k/mitigation)**(1.0/self.cbs_b)) * tech_term
|
barseghyanartur/oauth2app | refs/heads/develop | tests/testsite/apps/oauth2/urls.py | 5 | #-*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url
from oauth2app.token import TokenGenerator
from oauth2app.consts import MAC
urlpatterns = patterns('',
(r'^missing_redirect_uri/?$', 'testsite.apps.oauth2.views.missing_redirect_uri'),
(r'^authorize_not_refreshable/?$', 'testsite.apps.oauth2.views.authorize_not_refreshable'),
(r'^authorize_mac/?$', 'testsite.apps.oauth2.views.authorize_mac'),
(r'^authorize_first_name/?$', 'testsite.apps.oauth2.views.authorize_first_name'),
(r'^authorize_first_name/?$', 'testsite.apps.oauth2.views.authorize_last_name'),
(r'^authorize_first_and_last_name/?$', 'testsite.apps.oauth2.views.authorize_first_and_last_name'),
(r'^authorize_no_scope/?$', 'testsite.apps.oauth2.views.authorize_no_scope'),
(r'^authorize_code/?$', 'testsite.apps.oauth2.views.authorize_code'),
(r'^authorize_token/?$', 'testsite.apps.oauth2.views.authorize_token'),
(r'^authorize_token_mac/?$', 'testsite.apps.oauth2.views.authorize_token_mac'),
(r'^authorize_code_and_token/?$', 'testsite.apps.oauth2.views.authorize_code_and_token'),
(r'^token/?$', 'oauth2app.token.handler'),
(r'^token_mac/?$', TokenGenerator(authentication_method=MAC))
)
|
daisukekobayashi/phase-only-correlation | refs/heads/master | pocpy/logpolar_opencv2.py | 1 | import cv2
import cv2.cv as cv
import numpy as np
def logpolar(src, center, magnitude_scale=40):
mat1 = cv.fromarray(np.float64(src))
mat2 = cv.CreateMat(src.shape[0], src.shape[1], mat1.type)
cv.LogPolar(
mat1,
mat2,
center,
magnitude_scale,
cv.CV_INTER_CUBIC + cv.CV_WARP_FILL_OUTLIERS,
)
return np.asarray(mat2)
|
jirutka/ansible-modules-extras | refs/heads/devel | web_infrastructure/jboss.py | 32 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Jeroen Hoekx <jeroen.hoekx@dsquare.be>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = """
module: jboss
version_added: "1.4"
short_description: deploy applications to JBoss
description:
- Deploy applications to JBoss standalone using the filesystem
options:
deployment:
required: true
description:
- The name of the deployment
src:
required: false
description:
- The remote path of the application ear or war to deploy
deploy_path:
required: false
default: /var/lib/jbossas/standalone/deployments
description:
- The location in the filesystem where the deployment scanner listens
state:
required: false
choices: [ present, absent ]
default: "present"
description:
- Whether the application should be deployed or undeployed
notes:
- "The JBoss standalone deployment-scanner has to be enabled in standalone.xml"
- "Ensure no identically named application is deployed through the JBoss CLI"
author: Jeroen Hoekx
"""
EXAMPLES = """
# Deploy a hello world application
- jboss: src=/tmp/hello-1.0-SNAPSHOT.war deployment=hello.war state=present
# Update the hello world application
- jboss: src=/tmp/hello-1.1-SNAPSHOT.war deployment=hello.war state=present
# Undeploy the hello world application
- jboss: deployment=hello.war state=absent
"""
import os
import shutil
import time
def is_deployed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.deployed"%(deployment)))
def is_undeployed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.undeployed"%(deployment)))
def is_failed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.failed"%(deployment)))
def main():
module = AnsibleModule(
argument_spec = dict(
src=dict(),
deployment=dict(required=True),
deploy_path=dict(default='/var/lib/jbossas/standalone/deployments'),
state=dict(choices=['absent', 'present'], default='present'),
),
)
changed = False
src = module.params['src']
deployment = module.params['deployment']
deploy_path = module.params['deploy_path']
state = module.params['state']
if state == 'present' and not src:
module.fail_json(msg="Argument 'src' required.")
if not os.path.exists(deploy_path):
module.fail_json(msg="deploy_path does not exist.")
deployed = is_deployed(deploy_path, deployment)
if state == 'present' and not deployed:
if not os.path.exists(src):
module.fail_json(msg='Source file %s does not exist.'%(src))
if is_failed(deploy_path, deployment):
### Clean up old failed deployment
os.remove(os.path.join(deploy_path, "%s.failed"%(deployment)))
shutil.copyfile(src, os.path.join(deploy_path, deployment))
while not deployed:
deployed = is_deployed(deploy_path, deployment)
if is_failed(deploy_path, deployment):
module.fail_json(msg='Deploying %s failed.'%(deployment))
time.sleep(1)
changed = True
if state == 'present' and deployed:
if module.sha1(src) != module.sha1(os.path.join(deploy_path, deployment)):
os.remove(os.path.join(deploy_path, "%s.deployed"%(deployment)))
shutil.copyfile(src, os.path.join(deploy_path, deployment))
deployed = False
while not deployed:
deployed = is_deployed(deploy_path, deployment)
if is_failed(deploy_path, deployment):
module.fail_json(msg='Deploying %s failed.'%(deployment))
time.sleep(1)
changed = True
if state == 'absent' and deployed:
os.remove(os.path.join(deploy_path, "%s.deployed"%(deployment)))
while deployed:
deployed = not is_undeployed(deploy_path, deployment)
if is_failed(deploy_path, deployment):
module.fail_json(msg='Undeploying %s failed.'%(deployment))
time.sleep(1)
changed = True
module.exit_json(changed=changed)
# import module snippets
from ansible.module_utils.basic import *
main()
|
Maccimo/intellij-community | refs/heads/master | python/testData/intentions/PyInvertIfConditionIntentionTest/commentsTypeBothMixedElse_after.py | 10 | def func():
value = "not-none"
if value is not None: # Regular
print("Not none")
else: # type: SomeType
print("None") |
dracos/QGIS | refs/heads/master | python/plugins/processing/algs/lidar/lastools/lasvalidate.py | 9 | # -*- coding: utf-8 -*-
"""
***************************************************************************
lasvalidate.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Martin Isenburg'
__date__ = 'September 2013'
__copyright__ = '(C) 2013, Martin Isenburg'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from LAStoolsUtils import LAStoolsUtils
from LAStoolsAlgorithm import LAStoolsAlgorithm
from processing.core.parameters import ParameterBoolean
from processing.core.outputs import OutputFile
class lasvalidate(LAStoolsAlgorithm):
ONE_REPORT_PER_FILE = "ONE_REPORT_PER_FILE"
OUTPUT = "OUTPUT"
def defineCharacteristics(self):
self.name = "lasvalidate"
self.group = "LAStools"
self.addParametersPointInputGUI()
self.addParameter(ParameterBoolean(lasvalidate.ONE_REPORT_PER_FILE,
self.tr("save report to '*_LVS.xml'"), False))
self.addOutput(OutputFile(lasvalidate.OUTPUT, self.tr("Output XML file")))
self.addParametersAdditionalGUI()
def processAlgorithm(self, progress):
commands = [os.path.join(LAStoolsUtils.LAStoolsPath(), "bin", "lasvalidate")]
self.addParametersPointInputCommands(commands)
if self.getParameterValue(lasvalidate.ONE_REPORT_PER_FILE):
commands.append("-oxml")
else:
commands.append("-o")
commands.append(self.getOutputValue(lasvalidate.OUTPUT))
self.addParametersAdditionalCommands(commands)
LAStoolsUtils.runLAStools(commands, progress)
|
lzamparo/crisprML | refs/heads/master | src/pkl_to_csv.py | 1 | import pickle
import re
extractor = re.compile("(chr[0-9|XY]{1,2}):([\d]+)-([\d]+)\_\[\'(-?1)")
def parse_kv(key, value, extractor):
guide = key[:-3]
string_val = value[0]
match = extractor.match(string_val)
if match:
chrom, start, end, strand = match.groups()
return guide, chrom, start, end, strand
else:
return guide, string_val, "error", "error", "error"
with open('gRNA_target_coordinates_annotation_dict.pkl','r') as f:
d = pickle.load(f)
with open('guide_to_target_region.csv','w') as f:
for k in d.keys():
guide, chrom, start, end, strand = parse_kv(k, d[k], extractor)
print >> f, ','.join([guide, chrom, start, end, strand])
|
ddv2005/intercom | refs/heads/master | 3rdparty/pjproject/tests/pjsua/scripts-call/400_tel_uri.py | 57 | # $Id: 400_tel_uri.py 3323 2010-09-28 07:43:18Z bennylp $
#
from inc_cfg import *
# Simple call
test_param = TestParam(
"tel: URI in From",
[
InstanceParam("callee", "--null-audio --max-calls=1 --id tel:+111"),
InstanceParam("caller", "--null-audio --max-calls=1")
]
)
|
chrishales/interpgain | refs/heads/master | task_interpgain.py | 1 | from taskinit import *
import numpy as np
# interpgain is released under a BSD 3-Clause License
# See LICENSE for details
# HISTORY:
# 1.0 28Sep2016 Initial version.
# 1.1 24Oct2016 Minor help file fixes, no change to code
#
def interpgain(caltable,obsid,field,extrapolate):
#
# Task interpgain
#
# Linearly interpolate missing gain solutions,
# overwriting the input caltable. Optionally
# perform extrapolation.
# Christopher A. Hales
#
# Version 1.1 (tested with CASA Version 4.7.0)
# 24 October 2016
casalog.origin('interpgain')
if not obsid.isdigit():
casalog.post('*** ERROR: This version does not support multiple OBSERVATION_ID selection.', 'ERROR')
casalog.post('*** ERROR: Exiting interpgain.', 'ERROR')
return
if not field.isdigit():
casalog.post('*** ERROR: This version does not support multiple FIELD_ID selection.', 'ERROR')
casalog.post('*** ERROR: Exiting interpgain.', 'ERROR')
return
selection0='OBSERVATION_ID=='+obsid+'&&FIELD_ID=='+field
tb.open(caltable,nomodify=False)
subt=tb.query(selection0)
spw=subt.getcol('SPECTRAL_WINDOW_ID')
ant=subt.getcol('ANTENNA1')
subt.done()
for a in np.unique(ant):
for s in np.unique(spw):
selection=selection0+'&&ANTENNA1=='+str(a)+'&&SPECTRAL_WINDOW_ID=='+str(s)
subt=tb.query(selection)
timecol=subt.getcol('TIME')
cparam=subt.getcol('CPARAM')
flag=subt.getcol('FLAG')
for p in range(2):
if (np.sum(flag[p,0])>0) & (np.sum(flag[p,0])<=len(timecol)-2):
# interpolate amp and phase separately
amp = np.abs(cparam[p,0])
phase = np.angle(cparam[p,0])
amp[flag[p,0]==True] = np.interp(timecol[flag[p,0]==True], \
timecol[flag[p,0]==False],amp[flag[p,0]==False])
phase[flag[p,0]==True] = (np.interp(timecol[flag[p,0]==True], \
timecol[flag[p,0]==False], \
np.unwrap(phase[flag[p,0]==False])) + np.pi) % \
(2 * np.pi ) - np.pi
if extrapolate:
cparam[p,0] = amp * np.exp(phase*1j)
flag[p,0] = False
else:
indxMIN = np.where(flag[p,0]==False)[0][0]
indxMAX = np.where(flag[p,0]==False)[0][-1]
cparam[p,0,indxMIN+1:indxMAX] = amp[indxMIN+1:indxMAX] * \
np.exp(phase[indxMIN+1:indxMAX]*1j)
flag[p,0,indxMIN+1:indxMAX] = False
subt.putcol('CPARAM',cparam)
subt.putcol('FLAG',flag)
subt.done()
tb.done()
|
LICEF/edx-platform | refs/heads/master | common/djangoapps/terrain/stubs/tests/test_youtube_stub.py | 51 | """
Unit test for stub YouTube implementation.
"""
import unittest
import requests
from ..youtube import StubYouTubeService
class StubYouTubeServiceTest(unittest.TestCase):
def setUp(self):
self.server = StubYouTubeService()
self.url = "http://127.0.0.1:{0}/".format(self.server.port)
self.server.config['time_to_response'] = 0.0
self.addCleanup(self.server.shutdown)
def test_unused_url(self):
response = requests.get(self.url + 'unused_url')
self.assertEqual("Unused url", response.content)
def test_video_url(self):
response = requests.get(
self.url + 'test_youtube/OEoXaMPEzfM?v=2&alt=jsonc&callback=callback_func'
)
# YouTube metadata for video `OEoXaMPEzfM` states that duration is 116.
self.assertEqual(
'callback_func({"data": {"duration": 116, "message": "I\'m youtube.", "id": "OEoXaMPEzfM"}})',
response.content
)
def test_transcript_url_equal(self):
response = requests.get(
self.url + 'test_transcripts_youtube/t__eq_exist'
)
self.assertEqual(
"".join([
'<?xml version="1.0" encoding="utf-8" ?>',
'<transcript><text start="1.0" dur="1.0">',
'Equal transcripts</text></transcript>'
]), response.content
)
def test_transcript_url_not_equal(self):
response = requests.get(
self.url + 'test_transcripts_youtube/t_neq_exist',
)
self.assertEqual(
"".join([
'<?xml version="1.0" encoding="utf-8" ?>',
'<transcript><text start="1.1" dur="5.5">',
'Transcripts sample, different that on server',
'</text></transcript>'
]), response.content
)
def test_transcript_not_found(self):
response = requests.get(self.url + 'test_transcripts_youtube/some_id')
self.assertEqual(404, response.status_code)
def test_reset_configuration(self):
reset_config_url = self.url + 'del_config'
# add some configuration data
self.server.config['test_reset'] = 'This is a reset config test'
# reset server configuration
response = requests.delete(reset_config_url)
self.assertEqual(response.status_code, 200)
# ensure that server config dict is empty after successful reset
self.assertEqual(self.server.config, {})
|
Mirantis/swift-encrypt | refs/heads/master | doc/source/conf.py | 13 | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2012 OpenStack Foundation.
#
# Swift documentation build configuration file, created by
# sphinx-quickstart on Tue May 18 13:50:15 2010.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import datetime
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.extend([os.path.abspath('../swift'), os.path.abspath('..'),
os.path.abspath('../bin')])
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath',
'sphinx.ext.ifconfig']
todo_include_todos = True
# Add any paths that contain templates here, relative to this directory.
# Changing the path so that the Hudson build output contains GA code and the
# source docs do not contain the code so local, offline sphinx builds are
# "clean."
templates_path = []
if os.getenv('HUDSON_PUBLISH_DOCS'):
templates_path = ['_ga', '_templates']
else:
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Swift'
copyright = u'%d, OpenStack Foundation' % datetime.datetime.now().year
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
from swift import __version__
version = __version__.rsplit('.', 1)[0]
# The full version, including alpha/beta/rc tags.
release = __version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
modindex_common_prefix = ['swift.']
# -- Options for HTML output -----------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme = 'default'
html_theme_path = ["."]
html_theme = '_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
git_cmd = "git log --pretty=format:'%ad, commit %h' --date=local -n1"
html_last_updated_fmt = os.popen(git_cmd).read()
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'swiftdoc'
# -- Options for LaTeX output -------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'Swift.tex', u'Swift Documentation',
u'Swift Team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('http://docs.python.org/', None),
'nova': ('http://nova.openstack.org', None),
'glance': ('http://glance.openstack.org', None)}
|
misterdanb/micropython | refs/heads/master | tests/basics/builtin_hex.py | 72 | # test builtin hex function
print(hex(1))
print(hex(-1))
print(hex(15))
print(hex(-15))
print(hex(12345))
print(hex(0x12345))
print(hex(12345678901234567890))
print(hex(0x12345678901234567890))
|
dexterx17/nodoSocket | refs/heads/master | clients/Python-2.7.6/Tools/freeze/makemakefile.py | 53 | # Write the actual Makefile.
import os
def makemakefile(outfp, makevars, files, target):
outfp.write("# Makefile generated by freeze.py script\n\n")
keys = makevars.keys()
keys.sort()
for key in keys:
outfp.write("%s=%s\n" % (key, makevars[key]))
outfp.write("\nall: %s\n\n" % target)
deps = []
for i in range(len(files)):
file = files[i]
if file[-2:] == '.c':
base = os.path.basename(file)
dest = base[:-2] + '.o'
outfp.write("%s: %s\n" % (dest, file))
outfp.write("\t$(CC) $(CFLAGS) $(CPPFLAGS) -c %s\n" % file)
files[i] = dest
deps.append(dest)
outfp.write("\n%s: %s\n" % (target, ' '.join(deps)))
outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" %
(' '.join(files), target))
outfp.write("\nclean:\n\t-rm -f *.o %s\n" % target)
|
florentx/OpenUpgrade | refs/heads/8.0 | addons/portal_project/__init__.py | 438 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import project
|
cwisecarver/osf.io | refs/heads/develop | api_tests/users/views/test_user_addons.py | 7 | # -*- coding: utf-8 -*-
import abc
from nose.tools import * # flake8: noqa
import re
import pytest
from api.base.settings.defaults import API_BASE
from tests.base import ApiAddonTestCase
from osf_tests.factories import AuthUserFactory
from addons.box.tests.factories import BoxAccountFactory
from addons.dataverse.tests.factories import DataverseAccountFactory
from addons.dropbox.tests.factories import DropboxAccountFactory
from addons.github.tests.factories import GitHubAccountFactory
from addons.googledrive.tests.factories import GoogleDriveAccountFactory
from addons.mendeley.tests.factories import MendeleyAccountFactory
from addons.owncloud.tests.factories import OwnCloudAccountFactory
from addons.s3.tests.factories import S3AccountFactory
from addons.zotero.tests.factories import ZoteroAccountFactory
class UserAddonListMixin(object):
def set_setting_list_url(self):
self.setting_list_url = '/{}users/{}/addons/'.format(
API_BASE, self.user._id
)
def test_settings_list_GET_returns_user_settings_if_present(self):
wrong_type = self.should_expect_errors()
res = self.app.get(
self.setting_list_url,
auth=self.user.auth)
if not wrong_type:
addon_data = res.json['data'][0]
assert_true(addon_data['attributes']['user_has_auth'])
assert_in(self.node._id, addon_data['links']['accounts'][self.account_id]['nodes_connected'][0])
if wrong_type:
assert_equal(res.status_code, 200)
assert_equal(res.json['data'], [])
def test_settings_list_GET_returns_none_if_absent(self):
try:
if self.user.external_accounts.count():
self.user.external_accounts.clear()
self.user.delete_addon(self.short_name, auth=self.auth)
except ValueError:
# If addon was mandatory -- OSFStorage
pass
res = self.app.get(
self.setting_list_url,
auth=self.user.auth)
addon_data = res.json['data']
assert_equal(addon_data, [])
def test_settings_list_raises_error_if_PUT(self):
res = self.app.put_json_api(self.setting_list_url, {
'id': self.short_name,
'type': 'user-addons'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_settings_list_raises_error_if_PATCH(self):
res = self.app.patch_json_api(self.setting_list_url, {
'id': self.short_name,
'type': 'user-addons'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_settings_list_raises_error_if_DELETE(self):
res = self.app.delete(
self.setting_list_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_settings_list_raises_error_if_nonauthenticated(self):
res = self.app.get(
self.setting_list_url,
expect_errors=True)
assert_equal(res.status_code, 401)
def test_settings_list_user_cannot_view_other_user(self):
other_user = AuthUserFactory()
res = self.app.get(
self.setting_list_url,
auth=other_user.auth,
expect_errors=True)
assert_equal(res.status_code, 403)
class UserAddonDetailMixin(object):
def set_setting_detail_url(self):
self.setting_detail_url = '/{}users/{}/addons/{}/'.format(
API_BASE, self.user._id, self.short_name
)
def test_settings_detail_GET_returns_user_settings_if_present(self):
wrong_type = self.should_expect_errors()
res = self.app.get(
self.setting_detail_url,
auth=self.user.auth,
expect_errors=wrong_type)
if not wrong_type:
addon_data = res.json['data']
assert_true(addon_data['attributes']['user_has_auth'])
assert_in(self.node._id, addon_data['links']['accounts'][self.account_id]['nodes_connected'][0])
if wrong_type:
assert_equal(res.status_code, 404)
def test_settings_detail_GET_raises_error_if_absent(self):
wrong_type = self.should_expect_errors()
try:
if self.user.external_accounts.count():
self.user.external_accounts.clear()
self.user.delete_addon(self.short_name, auth=self.auth)
except ValueError:
# If addon was mandatory -- OSFStorage
pass
res = self.app.get(
self.setting_detail_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 404)
if not wrong_type:
assert_in('Requested addon not enabled', res.json['errors'][0]['detail'])
if wrong_type:
assert re.match(r'Requested addon un(available|recognized)', (res.json['errors'][0]['detail']))
def test_settings_detail_raises_error_if_PUT(self):
res = self.app.put_json_api(self.setting_detail_url, {
'id': self.short_name,
'type': 'user-addon-detail'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_settings_detail_raises_error_if_PATCH(self):
res = self.app.patch_json_api(self.setting_detail_url, {
'id': self.short_name,
'type': 'user-addon-detail'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_settings_detail_raises_error_if_DELETE(self):
res = self.app.delete(
self.setting_detail_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_settings_detail_raises_error_if_nonauthenticated(self):
res = self.app.get(
self.setting_detail_url,
expect_errors=True)
assert_equal(res.status_code, 401)
def test_settings_detail_user_cannot_view_other_user(self):
other_user = AuthUserFactory()
res = self.app.get(
self.setting_detail_url,
auth=other_user.auth,
expect_errors=True)
assert_equal(res.status_code, 403)
class UserAddonAccountListMixin(object):
def set_account_list_url(self):
self.account_list_url = '/{}users/{}/addons/{}/accounts/'.format(
API_BASE, self.user._id, self.short_name
)
def test_account_list_GET_returns_accounts_if_present(self):
wrong_type = self.should_expect_errors()
res = self.app.get(
self.account_list_url,
auth=self.user.auth,
expect_errors=wrong_type)
if not wrong_type:
addon_data = res.json['data'][0]
assert_equal(addon_data['id'], self.account._id)
assert_equal(addon_data['attributes']['display_name'], self.account.display_name)
assert_equal(addon_data['attributes']['provider'], self.account.provider)
assert_equal(addon_data['attributes']['profile_url'], self.account.profile_url)
if wrong_type:
assert_equal(res.status_code, 404)
def test_account_list_raises_error_if_absent(self):
wrong_type = self.should_expect_errors()
try:
if self.user.external_accounts.count():
self.user.external_accounts.clear()
self.user.delete_addon(self.short_name, auth=self.auth)
except ValueError:
# If addon was mandatory -- OSFStorage
pass
res = self.app.get(
self.account_list_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 404)
if not wrong_type:
assert_in('Requested addon not enabled', res.json['errors'][0]['detail'])
if wrong_type:
assert re.match(r'Requested addon un(available|recognized)', (res.json['errors'][0]['detail']))
def test_account_list_raises_error_if_PUT(self):
res = self.app.put_json_api(self.account_list_url, {
'id': self.short_name,
'type': 'user-external_accounts'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_account_list_raises_error_if_PATCH(self):
res = self.app.patch_json_api(self.account_list_url, {
'id': self.short_name,
'type': 'user-external_accounts'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_account_list_raises_error_if_DELETE(self):
res = self.app.delete(
self.account_list_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_account_list_raises_error_if_nonauthenticated(self):
res = self.app.get(
self.account_list_url,
expect_errors=True)
assert_equal(res.status_code, 401)
def test_account_list_user_cannot_view_other_user(self):
other_user = AuthUserFactory()
res = self.app.get(
self.account_list_url,
auth=other_user.auth,
expect_errors=True)
assert_equal(res.status_code, 403)
class UserAddonAccountDetailMixin(object):
def set_account_detail_url(self):
self.account_detail_url = '/{}users/{}/addons/{}/accounts/{}/'.format(
API_BASE, self.user._id, self.short_name, self.account_id
)
def test_account_detail_GET_returns_account_if_enabled(self):
wrong_type = self.should_expect_errors()
res = self.app.get(
self.account_detail_url,
auth=self.user.auth,
expect_errors=wrong_type)
if not wrong_type:
addon_data = res.json['data']
assert_equal(addon_data['id'], self.account._id)
assert_equal(addon_data['attributes']['display_name'], self.account.display_name)
assert_equal(addon_data['attributes']['provider'], self.account.provider)
assert_equal(addon_data['attributes']['profile_url'], self.account.profile_url)
if wrong_type:
assert_equal(res.status_code, 404)
def test_account_detail_raises_error_if_not_found(self):
wrong_type = self.should_expect_errors()
try:
if self.user.external_accounts.count():
self.user.external_accounts.clear()
self.user.delete_addon(self.short_name, auth=self.auth)
except ValueError:
# If addon was mandatory -- OSFStorage
pass
res = self.app.get(
self.account_detail_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 404)
if not wrong_type:
assert_in('Requested addon not enabled', res.json['errors'][0]['detail'])
if wrong_type:
assert re.match(r'Requested addon un(available|recognized)', (res.json['errors'][0]['detail']))
def test_account_detail_raises_error_if_PUT(self):
res = self.app.put_json_api(self.account_detail_url, {
'id': self.short_name,
'type': 'user-external_account-detail'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_account_detail_raises_error_if_PATCH(self):
res = self.app.patch_json_api(self.account_detail_url, {
'id': self.short_name,
'type': 'user-external_account-detail'
}, auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_account_detail_raises_error_if_DELETE(self):
res = self.app.delete(
self.account_detail_url,
auth=self.user.auth,
expect_errors=True)
assert_equal(res.status_code, 405)
def test_account_detail_raises_error_if_nonauthenticated(self):
res = self.app.get(
self.account_detail_url,
expect_errors=True)
assert_equal(res.status_code, 401)
def test_account_detail_user_cannot_view_other_user(self):
other_user = AuthUserFactory()
res = self.app.get(
self.account_detail_url,
auth=other_user.auth,
expect_errors=True)
assert_equal(res.status_code, 403)
class UserAddonTestSuiteMixin(UserAddonListMixin, UserAddonDetailMixin, UserAddonAccountListMixin, UserAddonAccountDetailMixin):
def set_urls(self):
self.set_setting_list_url()
self.set_setting_detail_url()
self.set_account_list_url()
self.set_account_detail_url()
def should_expect_errors(self, success_types=('OAUTH', )):
return self.addon_type not in success_types
class UserOAuthAddonTestSuiteMixin(UserAddonTestSuiteMixin):
addon_type = 'OAUTH'
@abc.abstractproperty
def AccountFactory(self):
pass
class UserUnmanageableAddonTestSuiteMixin(UserAddonTestSuiteMixin):
addon_type = 'UNMANAGEABLE'
# UNMANAGEABLE
class TestUserForwardAddon(UserUnmanageableAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'forward'
class TestUserOsfStorageAddon(UserUnmanageableAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'osfstorage'
class TestUserTwoFactorAddon(UserUnmanageableAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'twofactor'
class TestUserWikiAddon(UserUnmanageableAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'wiki'
# OAUTH
class TestUserBoxAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'box'
AccountFactory = BoxAccountFactory
class TestUserDataverseAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'dataverse'
AccountFactory = DataverseAccountFactory
class TestUserDropboxAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'dropbox'
AccountFactory = DropboxAccountFactory
class TestUserGitHubAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'github'
AccountFactory = GitHubAccountFactory
class TestUserGoogleDriveAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'googledrive'
AccountFactory = GoogleDriveAccountFactory
class TestUserMendeleyAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'mendeley'
AccountFactory = MendeleyAccountFactory
class TestUserS3Addon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 's3'
AccountFactory = S3AccountFactory
class TestUserZoteroAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'zotero'
AccountFactory = ZoteroAccountFactory
class TestUserOwnCloudAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'owncloud'
AccountFactory = OwnCloudAccountFactory
@pytest.mark.skip('Unskip when figshare v2 addon is ported')
class TestUserFigshareAddon(UserOAuthAddonTestSuiteMixin, ApiAddonTestCase):
short_name = 'figshare'
# AccountFactory = FigshareAccountFactory
class TestUserInvalidAddon(UserAddonTestSuiteMixin, ApiAddonTestCase):
addon_type = 'INVALID'
short_name = 'fake'
|
martinogden/django-banner-rotator | refs/heads/master | banner_rotator/models.py | 1 | #-*- coding:utf-8 -*-
from __future__ import unicode_literals
try:
from hashlib import md5
except ImportError:
from md5 import md5
from time import time
from django.contrib.auth.models import User
from django.db import models
from django.core.validators import MaxLengthValidator
from django.utils.translation import ugettext_lazy as _
from banner_rotator.managers import BannerManager
def get_banner_upload_to(instance, filename):
"""
Формирует путь для загрузки файлов
"""
filename_parts = filename.split('.')
ext = '.%s' % filename_parts[-1] if len(filename_parts) > 1 else ''
new_filename = md5(('%s-%s' % (filename, time())).encode('utf-8')).hexdigest()
return 'banner/%s%s' % (new_filename, ext)
class Campaign(models.Model):
name = models.CharField(_('Name'), max_length=255)
created_at = models.DateTimeField(_('Create at'), auto_now_add=True)
updated_at = models.DateTimeField(_('Update at'), auto_now=True)
class Meta:
verbose_name = _('campaign')
verbose_name_plural = _('campaigns')
def __unicode__(self):
return self.name
class Place(models.Model):
name = models.CharField(_('Name'), max_length=255)
slug = models.SlugField(_('Slug'))
width = models.SmallIntegerField(_('Width'), blank=True, null=True, default=None)
height = models.SmallIntegerField(_('Height'), blank=True, null=True, default=None)
class Meta:
unique_together = ('slug',)
verbose_name = _('place')
verbose_name_plural = _('places')
def __unicode__(self):
size_str = self.size_str()
return '%s (%s)' % (self.name, size_str) if size_str else self.name
def size_str(self):
if self.width and self.height:
return '%sx%s' % (self.width, self.height)
elif self.width:
return '%sxX' % self.width
elif self.height:
return 'Xx%s' % self.height
else:
return ''
size_str.short_description = _('Size')
class Banner(models.Model):
URL_TARGET_CHOICES = (
('_self', _('Current page')),
('_blank', _('Blank page')),
)
campaign = models.ForeignKey(Campaign, verbose_name=_('Campaign'), blank=True, null=True, default=None,
related_name="banners", db_index=True)
name = models.CharField(_('Name'), max_length=255)
alt = models.CharField(_('Image alt'), max_length=255, blank=True, default='')
url = models.URLField(_('URL'))
url_target = models.CharField(_('Target'), max_length=10, choices=URL_TARGET_CHOICES, default='')
views = models.IntegerField(_('Views'), default=0)
max_views = models.IntegerField(_('Max views'), default=0)
max_clicks = models.IntegerField(_('Max clicks'), default=0)
weight = models.IntegerField(_('Weight'), help_text=_("A ten will display 10 times more often that a one."),
choices=[[i, i] for i in range(1, 11)], default=5)
file = models.FileField(_('File'), upload_to=get_banner_upload_to)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
start_at = models.DateTimeField(_('Start at'), blank=True, null=True, default=None)
finish_at = models.DateTimeField(_('Finish at'), blank=True, null=True, default=None)
is_active = models.BooleanField(_('Is active'), default=True)
places = models.ManyToManyField(Place, verbose_name=_('Place'), related_name="banners", db_index=True)
objects = BannerManager()
class Meta:
verbose_name = _('banner')
verbose_name_plural = _('banners')
def __unicode__(self):
return self.name
def is_swf(self):
return self.file.name.lower().endswith("swf")
def view(self):
self.views = models.F('views') + 1
self.save()
return ''
def click(self, request):
click = {
'banner': self,
'place': request.GET['place_slug'],
'ip': request.META.get('REMOTE_ADDR'),
'user_agent': request.META.get('HTTP_USER_AGENT'),
'referrer': request.META.get('HTTP_REFERER'),
}
if request.user.is_authenticated():
click['user'] = request.user
return Click.objects.create(**click)
@models.permalink
def get_absolute_url(self):
return 'banner_click', (), {'banner_id': self.pk}
def admin_clicks_str(self):
if self.max_clicks:
return '%s / %s' % (self.clicks, self.max_clicks)
return '%s' % self.clicks
admin_clicks_str.short_description = _('Clicks')
def admin_views_str(self):
if self.max_views:
return '%s / %s' % (self.views, self.max_views)
return '%s' % self.views
admin_views_str.short_description = _('Views')
class Click(models.Model):
banner = models.ForeignKey(Banner, related_name="clicks")
user = models.ForeignKey(User, null=True, blank=True, related_name="banner_clicks")
datetime = models.DateTimeField("Clicked at", auto_now_add=True)
ip = models.IPAddressField(null=True, blank=True)
user_agent = models.TextField(validators=[MaxLengthValidator(1000)], null=True, blank=True)
referrer = models.URLField(null=True, blank=True)
|
zymtech/Scrapiders | refs/heads/master | jd_zhilian/jd_zhilian/spiders/jd.py | 1 | # -*- coding = utf-8 -*-
from scrapy import Spider
from scrapy.http import Request
import datetime
import urllib
import os
from scrapy.exceptions import IgnoreRequest
from jd_zhilian.items import JdZhilianItem
class jd(Spider):
name = "jd_zhilian"
allowed_domain = ["zhaopin.com"]
#start_urls = ["http://sou.zhaopin.com/jobs/searchresult.ashx?p=1"]
datafile = os.path.join(os.getcwd(),"jobs.txt")
jobkws = ' '.join(open(datafile,'rb').readlines()).split(' ')
baseurl = "http://sou.zhaopin.com/jobs/searchresult.ashx?"
urls = []
for kw in jobkws:
url = baseurl + 'kw=' + urllib.quote(kw)
urls.append(url)
def start_requests(self):
for url in self.urls:
yield Request(url , callback=self.parse0, errback=self.errback)
def errback(self, failure):
raise IgnoreRequest("ignore this request")
def parse0(self, response):
#pagestr = response.xpath
#page = re.search
#for i in range(1, str(page)+1):
for i in range(1, 301):
url = response.url + '&' + 'p=' + str(i)
yield Request(url, callback=self.parse, errback=self.errback)
def parse(self, response):
url_data = response.xpath('//div[@id="newlist_list_content_table"]//td[@class="zwmc"]//a/@href').extract()
for company_url in url_data:
yield Request(company_url,callback=self.parse2, errback=self.errback)
def parse2(self, response):
item = JdZhilianItem()
item['joblink'] = response.url
item['companyname'] = response.xpath('//div[@class="inner-left fl"]/h2/a/text()').extract()[0]
item['salary'] = response.xpath('//ul[@class="terminal-ul clearfix"]//strong/text()').extract()[0]
item['workplace'] = response.xpath('//ul[@class="terminal-ul clearfix"]//strong/a/text()').extract()[0] +\
response.xpath('//ul[@class="terminal-ul clearfix"]//strong/text()').extract()[1]
item['updatetime'] = response.xpath('//span[@id="span4freshdate"]/text()').extract()[0]
#item['jobtype'] = response.xpath('//ul[@class="terminal-ul clearfix"]//strong/text()').extract()[2]
item['workexperience'] = response.xpath('//ul[@class="terminal-ul clearfix"]//strong/text()').extract()[3]
item['education'] = response.xpath('//ul[@class="terminal-ul clearfix"]//strong/text()').extract()[4]
item['jobcategory'] = response.xpath('//ul[@class="terminal-ul clearfix"]//strong/a/text()').extract()[-1]
item['crawltime'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# job requirement
# require_data = response.xpath(
# '//body/div[@class="terminalpage clearfix"]/div[@class="terminalpage-left"]/div[@class="terminalpage-main clearfix"]/div[@class="tab-cont-box"]/div[1]/p//text()').extract()
# item['jobdetails'] = ''
# for i in require_data:
# i_middle = re.sub(r'<.*?>', r'', i, re.S)
# item['jobdetails'] += re.sub(r'\s*', r'', i_middle, re.S)
item['jobdetails'] = '<br>'.join(response.xpath('//div[@class="tab-inner-cont"]//p/text()').extract())
# company address
company_sel = response.xpath(
'//body/div[@class="terminalpage clearfix"]/div[@class="terminalpage-left"]/div[@class="terminalpage-main clearfix"]/div[@class="tab-cont-box"]/div[last()]//text()').extract()
item['companyinfo'] = ''
for sel in company_sel:
item['companyinfo'] += sel
#company_data = re.search(r'<h2>\s*(.*?)\s*<a', company_data[0], re.S).group(1)
return item
|
houzhenggang/hiwifi-openwrt-HC5661-HC5761 | refs/heads/master | staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/telnetlib.py | 108 | r"""TELNET client class.
Based on RFC 854: TELNET Protocol Specification, by J. Postel and
J. Reynolds
Example:
>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write('guido\r\n')
>>> print tn.read_all()
Login Name TTY Idle When Where
guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
>>>
Note that read_all() won't read until eof -- it just reads some data
-- but it guarantees to read at least one byte unless EOF is hit.
It is possible to pass a Telnet object to select.select() in order to
wait until more data is available. Note that in this case,
read_eager() may return '' even if there was data on the socket,
because the protocol negotiation may have eaten the data. This is why
EOFError is needed in some cases to distinguish between "no data" and
"connection closed" (since the socket also appears ready for reading
when it is closed).
To do:
- option negotiation
- timeout should be intrinsic to the connection object instead of an
option on one of the read calls only
"""
# Imported modules
import sys
import socket
import select
__all__ = ["Telnet"]
# Tunable parameters
DEBUGLEVEL = 0
# Telnet protocol defaults
TELNET_PORT = 23
# Telnet protocol characters (don't change)
IAC = chr(255) # "Interpret As Command"
DONT = chr(254)
DO = chr(253)
WONT = chr(252)
WILL = chr(251)
theNULL = chr(0)
SE = chr(240) # Subnegotiation End
NOP = chr(241) # No Operation
DM = chr(242) # Data Mark
BRK = chr(243) # Break
IP = chr(244) # Interrupt process
AO = chr(245) # Abort output
AYT = chr(246) # Are You There
EC = chr(247) # Erase Character
EL = chr(248) # Erase Line
GA = chr(249) # Go Ahead
SB = chr(250) # Subnegotiation Begin
# Telnet protocol options code (don't change)
# These ones all come from arpa/telnet.h
BINARY = chr(0) # 8-bit data path
ECHO = chr(1) # echo
RCP = chr(2) # prepare to reconnect
SGA = chr(3) # suppress go ahead
NAMS = chr(4) # approximate message size
STATUS = chr(5) # give status
TM = chr(6) # timing mark
RCTE = chr(7) # remote controlled transmission and echo
NAOL = chr(8) # negotiate about output line width
NAOP = chr(9) # negotiate about output page size
NAOCRD = chr(10) # negotiate about CR disposition
NAOHTS = chr(11) # negotiate about horizontal tabstops
NAOHTD = chr(12) # negotiate about horizontal tab disposition
NAOFFD = chr(13) # negotiate about formfeed disposition
NAOVTS = chr(14) # negotiate about vertical tab stops
NAOVTD = chr(15) # negotiate about vertical tab disposition
NAOLFD = chr(16) # negotiate about output LF disposition
XASCII = chr(17) # extended ascii character set
LOGOUT = chr(18) # force logout
BM = chr(19) # byte macro
DET = chr(20) # data entry terminal
SUPDUP = chr(21) # supdup protocol
SUPDUPOUTPUT = chr(22) # supdup output
SNDLOC = chr(23) # send location
TTYPE = chr(24) # terminal type
EOR = chr(25) # end or record
TUID = chr(26) # TACACS user identification
OUTMRK = chr(27) # output marking
TTYLOC = chr(28) # terminal location number
VT3270REGIME = chr(29) # 3270 regime
X3PAD = chr(30) # X.3 PAD
NAWS = chr(31) # window size
TSPEED = chr(32) # terminal speed
LFLOW = chr(33) # remote flow control
LINEMODE = chr(34) # Linemode option
XDISPLOC = chr(35) # X Display Location
OLD_ENVIRON = chr(36) # Old - Environment variables
AUTHENTICATION = chr(37) # Authenticate
ENCRYPT = chr(38) # Encryption option
NEW_ENVIRON = chr(39) # New - Environment variables
# the following ones come from
# http://www.iana.org/assignments/telnet-options
# Unfortunately, that document does not assign identifiers
# to all of them, so we are making them up
TN3270E = chr(40) # TN3270E
XAUTH = chr(41) # XAUTH
CHARSET = chr(42) # CHARSET
RSP = chr(43) # Telnet Remote Serial Port
COM_PORT_OPTION = chr(44) # Com Port Control Option
SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
TLS = chr(46) # Telnet Start TLS
KERMIT = chr(47) # KERMIT
SEND_URL = chr(48) # SEND-URL
FORWARD_X = chr(49) # FORWARD_X
PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
EXOPL = chr(255) # Extended-Options-List
NOOPT = chr(0)
class Telnet:
"""Telnet interface class.
An instance of this class represents a connection to a telnet
server. The instance is initially not connected; the open()
method must be used to establish a connection. Alternatively, the
host name and optional port number can be passed to the
constructor, too.
Don't try to reopen an already connected instance.
This class has many read_*() methods. Note that some of them
raise EOFError when the end of the connection is read, because
they can return an empty string for other reasons. See the
individual doc strings.
read_until(expected, [timeout])
Read until the expected string has been seen, or a timeout is
hit (default is no timeout); may block.
read_all()
Read all data until EOF; may block.
read_some()
Read at least one byte or EOF; may block.
read_very_eager()
Read all data available already queued or on the socket,
without blocking.
read_eager()
Read either data already queued or some data available on the
socket, without blocking.
read_lazy()
Read all data in the raw queue (processing it first), without
doing any socket I/O.
read_very_lazy()
Reads all data in the cooked queue, without doing any socket
I/O.
read_sb_data()
Reads available data between SB ... SE sequence. Don't block.
set_option_negotiation_callback(callback)
Each time a telnet option is read on the input flow, this callback
(if set) is called with the following parameters :
callback(telnet socket, command, option)
option will be chr(0) when there is no option.
No other action is done afterwards by telnetlib.
"""
def __init__(self, host=None, port=0,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
"""Constructor.
When called without arguments, create an unconnected instance.
With a hostname argument, it connects the instance; port number
and timeout are optional.
"""
self.debuglevel = DEBUGLEVEL
self.host = host
self.port = port
self.timeout = timeout
self.sock = None
self.rawq = ''
self.irawq = 0
self.cookedq = ''
self.eof = 0
self.iacseq = '' # Buffer for IAC sequence.
self.sb = 0 # flag for SB and SE sequence.
self.sbdataq = ''
self.option_callback = None
if host is not None:
self.open(host, port, timeout)
def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
"""Connect to a host.
The optional second argument is the port number, which
defaults to the standard telnet port (23).
Don't try to reopen an already connected instance.
"""
self.eof = 0
if not port:
port = TELNET_PORT
self.host = host
self.port = port
self.timeout = timeout
self.sock = socket.create_connection((host, port), timeout)
def __del__(self):
"""Destructor -- close the connection."""
self.close()
def msg(self, msg, *args):
"""Print a debug message, when the debug level is > 0.
If extra arguments are present, they are substituted in the
message using the standard string formatting operator.
"""
if self.debuglevel > 0:
print 'Telnet(%s,%s):' % (self.host, self.port),
if args:
print msg % args
else:
print msg
def set_debuglevel(self, debuglevel):
"""Set the debug level.
The higher it is, the more debug output you get (on sys.stdout).
"""
self.debuglevel = debuglevel
def close(self):
"""Close the connection."""
if self.sock:
self.sock.close()
self.sock = 0
self.eof = 1
self.iacseq = ''
self.sb = 0
def get_socket(self):
"""Return the socket object used internally."""
return self.sock
def fileno(self):
"""Return the fileno() of the socket object used internally."""
return self.sock.fileno()
def write(self, buffer):
"""Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
socket.error if the connection is closed.
"""
if IAC in buffer:
buffer = buffer.replace(IAC, IAC+IAC)
self.msg("send %r", buffer)
self.sock.sendall(buffer)
def read_until(self, match, timeout=None):
"""Read until a given string is encountered or until timeout.
When no match is found, return whatever is available instead,
possibly the empty string. Raise EOFError if the connection
is closed and no cooked data is available.
"""
n = len(match)
self.process_rawq()
i = self.cookedq.find(match)
if i >= 0:
i = i+n
buf = self.cookedq[:i]
self.cookedq = self.cookedq[i:]
return buf
s_reply = ([self], [], [])
s_args = s_reply
if timeout is not None:
s_args = s_args + (timeout,)
from time import time
time_start = time()
while not self.eof and select.select(*s_args) == s_reply:
i = max(0, len(self.cookedq)-n)
self.fill_rawq()
self.process_rawq()
i = self.cookedq.find(match, i)
if i >= 0:
i = i+n
buf = self.cookedq[:i]
self.cookedq = self.cookedq[i:]
return buf
if timeout is not None:
elapsed = time() - time_start
if elapsed >= timeout:
break
s_args = s_reply + (timeout-elapsed,)
return self.read_very_lazy()
def read_all(self):
"""Read all data until EOF; block until connection closed."""
self.process_rawq()
while not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = ''
return buf
def read_some(self):
"""Read at least one byte of cooked data unless EOF is hit.
Return '' if EOF is hit. Block if no data is immediately
available.
"""
self.process_rawq()
while not self.cookedq and not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = ''
return buf
def read_very_eager(self):
"""Read everything that's possible without blocking in I/O (eager).
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
"""
self.process_rawq()
while not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy()
def read_eager(self):
"""Read readily available data.
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
"""
self.process_rawq()
while not self.cookedq and not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy()
def read_lazy(self):
"""Process and return data that's already in the queues (lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block
unless in the midst of an IAC sequence.
"""
self.process_rawq()
return self.read_very_lazy()
def read_very_lazy(self):
"""Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block.
"""
buf = self.cookedq
self.cookedq = ''
if not buf and self.eof and not self.rawq:
raise EOFError, 'telnet connection closed'
return buf
def read_sb_data(self):
"""Return any data available in the SB ... SE queue.
Return '' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block.
"""
buf = self.sbdataq
self.sbdataq = ''
return buf
def set_option_negotiation_callback(self, callback):
"""Provide a callback function called after each receipt of a telnet option."""
self.option_callback = callback
def process_rawq(self):
"""Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
buf = ['', '']
try:
while self.rawq:
c = self.rawq_getchar()
if not self.iacseq:
if c == theNULL:
continue
if c == "\021":
continue
if c != IAC:
buf[self.sb] = buf[self.sb] + c
continue
else:
self.iacseq += c
elif len(self.iacseq) == 1:
# 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
self.iacseq += c
continue
self.iacseq = ''
if c == IAC:
buf[self.sb] = buf[self.sb] + c
else:
if c == SB: # SB ... SE start.
self.sb = 1
self.sbdataq = ''
elif c == SE:
self.sb = 0
self.sbdataq = self.sbdataq + buf[1]
buf[1] = ''
if self.option_callback:
# Callback is supposed to look into
# the sbdataq
self.option_callback(self.sock, c, NOOPT)
else:
# We can't offer automatic processing of
# suboptions. Alas, we should not get any
# unless we did a WILL/DO before.
self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2:
cmd = self.iacseq[1]
self.iacseq = ''
opt = c
if cmd in (DO, DONT):
self.msg('IAC %s %d',
cmd == DO and 'DO' or 'DONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
self.msg('IAC %s %d',
cmd == WILL and 'WILL' or 'WONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar()
self.iacseq = '' # Reset on EOF
self.sb = 0
pass
self.cookedq = self.cookedq + buf[0]
self.sbdataq = self.sbdataq + buf[1]
def rawq_getchar(self):
"""Get next char from raw queue.
Block if no data is immediately available. Raise EOFError
when connection is closed.
"""
if not self.rawq:
self.fill_rawq()
if self.eof:
raise EOFError
c = self.rawq[self.irawq]
self.irawq = self.irawq + 1
if self.irawq >= len(self.rawq):
self.rawq = ''
self.irawq = 0
return c
def fill_rawq(self):
"""Fill raw queue from exactly one recv() system call.
Block if no data is immediately available. Set self.eof when
connection is closed.
"""
if self.irawq >= len(self.rawq):
self.rawq = ''
self.irawq = 0
# The buffer size should be fairly small so as to avoid quadratic
# behavior in process_rawq() above
buf = self.sock.recv(50)
self.msg("recv %r", buf)
self.eof = (not buf)
self.rawq = self.rawq + buf
def sock_avail(self):
"""Test whether data is available on the socket."""
return select.select([self], [], [], 0) == ([self], [], [])
def interact(self):
"""Interaction function, emulates a very dumb telnet client."""
if sys.platform == "win32":
self.mt_interact()
return
while 1:
rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
if self in rfd:
try:
text = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
break
if text:
sys.stdout.write(text)
sys.stdout.flush()
if sys.stdin in rfd:
line = sys.stdin.readline()
if not line:
break
self.write(line)
def mt_interact(self):
"""Multithreaded version of interact()."""
import thread
thread.start_new_thread(self.listener, ())
while 1:
line = sys.stdin.readline()
if not line:
break
self.write(line)
def listener(self):
"""Helper for mt_interact() -- this executes in the other thread."""
while 1:
try:
data = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
return
if data:
sys.stdout.write(data)
else:
sys.stdout.flush()
def expect(self, list, timeout=None):
"""Read until one from a list of a regular expressions matches.
The first argument is a list of regular expressions, either
compiled (re.RegexObject instances) or uncompiled (strings).
The optional second argument is a timeout, in seconds; default
is no timeout.
Return a tuple of three items: the index in the list of the
first regular expression that matches; the match object
returned; and the text read up till and including the match.
If EOF is read and no text was read, raise EOFError.
Otherwise, when nothing matches, return (-1, None, text) where
text is the text received so far (may be the empty string if a
timeout happened).
If a regular expression ends with a greedy match (e.g. '.*')
or if more than one expression can match the same input, the
results are undeterministic, and may depend on the I/O timing.
"""
re = None
list = list[:]
indices = range(len(list))
for i in indices:
if not hasattr(list[i], "search"):
if not re: import re
list[i] = re.compile(list[i])
if timeout is not None:
from time import time
time_start = time()
while 1:
self.process_rawq()
for i in indices:
m = list[i].search(self.cookedq)
if m:
e = m.end()
text = self.cookedq[:e]
self.cookedq = self.cookedq[e:]
return (i, m, text)
if self.eof:
break
if timeout is not None:
elapsed = time() - time_start
if elapsed >= timeout:
break
s_args = ([self.fileno()], [], [], timeout-elapsed)
r, w, x = select.select(*s_args)
if not r:
break
self.fill_rawq()
text = self.read_very_lazy()
if not text and self.eof:
raise EOFError
return (-1, None, text)
def test():
"""Test program for telnetlib.
Usage: python telnetlib.py [-d] ... [host [port]]
Default host is localhost; default port is 23.
"""
debuglevel = 0
while sys.argv[1:] and sys.argv[1] == '-d':
debuglevel = debuglevel+1
del sys.argv[1]
host = 'localhost'
if sys.argv[1:]:
host = sys.argv[1]
port = 0
if sys.argv[2:]:
portstr = sys.argv[2]
try:
port = int(portstr)
except ValueError:
port = socket.getservbyname(portstr, 'tcp')
tn = Telnet()
tn.set_debuglevel(debuglevel)
tn.open(host, port, timeout=0.5)
tn.interact()
tn.close()
if __name__ == '__main__':
test()
|
etherkit/OpenBeacon2 | refs/heads/master | client/win/venv/Lib/site-packages/pip/_vendor/pep517/colorlog.py | 56 | """Nicer log formatting with colours.
Code copied from Tornado, Apache licensed.
"""
# Copyright 2012 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import sys
try:
import curses
except ImportError:
curses = None
def _stderr_supports_color():
color = False
if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
try:
curses.setupterm()
if curses.tigetnum("colors") > 0:
color = True
except Exception:
pass
return color
class LogFormatter(logging.Formatter):
"""Log formatter with colour support
"""
DEFAULT_COLORS = {
logging.INFO: 2, # Green
logging.WARNING: 3, # Yellow
logging.ERROR: 1, # Red
logging.CRITICAL: 1,
}
def __init__(self, color=True, datefmt=None):
r"""
:arg bool color: Enables color support.
:arg string fmt: Log message format.
It will be applied to the attributes dict of log records. The
text between ``%(color)s`` and ``%(end_color)s`` will be colored
depending on the level if color support is on.
:arg dict colors: color mappings from logging level to terminal color
code
:arg string datefmt: Datetime format.
Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.
.. versionchanged:: 3.2
Added ``fmt`` and ``datefmt`` arguments.
"""
logging.Formatter.__init__(self, datefmt=datefmt)
self._colors = {}
if color and _stderr_supports_color():
# The curses module has some str/bytes confusion in
# python3. Until version 3.2.3, most methods return
# bytes, but only accept strings. In addition, we want to
# output these strings with the logging module, which
# works with unicode strings. The explicit calls to
# unicode() below are harmless in python2 but will do the
# right conversion in python 3.
fg_color = (curses.tigetstr("setaf") or
curses.tigetstr("setf") or "")
if (3, 0) < sys.version_info < (3, 2, 3):
fg_color = str(fg_color, "ascii")
for levelno, code in self.DEFAULT_COLORS.items():
self._colors[levelno] = str(
curses.tparm(fg_color, code), "ascii")
self._normal = str(curses.tigetstr("sgr0"), "ascii")
scr = curses.initscr()
self.termwidth = scr.getmaxyx()[1]
curses.endwin()
else:
self._normal = ''
# Default width is usually 80, but too wide is
# worse than too narrow
self.termwidth = 70
def formatMessage(self, record):
mlen = len(record.message)
right_text = '{initial}-{name}'.format(initial=record.levelname[0],
name=record.name)
if mlen + len(right_text) < self.termwidth:
space = ' ' * (self.termwidth - (mlen + len(right_text)))
else:
space = ' '
if record.levelno in self._colors:
start_color = self._colors[record.levelno]
end_color = self._normal
else:
start_color = end_color = ''
return record.message + space + start_color + right_text + end_color
def enable_colourful_output(level=logging.INFO):
handler = logging.StreamHandler()
handler.setFormatter(LogFormatter())
logging.root.addHandler(handler)
logging.root.setLevel(level)
|
comran/SpartanBalloon2016 | refs/heads/master | third_party/googletest/googlemock/test/gmock_test_utils.py | 769 | #!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test utilities for Google C++ Mocking Framework."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import sys
# Determines path to gtest_test_utils and imports it.
SCRIPT_DIR = os.path.dirname(__file__) or '.'
# isdir resolves symbolic links.
gtest_tests_util_dir = os.path.join(SCRIPT_DIR, '../gtest/test')
if os.path.isdir(gtest_tests_util_dir):
GTEST_TESTS_UTIL_DIR = gtest_tests_util_dir
else:
GTEST_TESTS_UTIL_DIR = os.path.join(SCRIPT_DIR, '../../gtest/test')
sys.path.append(GTEST_TESTS_UTIL_DIR)
import gtest_test_utils # pylint: disable-msg=C6204
def GetSourceDir():
"""Returns the absolute path of the directory where the .py files are."""
return gtest_test_utils.GetSourceDir()
def GetTestExecutablePath(executable_name):
"""Returns the absolute path of the test binary given its name.
The function will print a message and abort the program if the resulting file
doesn't exist.
Args:
executable_name: name of the test binary that the test script runs.
Returns:
The absolute path of the test binary.
"""
return gtest_test_utils.GetTestExecutablePath(executable_name)
def GetExitStatus(exit_code):
"""Returns the argument to exit(), or -1 if exit() wasn't called.
Args:
exit_code: the result value of os.system(command).
"""
if os.name == 'nt':
# On Windows, os.WEXITSTATUS() doesn't work and os.system() returns
# the argument to exit() directly.
return exit_code
else:
# On Unix, os.WEXITSTATUS() must be used to extract the exit status
# from the result of os.system().
if os.WIFEXITED(exit_code):
return os.WEXITSTATUS(exit_code)
else:
return -1
# Suppresses the "Invalid const name" lint complaint
# pylint: disable-msg=C6409
# Exposes utilities from gtest_test_utils.
Subprocess = gtest_test_utils.Subprocess
TestCase = gtest_test_utils.TestCase
environ = gtest_test_utils.environ
SetEnvVar = gtest_test_utils.SetEnvVar
PREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR
# pylint: enable-msg=C6409
def Main():
"""Runs the unit test."""
gtest_test_utils.Main()
|
cg31/tensorflow | refs/heads/master | tensorflow/contrib/tensor_forest/hybrid/python/layers/decisions_to_data_test.py | 25 | # Copyright 2016 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
# pylint: disable=unused-import
import tensorflow as tf
from tensorflow.contrib.tensor_forest.hybrid.python.layers import decisions_to_data
from tensorflow.contrib.tensor_forest.python import tensor_forest
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util
from tensorflow.python.framework.ops import Operation
from tensorflow.python.framework.ops import Tensor
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import googletest
class DecisionsToDataTest(test_util.TensorFlowTestCase):
def setUp(self):
self.params = tensor_forest.ForestHParams(
num_classes=2,
num_features=31,
layer_size=11,
num_layers=13,
num_trees=17,
connection_probability=0.1,
hybrid_tree_depth=4,
regularization_strength=0.01,
regularization="",
learning_rate=0.01,
weight_init_mean=0.0,
weight_init_std=0.1)
self.params.regression = False
self.params.num_nodes = 2**self.params.hybrid_tree_depth - 1
self.params.num_leaves = 2**(self.params.hybrid_tree_depth - 1)
# pylint: disable=W0612
self.input_data = constant_op.constant(
[[random.uniform(-1, 1) for i in range(self.params.num_features)]
for _ in range(100)])
def testInferenceConstruction(self):
with variable_scope.variable_scope(
"DecisionsToDataTest_testInferenceContruction"):
graph_builder = decisions_to_data.DecisionsToDataLayer(
self.params, 0, None)
unused_graph = graph_builder.inference_graph(self.input_data)
if __name__ == "__main__":
googletest.main()
|
sharonpkingsley/BINF3111 | refs/heads/master | old/config.py | 2 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')
|
tsl143/zamboni | refs/heads/master | mkt/stats/tests/test_views.py | 18 | import json
import mock
import requests
from nose.tools import eq_, ok_
from rest_framework.reverse import reverse
from django.conf import settings
import mkt
from mkt.api.tests.test_oauth import RestOAuth
from mkt.purchase.models import Contribution
from mkt.site.fixtures import fixture
from mkt.site.tests import app_factory
from mkt.stats.views import APP_STATS, STATS, _get_monolith_data
class StatsAPITestMixin(object):
def setUp(self):
super(StatsAPITestMixin, self).setUp()
patches = [
mock.patch('monolith.client.Client'),
mock.patch.object(settings, 'MONOLITH_SERVER', 'http://0.0.0.0:0'),
]
for patch in patches:
patch.start()
self.addCleanup(patch.stop)
def test_cors(self):
res = self.client.get(self.url(), data=self.data)
self.assertCORS(res, 'get')
def test_verbs(self):
self._allowed_verbs(self.url(), ['get'])
@mock.patch('monolith.client.Client')
def test_monolith_down(self, mocked):
mocked.side_effect = requests.ConnectionError
res = self.client.get(self.url(), data=self.data)
eq_(res.status_code, 503)
def test_anon(self):
res = self.anon.get(self.url())
eq_(res.status_code, 403)
class GlobalStatsAPITestMixin(StatsAPITestMixin):
def test_anon(self):
"""Global stats are allowed by anonymous users."""
res = self.anon.get(self.url(), data=self.data or {})
eq_(res.status_code, 200)
class TestGlobalStatsResource(GlobalStatsAPITestMixin, RestOAuth):
def setUp(self):
super(TestGlobalStatsResource, self).setUp()
self.grant_permission(self.profile, 'Stats:View')
self.data = {'start': '2013-04-01',
'end': '2013-04-15',
'interval': 'day'}
def url(self, metric=None):
metric = metric or STATS.keys()[0]
return reverse('global_stats', kwargs={'metric': metric})
def test_bad_metric(self):
res = self.client.get(self.url('foo'))
eq_(res.status_code, 404)
def test_missing_args(self):
res = self.client.get(self.url())
eq_(res.status_code, 400)
data = json.loads(res.content)
for f in ('start', 'end', 'interval'):
eq_(data['detail'][f], ['This field is required.'])
def test_good(self):
res = self.client.get(self.url(), data=self.data)
eq_(res.status_code, 200)
eq_(json.loads(res.content)['objects'], [])
@mock.patch('monolith.client.Client')
def test_dimensions(self, mocked):
client = mock.MagicMock()
mocked.return_value = client
data = self.data.copy()
data.update({'region': 'br', 'package_type': 'hosted'})
res = self.client.get(self.url('apps_added_by_package'), data=data)
eq_(res.status_code, 200)
ok_(client.called)
eq_(client.call_args[1], {'region': 'br', 'package_type': 'hosted'})
@mock.patch('monolith.client.Client')
def test_dimensions_default(self, mocked):
client = mock.MagicMock()
mocked.return_value = client
res = self.client.get(self.url('apps_added_by_package'),
data=self.data)
eq_(res.status_code, 200)
ok_(client.called)
eq_(client.call_args[1], {'region': 'us', 'package_type': 'hosted'})
@mock.patch('monolith.client.Client')
def test_dimensions_default_is_none(self, mocked):
client = mock.MagicMock()
mocked.return_value = client
res = self.client.get(self.url('apps_installed'), data=self.data)
eq_(res.status_code, 200)
ok_(client.called)
eq_(client.call_args[1], {})
data = self.data.copy()
data['region'] = 'us'
res = self.client.get(self.url('apps_installed'), data=data)
eq_(res.status_code, 200)
ok_(client.called)
eq_(client.call_args[1], {'region': 'us'})
@mock.patch('monolith.client.Client')
def test_coersion(self, mocked):
client = mock.MagicMock()
client.return_value = [{'count': 1.99, 'date': '2013-10-10'}]
mocked.return_value = client
data = _get_monolith_data(
{'metric': 'foo', 'coerce': {'count': str}}, '2013-10-10',
'2013-10-10', 'day', {})
eq_(type(data['objects'][0]['count']), str)
class TestAppStatsResource(StatsAPITestMixin, RestOAuth):
fixtures = fixture('user_2519')
def setUp(self):
super(TestAppStatsResource, self).setUp()
self.app = app_factory(status=mkt.STATUS_PUBLIC)
self.app.addonuser_set.create(user=self.user)
self.data = {'start': '2013-04-01', 'end': '2013-04-15',
'interval': 'day'}
def url(self, pk=None, metric=None):
pk = pk or self.app.pk
metric = metric or APP_STATS.keys()[0]
return reverse('app_stats', kwargs={'pk': pk, 'metric': metric})
def test_owner(self):
self.app.update(public_stats=True)
res = self.client.get(self.url(), data=self.data)
eq_(res.status_code, 200)
# Also test owner with public_stats=False
self.app.update(public_stats=False)
res = self.client.get(self.url(), data=self.data)
eq_(res.status_code, 200)
def test_perms(self):
self.app.addonuser_set.all().delete()
self.grant_permission(self.profile, 'Stats:View')
res = self.client.get(self.url(), data=self.data)
eq_(res.status_code, 200)
def test_public_anonymous(self):
self.app.update(public_stats=True)
self.app.addonuser_set.all().delete()
res = self.anon.get(self.url(), data=self.data)
eq_(res.status_code, 200)
def test_non_public_anonymous(self):
self.app.update(public_stats=False)
self.app.addonuser_set.all().delete()
res = self.anon.get(self.url(), data=self.data)
eq_(res.status_code, 403)
def test_bad_app(self):
res = self.client.get(self.url(pk=99999999))
eq_(res.status_code, 404)
def test_bad_metric(self):
res = self.client.get(self.url(metric='foo'))
eq_(res.status_code, 404)
def test_missing_args(self):
res = self.client.get(self.url())
eq_(res.status_code, 400)
data = json.loads(res.content)
for f in ('start', 'end', 'interval'):
eq_(data['detail'][f], ['This field is required.'])
class TestGlobalStatsTotalResource(GlobalStatsAPITestMixin, RestOAuth):
fixtures = fixture('user_2519')
def setUp(self):
super(TestGlobalStatsTotalResource, self).setUp()
self.grant_permission(self.profile, 'Stats:View')
self.data = None # For the mixin tests.
def url(self):
return reverse('global_stats_total')
def test_perms(self):
res = self.client.get(self.url())
eq_(res.status_code, 200)
class TestAppStatsTotalResource(StatsAPITestMixin, RestOAuth):
fixtures = fixture('user_2519')
def setUp(self):
super(TestAppStatsTotalResource, self).setUp()
self.app = app_factory(status=mkt.STATUS_PUBLIC)
self.app.addonuser_set.create(user=self.user)
self.data = None # For the mixin tests.
def url(self, pk=None, metric=None):
pk = pk or self.app.pk
return reverse('app_stats_total', kwargs={'pk': pk})
def test_owner(self):
self.app.update(public_stats=True)
res = self.client.get(self.url())
eq_(res.status_code, 200)
# Also test owner with public_stats=False
self.app.update(public_stats=False)
res = self.client.get(self.url(), data=self.data)
eq_(res.status_code, 200)
def test_perms(self):
self.app.addonuser_set.all().delete()
self.grant_permission(self.profile, 'Stats:View')
res = self.client.get(self.url())
eq_(res.status_code, 200)
def test_public_anonymous(self):
self.app.update(public_stats=True)
self.app.addonuser_set.all().delete()
res = self.anon.get(self.url(), data=self.data)
eq_(res.status_code, 200)
def test_non_public_anonymous(self):
self.app.update(public_stats=False)
self.app.addonuser_set.all().delete()
res = self.anon.get(self.url(), data=self.data)
eq_(res.status_code, 403)
def test_bad_app(self):
res = self.client.get(self.url(pk=99999999))
eq_(res.status_code, 404)
class TestTransactionResource(RestOAuth):
fixtures = fixture('prices', 'user_2519', 'webapp_337141')
def setUp(self):
super(TestTransactionResource, self).setUp()
Contribution.objects.create(
addon_id=337141,
amount='1.89',
currency='EUR',
price_tier_id=2,
uuid='abcdef123456',
transaction_id='abc-def',
type=1,
user=self.user
)
def url(self, t_id=None):
t_id = t_id or 'abc-def'
return reverse('transaction_api', kwargs={'transaction_id': t_id})
def test_cors(self):
res = self.client.get(self.url())
self.assertCORS(res, 'get')
def test_verbs(self):
self.grant_permission(self.profile, 'RevenueStats:View')
self._allowed_verbs(self.url(), ['get'])
def test_anon(self):
res = self.anon.get(self.url())
eq_(res.status_code, 403)
def test_bad_txn(self):
self.grant_permission(self.profile, 'RevenueStats:View')
res = self.client.get(self.url('foo'))
eq_(res.status_code, 404)
def test_good_but_no_permission(self):
res = self.client.get(self.url())
eq_(res.status_code, 403)
def test_good(self):
self.grant_permission(self.profile, 'RevenueStats:View')
res = self.client.get(self.url())
eq_(res.status_code, 200)
obj = json.loads(res.content)
eq_(obj['id'], 'abc-def')
eq_(obj['app_id'], 337141)
eq_(obj['amount_USD'], '1.99')
eq_(obj['type'], 'Purchase')
|
stevehof/CouchPotatoServer | refs/heads/master | couchpotato/core/media/_base/matcher/main.py | 15 | from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.helpers.variable import possibleTitles
from couchpotato.core.logger import CPLog
from couchpotato.core.media._base.matcher.base import MatcherBase
from caper import Caper
log = CPLog(__name__)
class Matcher(MatcherBase):
def __init__(self):
super(Matcher, self).__init__()
self.caper = Caper()
addEvent('matcher.parse', self.parse)
addEvent('matcher.match', self.match)
addEvent('matcher.flatten_info', self.flattenInfo)
addEvent('matcher.construct_from_raw', self.constructFromRaw)
addEvent('matcher.correct_title', self.correctTitle)
addEvent('matcher.correct_quality', self.correctQuality)
def parse(self, name, parser='scene'):
return self.caper.parse(name, parser)
def match(self, release, media, quality):
match = fireEvent('matcher.parse', release['name'], single = True)
if len(match.chains) < 1:
log.info2('Wrong: %s, unable to parse release name (no chains)', release['name'])
return False
for chain in match.chains:
if fireEvent('%s.matcher.correct' % media['type'], chain, release, media, quality, single = True):
return chain
return False
def correctTitle(self, chain, media):
root_library = media['library']['root_library']
if 'show_name' not in chain.info or not len(chain.info['show_name']):
log.info('Wrong: missing show name in parsed result')
return False
# Get the lower-case parsed show name from the chain
chain_words = [x.lower() for x in chain.info['show_name']]
# Build a list of possible titles of the media we are searching for
titles = root_library['info']['titles']
# Add year suffix titles (will result in ['<name_one>', '<name_one> <suffix_one>', '<name_two>', ...])
suffixes = [None, root_library['info']['year']]
titles = [
title + ((' %s' % suffix) if suffix else '')
for title in titles
for suffix in suffixes
]
# Check show titles match
# TODO check xem names
for title in titles:
for valid_words in [x.split(' ') for x in possibleTitles(title)]:
if valid_words == chain_words:
return True
return False
def correctQuality(self, chain, quality, quality_map):
if quality['identifier'] not in quality_map:
log.info2('Wrong: unknown preferred quality %s', quality['identifier'])
return False
if 'video' not in chain.info:
log.info2('Wrong: no video tags found')
return False
video_tags = quality_map[quality['identifier']]
if not self.chainMatch(chain, 'video', video_tags):
log.info2('Wrong: %s tags not in chain', video_tags)
return False
return True
|
vicenteneto/online-judge-solutions | refs/heads/master | URI/1-Beginner/1557.py | 1 | # -*- coding: utf-8 -*-
while 1:
n = int(raw_input())
if not n:
break
A = [['1' for x in range(n)] for y in range(n)]
last_len = len(str((2 ** (n - 1)) ** 2))
for i in range(n):
line = ''
for j in range(n):
if i == 0 and j == 0:
A[i][j] = '1'
elif j == 0:
A[i][j] = str(int(A[i - 1][j]) * 2)
elif j > 0:
A[i][j] = str(int(A[i][j - 1]) * 2)
actual_len = len(A[i][j])
line += (last_len - actual_len) * ' ' + A[i][j] if actual_len < last_len else A[i][j]
line += ' ' if j != n - 1 else ''
print line
print
|
zaxtax/scikit-learn | refs/heads/master | examples/covariance/plot_lw_vs_oas.py | 159 | """
=============================
Ledoit-Wolf vs OAS estimation
=============================
The usual covariance maximum likelihood estimate can be regularized
using shrinkage. Ledoit and Wolf proposed a close formula to compute
the asymptotically optimal shrinkage parameter (minimizing a MSE
criterion), yielding the Ledoit-Wolf covariance estimate.
Chen et al. proposed an improvement of the Ledoit-Wolf shrinkage
parameter, the OAS coefficient, whose convergence is significantly
better under the assumption that the data are Gaussian.
This example, inspired from Chen's publication [1], shows a comparison
of the estimated MSE of the LW and OAS methods, using Gaussian
distributed data.
[1] "Shrinkage Algorithms for MMSE Covariance Estimation"
Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import toeplitz, cholesky
from sklearn.covariance import LedoitWolf, OAS
np.random.seed(0)
###############################################################################
n_features = 100
# simulation covariance matrix (AR(1) process)
r = 0.1
real_cov = toeplitz(r ** np.arange(n_features))
coloring_matrix = cholesky(real_cov)
n_samples_range = np.arange(6, 31, 1)
repeat = 100
lw_mse = np.zeros((n_samples_range.size, repeat))
oa_mse = np.zeros((n_samples_range.size, repeat))
lw_shrinkage = np.zeros((n_samples_range.size, repeat))
oa_shrinkage = np.zeros((n_samples_range.size, repeat))
for i, n_samples in enumerate(n_samples_range):
for j in range(repeat):
X = np.dot(
np.random.normal(size=(n_samples, n_features)), coloring_matrix.T)
lw = LedoitWolf(store_precision=False, assume_centered=True)
lw.fit(X)
lw_mse[i, j] = lw.error_norm(real_cov, scaling=False)
lw_shrinkage[i, j] = lw.shrinkage_
oa = OAS(store_precision=False, assume_centered=True)
oa.fit(X)
oa_mse[i, j] = oa.error_norm(real_cov, scaling=False)
oa_shrinkage[i, j] = oa.shrinkage_
# plot MSE
plt.subplot(2, 1, 1)
plt.errorbar(n_samples_range, lw_mse.mean(1), yerr=lw_mse.std(1),
label='Ledoit-Wolf', color='navy', lw=2)
plt.errorbar(n_samples_range, oa_mse.mean(1), yerr=oa_mse.std(1),
label='OAS', color='darkorange', lw=2)
plt.ylabel("Squared error")
plt.legend(loc="upper right")
plt.title("Comparison of covariance estimators")
plt.xlim(5, 31)
# plot shrinkage coefficient
plt.subplot(2, 1, 2)
plt.errorbar(n_samples_range, lw_shrinkage.mean(1), yerr=lw_shrinkage.std(1),
label='Ledoit-Wolf', color='navy', lw=2)
plt.errorbar(n_samples_range, oa_shrinkage.mean(1), yerr=oa_shrinkage.std(1),
label='OAS', color='darkorange', lw=2)
plt.xlabel("n_samples")
plt.ylabel("Shrinkage")
plt.legend(loc="lower right")
plt.ylim(plt.ylim()[0], 1. + (plt.ylim()[1] - plt.ylim()[0]) / 10.)
plt.xlim(5, 31)
plt.show()
|
ChanduERP/odoo | refs/heads/8.0 | addons/survey/__init__.py | 385 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import survey
import controllers
import wizard
|
clarkperkins/stackdio | refs/heads/master | stackdio/core/warnings.py | 2 | # -*- coding: utf-8 -*-
# Copyright 2017, Digital Reasoning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import unicode_literals
class StackdioWarning(Warning):
pass
|
rcoscali/external-chromium-trace | refs/heads/master | trace-viewer/third_party/pywebsocket/src/mod_pywebsocket/util.py | 35 | # Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""WebSocket utilities.
"""
import array
import errno
# Import hash classes from a module available and recommended for each Python
# version and re-export those symbol. Use sha and md5 module in Python 2.4, and
# hashlib module in Python 2.6.
try:
import hashlib
md5_hash = hashlib.md5
sha1_hash = hashlib.sha1
except ImportError:
import md5
import sha
md5_hash = md5.md5
sha1_hash = sha.sha
import StringIO
import logging
import os
import re
import socket
import traceback
import zlib
def get_stack_trace():
"""Get the current stack trace as string.
This is needed to support Python 2.3.
TODO: Remove this when we only support Python 2.4 and above.
Use traceback.format_exc instead.
"""
out = StringIO.StringIO()
traceback.print_exc(file=out)
return out.getvalue()
def prepend_message_to_exception(message, exc):
"""Prepend message to the exception."""
exc.args = (message + str(exc),)
return
def __translate_interp(interp, cygwin_path):
"""Translate interp program path for Win32 python to run cygwin program
(e.g. perl). Note that it doesn't support path that contains space,
which is typically true for Unix, where #!-script is written.
For Win32 python, cygwin_path is a directory of cygwin binaries.
Args:
interp: interp command line
cygwin_path: directory name of cygwin binary, or None
Returns:
translated interp command line.
"""
if not cygwin_path:
return interp
m = re.match('^[^ ]*/([^ ]+)( .*)?', interp)
if m:
cmd = os.path.join(cygwin_path, m.group(1))
return cmd + m.group(2)
return interp
def get_script_interp(script_path, cygwin_path=None):
"""Gets #!-interpreter command line from the script.
It also fixes command path. When Cygwin Python is used, e.g. in WebKit,
it could run "/usr/bin/perl -wT hello.pl".
When Win32 Python is used, e.g. in Chromium, it couldn't. So, fix
"/usr/bin/perl" to "<cygwin_path>\perl.exe".
Args:
script_path: pathname of the script
cygwin_path: directory name of cygwin binary, or None
Returns:
#!-interpreter command line, or None if it is not #!-script.
"""
fp = open(script_path)
line = fp.readline()
fp.close()
m = re.match('^#!(.*)', line)
if m:
return __translate_interp(m.group(1), cygwin_path)
return None
def wrap_popen3_for_win(cygwin_path):
"""Wrap popen3 to support #!-script on Windows.
Args:
cygwin_path: path for cygwin binary if command path is needed to be
translated. None if no translation required.
"""
__orig_popen3 = os.popen3
def __wrap_popen3(cmd, mode='t', bufsize=-1):
cmdline = cmd.split(' ')
interp = get_script_interp(cmdline[0], cygwin_path)
if interp:
cmd = interp + ' ' + cmd
return __orig_popen3(cmd, mode, bufsize)
os.popen3 = __wrap_popen3
def hexify(s):
return ' '.join(map(lambda x: '%02x' % ord(x), s))
def get_class_logger(o):
return logging.getLogger(
'%s.%s' % (o.__class__.__module__, o.__class__.__name__))
class NoopMasker(object):
"""A masking object that has the same interface as RepeatedXorMasker but
just returns the string passed in without making any change.
"""
def __init__(self):
pass
def mask(self, s):
return s
class RepeatedXorMasker(object):
"""A masking object that applies XOR on the string given to mask method
with the masking bytes given to the constructor repeatedly. This object
remembers the position in the masking bytes the last mask method call
ended and resumes from that point on the next mask method call.
"""
def __init__(self, mask):
self._mask = map(ord, mask)
self._mask_size = len(self._mask)
self._count = 0
def mask(self, s):
result = array.array('B')
result.fromstring(s)
# Use temporary local variables to eliminate the cost to access
# attributes
count = self._count
mask = self._mask
mask_size = self._mask_size
for i in xrange(len(result)):
result[i] ^= mask[count]
count = (count + 1) % mask_size
self._count = count
return result.tostring()
class DeflateRequest(object):
"""A wrapper class for request object to intercept send and recv to perform
deflate compression and decompression transparently.
"""
def __init__(self, request):
self._request = request
self.connection = DeflateConnection(request.connection)
def __getattribute__(self, name):
if name in ('_request', 'connection'):
return object.__getattribute__(self, name)
return self._request.__getattribute__(name)
def __setattr__(self, name, value):
if name in ('_request', 'connection'):
return object.__setattr__(self, name, value)
return self._request.__setattr__(name, value)
# By making wbits option negative, we can suppress CMF/FLG (2 octet) and
# ADLER32 (4 octet) fields of zlib so that we can use zlib module just as
# deflate library. DICTID won't be added as far as we don't set dictionary.
# LZ77 window of 32K will be used for both compression and decompression.
# For decompression, we can just use 32K to cover any windows size. For
# compression, we use 32K so receivers must use 32K.
#
# Compression level is Z_DEFAULT_COMPRESSION. We don't have to match level
# to decode.
#
# See zconf.h, deflate.cc, inflate.cc of zlib library, and zlibmodule.c of
# Python. See also RFC1950 (ZLIB 3.3).
class _Deflater(object):
def __init__(self, window_bits):
self._logger = get_class_logger(self)
self._compress = zlib.compressobj(
zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -window_bits)
def compress_and_flush(self, bytes):
compressed_bytes = self._compress.compress(bytes)
compressed_bytes += self._compress.flush(zlib.Z_SYNC_FLUSH)
self._logger.debug('Compress input %r', bytes)
self._logger.debug('Compress result %r', compressed_bytes)
return compressed_bytes
class _Inflater(object):
def __init__(self):
self._logger = get_class_logger(self)
self._unconsumed = ''
self.reset()
def decompress(self, size):
if not (size == -1 or size > 0):
raise Exception('size must be -1 or positive')
data = ''
while True:
if size == -1:
data += self._decompress.decompress(self._unconsumed)
# See Python bug http://bugs.python.org/issue12050 to
# understand why the same code cannot be used for updating
# self._unconsumed for here and else block.
self._unconsumed = ''
else:
data += self._decompress.decompress(
self._unconsumed, size - len(data))
self._unconsumed = self._decompress.unconsumed_tail
if self._decompress.unused_data:
# Encountered a last block (i.e. a block with BFINAL = 1) and
# found a new stream (unused_data). We cannot use the same
# zlib.Decompress object for the new stream. Create a new
# Decompress object to decompress the new one.
#
# It's fine to ignore unconsumed_tail if unused_data is not
# empty.
self._unconsumed = self._decompress.unused_data
self.reset()
if size >= 0 and len(data) == size:
# data is filled. Don't call decompress again.
break
else:
# Re-invoke Decompress.decompress to try to decompress all
# available bytes before invoking read which blocks until
# any new byte is available.
continue
else:
# Here, since unused_data is empty, even if unconsumed_tail is
# not empty, bytes of requested length are already in data. We
# don't have to "continue" here.
break
if data:
self._logger.debug('Decompressed %r', data)
return data
def append(self, data):
self._logger.debug('Appended %r', data)
self._unconsumed += data
def reset(self):
self._logger.debug('Reset')
self._decompress = zlib.decompressobj(-zlib.MAX_WBITS)
# Compresses/decompresses given octets using the method introduced in RFC1979.
class _RFC1979Deflater(object):
"""A compressor class that applies DEFLATE to given byte sequence and
flushes using the algorithm described in the RFC1979 section 2.1.
"""
def __init__(self, window_bits, no_context_takeover):
self._deflater = None
if window_bits is None:
window_bits = zlib.MAX_WBITS
self._window_bits = window_bits
self._no_context_takeover = no_context_takeover
def filter(self, bytes):
if self._deflater is None or self._no_context_takeover:
self._deflater = _Deflater(self._window_bits)
# Strip last 4 octets which is LEN and NLEN field of a non-compressed
# block added for Z_SYNC_FLUSH.
return self._deflater.compress_and_flush(bytes)[:-4]
class _RFC1979Inflater(object):
"""A decompressor class for byte sequence compressed and flushed following
the algorithm described in the RFC1979 section 2.1.
"""
def __init__(self):
self._inflater = _Inflater()
def filter(self, bytes):
# Restore stripped LEN and NLEN field of a non-compressed block added
# for Z_SYNC_FLUSH.
self._inflater.append(bytes + '\x00\x00\xff\xff')
return self._inflater.decompress(-1)
class DeflateSocket(object):
"""A wrapper class for socket object to intercept send and recv to perform
deflate compression and decompression transparently.
"""
# Size of the buffer passed to recv to receive compressed data.
_RECV_SIZE = 4096
def __init__(self, socket):
self._socket = socket
self._logger = get_class_logger(self)
self._deflater = _Deflater(zlib.MAX_WBITS)
self._inflater = _Inflater()
def recv(self, size):
"""Receives data from the socket specified on the construction up
to the specified size. Once any data is available, returns it even
if it's smaller than the specified size.
"""
# TODO(tyoshino): Allow call with size=0. It should block until any
# decompressed data is available.
if size <= 0:
raise Exception('Non-positive size passed')
while True:
data = self._inflater.decompress(size)
if len(data) != 0:
return data
read_data = self._socket.recv(DeflateSocket._RECV_SIZE)
if not read_data:
return ''
self._inflater.append(read_data)
def sendall(self, bytes):
self.send(bytes)
def send(self, bytes):
self._socket.sendall(self._deflater.compress_and_flush(bytes))
return len(bytes)
class DeflateConnection(object):
"""A wrapper class for request object to intercept write and read to
perform deflate compression and decompression transparently.
"""
def __init__(self, connection):
self._connection = connection
self._logger = get_class_logger(self)
self._deflater = _Deflater(zlib.MAX_WBITS)
self._inflater = _Inflater()
def get_remote_addr(self):
return self._connection.remote_addr
remote_addr = property(get_remote_addr)
def put_bytes(self, bytes):
self.write(bytes)
def read(self, size=-1):
"""Reads at most size bytes. Blocks until there's at least one byte
available.
"""
# TODO(tyoshino): Allow call with size=0.
if not (size == -1 or size > 0):
raise Exception('size must be -1 or positive')
data = ''
while True:
if size == -1:
data += self._inflater.decompress(-1)
else:
data += self._inflater.decompress(size - len(data))
if size >= 0 and len(data) != 0:
break
# TODO(tyoshino): Make this read efficient by some workaround.
#
# In 3.0.3 and prior of mod_python, read blocks until length bytes
# was read. We don't know the exact size to read while using
# deflate, so read byte-by-byte.
#
# _StandaloneRequest.read that ultimately performs
# socket._fileobject.read also blocks until length bytes was read
read_data = self._connection.read(1)
if not read_data:
break
self._inflater.append(read_data)
return data
def write(self, bytes):
self._connection.write(self._deflater.compress_and_flush(bytes))
def _is_ewouldblock_errno(error_number):
"""Returns True iff error_number indicates that receive operation would
block. To make this portable, we check availability of errno and then
compare them.
"""
for error_name in ['WSAEWOULDBLOCK', 'EWOULDBLOCK', 'EAGAIN']:
if (error_name in dir(errno) and
error_number == getattr(errno, error_name)):
return True
return False
def drain_received_data(raw_socket):
# Set the socket non-blocking.
original_timeout = raw_socket.gettimeout()
raw_socket.settimeout(0.0)
drained_data = []
# Drain until the socket is closed or no data is immediately
# available for read.
while True:
try:
data = raw_socket.recv(1)
if not data:
break
drained_data.append(data)
except socket.error, e:
# e can be either a pair (errno, string) or just a string (or
# something else) telling what went wrong. We suppress only
# the errors that indicates that the socket blocks. Those
# exceptions can be parsed as a pair (errno, string).
try:
error_number, message = e
except:
# Failed to parse socket.error.
raise e
if _is_ewouldblock_errno(error_number):
break
else:
raise e
# Rollback timeout value.
raw_socket.settimeout(original_timeout)
return ''.join(drained_data)
# vi:sts=4 sw=4 et
|
Aerojspark/PyFR | refs/heads/develop | pyfr/backends/base/kernels.py | 1 | # -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import itertools as it
import types
from pyfr.util import memoize, proxylist
class _BaseKernel(object):
def __call__(self, *args, **kwargs):
return self, args, kwargs
@property
def retval(self):
return None
def run(self, queue, *args, **kwargs):
pass
class ComputeKernel(_BaseKernel):
ktype = 'compute'
class MPIKernel(_BaseKernel):
ktype = 'mpi'
class NullComputeKernel(ComputeKernel):
pass
class NullMPIKernel(MPIKernel):
pass
class _MetaKernel(object):
def __init__(self, kernels):
self._kernels = proxylist(kernels)
def run(self, queue, *args, **kwargs):
self._kernels.run(queue, *args, **kwargs)
class ComputeMetaKernel(_MetaKernel, ComputeKernel):
pass
class MPIMetaKernel(_MetaKernel, MPIKernel):
pass
class BaseKernelProvider(object):
def __init__(self, backend):
self.backend = backend
class BasePointwiseKernelProvider(BaseKernelProvider, metaclass=ABCMeta):
kernel_generator_cls = None
@memoize
def _render_kernel(self, name, mod, tplargs):
# Copy the provided argument list
tplargs = dict(tplargs)
# Backend-specfic generator classes
tplargs['_kernel_generator'] = self.kernel_generator_cls
# Macro definitions
tplargs['_macros'] = {}
# Backchannel for obtaining kernel argument types
tplargs['_kernel_argspecs'] = argspecs = {}
# Render the template to yield the source code
tpl = self.backend.lookup.get_template(mod)
src = tpl.render(**tplargs)
# Check the kernel exists in the template
if name not in argspecs:
raise ValueError('Kernel "{}" not defined in template'
.format(name))
# Extract the metadata for the kernel
ndim, argn, argt = argspecs[name]
return src, ndim, argn, argt
@abstractmethod
def _build_kernel(self, name, src, args):
pass
def _build_arglst(self, dims, argn, argt, argdict):
# Possible matrix types
mattypes = (
self.backend.const_matrix_cls, self.backend.matrix_cls,
self.backend.matrix_bank_cls, self.backend.matrix_rslice_cls,
self.backend.xchg_matrix_cls
)
# Possible view types
viewtypes = (self.backend.view_cls, self.backend.xchg_view_cls)
# First arguments are the iteration dimensions
ndim, arglst = len(dims), [int(d) for d in dims]
# Followed by the objects themselves
for aname, atypes in zip(argn[ndim:], argt[ndim:]):
try:
ka = argdict[aname]
except KeyError:
# Allow scalar arguments to be resolved at runtime
if len(atypes) == 1 and atypes[0] == self.backend.fpdtype:
ka = aname
else:
raise
# Matrix
if isinstance(ka, mattypes):
arglst += [ka, ka.leadsubdim] if len(atypes) == 2 else [ka]
# View
elif isinstance(ka, viewtypes):
if isinstance(ka, self.backend.view_cls):
view = ka
else:
view = ka.view
arglst += [view.basedata, view.mapping]
arglst += [view.cstrides] if len(atypes) >= 3 else []
arglst += [view.rstrides] if len(atypes) == 4 else []
# Other; let the backend handle it
else:
arglst.append(ka)
return arglst
@abstractmethod
def _instantiate_kernel(self, dims, fun, arglst):
pass
def register(self, mod):
# Derive the name of the kernel from the module
name = mod[mod.rfind('.') + 1:]
# See if a kernel has already been registered under this name
if hasattr(self, name):
# Same name different module
if getattr(self, name)._mod != mod:
raise RuntimeError('Attempt to re-register "{}" with a '
'different module'.format(name))
# Otherwise (since we're already registered) return
else:
return
# Generate the kernel providing method
def kernel_meth(self, tplargs, dims, **kwargs):
# Render the source of kernel
src, ndim, argn, argt = self._render_kernel(name, mod, tplargs)
# Compile the kernel
fun = self._build_kernel(name, src, list(it.chain(*argt)))
# Process the argument list
argb = self._build_arglst(dims, argn, argt, kwargs)
# Return a ComputeKernel subclass instance
return self._instantiate_kernel(dims, fun, argb)
# Attach the module to the method as an attribute
kernel_meth._mod = mod
# Bind
setattr(self, name, types.MethodType(kernel_meth, self))
class NotSuitableError(Exception):
pass
|
DarthMaulware/EquationGroupLeaks | refs/heads/master | Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/file/cmd/strings/data/__init__.py | 148 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
pass |
dfrey382/opencharity | refs/heads/master | node_modules/node-gyp/gyp/pylib/gyp/simple_copy.py | 1869 | # Copyright 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A clone of the default copy.deepcopy that doesn't handle cyclic
structures or complex types except for dicts and lists. This is
because gyp copies so large structure that small copy overhead ends up
taking seconds in a project the size of Chromium."""
class Error(Exception):
pass
__all__ = ["Error", "deepcopy"]
def deepcopy(x):
"""Deep copy operation on gyp objects such as strings, ints, dicts
and lists. More than twice as fast as copy.deepcopy but much less
generic."""
try:
return _deepcopy_dispatch[type(x)](x)
except KeyError:
raise Error('Unsupported type %s for deepcopy. Use copy.deepcopy ' +
'or expand simple_copy support.' % type(x))
_deepcopy_dispatch = d = {}
def _deepcopy_atomic(x):
return x
for x in (type(None), int, long, float,
bool, str, unicode, type):
d[x] = _deepcopy_atomic
def _deepcopy_list(x):
return [deepcopy(a) for a in x]
d[list] = _deepcopy_list
def _deepcopy_dict(x):
y = {}
for key, value in x.iteritems():
y[deepcopy(key)] = deepcopy(value)
return y
d[dict] = _deepcopy_dict
del d
|
maurofaccenda/ansible | refs/heads/devel | lib/ansible/modules/cloud/amazon/ec2_asg.py | 14 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
DOCUMENTATION = """
---
module: ec2_asg
short_description: Create or delete AWS Autoscaling Groups
description:
- Can create or delete AWS Autoscaling Groups
- Works with the ec2_lc module to manage Launch Configurations
version_added: "1.6"
author: "Gareth Rushgrove (@garethr)"
options:
state:
description:
- register or deregister the instance
required: false
choices: ['present', 'absent']
default: present
name:
description:
- Unique name for group to be created or deleted
required: true
load_balancers:
description:
- List of ELB names to use for the group
required: false
availability_zones:
description:
- List of availability zone names in which to create the group. Defaults to all the availability zones in the region if vpc_zone_identifier is not set.
required: false
launch_config_name:
description:
- Name of the Launch configuration to use for the group. See the ec2_lc module for managing these.
required: true
min_size:
description:
- Minimum number of instances in group, if unspecified then the current group value will be used.
required: false
max_size:
description:
- Maximum number of instances in group, if unspecified then the current group value will be used.
required: false
placement_group:
description:
- Physical location of your cluster placement group created in Amazon EC2.
required: false
version_added: "2.3"
default: None
desired_capacity:
description:
- Desired number of instances in group, if unspecified then the current group value will be used.
required: false
replace_all_instances:
description:
- In a rolling fashion, replace all instances with an old launch configuration with one from the current launch configuration.
required: false
version_added: "1.8"
default: False
replace_batch_size:
description:
- Number of instances you'd like to replace at a time. Used with replace_all_instances.
required: false
version_added: "1.8"
default: 1
replace_instances:
description:
- List of instance_ids belonging to the named ASG that you would like to terminate and be replaced with instances matching the current launch
configuration.
required: false
version_added: "1.8"
default: None
lc_check:
description:
- Check to make sure instances that are being replaced with replace_instances do not already have the current launch_config.
required: false
version_added: "1.8"
default: True
vpc_zone_identifier:
description:
- List of VPC subnets to use
required: false
default: None
tags:
description:
- A list of tags to add to the Auto Scale Group. Optional key is 'propagate_at_launch', which defaults to true.
required: false
default: None
version_added: "1.7"
health_check_period:
description:
- Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.
required: false
default: 500 seconds
version_added: "1.7"
health_check_type:
description:
- The service you want the health status from, Amazon EC2 or Elastic Load Balancer.
required: false
default: EC2
version_added: "1.7"
choices: ['EC2', 'ELB']
default_cooldown:
description:
- The number of seconds after a scaling activity completes before another can begin.
required: false
default: 300 seconds
version_added: "2.0"
wait_timeout:
description:
- how long before wait instances to become viable when replaced. Used in conjunction with instance_ids option.
default: 300
version_added: "1.8"
wait_for_instances:
description:
- Wait for the ASG instances to be in a ready state before exiting. If instances are behind an ELB, it will wait until the ELB determines all
instances have a lifecycle_state of "InService" and a health_status of "Healthy".
version_added: "1.9"
default: yes
required: False
termination_policies:
description:
- An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity.
- For 'Default', when used to create a new autoscaling group, the "Default"i value is used. When used to change an existent autoscaling group, the
current termination policies are maintained.
required: false
default: Default
choices: ['OldestInstance', 'NewestInstance', 'OldestLaunchConfiguration', 'ClosestToNextInstanceHour', 'Default']
version_added: "2.0"
notification_topic:
description:
- A SNS topic ARN to send auto scaling notifications to.
default: None
required: false
version_added: "2.2"
notification_types:
description:
- A list of auto scaling events to trigger notifications on.
default:
- 'autoscaling:EC2_INSTANCE_LAUNCH'
- 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR'
- 'autoscaling:EC2_INSTANCE_TERMINATE'
- 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR'
required: false
version_added: "2.2"
suspend_processes:
description:
- A list of scaling processes to suspend.
required: False
default: []
choices: ['Launch', 'Terminate', 'HealthCheck', 'ReplaceUnhealthy', 'AZRebalance', 'AlarmNotification', 'ScheduledActions', 'AddToLoadBalancer']
version_added: "2.3"
extends_documentation_fragment:
- aws
- ec2
"""
EXAMPLES = '''
# Basic configuration
- ec2_asg:
name: special
load_balancers: [ 'lb1', 'lb2' ]
availability_zones: [ 'eu-west-1a', 'eu-west-1b' ]
launch_config_name: 'lc-1'
min_size: 1
max_size: 10
desired_capacity: 5
vpc_zone_identifier: [ 'subnet-abcd1234', 'subnet-1a2b3c4d' ]
tags:
- environment: production
propagate_at_launch: no
# Rolling ASG Updates
# Below is an example of how to assign a new launch config to an ASG and terminate old instances.
#
# All instances in "myasg" that do not have the launch configuration named "my_new_lc" will be terminated in
# a rolling fashion with instances using the current launch configuration, "my_new_lc".
#
# This could also be considered a rolling deploy of a pre-baked AMI.
#
# If this is a newly created group, the instances will not be replaced since all instances
# will have the current launch configuration.
- name: create launch config
ec2_lc:
name: my_new_lc
image_id: ami-lkajsf
key_name: mykey
region: us-east-1
security_groups: sg-23423
instance_type: m1.small
assign_public_ip: yes
- ec2_asg:
name: myasg
launch_config_name: my_new_lc
health_check_period: 60
health_check_type: ELB
replace_all_instances: yes
min_size: 5
max_size: 5
desired_capacity: 5
region: us-east-1
# To only replace a couple of instances instead of all of them, supply a list
# to "replace_instances":
- ec2_asg:
name: myasg
launch_config_name: my_new_lc
health_check_period: 60
health_check_type: ELB
replace_instances:
- i-b345231
- i-24c2931
min_size: 5
max_size: 5
desired_capacity: 5
region: us-east-1
'''
import time
import logging as log
import traceback
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
log.getLogger('boto').setLevel(log.CRITICAL)
#log.basicConfig(filename='/tmp/ansible_ec2_asg.log',level=log.DEBUG, format='%(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
try:
import boto.ec2.autoscale
from boto.ec2.autoscale import AutoScaleConnection, AutoScalingGroup, Tag
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
ASG_ATTRIBUTES = ('availability_zones', 'default_cooldown', 'desired_capacity',
'health_check_period', 'health_check_type', 'launch_config_name',
'load_balancers', 'max_size', 'min_size', 'name', 'placement_group',
'termination_policies', 'vpc_zone_identifier')
INSTANCE_ATTRIBUTES = ('instance_id', 'health_status', 'lifecycle_state', 'launch_config_name')
def enforce_required_arguments(module):
''' As many arguments are not required for autoscale group deletion
they cannot be mandatory arguments for the module, so we enforce
them here '''
missing_args = []
for arg in ('min_size', 'max_size', 'launch_config_name'):
if module.params[arg] is None:
missing_args.append(arg)
if missing_args:
module.fail_json(msg="Missing required arguments for autoscaling group create/update: %s" % ",".join(missing_args))
def get_properties(autoscaling_group):
properties = dict((attr, getattr(autoscaling_group, attr)) for attr in ASG_ATTRIBUTES)
# Ugly hack to make this JSON-serializable. We take a list of boto Tag
# objects and replace them with a dict-representation. Needed because the
# tags are included in ansible's return value (which is jsonified)
if 'tags' in properties and isinstance(properties['tags'], list):
serializable_tags = {}
for tag in properties['tags']:
serializable_tags[tag.key] = [tag.value, tag.propagate_at_launch]
properties['tags'] = serializable_tags
properties['healthy_instances'] = 0
properties['in_service_instances'] = 0
properties['unhealthy_instances'] = 0
properties['pending_instances'] = 0
properties['viable_instances'] = 0
properties['terminating_instances'] = 0
instance_facts = {}
if autoscaling_group.instances:
properties['instances'] = [i.instance_id for i in autoscaling_group.instances]
for i in autoscaling_group.instances:
instance_facts[i.instance_id] = {'health_status': i.health_status,
'lifecycle_state': i.lifecycle_state,
'launch_config_name': i.launch_config_name }
if i.health_status == 'Healthy' and i.lifecycle_state == 'InService':
properties['viable_instances'] += 1
if i.health_status == 'Healthy':
properties['healthy_instances'] += 1
else:
properties['unhealthy_instances'] += 1
if i.lifecycle_state == 'InService':
properties['in_service_instances'] += 1
if i.lifecycle_state == 'Terminating':
properties['terminating_instances'] += 1
if i.lifecycle_state == 'Pending':
properties['pending_instances'] += 1
else:
properties['instances'] = []
properties['instance_facts'] = instance_facts
properties['load_balancers'] = autoscaling_group.load_balancers
if getattr(autoscaling_group, "tags", None):
properties['tags'] = dict((t.key, t.value) for t in autoscaling_group.tags)
return properties
def elb_dreg(asg_connection, module, group_name, instance_id):
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
as_group = asg_connection.get_all_groups(names=[group_name])[0]
wait_timeout = module.params.get('wait_timeout')
props = get_properties(as_group)
count = 1
if as_group.load_balancers and as_group.health_check_type == 'ELB':
try:
elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
else:
return
for lb in as_group.load_balancers:
elb_connection.deregister_instances(lb, instance_id)
log.debug("De-registering {0} from ELB {1}".format(instance_id, lb))
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and count > 0:
count = 0
for lb in as_group.load_balancers:
lb_instances = elb_connection.describe_instance_health(lb)
for i in lb_instances:
if i.instance_id == instance_id and i.state == "InService":
count += 1
log.debug("{0}: {1}, {2}".format(i.instance_id, i.state, i.description))
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for instance to deregister. {0}".format(time.asctime()))
def elb_healthy(asg_connection, elb_connection, module, group_name):
healthy_instances = set()
as_group = asg_connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
# get healthy, inservice instances from ASG
instances = []
for instance, settings in props['instance_facts'].items():
if settings['lifecycle_state'] == 'InService' and settings['health_status'] == 'Healthy':
instances.append(instance)
log.debug("ASG considers the following instances InService and Healthy: {0}".format(instances))
log.debug("ELB instance status:")
for lb in as_group.load_balancers:
# we catch a race condition that sometimes happens if the instance exists in the ASG
# but has not yet show up in the ELB
try:
lb_instances = elb_connection.describe_instance_health(lb, instances=instances)
except boto.exception.BotoServerError as e:
if e.error_code == 'InvalidInstance':
return None
module.fail_json(msg=str(e))
for i in lb_instances:
if i.state == "InService":
healthy_instances.add(i.instance_id)
log.debug("{0}: {1}".format(i.instance_id, i.state))
return len(healthy_instances)
def wait_for_elb(asg_connection, module, group_name):
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
wait_timeout = module.params.get('wait_timeout')
# if the health_check_type is ELB, we want to query the ELBs directly for instance
# status as to avoid health_check_grace period that is awarded to ASG instances
as_group = asg_connection.get_all_groups(names=[group_name])[0]
if as_group.load_balancers and as_group.health_check_type == 'ELB':
log.debug("Waiting for ELB to consider instances healthy.")
try:
elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
wait_timeout = time.time() + wait_timeout
healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name)
while healthy_instances < as_group.min_size and wait_timeout > time.time():
healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name)
log.debug("ELB thinks {0} instances are healthy.".format(healthy_instances))
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for ELB instances to be healthy. %s" % time.asctime())
log.debug("Waiting complete. ELB thinks {0} instances are healthy.".format(healthy_instances))
def suspend_processes(as_group, module):
suspend_processes = set(module.params.get('suspend_processes'))
try:
suspended_processes = set([p.process_name for p in as_group.suspended_processes])
except AttributeError:
# New ASG being created, no suspended_processes defined yet
suspended_processes = set()
if suspend_processes == suspended_processes:
return False
resume_processes = list(suspended_processes - suspend_processes)
if resume_processes:
as_group.resume_processes(resume_processes)
if suspend_processes:
as_group.suspend_processes(list(suspend_processes))
return True
def create_autoscaling_group(connection, module):
group_name = module.params.get('name')
load_balancers = module.params['load_balancers']
availability_zones = module.params['availability_zones']
launch_config_name = module.params.get('launch_config_name')
min_size = module.params['min_size']
max_size = module.params['max_size']
placement_group = module.params.get('placement_group')
desired_capacity = module.params.get('desired_capacity')
vpc_zone_identifier = module.params.get('vpc_zone_identifier')
set_tags = module.params.get('tags')
health_check_period = module.params.get('health_check_period')
health_check_type = module.params.get('health_check_type')
default_cooldown = module.params.get('default_cooldown')
wait_for_instances = module.params.get('wait_for_instances')
as_groups = connection.get_all_groups(names=[group_name])
wait_timeout = module.params.get('wait_timeout')
termination_policies = module.params.get('termination_policies')
notification_topic = module.params.get('notification_topic')
notification_types = module.params.get('notification_types')
if not vpc_zone_identifier and not availability_zones:
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
try:
ec2_connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
elif vpc_zone_identifier:
vpc_zone_identifier = ','.join(vpc_zone_identifier)
asg_tags = []
for tag in set_tags:
for k,v in tag.items():
if k !='propagate_at_launch':
asg_tags.append(Tag(key=k,
value=v,
propagate_at_launch=bool(tag.get('propagate_at_launch', True)),
resource_id=group_name))
if not as_groups:
if not vpc_zone_identifier and not availability_zones:
availability_zones = module.params['availability_zones'] = [zone.name for zone in ec2_connection.get_all_zones()]
enforce_required_arguments(module)
launch_configs = connection.get_all_launch_configurations(names=[launch_config_name])
if len(launch_configs) == 0:
module.fail_json(msg="No launch config found with name %s" % launch_config_name)
ag = AutoScalingGroup(
group_name=group_name,
load_balancers=load_balancers,
availability_zones=availability_zones,
launch_config=launch_configs[0],
min_size=min_size,
max_size=max_size,
placement_group=placement_group,
desired_capacity=desired_capacity,
vpc_zone_identifier=vpc_zone_identifier,
connection=connection,
tags=asg_tags,
health_check_period=health_check_period,
health_check_type=health_check_type,
default_cooldown=default_cooldown,
termination_policies=termination_policies)
try:
connection.create_auto_scaling_group(ag)
suspend_processes(ag, module)
if wait_for_instances:
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances')
wait_for_elb(connection, module, group_name)
if notification_topic:
ag.put_notification_configuration(notification_topic, notification_types)
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
changed = True
return(changed, asg_properties)
except BotoServerError as e:
module.fail_json(msg="Failed to create Autoscaling Group: %s" % str(e), exception=traceback.format_exc())
else:
as_group = as_groups[0]
changed = False
if suspend_processes(as_group, module):
changed = True
for attr in ASG_ATTRIBUTES:
if module.params.get(attr, None) is not None:
module_attr = module.params.get(attr)
if attr == 'vpc_zone_identifier':
module_attr = ','.join(module_attr)
group_attr = getattr(as_group, attr)
# we do this because AWS and the module may return the same list
# sorted differently
if attr != 'termination_policies':
try:
module_attr.sort()
except:
pass
try:
group_attr.sort()
except:
pass
if group_attr != module_attr:
changed = True
setattr(as_group, attr, module_attr)
if len(set_tags) > 0:
have_tags = {}
want_tags = {}
for tag in asg_tags:
want_tags[tag.key] = [tag.value, tag.propagate_at_launch]
dead_tags = []
if getattr(as_group, "tags", None):
for tag in as_group.tags:
have_tags[tag.key] = [tag.value, tag.propagate_at_launch]
if tag.key not in want_tags:
changed = True
dead_tags.append(tag)
elif getattr(as_group, "tags", None) is None and asg_tags:
module.warn("It appears your ASG is attached to a target group. This is a boto2 bug. Tags will be added but no tags are able to be removed.")
if dead_tags != []:
connection.delete_tags(dead_tags)
if have_tags != want_tags:
changed = True
connection.create_or_update_tags(asg_tags)
# handle loadbalancers separately because None != []
load_balancers = module.params.get('load_balancers') or []
if load_balancers and as_group.load_balancers != load_balancers:
changed = True
as_group.load_balancers = module.params.get('load_balancers')
if changed:
try:
as_group.update()
except BotoServerError as e:
module.fail_json(msg="Failed to update Autoscaling Group: %s" % str(e), exception=traceback.format_exc())
if notification_topic:
try:
as_group.put_notification_configuration(notification_topic, notification_types)
except BotoServerError as e:
module.fail_json(msg="Failed to update Autoscaling Group notifications: %s" % str(e), exception=traceback.format_exc())
if wait_for_instances:
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances')
wait_for_elb(connection, module, group_name)
try:
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
except BotoServerError as e:
module.fail_json(msg="Failed to read existing Autoscaling Groups: %s" % str(e), exception=traceback.format_exc())
return(changed, asg_properties)
def delete_autoscaling_group(connection, module):
group_name = module.params.get('name')
notification_topic = module.params.get('notification_topic')
wait_for_instances = module.params.get('wait_for_instances')
if notification_topic:
ag.delete_notification_configuration(notification_topic)
groups = connection.get_all_groups(names=[group_name])
if groups:
group = groups[0]
if not wait_for_instances:
group.delete(True)
return True
group.max_size = 0
group.min_size = 0
group.desired_capacity = 0
group.update()
instances = True
while instances:
tmp_groups = connection.get_all_groups(names=[group_name])
if tmp_groups:
tmp_group = tmp_groups[0]
if not tmp_group.instances:
instances = False
time.sleep(10)
group.delete()
while len(connection.get_all_groups(names=[group_name])):
time.sleep(5)
return True
return False
def get_chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
def update_size(group, max_size, min_size, dc):
log.debug("setting ASG sizes")
log.debug("minimum size: {0}, desired_capacity: {1}, max size: {2}".format(min_size, dc, max_size ))
group.max_size = max_size
group.min_size = min_size
group.desired_capacity = dc
group.update()
def replace(connection, module):
batch_size = module.params.get('replace_batch_size')
wait_timeout = module.params.get('wait_timeout')
group_name = module.params.get('name')
max_size = module.params.get('max_size')
min_size = module.params.get('min_size')
desired_capacity = module.params.get('desired_capacity')
lc_check = module.params.get('lc_check')
replace_instances = module.params.get('replace_instances')
as_group = connection.get_all_groups(names=[group_name])[0]
wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances')
props = get_properties(as_group)
instances = props['instances']
if replace_instances:
instances = replace_instances
#check if min_size/max_size/desired capacity have been specified and if not use ASG values
if min_size is None:
min_size = as_group.min_size
if max_size is None:
max_size = as_group.max_size
if desired_capacity is None:
desired_capacity = as_group.desired_capacity
# check to see if instances are replaceable if checking launch configs
new_instances, old_instances = get_instances_by_lc(props, lc_check, instances)
num_new_inst_needed = desired_capacity - len(new_instances)
if lc_check:
if num_new_inst_needed == 0 and old_instances:
log.debug("No new instances needed, but old instances are present. Removing old instances")
terminate_batch(connection, module, old_instances, instances, True)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
changed = True
return(changed, props)
# we don't want to spin up extra instances if not necessary
if num_new_inst_needed < batch_size:
log.debug("Overriding batch size to {0}".format(num_new_inst_needed))
batch_size = num_new_inst_needed
if not old_instances:
changed = False
return(changed, props)
# set temporary settings and wait for them to be reached
# This should get overwritten if the number of instances left is less than the batch size.
as_group = connection.get_all_groups(names=[group_name])[0]
update_size(as_group, max_size + batch_size, min_size + batch_size, desired_capacity + batch_size)
wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances')
wait_for_elb(connection, module, group_name)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
instances = props['instances']
if replace_instances:
instances = replace_instances
log.debug("beginning main loop")
for i in get_chunks(instances, batch_size):
# break out of this loop if we have enough new instances
break_early, desired_size, term_instances = terminate_batch(connection, module, i, instances, False)
wait_for_term_inst(connection, module, term_instances)
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, 'viable_instances')
wait_for_elb(connection, module, group_name)
as_group = connection.get_all_groups(names=[group_name])[0]
if break_early:
log.debug("breaking loop")
break
update_size(as_group, max_size, min_size, desired_capacity)
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
log.debug("Rolling update complete.")
changed=True
return(changed, asg_properties)
def get_instances_by_lc(props, lc_check, initial_instances):
new_instances = []
old_instances = []
# old instances are those that have the old launch config
if lc_check:
for i in props['instances']:
if props['instance_facts'][i]['launch_config_name'] == props['launch_config_name']:
new_instances.append(i)
else:
old_instances.append(i)
else:
log.debug("Comparing initial instances with current: {0}".format(initial_instances))
for i in props['instances']:
if i not in initial_instances:
new_instances.append(i)
else:
old_instances.append(i)
log.debug("New instances: {0}, {1}".format(len(new_instances), new_instances))
log.debug("Old instances: {0}, {1}".format(len(old_instances), old_instances))
return new_instances, old_instances
def list_purgeable_instances(props, lc_check, replace_instances, initial_instances):
instances_to_terminate = []
instances = ( inst_id for inst_id in replace_instances if inst_id in props['instances'])
# check to make sure instances given are actually in the given ASG
# and they have a non-current launch config
if lc_check:
for i in instances:
if props['instance_facts'][i]['launch_config_name'] != props['launch_config_name']:
instances_to_terminate.append(i)
else:
for i in instances:
if i in initial_instances:
instances_to_terminate.append(i)
return instances_to_terminate
def terminate_batch(connection, module, replace_instances, initial_instances, leftovers=False):
batch_size = module.params.get('replace_batch_size')
min_size = module.params.get('min_size')
desired_capacity = module.params.get('desired_capacity')
group_name = module.params.get('name')
wait_timeout = int(module.params.get('wait_timeout'))
lc_check = module.params.get('lc_check')
decrement_capacity = False
break_loop = False
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
desired_size = as_group.min_size
new_instances, old_instances = get_instances_by_lc(props, lc_check, initial_instances)
num_new_inst_needed = desired_capacity - len(new_instances)
# check to make sure instances given are actually in the given ASG
# and they have a non-current launch config
instances_to_terminate = list_purgeable_instances(props, lc_check, replace_instances, initial_instances)
log.debug("new instances needed: {0}".format(num_new_inst_needed))
log.debug("new instances: {0}".format(new_instances))
log.debug("old instances: {0}".format(old_instances))
log.debug("batch instances: {0}".format(",".join(instances_to_terminate)))
if num_new_inst_needed == 0:
decrement_capacity = True
if as_group.min_size != min_size:
as_group.min_size = min_size
as_group.update()
log.debug("Updating minimum size back to original of {0}".format(min_size))
#if are some leftover old instances, but we are already at capacity with new ones
# we don't want to decrement capacity
if leftovers:
decrement_capacity = False
break_loop = True
instances_to_terminate = old_instances
desired_size = min_size
log.debug("No new instances needed")
if num_new_inst_needed < batch_size and num_new_inst_needed !=0 :
instances_to_terminate = instances_to_terminate[:num_new_inst_needed]
decrement_capacity = False
break_loop = False
log.debug("{0} new instances needed".format(num_new_inst_needed))
log.debug("decrementing capacity: {0}".format(decrement_capacity))
for instance_id in instances_to_terminate:
elb_dreg(connection, module, group_name, instance_id)
log.debug("terminating instance: {0}".format(instance_id))
connection.terminate_instance(instance_id, decrement_capacity=decrement_capacity)
# we wait to make sure the machines we marked as Unhealthy are
# no longer in the list
return break_loop, desired_size, instances_to_terminate
def wait_for_term_inst(connection, module, term_instances):
batch_size = module.params.get('replace_batch_size')
wait_timeout = module.params.get('wait_timeout')
group_name = module.params.get('name')
lc_check = module.params.get('lc_check')
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
count = 1
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and count > 0:
log.debug("waiting for instances to terminate")
count = 0
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
instance_facts = props['instance_facts']
instances = ( i for i in instance_facts if i in term_instances)
for i in instances:
lifecycle = instance_facts[i]['lifecycle_state']
health = instance_facts[i]['health_status']
log.debug("Instance {0} has state of {1},{2}".format(i,lifecycle,health ))
if lifecycle == 'Terminating' or health == 'Unhealthy':
count += 1
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for old instances to terminate. %s" % time.asctime())
def wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, prop):
# make sure we have the latest stats after that last loop.
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop]))
# now we make sure that we have enough instances in a viable state
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and desired_size > props[prop]:
log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop]))
time.sleep(10)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for new instances to become viable. %s" % time.asctime())
log.debug("Reached {0}: {1}".format(prop, desired_size))
return props
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
name=dict(required=True, type='str'),
load_balancers=dict(type='list'),
availability_zones=dict(type='list'),
launch_config_name=dict(type='str'),
min_size=dict(type='int'),
max_size=dict(type='int'),
placement_group=dict(type='str'),
desired_capacity=dict(type='int'),
vpc_zone_identifier=dict(type='list'),
replace_batch_size=dict(type='int', default=1),
replace_all_instances=dict(type='bool', default=False),
replace_instances=dict(type='list', default=[]),
lc_check=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=300),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(type='list', default=[]),
health_check_period=dict(type='int', default=300),
health_check_type=dict(default='EC2', choices=['EC2', 'ELB']),
default_cooldown=dict(type='int', default=300),
wait_for_instances=dict(type='bool', default=True),
termination_policies=dict(type='list', default='Default'),
notification_topic=dict(type='str', default=None),
notification_types=dict(type='list', default=[
'autoscaling:EC2_INSTANCE_LAUNCH',
'autoscaling:EC2_INSTANCE_LAUNCH_ERROR',
'autoscaling:EC2_INSTANCE_TERMINATE',
'autoscaling:EC2_INSTANCE_TERMINATE_ERROR'
]),
suspend_processes=dict(type='list', default=[])
),
)
module = AnsibleModule(
argument_spec=argument_spec,
mutually_exclusive = [['replace_all_instances', 'replace_instances']]
)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
state = module.params.get('state')
replace_instances = module.params.get('replace_instances')
replace_all_instances = module.params.get('replace_all_instances')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
try:
connection = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params)
if not connection:
module.fail_json(msg="failed to connect to AWS for the given region: %s" % str(region))
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
changed = create_changed = replace_changed = False
if state == 'present':
create_changed, asg_properties=create_autoscaling_group(connection, module)
elif state == 'absent':
changed = delete_autoscaling_group(connection, module)
module.exit_json( changed = changed )
if replace_all_instances or replace_instances:
replace_changed, asg_properties=replace(connection, module)
if create_changed or replace_changed:
changed = True
module.exit_json( changed = changed, **asg_properties )
if __name__ == '__main__':
main()
|
Serag8/Bachelor | refs/heads/master | google_appengine/lib/django-1.5/django/conf/urls/shortcut.py | 205 | from django.conf.urls import patterns
urlpatterns = patterns('django.views',
(r'^(?P<content_type_id>\d+)/(?P<object_id>.*)/$', 'defaults.shortcut'),
)
|
dmitriy-serdyuk/fuel | refs/heads/master | fuel/bin/fuel_info.py | 19 | #!/usr/bin/env python
"""Fuel utility for extracting metadata."""
import argparse
import os
import h5py
message_prefix_template = 'Metadata for {}'
message_body_template = """
The command used to generate this file is
{}
Relevant versions are
H5PYDataset {}
fuel.converters {}
"""
def main(args=None):
"""Entry point for `fuel-info` script.
This function can also be imported and used from Python.
Parameters
----------
args : iterable, optional (default: None)
A list of arguments that will be passed to Fuel's information
utility. If this argument is not specified, `sys.argv[1:]` will
be used.
"""
parser = argparse.ArgumentParser(
description='Extracts metadata from a Fuel-converted HDF5 file.')
parser.add_argument("filename", help="HDF5 file to analyze")
args = parser.parse_args()
with h5py.File(args.filename, 'r') as h5file:
interface_version = h5file.attrs.get('h5py_interface_version', 'N/A')
fuel_convert_version = h5file.attrs.get('fuel_convert_version', 'N/A')
fuel_convert_command = h5file.attrs.get('fuel_convert_command', 'N/A')
message_prefix = message_prefix_template.format(
os.path.basename(args.filename))
message_body = message_body_template.format(
fuel_convert_command, interface_version, fuel_convert_version)
message = ''.join(['\n', message_prefix, '\n', '=' * len(message_prefix),
message_body])
print(message)
if __name__ == "__main__":
main()
|
benjaminjkraft/django | refs/heads/master | tests/defer_regress/models.py | 282 | """
Regression tests for defer() / only() behavior.
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Item(models.Model):
name = models.CharField(max_length=15)
text = models.TextField(default="xyzzy")
value = models.IntegerField()
other_value = models.IntegerField(default=0)
def __str__(self):
return self.name
class RelatedItem(models.Model):
item = models.ForeignKey(Item, models.CASCADE)
class ProxyRelated(RelatedItem):
class Meta:
proxy = True
class Child(models.Model):
name = models.CharField(max_length=10)
value = models.IntegerField()
@python_2_unicode_compatible
class Leaf(models.Model):
name = models.CharField(max_length=10)
child = models.ForeignKey(Child, models.CASCADE)
second_child = models.ForeignKey(Child, models.SET_NULL, related_name="other", null=True)
value = models.IntegerField(default=42)
def __str__(self):
return self.name
class ResolveThis(models.Model):
num = models.FloatField()
name = models.CharField(max_length=16)
class Proxy(Item):
class Meta:
proxy = True
@python_2_unicode_compatible
class SimpleItem(models.Model):
name = models.CharField(max_length=15)
value = models.IntegerField()
def __str__(self):
return self.name
class Feature(models.Model):
item = models.ForeignKey(SimpleItem, models.CASCADE)
class SpecialFeature(models.Model):
feature = models.ForeignKey(Feature, models.CASCADE)
class OneToOneItem(models.Model):
item = models.OneToOneField(Item, models.CASCADE, related_name="one_to_one_item")
name = models.CharField(max_length=15)
class ItemAndSimpleItem(models.Model):
item = models.ForeignKey(Item, models.CASCADE)
simple = models.ForeignKey(SimpleItem, models.CASCADE)
class Profile(models.Model):
profile1 = models.CharField(max_length=1000, default='profile1')
class Location(models.Model):
location1 = models.CharField(max_length=1000, default='location1')
class Request(models.Model):
profile = models.ForeignKey(Profile, models.SET_NULL, null=True, blank=True)
location = models.ForeignKey(Location, models.CASCADE)
items = models.ManyToManyField(Item)
request1 = models.CharField(default='request1', max_length=1000)
request2 = models.CharField(default='request2', max_length=1000)
request3 = models.CharField(default='request3', max_length=1000)
request4 = models.CharField(default='request4', max_length=1000)
class Base(models.Model):
text = models.TextField()
class Derived(Base):
other_text = models.TextField()
|
yokose-ks/edx-platform | refs/heads/gacco3/master | cms/djangoapps/contentstore/tests/test_transcripts_utils.py | 10 | # -*- coding: utf-8 -*-
""" Tests for transcripts_utils. """
import unittest
from uuid import uuid4
import copy
import textwrap
from mock import patch, Mock
from pymongo import MongoClient
from django.test.utils import override_settings
from django.conf import settings
from django.utils import translation
from nose.plugins.skip import SkipTest
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.contentstore.content import StaticContent
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.exceptions import NotFoundError
from xmodule.contentstore.django import contentstore, _CONTENTSTORE
from xmodule.video_module import transcripts_utils
from contentstore.tests.modulestore_config import TEST_MODULESTORE
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
class TestGenerateSubs(unittest.TestCase):
"""Tests for `generate_subs` function."""
def setUp(self):
self.source_subs = {
'start': [100, 200, 240, 390, 1000],
'end': [200, 240, 380, 1000, 1500],
'text': [
'subs #1',
'subs #2',
'subs #3',
'subs #4',
'subs #5'
]
}
def test_generate_subs_increase_speed(self):
subs = transcripts_utils.generate_subs(2, 1, self.source_subs)
self.assertDictEqual(
subs,
{
'start': [200, 400, 480, 780, 2000],
'end': [400, 480, 760, 2000, 3000],
'text': ['subs #1', 'subs #2', 'subs #3', 'subs #4', 'subs #5']
}
)
def test_generate_subs_decrease_speed_1(self):
subs = transcripts_utils.generate_subs(0.5, 1, self.source_subs)
self.assertDictEqual(
subs,
{
'start': [50, 100, 120, 195, 500],
'end': [100, 120, 190, 500, 750],
'text': ['subs #1', 'subs #2', 'subs #3', 'subs #4', 'subs #5']
}
)
def test_generate_subs_decrease_speed_2(self):
"""Test for correct devision during `generate_subs` process."""
subs = transcripts_utils.generate_subs(1, 2, self.source_subs)
self.assertDictEqual(
subs,
{
'start': [50, 100, 120, 195, 500],
'end': [100, 120, 190, 500, 750],
'text': ['subs #1', 'subs #2', 'subs #3', 'subs #4', 'subs #5']
}
)
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE, MODULESTORE=TEST_MODULESTORE)
class TestSaveSubsToStore(ModuleStoreTestCase):
"""Tests for `save_subs_to_store` function."""
org = 'MITx'
number = '999'
display_name = 'Test course'
def clear_subs_content(self):
"""Remove, if subtitles content exists."""
try:
content = contentstore().find(self.content_location)
contentstore().delete(content.get_id())
except NotFoundError:
pass
def setUp(self):
self.course = CourseFactory.create(
org=self.org, number=self.number, display_name=self.display_name)
self.subs = {
'start': [100, 200, 240, 390, 1000],
'end': [200, 240, 380, 1000, 1500],
'text': [
'subs #1',
'subs #2',
'subs #3',
'subs #4',
'subs #5'
]
}
self.subs_id = str(uuid4())
filename = 'subs_{0}.srt.sjson'.format(self.subs_id)
self.content_location = StaticContent.compute_location(
self.org, self.number, filename
)
# incorrect subs
self.unjsonable_subs = set([1]) # set can't be serialized
self.unjsonable_subs_id = str(uuid4())
filename_unjsonable = 'subs_{0}.srt.sjson'.format(self.unjsonable_subs_id)
self.content_location_unjsonable = StaticContent.compute_location(
self.org, self.number, filename_unjsonable
)
self.clear_subs_content()
def test_save_subs_to_store(self):
with self.assertRaises(NotFoundError):
contentstore().find(self.content_location)
result_location = transcripts_utils.save_subs_to_store(
self.subs,
self.subs_id,
self.course)
self.assertTrue(contentstore().find(self.content_location))
self.assertEqual(result_location, self.content_location)
def test_save_unjsonable_subs_to_store(self):
"""
Assures that subs, that can't be dumped, can't be found later.
"""
with self.assertRaises(NotFoundError):
contentstore().find(self.content_location_unjsonable)
with self.assertRaises(TypeError):
transcripts_utils.save_subs_to_store(
self.unjsonable_subs,
self.unjsonable_subs_id,
self.course)
with self.assertRaises(NotFoundError):
contentstore().find(self.content_location_unjsonable)
def tearDown(self):
self.clear_subs_content()
MongoClient().drop_database(TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'])
_CONTENTSTORE.clear()
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE, MODULESTORE=TEST_MODULESTORE)
class TestDownloadYoutubeSubs(ModuleStoreTestCase):
"""Tests for `download_youtube_subs` function."""
org = 'MITx'
number = '999'
display_name = 'Test course'
def clear_subs_content(self, youtube_subs):
"""Remove, if subtitles content exists."""
for subs_id in youtube_subs.values():
filename = 'subs_{0}.srt.sjson'.format(subs_id)
content_location = StaticContent.compute_location(
self.org, self.number, filename
)
try:
content = contentstore().find(content_location)
contentstore().delete(content.get_id())
except NotFoundError:
pass
def setUp(self):
self.course = CourseFactory.create(
org=self.org, number=self.number, display_name=self.display_name)
def tearDown(self):
MongoClient().drop_database(TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'])
_CONTENTSTORE.clear()
def test_success_downloading_subs(self):
response = textwrap.dedent("""<?xml version="1.0" encoding="utf-8" ?>
<transcript>
<text start="0" dur="0.27"></text>
<text start="0.27" dur="2.45">Test text 1.</text>
<text start="2.72">Test text 2.</text>
<text start="5.43" dur="1.73">Test text 3.</text>
</transcript>
""")
good_youtube_subs = {
0.5: 'good_id_1',
1.0: 'good_id_2',
2.0: 'good_id_3'
}
self.clear_subs_content(good_youtube_subs)
with patch('xmodule.video_module.transcripts_utils.requests.get') as mock_get:
mock_get.return_value = Mock(status_code=200, text=response, content=response)
# Check transcripts_utils.GetTranscriptsFromYouTubeException not thrown
transcripts_utils.download_youtube_subs(good_youtube_subs, self.course, settings)
mock_get.assert_any_call('http://video.google.com/timedtext', params={'lang': 'en', 'v': 'good_id_1'})
mock_get.assert_any_call('http://video.google.com/timedtext', params={'lang': 'en', 'v': 'good_id_2'})
mock_get.assert_any_call('http://video.google.com/timedtext', params={'lang': 'en', 'v': 'good_id_3'})
# Check assets status after importing subtitles.
for subs_id in good_youtube_subs.values():
filename = 'subs_{0}.srt.sjson'.format(subs_id)
content_location = StaticContent.compute_location(
self.org, self.number, filename
)
self.assertTrue(contentstore().find(content_location))
self.clear_subs_content(good_youtube_subs)
def test_subs_for_html5_vid_with_periods(self):
"""
This is to verify a fix whereby subtitle files uploaded against
a HTML5 video that contains periods in the name causes
incorrect subs name parsing
"""
html5_ids = transcripts_utils.get_html5_ids(['foo.mp4', 'foo.1.bar.mp4', 'foo/bar/baz.1.4.mp4', 'foo'])
self.assertEqual(4, len(html5_ids))
self.assertEqual(html5_ids[0], 'foo')
self.assertEqual(html5_ids[1], 'foo.1.bar')
self.assertEqual(html5_ids[2], 'baz.1.4')
self.assertEqual(html5_ids[3], 'foo')
@patch('xmodule.video_module.transcripts_utils.requests.get')
def test_fail_downloading_subs(self, mock_get):
mock_get.return_value = Mock(status_code=404, text='Error 404')
bad_youtube_subs = {
0.5: 'BAD_YOUTUBE_ID1',
1.0: 'BAD_YOUTUBE_ID2',
2.0: 'BAD_YOUTUBE_ID3'
}
self.clear_subs_content(bad_youtube_subs)
with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException):
transcripts_utils.download_youtube_subs(bad_youtube_subs, self.course, settings)
# Check assets status after importing subtitles.
for subs_id in bad_youtube_subs.values():
filename = 'subs_{0}.srt.sjson'.format(subs_id)
content_location = StaticContent.compute_location(
self.org, self.number, filename
)
with self.assertRaises(NotFoundError):
contentstore().find(content_location)
self.clear_subs_content(bad_youtube_subs)
def test_success_downloading_chinese_transcripts(self):
# Disabled 11/14/13
# This test is flakey because it performs an HTTP request on an external service
# Re-enable when `requests.get` is patched using `mock.patch`
raise SkipTest
good_youtube_subs = {
1.0: 'j_jEn79vS3g', # Chinese, utf-8
}
self.clear_subs_content(good_youtube_subs)
# Check transcripts_utils.GetTranscriptsFromYouTubeException not thrown
transcripts_utils.download_youtube_subs(good_youtube_subs, self.course, settings)
# Check assets status after importing subtitles.
for subs_id in good_youtube_subs.values():
filename = 'subs_{0}.srt.sjson'.format(subs_id)
content_location = StaticContent.compute_location(
self.org, self.number, filename
)
self.assertTrue(contentstore().find(content_location))
self.clear_subs_content(good_youtube_subs)
class TestGenerateSubsFromSource(TestDownloadYoutubeSubs):
"""Tests for `generate_subs_from_source` function."""
def test_success_generating_subs(self):
youtube_subs = {
0.5: 'JMD_ifUUfsU',
1.0: 'hI10vDNYz4M',
2.0: 'AKqURZnYqpk'
}
srt_filedata = textwrap.dedent("""
1
00:00:10,500 --> 00:00:13,000
Elephant's Dream
2
00:00:15,000 --> 00:00:18,000
At the left we can see...
""")
self.clear_subs_content(youtube_subs)
# Check transcripts_utils.TranscriptsGenerationException not thrown.
# Also checks that uppercase file extensions are supported.
transcripts_utils.generate_subs_from_source(youtube_subs, 'SRT', srt_filedata, self.course)
# Check assets status after importing subtitles.
for subs_id in youtube_subs.values():
filename = 'subs_{0}.srt.sjson'.format(subs_id)
content_location = StaticContent.compute_location(
self.org, self.number, filename
)
self.assertTrue(contentstore().find(content_location))
self.clear_subs_content(youtube_subs)
def test_fail_bad_subs_type(self):
youtube_subs = {
0.5: 'JMD_ifUUfsU',
1.0: 'hI10vDNYz4M',
2.0: 'AKqURZnYqpk'
}
srt_filedata = textwrap.dedent("""
1
00:00:10,500 --> 00:00:13,000
Elephant's Dream
2
00:00:15,000 --> 00:00:18,000
At the left we can see...
""")
with self.assertRaises(transcripts_utils.TranscriptsGenerationException) as cm:
transcripts_utils.generate_subs_from_source(youtube_subs, 'BAD_FORMAT', srt_filedata, self.course)
exception_message = cm.exception.message
self.assertEqual(exception_message, "We support only SubRip (*.srt) transcripts format.")
def test_fail_bad_subs_filedata(self):
youtube_subs = {
0.5: 'JMD_ifUUfsU',
1.0: 'hI10vDNYz4M',
2.0: 'AKqURZnYqpk'
}
srt_filedata = """BAD_DATA"""
with self.assertRaises(transcripts_utils.TranscriptsGenerationException) as cm:
transcripts_utils.generate_subs_from_source(youtube_subs, 'srt', srt_filedata, self.course)
exception_message = cm.exception.message
self.assertEqual(exception_message, "Something wrong with SubRip transcripts file during parsing.")
class TestGenerateSrtFromSjson(TestDownloadYoutubeSubs):
"""Tests for `generate_srt_from_sjson` function."""
def test_success_generating_subs(self):
sjson_subs = {
'start': [100, 200, 240, 390, 54000],
'end': [200, 240, 380, 1000, 78400],
'text': [
'subs #1',
'subs #2',
'subs #3',
'subs #4',
'subs #5'
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 1)
self.assertTrue(srt_subs)
expected_subs = [
'00:00:00,100 --> 00:00:00,200\nsubs #1',
'00:00:00,200 --> 00:00:00,240\nsubs #2',
'00:00:00,240 --> 00:00:00,380\nsubs #3',
'00:00:00,390 --> 00:00:01,000\nsubs #4',
'00:00:54,000 --> 00:01:18,400\nsubs #5',
]
for sub in expected_subs:
self.assertIn(sub, srt_subs)
def test_success_generating_subs_speed_up(self):
sjson_subs = {
'start': [100, 200, 240, 390, 54000],
'end': [200, 240, 380, 1000, 78400],
'text': [
'subs #1',
'subs #2',
'subs #3',
'subs #4',
'subs #5'
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 0.5)
self.assertTrue(srt_subs)
expected_subs = [
'00:00:00,050 --> 00:00:00,100\nsubs #1',
'00:00:00,100 --> 00:00:00,120\nsubs #2',
'00:00:00,120 --> 00:00:00,190\nsubs #3',
'00:00:00,195 --> 00:00:00,500\nsubs #4',
'00:00:27,000 --> 00:00:39,200\nsubs #5',
]
for sub in expected_subs:
self.assertIn(sub, srt_subs)
def test_success_generating_subs_speed_down(self):
sjson_subs = {
'start': [100, 200, 240, 390, 54000],
'end': [200, 240, 380, 1000, 78400],
'text': [
'subs #1',
'subs #2',
'subs #3',
'subs #4',
'subs #5'
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 2)
self.assertTrue(srt_subs)
expected_subs = [
'00:00:00,200 --> 00:00:00,400\nsubs #1',
'00:00:00,400 --> 00:00:00,480\nsubs #2',
'00:00:00,480 --> 00:00:00,760\nsubs #3',
'00:00:00,780 --> 00:00:02,000\nsubs #4',
'00:01:48,000 --> 00:02:36,800\nsubs #5',
]
for sub in expected_subs:
self.assertIn(sub, srt_subs)
def test_fail_generating_subs(self):
sjson_subs = {
'start': [100, 200],
'end': [100],
'text': [
'subs #1',
'subs #2'
]
}
srt_subs = transcripts_utils.generate_srt_from_sjson(sjson_subs, 1)
self.assertFalse(srt_subs)
class TestYoutubeTranscripts(unittest.TestCase):
"""
Tests for checking right datastructure returning when using youtube api.
"""
@patch('xmodule.video_module.transcripts_utils.requests.get')
def test_youtube_bad_status_code(self, mock_get):
mock_get.return_value = Mock(status_code=404, text='test')
youtube_id = 'bad_youtube_id'
with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException):
transcripts_utils.get_transcripts_from_youtube(youtube_id, settings, translation)
@patch('xmodule.video_module.transcripts_utils.requests.get')
def test_youtube_empty_text(self, mock_get):
mock_get.return_value = Mock(status_code=200, text='')
youtube_id = 'bad_youtube_id'
with self.assertRaises(transcripts_utils.GetTranscriptsFromYouTubeException):
transcripts_utils.get_transcripts_from_youtube(youtube_id, settings, translation)
def test_youtube_good_result(self):
response = textwrap.dedent("""<?xml version="1.0" encoding="utf-8" ?>
<transcript>
<text start="0" dur="0.27"></text>
<text start="0.27" dur="2.45">Test text 1.</text>
<text start="2.72">Test text 2.</text>
<text start="5.43" dur="1.73">Test text 3.</text>
</transcript>
""")
expected_transcripts = {
'start': [270, 2720, 5430],
'end': [2720, 2720, 7160],
'text': ['Test text 1.', 'Test text 2.', 'Test text 3.']
}
youtube_id = 'good_youtube_id'
with patch('xmodule.video_module.transcripts_utils.requests.get') as mock_get:
mock_get.return_value = Mock(status_code=200, text=response, content=response)
transcripts = transcripts_utils.get_transcripts_from_youtube(youtube_id, settings, translation)
self.assertEqual(transcripts, expected_transcripts)
mock_get.assert_called_with('http://video.google.com/timedtext', params={'lang': 'en', 'v': 'good_youtube_id'})
class TestTranscript(unittest.TestCase):
"""
Tests for Transcript class e.g. different transcript conversions.
"""
def setUp(self):
self.srt_transcript = textwrap.dedent("""\
0
00:00:10,500 --> 00:00:13,000
Elephant's Dream
1
00:00:15,000 --> 00:00:18,000
At the left we can see...
""")
self.sjson_transcript = textwrap.dedent("""\
{
"start": [
10500,
15000
],
"end": [
13000,
18000
],
"text": [
"Elephant's Dream",
"At the left we can see..."
]
}
""")
self.txt_transcript = u"Elephant's Dream\nAt the left we can see..."
def test_convert_srt_to_txt(self):
expected = self.txt_transcript
actual = transcripts_utils.Transcript.convert(self.srt_transcript, 'srt', 'txt')
self.assertEqual(actual, expected)
def test_convert_srt_to_srt(self):
expected = self.srt_transcript
actual = transcripts_utils.Transcript.convert(self.srt_transcript, 'srt', 'srt')
self.assertEqual(actual, expected)
def test_convert_sjson_to_txt(self):
expected = self.txt_transcript
actual = transcripts_utils.Transcript.convert(self.sjson_transcript, 'sjson', 'txt')
self.assertEqual(actual, expected)
def test_convert_sjson_to_srt(self):
expected = self.srt_transcript
actual = transcripts_utils.Transcript.convert(self.sjson_transcript, 'sjson', 'srt')
self.assertEqual(actual, expected)
def test_convert_srt_to_sjson(self):
with self.assertRaises(NotImplementedError):
transcripts_utils.Transcript.convert(self.srt_transcript, 'srt', 'sjson')
class TestSubsFilename(unittest.TestCase):
"""
Tests for subs_filename funtion.
"""
def test_unicode(self):
name = transcripts_utils.subs_filename(u"˙∆©ƒƒƒ")
self.assertEqual(name, u'subs_˙∆©ƒƒƒ.srt.sjson')
name = transcripts_utils.subs_filename(u"˙∆©ƒƒƒ", 'uk')
self.assertEqual(name, u'uk_subs_˙∆©ƒƒƒ.srt.sjson')
|
kokushozero/mifsaDBProject | refs/heads/master | web2py/applications/welcome/languages/zh-tw.py | 149 | # coding: utf8
{
'!langcode!': 'zh-cn',
'!langname!': '中文',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新" 是選擇性的條件式, 格式就像 "欄位1=\'值\'". 但是 JOIN 的資料不可以使用 update 或是 delete"',
'%s %%{row} deleted': '已刪除 %s 筆',
'%s %%{row} updated': '已更新 %s 筆',
'%s selected': '%s 已選擇',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'(something like "it-it")': '(格式類似 "zh-tw")',
'A new version of web2py is available': '新版的 web2py 已發行',
'A new version of web2py is available: %s': '新版的 web2py 已發行: %s',
'about': '關於',
'About': '關於',
'About application': '關於本應用程式',
'Access Control': 'Access Control',
'Admin is disabled because insecure channel': '管理功能(Admin)在不安全連線環境下自動關閉',
'Admin is disabled because unsecure channel': '管理功能(Admin)在不安全連線環境下自動關閉',
'Administrative Interface': 'Administrative Interface',
'Administrative interface': '點此處進入管理介面',
'Administrator Password:': '管理員密碼:',
'Ajax Recipes': 'Ajax Recipes',
'An error occured, please %s the page': 'An error occured, please %s the page',
'appadmin is disabled because insecure channel': '因為來自非安全通道,管理介面關閉',
'Are you sure you want to delete file "%s"?': '確定要刪除檔案"%s"?',
'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?',
'Are you sure you want to uninstall application "%s"': '確定要移除應用程式 "%s"',
'Are you sure you want to uninstall application "%s"?': '確定要移除應用程式 "%s"',
'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '注意: 登入管理帳號需要安全連線(HTTPS)或是在本機連線(localhost).',
'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '注意: 因為在測試模式不保證多執行緒安全性,也就是說不可以同時執行多個測試案例',
'ATTENTION: you cannot edit the running application!': '注意:不可編輯正在執行的應用程式!',
'Authentication': '驗證',
'Available Databases and Tables': '可提供的資料庫和資料表',
'Buy this book': 'Buy this book',
'cache': '快取記憶體',
'Cache': 'Cache',
'Cache Keys': 'Cache Keys',
'Cannot be empty': '不可空白',
'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': '無法編譯:應用程式中含有錯誤,請除錯後再試一次.',
'Change Password': '變更密碼',
'change password': '變更密碼',
'Check to delete': '打勾代表刪除',
'Check to delete:': '點選以示刪除:',
'Clear CACHE?': 'Clear CACHE?',
'Clear DISK': 'Clear DISK',
'Clear RAM': 'Clear RAM',
'Client IP': '客戶端網址(IP)',
'Community': 'Community',
'Components and Plugins': 'Components and Plugins',
'Controller': '控件',
'Controllers': '控件',
'Copyright': '版權所有',
'Create new application': '創建應用程式',
'Created By': 'Created By',
'Created On': 'Created On',
'Current request': '目前網路資料要求(request)',
'Current response': '目前網路資料回應(response)',
'Current session': '目前網路連線資訊(session)',
'customize me!': '請調整我!',
'data uploaded': '資料已上傳',
'Database': '資料庫',
'Database %s select': '已選擇 %s 資料庫',
'Date and Time': '日期和時間',
'db': 'db',
'DB Model': '資料庫模組',
'Delete': '刪除',
'Delete:': '刪除:',
'Demo': 'Demo',
'Deploy on Google App Engine': '配置到 Google App Engine',
'Deployment Recipes': 'Deployment Recipes',
'Description': '描述',
'DESIGN': '設計',
'design': '設計',
'Design for': '設計為了',
'DISK': 'DISK',
'Disk Cache Keys': 'Disk Cache Keys',
'Disk Cleared': 'Disk Cleared',
'Documentation': 'Documentation',
"Don't know what to do?": "Don't know what to do?",
'done!': '完成!',
'Download': 'Download',
'E-mail': '電子郵件',
'EDIT': '編輯',
'Edit': '編輯',
'Edit application': '編輯應用程式',
'Edit current record': '編輯當前紀錄',
'edit profile': '編輯設定檔',
'Edit Profile': '編輯設定檔',
'Edit This App': '編輯本應用程式',
'Editing file': '編輯檔案',
'Editing file "%s"': '編輯檔案"%s"',
'Email and SMS': 'Email and SMS',
'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g',
'Error logs for "%(app)s"': '"%(app)s"的錯誤紀錄',
'Errors': 'Errors',
'export as csv file': '以逗號分隔檔(csv)格式匯出',
'FAQ': 'FAQ',
'First name': '名',
'Forgot username?': 'Forgot username?',
'Forms and Validators': 'Forms and Validators',
'Free Applications': 'Free Applications',
'Functions with no doctests will result in [passed] tests.': '沒有 doctests 的函式會顯示 [passed].',
'Group ID': '群組編號',
'Groups': 'Groups',
'Hello World': '嗨! 世界',
'Home': 'Home',
'How did you get here?': 'How did you get here?',
'import': 'import',
'Import/Export': '匯入/匯出',
'Index': '索引',
'insert new': '插入新資料',
'insert new %s': '插入新資料 %s',
'Installed applications': '已安裝應用程式',
'Internal State': '內部狀態',
'Introduction': 'Introduction',
'Invalid action': '不合法的動作(action)',
'Invalid email': '不合法的電子郵件',
'Invalid Query': '不合法的查詢',
'invalid request': '不合法的網路要求(request)',
'Is Active': 'Is Active',
'Key': 'Key',
'Language files (static strings) updated': '語言檔已更新',
'Languages': '各國語言',
'Last name': '姓',
'Last saved on:': '最後儲存時間:',
'Layout': '網頁配置',
'Layout Plugins': 'Layout Plugins',
'Layouts': 'Layouts',
'License for': '軟體版權為',
'Live Chat': 'Live Chat',
'login': '登入',
'Login': '登入',
'Login to the Administrative Interface': '登入到管理員介面',
'logout': '登出',
'Logout': '登出',
'Lost Password': '密碼遺忘',
'Lost password?': 'Lost password?',
'Main Menu': '主選單',
'Manage Cache': 'Manage Cache',
'Menu Model': '選單模組(menu)',
'Models': '資料模組',
'Modified By': 'Modified By',
'Modified On': 'Modified On',
'Modules': '程式模組',
'My Sites': 'My Sites',
'Name': '名字',
'New Record': '新紀錄',
'new record inserted': '已插入新紀錄',
'next 100 rows': '往後 100 筆',
'NO': '否',
'No databases in this application': '這應用程式不含資料庫',
'Object or table name': 'Object or table name',
'Online examples': '點此處進入線上範例',
'or import from csv file': '或是從逗號分隔檔(CSV)匯入',
'Origin': '原文',
'Original/Translation': '原文/翻譯',
'Other Plugins': 'Other Plugins',
'Other Recipes': 'Other Recipes',
'Overview': 'Overview',
'Password': '密碼',
"Password fields don't match": '密碼欄不匹配',
'Peeking at file': '選擇檔案',
'Plugins': 'Plugins',
'Powered by': '基於以下技術構建:',
'Preface': 'Preface',
'previous 100 rows': '往前 100 筆',
'Python': 'Python',
'Query:': '查詢:',
'Quick Examples': 'Quick Examples',
'RAM': 'RAM',
'RAM Cache Keys': 'RAM Cache Keys',
'Ram Cleared': 'Ram Cleared',
'Recipes': 'Recipes',
'Record': '紀錄',
'record does not exist': '紀錄不存在',
'Record ID': '紀錄編號',
'Record id': '紀錄編號',
'Register': '註冊',
'register': '註冊',
'Registration identifier': 'Registration identifier',
'Registration key': '註冊金鑰',
'reload': 'reload',
'Remember me (for 30 days)': '記住我(30 天)',
'Reset Password key': '重設密碼',
'Resolve Conflict file': '解決衝突檔案',
'Role': '角色',
'Rows in Table': '在資料表裏的資料',
'Rows selected': '筆資料被選擇',
'Saved file hash:': '檔案雜湊值已紀錄:',
'Semantic': 'Semantic',
'Services': 'Services',
'Size of cache:': 'Size of cache:',
'state': '狀態',
'Static files': '靜態檔案',
'Statistics': 'Statistics',
'Stylesheet': '網頁風格檔',
'submit': 'submit',
'Submit': '傳送',
'Support': 'Support',
'Sure you want to delete this object?': '確定要刪除此物件?',
'Table': '資料表',
'Table name': '資料表名稱',
'Testing application': '測試中的應用程式',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"查詢"是一個像 "db.表1.欄位1==\'值\'" 的條件式. 以"db.表1.欄位1==db.表2.欄位2"方式則相當於執行 JOIN SQL.',
'The Core': 'The Core',
'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s',
'The Views': 'The Views',
'There are no controllers': '沒有控件(controllers)',
'There are no models': '沒有資料庫模組(models)',
'There are no modules': '沒有程式模組(modules)',
'There are no static files': '沒有靜態檔案',
'There are no translators, only default language is supported': '沒有翻譯檔,只支援原始語言',
'There are no views': '沒有視圖',
'This App': 'This App',
'This is the %(filename)s template': '這是%(filename)s檔案的樣板(template)',
'Ticket': '問題單',
'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)',
'Timestamp': '時間標記',
'Twitter': 'Twitter',
'Unable to check for upgrades': '無法做升級檢查',
'Unable to download': '無法下載',
'Unable to download app': '無法下載應用程式',
'unable to parse csv file': '無法解析逗號分隔檔(csv)',
'Update:': '更新:',
'Upload existing application': '更新存在的應用程式',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': '使用下列方式來組合更複雜的條件式, (...)&(...) 代表同時存在的條件, (...)|(...) 代表擇一的條件, ~(...)則代表反向條件.',
'User %(id)s Logged-in': '使用者 %(id)s 已登入',
'User %(id)s Registered': '使用者 %(id)s 已註冊',
'User ID': '使用者編號',
'Verify Password': '驗證密碼',
'Videos': 'Videos',
'View': '視圖',
'Views': '視圖',
'Welcome': 'Welcome',
'Welcome %s': '歡迎 %s',
'Welcome to web2py': '歡迎使用 web2py',
'Welcome to web2py!': 'Welcome to web2py!',
'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s',
'YES': '是',
'You are successfully running web2py': 'You are successfully running web2py',
'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs',
'You visited the url %s': 'You visited the url %s',
}
|
yencarnacion/jaikuengine | refs/heads/master | .google_appengine/lib/django-1.5/django/contrib/gis/tests/inspectapp/models.py | 312 | from django.contrib.gis.db import models
class AllOGRFields(models.Model):
f_decimal = models.FloatField()
f_float = models.FloatField()
f_int = models.IntegerField()
f_char = models.CharField(max_length=10)
f_date = models.DateField()
f_datetime = models.DateTimeField()
f_time = models.TimeField()
geom = models.PolygonField()
objects = models.GeoManager()
|
georgejhunt/olpc-kernel | refs/heads/xsce4.1 | scripts/gdb/linux/cpus.py | 997 | #
# gdb helper commands and functions for Linux kernel debugging
#
# per-cpu tools
#
# Copyright (c) Siemens AG, 2011-2013
#
# Authors:
# Jan Kiszka <jan.kiszka@siemens.com>
#
# This work is licensed under the terms of the GNU GPL version 2.
#
import gdb
from linux import tasks, utils
MAX_CPUS = 4096
def get_current_cpu():
if utils.get_gdbserver_type() == utils.GDBSERVER_QEMU:
return gdb.selected_thread().num - 1
elif utils.get_gdbserver_type() == utils.GDBSERVER_KGDB:
tid = gdb.selected_thread().ptid[2]
if tid > (0x100000000 - MAX_CPUS - 2):
return 0x100000000 - tid - 2
else:
return tasks.get_thread_info(tasks.get_task_by_pid(tid))['cpu']
else:
raise gdb.GdbError("Sorry, obtaining the current CPU is not yet "
"supported with this gdb server.")
def per_cpu(var_ptr, cpu):
if cpu == -1:
cpu = get_current_cpu()
if utils.is_target_arch("sparc:v9"):
offset = gdb.parse_and_eval(
"trap_block[{0}].__per_cpu_base".format(str(cpu)))
else:
try:
offset = gdb.parse_and_eval(
"__per_cpu_offset[{0}]".format(str(cpu)))
except gdb.error:
# !CONFIG_SMP case
offset = 0
pointer = var_ptr.cast(utils.get_long_type()) + offset
return pointer.cast(var_ptr.type).dereference()
cpu_mask = {}
def cpu_mask_invalidate(event):
global cpu_mask
cpu_mask = {}
gdb.events.stop.disconnect(cpu_mask_invalidate)
if hasattr(gdb.events, 'new_objfile'):
gdb.events.new_objfile.disconnect(cpu_mask_invalidate)
def cpu_list(mask_name):
global cpu_mask
mask = None
if mask_name in cpu_mask:
mask = cpu_mask[mask_name]
if mask is None:
mask = gdb.parse_and_eval(mask_name + ".bits")
if hasattr(gdb, 'events'):
cpu_mask[mask_name] = mask
gdb.events.stop.connect(cpu_mask_invalidate)
if hasattr(gdb.events, 'new_objfile'):
gdb.events.new_objfile.connect(cpu_mask_invalidate)
bits_per_entry = mask[0].type.sizeof * 8
num_entries = mask.type.sizeof * 8 / bits_per_entry
entry = -1
bits = 0
while True:
while bits == 0:
entry += 1
if entry == num_entries:
return
bits = mask[entry]
if bits != 0:
bit = 0
break
while bits & 1 == 0:
bits >>= 1
bit += 1
cpu = entry * bits_per_entry + bit
bits >>= 1
bit += 1
yield cpu
class PerCpu(gdb.Function):
"""Return per-cpu variable.
$lx_per_cpu("VAR"[, CPU]): Return the per-cpu variable called VAR for the
given CPU number. If CPU is omitted, the CPU of the current context is used.
Note that VAR has to be quoted as string."""
def __init__(self):
super(PerCpu, self).__init__("lx_per_cpu")
def invoke(self, var_name, cpu=-1):
var_ptr = gdb.parse_and_eval("&" + var_name.string())
return per_cpu(var_ptr, cpu)
PerCpu()
class LxCurrentFunc(gdb.Function):
"""Return current task.
$lx_current([CPU]): Return the per-cpu task variable for the given CPU
number. If CPU is omitted, the CPU of the current context is used."""
def __init__(self):
super(LxCurrentFunc, self).__init__("lx_current")
def invoke(self, cpu=-1):
var_ptr = gdb.parse_and_eval("¤t_task")
return per_cpu(var_ptr, cpu).dereference()
LxCurrentFunc()
|
noahchense/upm | refs/heads/master | examples/python/ina132.py | 16 | #!/usr/bin/python
# Author: Zion Orent <zorent@ics.com>
# Copyright (c) 2015 Intel Corporation.
#
# 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 to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import time, sys, signal, atexit
import pyupm_ina132 as upmIna132
# Tested with the INA132 Differential Amplifier Sensor module.
# Instantiate an INA132 on analog pin A0
myDifferentialAmplifier = upmIna132.INA132(0)
## Exit handlers ##
# This stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This lets you run code on exit,
# including functions from myDifferentialAmplifier
def exitHandler():
print "Exiting"
sys.exit(0)
# Register exit handlers
atexit.register(exitHandler)
signal.signal(signal.SIGINT, SIGINTHandler)
while(1):
print myDifferentialAmplifier.value()
time.sleep(1)
|
Reggad/gameEngines1 | refs/heads/master | Dependancies/SDL_ttf/external/freetype-2.4.12/src/tools/docmaker/docbeauty.py | 877 | #!/usr/bin/env python
#
# DocBeauty (c) 2003, 2004, 2008 David Turner <david@freetype.org>
#
# This program is used to beautify the documentation comments used
# in the FreeType 2 public headers.
#
from sources import *
from content import *
from utils import *
import utils
import sys, os, time, string, getopt
content_processor = ContentProcessor()
def beautify_block( block ):
if block.content:
content_processor.reset()
markups = content_processor.process_content( block.content )
text = []
first = 1
for markup in markups:
text.extend( markup.beautify( first ) )
first = 0
# now beautify the documentation "borders" themselves
lines = [" /*************************************************************************"]
for l in text:
lines.append( " *" + l )
lines.append( " */" )
block.lines = lines
def usage():
print "\nDocBeauty 0.1 Usage information\n"
print " docbeauty [options] file1 [file2 ...]\n"
print "using the following options:\n"
print " -h : print this page"
print " -b : backup original files with the 'orig' extension"
print ""
print " --backup : same as -b"
def main( argv ):
"""main program loop"""
global output_dir
try:
opts, args = getopt.getopt( sys.argv[1:], \
"hb", \
["help", "backup"] )
except getopt.GetoptError:
usage()
sys.exit( 2 )
if args == []:
usage()
sys.exit( 1 )
# process options
#
output_dir = None
do_backup = None
for opt in opts:
if opt[0] in ( "-h", "--help" ):
usage()
sys.exit( 0 )
if opt[0] in ( "-b", "--backup" ):
do_backup = 1
# create context and processor
source_processor = SourceProcessor()
# retrieve the list of files to process
file_list = make_file_list( args )
for filename in file_list:
source_processor.parse_file( filename )
for block in source_processor.blocks:
beautify_block( block )
new_name = filename + ".new"
ok = None
try:
file = open( new_name, "wt" )
for block in source_processor.blocks:
for line in block.lines:
file.write( line )
file.write( "\n" )
file.close()
except:
ok = 0
# if called from the command line
#
if __name__ == '__main__':
main( sys.argv )
# eof
|
alxgu/ansible | refs/heads/devel | lib/ansible/module_utils/network/ios/providers/cli/config/bgp/neighbors.py | 14 | #
# (c) 2019, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
import re
from ansible.module_utils.six import iteritems
from ansible.module_utils.network.common.utils import to_list
from ansible.module_utils.network.ios.providers.providers import CliProvider
class Neighbors(CliProvider):
def render(self, config=None, nbr_list=None):
commands = list()
safe_list = list()
if not nbr_list:
nbr_list = self.get_value('config.neighbors')
for item in nbr_list:
neighbor_commands = list()
context = 'neighbor %s' % item['neighbor']
cmd = '%s remote-as %s' % (context, item['remote_as'])
if not config or cmd not in config:
neighbor_commands.append(cmd)
for key, value in iteritems(item):
if value is not None:
meth = getattr(self, '_render_%s' % key, None)
if meth:
resp = meth(item, config)
if resp:
neighbor_commands.extend(to_list(resp))
commands.extend(neighbor_commands)
safe_list.append(context)
if self.params['operation'] == 'replace':
if config and safe_list:
commands.extend(self._negate_config(config, safe_list))
return commands
def _negate_config(self, config, safe_list=None):
commands = list()
matches = re.findall(r'(neighbor \S+)', config, re.M)
for item in set(matches).difference(safe_list):
commands.append('no %s' % item)
return commands
def _render_local_as(self, item, config=None):
cmd = 'neighbor %s local-as %s' % (item['neighbor'], item['local_as'])
if not config or cmd not in config:
return cmd
def _render_port(self, item, config=None):
cmd = 'neighbor %s port %s' % (item['neighbor'], item['port'])
if not config or cmd not in config:
return cmd
def _render_description(self, item, config=None):
cmd = 'neighbor %s description %s' % (item['neighbor'], item['description'])
if not config or cmd not in config:
return cmd
def _render_enabled(self, item, config=None):
cmd = 'neighbor %s shutdown' % item['neighbor']
if item['enabled'] is True:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_update_source(self, item, config=None):
cmd = 'neighbor %s update-source %s' % (item['neighbor'], item['update_source'])
if not config or cmd not in config:
return cmd
def _render_password(self, item, config=None):
cmd = 'neighbor %s password %s' % (item['neighbor'], item['password'])
if not config or cmd not in config:
return cmd
def _render_ebgp_multihop(self, item, config=None):
cmd = 'neighbor %s ebgp-multihop %s' % (item['neighbor'], item['ebgp_multihop'])
if not config or cmd not in config:
return cmd
def _render_peer_group(self, item, config=None):
cmd = 'neighbor %s peer-group %s' % (item['neighbor'], item['peer_group'])
if not config or cmd not in config:
return cmd
def _render_timers(self, item, config):
"""generate bgp timer related configuration
"""
keepalive = item['timers']['keepalive']
holdtime = item['timers']['holdtime']
min_neighbor_holdtime = item['timers']['min_neighbor_holdtime']
neighbor = item['neighbor']
if keepalive and holdtime:
cmd = 'neighbor %s timers %s %s' % (neighbor, keepalive, holdtime)
if min_neighbor_holdtime:
cmd += ' %s' % min_neighbor_holdtime
if not config or cmd not in config:
return cmd
class AFNeighbors(CliProvider):
def render(self, config=None, nbr_list=None):
commands = list()
if not nbr_list:
return
for item in nbr_list:
neighbor_commands = list()
for key, value in iteritems(item):
if value is not None:
meth = getattr(self, '_render_%s' % key, None)
if meth:
resp = meth(item, config)
if resp:
neighbor_commands.extend(to_list(resp))
commands.extend(neighbor_commands)
return commands
def _render_advertisement_interval(self, item, config=None):
cmd = 'neighbor %s advertisement-interval %s' % (item['neighbor'], item['advertisement_interval'])
if not config or cmd not in config:
return cmd
def _render_route_reflector_client(self, item, config=None):
cmd = 'neighbor %s route-reflector-client' % item['neighbor']
if item['route_reflector_client'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_route_server_client(self, item, config=None):
cmd = 'neighbor %s route-server-client' % item['neighbor']
if item['route_server_client'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_remove_private_as(self, item, config=None):
cmd = 'neighbor %s remove-private-as' % item['neighbor']
if item['remove_private_as'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_next_hop_self(self, item, config=None):
cmd = 'neighbor %s activate' % item['neighbor']
if item['next_hop_self'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_activate(self, item, config=None):
cmd = 'neighbor %s activate' % item['neighbor']
if item['activate'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_maximum_prefix(self, item, config=None):
cmd = 'neighbor %s maximum-prefix %s' % (item['neighbor'], item['maximum_prefix'])
if not config or cmd not in config:
return cmd
|
ashishlal/pjproject-2.0.1 | refs/heads/master | tests/pjsua/scripts-recvfrom/203_reg_good_empty_realm.py | 58 | # $Id: 203_reg_good_empty_realm.py 3150 2010-04-29 00:23:43Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
pjsua = "--null-audio --id=sip:CLIENT --registrar sip:127.0.0.1:$PORT " + \
"--realm=* --user=username --password=password " + \
"--auto-update-nat=0"
# 401 Response, missing realm value
req1 = sip.RecvfromTransaction("Initial request", 401,
include=["REGISTER sip"],
exclude=[],
resp_hdr=['WWW-Authenticate: Digest']
)
# Client should retry, we giving it another 401 with empty realm
req2 = sip.RecvfromTransaction("REGISTER retry #1 of 2", 407,
include=["REGISTER sip"],
exclude=[],
resp_hdr=['Proxy-Authenticate: Digest realm=""']
)
# Client should retry
req3 = sip.RecvfromTransaction("REGISTER retry #2 of 2", 200,
include=[],
exclude=[],
expect="registration success"
)
recvfrom_cfg = sip.RecvfromCfg("Registration with empty realm",
pjsua, [req1, req2, req3])
|
fafaman/django | refs/heads/master | django/contrib/gis/db/models/functions.py | 209 | from decimal import Decimal
from django.contrib.gis.db.models.fields import GeometryField
from django.contrib.gis.db.models.sql import AreaField
from django.contrib.gis.geos.geometry import GEOSGeometry
from django.contrib.gis.measure import (
Area as AreaMeasure, Distance as DistanceMeasure,
)
from django.core.exceptions import FieldError
from django.db.models import FloatField, IntegerField, TextField
from django.db.models.expressions import Func, Value
from django.utils import six
NUMERIC_TYPES = six.integer_types + (float, Decimal)
class GeoFunc(Func):
function = None
output_field_class = None
geom_param_pos = 0
def __init__(self, *expressions, **extra):
if 'output_field' not in extra and self.output_field_class:
extra['output_field'] = self.output_field_class()
super(GeoFunc, self).__init__(*expressions, **extra)
@property
def name(self):
return self.__class__.__name__
@property
def srid(self):
expr = self.source_expressions[self.geom_param_pos]
if hasattr(expr, 'srid'):
return expr.srid
try:
return expr.field.srid
except (AttributeError, FieldError):
return None
def as_sql(self, compiler, connection):
if self.function is None:
self.function = connection.ops.spatial_function_name(self.name)
return super(GeoFunc, self).as_sql(compiler, connection)
def resolve_expression(self, *args, **kwargs):
res = super(GeoFunc, self).resolve_expression(*args, **kwargs)
base_srid = res.srid
if not base_srid:
raise TypeError("Geometry functions can only operate on geometric content.")
for pos, expr in enumerate(res.source_expressions[1:], start=1):
if isinstance(expr, GeomValue) and expr.srid != base_srid:
# Automatic SRID conversion so objects are comparable
res.source_expressions[pos] = Transform(expr, base_srid).resolve_expression(*args, **kwargs)
return res
def _handle_param(self, value, param_name='', check_types=None):
if not hasattr(value, 'resolve_expression'):
if check_types and not isinstance(value, check_types):
raise TypeError(
"The %s parameter has the wrong type: should be %s." % (
param_name, str(check_types))
)
return value
class GeomValue(Value):
geography = False
@property
def srid(self):
return self.value.srid
def as_sql(self, compiler, connection):
if self.geography:
self.value = connection.ops.Adapter(self.value, geography=self.geography)
else:
self.value = connection.ops.Adapter(self.value)
return super(GeomValue, self).as_sql(compiler, connection)
def as_mysql(self, compiler, connection):
return 'GeomFromText(%%s, %s)' % self.srid, [connection.ops.Adapter(self.value)]
def as_sqlite(self, compiler, connection):
return 'GeomFromText(%%s, %s)' % self.srid, [connection.ops.Adapter(self.value)]
class GeoFuncWithGeoParam(GeoFunc):
def __init__(self, expression, geom, *expressions, **extra):
if not hasattr(geom, 'srid'):
# Try to interpret it as a geometry input
try:
geom = GEOSGeometry(geom)
except Exception:
raise ValueError("This function requires a geometric parameter.")
if not geom.srid:
raise ValueError("Please provide a geometry attribute with a defined SRID.")
geom = GeomValue(geom)
super(GeoFuncWithGeoParam, self).__init__(expression, geom, *expressions, **extra)
class SQLiteDecimalToFloatMixin(object):
"""
By default, Decimal values are converted to str by the SQLite backend, which
is not acceptable by the GIS functions expecting numeric values.
"""
def as_sqlite(self, compiler, connection):
for expr in self.get_source_expressions():
if hasattr(expr, 'value') and isinstance(expr.value, Decimal):
expr.value = float(expr.value)
return super(SQLiteDecimalToFloatMixin, self).as_sql(compiler, connection)
class Area(GeoFunc):
def as_sql(self, compiler, connection):
if connection.ops.oracle:
self.output_field = AreaField('sq_m') # Oracle returns area in units of meters.
else:
if connection.ops.geography:
# Geography fields support area calculation, returns square meters.
self.output_field = AreaField('sq_m')
elif not self.output_field.geodetic(connection):
# Getting the area units of the geographic field.
units = self.output_field.units_name(connection)
if units:
self.output_field = AreaField(
AreaMeasure.unit_attname(self.output_field.units_name(connection)))
else:
self.output_field = FloatField()
else:
# TODO: Do we want to support raw number areas for geodetic fields?
raise NotImplementedError('Area on geodetic coordinate systems not supported.')
return super(Area, self).as_sql(compiler, connection)
class AsGeoJSON(GeoFunc):
output_field_class = TextField
def __init__(self, expression, bbox=False, crs=False, precision=8, **extra):
expressions = [expression]
if precision is not None:
expressions.append(self._handle_param(precision, 'precision', six.integer_types))
options = 0
if crs and bbox:
options = 3
elif bbox:
options = 1
elif crs:
options = 2
if options:
expressions.append(options)
super(AsGeoJSON, self).__init__(*expressions, **extra)
class AsGML(GeoFunc):
geom_param_pos = 1
output_field_class = TextField
def __init__(self, expression, version=2, precision=8, **extra):
expressions = [version, expression]
if precision is not None:
expressions.append(self._handle_param(precision, 'precision', six.integer_types))
super(AsGML, self).__init__(*expressions, **extra)
class AsKML(AsGML):
def as_sqlite(self, compiler, connection):
# No version parameter
self.source_expressions.pop(0)
return super(AsKML, self).as_sql(compiler, connection)
class AsSVG(GeoFunc):
output_field_class = TextField
def __init__(self, expression, relative=False, precision=8, **extra):
relative = relative if hasattr(relative, 'resolve_expression') else int(relative)
expressions = [
expression,
relative,
self._handle_param(precision, 'precision', six.integer_types),
]
super(AsSVG, self).__init__(*expressions, **extra)
class BoundingCircle(GeoFunc):
def __init__(self, expression, num_seg=48, **extra):
super(BoundingCircle, self).__init__(*[expression, num_seg], **extra)
class Centroid(GeoFunc):
pass
class Difference(GeoFuncWithGeoParam):
pass
class DistanceResultMixin(object):
def convert_value(self, value, expression, connection, context):
if value is None:
return None
geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info
if geo_field.geodetic(connection):
dist_att = 'm'
else:
units = geo_field.units_name(connection)
if units:
dist_att = DistanceMeasure.unit_attname(units)
else:
dist_att = None
if dist_att:
return DistanceMeasure(**{dist_att: value})
return value
class Distance(DistanceResultMixin, GeoFuncWithGeoParam):
output_field_class = FloatField
spheroid = None
def __init__(self, expr1, expr2, spheroid=None, **extra):
expressions = [expr1, expr2]
if spheroid is not None:
self.spheroid = spheroid
expressions += (self._handle_param(spheroid, 'spheroid', bool),)
super(Distance, self).__init__(*expressions, **extra)
def as_postgresql(self, compiler, connection):
geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info
src_field = self.get_source_fields()[0]
geography = src_field.geography and self.srid == 4326
if geography:
# Set parameters as geography if base field is geography
for pos, expr in enumerate(
self.source_expressions[self.geom_param_pos + 1:], start=self.geom_param_pos + 1):
if isinstance(expr, GeomValue):
expr.geography = True
elif geo_field.geodetic(connection):
# Geometry fields with geodetic (lon/lat) coordinates need special distance functions
if self.spheroid:
self.function = 'ST_Distance_Spheroid' # More accurate, resource intensive
# Replace boolean param by the real spheroid of the base field
self.source_expressions[2] = Value(geo_field._spheroid)
else:
self.function = 'ST_Distance_Sphere'
return super(Distance, self).as_sql(compiler, connection)
class Envelope(GeoFunc):
pass
class ForceRHR(GeoFunc):
pass
class GeoHash(GeoFunc):
output_field_class = TextField
def __init__(self, expression, precision=None, **extra):
expressions = [expression]
if precision is not None:
expressions.append(self._handle_param(precision, 'precision', six.integer_types))
super(GeoHash, self).__init__(*expressions, **extra)
class Intersection(GeoFuncWithGeoParam):
pass
class Length(DistanceResultMixin, GeoFunc):
output_field_class = FloatField
def __init__(self, expr1, spheroid=True, **extra):
self.spheroid = spheroid
super(Length, self).__init__(expr1, **extra)
def as_sql(self, compiler, connection):
geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info
if geo_field.geodetic(connection) and not connection.features.supports_length_geodetic:
raise NotImplementedError("This backend doesn't support Length on geodetic fields")
return super(Length, self).as_sql(compiler, connection)
def as_postgresql(self, compiler, connection):
geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info
src_field = self.get_source_fields()[0]
geography = src_field.geography and self.srid == 4326
if geography:
self.source_expressions.append(Value(self.spheroid))
elif geo_field.geodetic(connection):
# Geometry fields with geodetic (lon/lat) coordinates need length_spheroid
self.function = 'ST_Length_Spheroid'
self.source_expressions.append(Value(geo_field._spheroid))
else:
dim = min(f.dim for f in self.get_source_fields() if f)
if dim > 2:
self.function = connection.ops.length3d
return super(Length, self).as_sql(compiler, connection)
def as_sqlite(self, compiler, connection):
geo_field = GeometryField(srid=self.srid)
if geo_field.geodetic(connection):
if self.spheroid:
self.function = 'GeodesicLength'
else:
self.function = 'GreatCircleLength'
return super(Length, self).as_sql(compiler, connection)
class MemSize(GeoFunc):
output_field_class = IntegerField
class NumGeometries(GeoFunc):
output_field_class = IntegerField
class NumPoints(GeoFunc):
output_field_class = IntegerField
def as_sqlite(self, compiler, connection):
if self.source_expressions[self.geom_param_pos].output_field.geom_type != 'LINESTRING':
raise TypeError("Spatialite NumPoints can only operate on LineString content")
return super(NumPoints, self).as_sql(compiler, connection)
class Perimeter(DistanceResultMixin, GeoFunc):
output_field_class = FloatField
def as_postgresql(self, compiler, connection):
dim = min(f.dim for f in self.get_source_fields())
if dim > 2:
self.function = connection.ops.perimeter3d
return super(Perimeter, self).as_sql(compiler, connection)
class PointOnSurface(GeoFunc):
pass
class Reverse(GeoFunc):
pass
class Scale(SQLiteDecimalToFloatMixin, GeoFunc):
def __init__(self, expression, x, y, z=0.0, **extra):
expressions = [
expression,
self._handle_param(x, 'x', NUMERIC_TYPES),
self._handle_param(y, 'y', NUMERIC_TYPES),
]
if z != 0.0:
expressions.append(self._handle_param(z, 'z', NUMERIC_TYPES))
super(Scale, self).__init__(*expressions, **extra)
class SnapToGrid(SQLiteDecimalToFloatMixin, GeoFunc):
def __init__(self, expression, *args, **extra):
nargs = len(args)
expressions = [expression]
if nargs in (1, 2):
expressions.extend(
[self._handle_param(arg, '', NUMERIC_TYPES) for arg in args]
)
elif nargs == 4:
# Reverse origin and size param ordering
expressions.extend(
[self._handle_param(arg, '', NUMERIC_TYPES) for arg in args[2:]]
)
expressions.extend(
[self._handle_param(arg, '', NUMERIC_TYPES) for arg in args[0:2]]
)
else:
raise ValueError('Must provide 1, 2, or 4 arguments to `SnapToGrid`.')
super(SnapToGrid, self).__init__(*expressions, **extra)
class SymDifference(GeoFuncWithGeoParam):
pass
class Transform(GeoFunc):
def __init__(self, expression, srid, **extra):
expressions = [
expression,
self._handle_param(srid, 'srid', six.integer_types),
]
super(Transform, self).__init__(*expressions, **extra)
@property
def srid(self):
# Make srid the resulting srid of the transformation
return self.source_expressions[self.geom_param_pos + 1].value
def convert_value(self, value, expression, connection, context):
value = super(Transform, self).convert_value(value, expression, connection, context)
if not connection.ops.postgis and not value.srid:
# Some backends do not set the srid on the returning geometry
value.srid = self.srid
return value
class Translate(Scale):
def as_sqlite(self, compiler, connection):
func_name = connection.ops.spatial_function_name(self.name)
if func_name == 'ST_Translate' and len(self.source_expressions) < 4:
# Always provide the z parameter for ST_Translate (Spatialite >= 3.1)
self.source_expressions.append(Value(0))
elif func_name == 'ShiftCoords' and len(self.source_expressions) > 3:
raise ValueError("This version of Spatialite doesn't support 3D")
return super(Translate, self).as_sqlite(compiler, connection)
class Union(GeoFuncWithGeoParam):
pass
|
rven/odoo | refs/heads/14.0-fix-partner-merge-mail-activity | addons/repair/models/account_move.py | 2 | # -*- coding: utf-8 -*-
from odoo import models, fields
class AccountMove(models.Model):
_inherit = 'account.move'
repair_ids = fields.One2many('repair.order', 'invoice_id', readonly=True, copy=False)
def unlink(self):
repairs = self.sudo().repair_ids.filtered(lambda repair: repair.state != 'cancel')
if repairs:
repairs.sudo(False).state = '2binvoiced'
return super().unlink()
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
repair_line_ids = fields.One2many('repair.line', 'invoice_line_id', readonly=True, copy=False)
repair_fee_ids = fields.One2many('repair.fee', 'invoice_line_id', readonly=True, copy=False)
|
alexgorban/models | refs/heads/master | research/textsum/data.py | 23 | # Copyright 2016 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Data batchers for data described in ..//data_prep/README.md."""
import glob
import random
import struct
import sys
from tensorflow.core.example import example_pb2
# Special tokens
PARAGRAPH_START = '<p>'
PARAGRAPH_END = '</p>'
SENTENCE_START = '<s>'
SENTENCE_END = '</s>'
UNKNOWN_TOKEN = '<UNK>'
PAD_TOKEN = '<PAD>'
DOCUMENT_START = '<d>'
DOCUMENT_END = '</d>'
class Vocab(object):
"""Vocabulary class for mapping words and ids."""
def __init__(self, vocab_file, max_size):
self._word_to_id = {}
self._id_to_word = {}
self._count = 0
with open(vocab_file, 'r') as vocab_f:
for line in vocab_f:
pieces = line.split()
if len(pieces) != 2:
sys.stderr.write('Bad line: %s\n' % line)
continue
if pieces[0] in self._word_to_id:
raise ValueError('Duplicated word: %s.' % pieces[0])
self._word_to_id[pieces[0]] = self._count
self._id_to_word[self._count] = pieces[0]
self._count += 1
if self._count > max_size:
raise ValueError('Too many words: >%d.' % max_size)
def CheckVocab(self, word):
if word not in self._word_to_id:
return None
return self._word_to_id[word]
def WordToId(self, word):
if word not in self._word_to_id:
return self._word_to_id[UNKNOWN_TOKEN]
return self._word_to_id[word]
def IdToWord(self, word_id):
if word_id not in self._id_to_word:
raise ValueError('id not found in vocab: %d.' % word_id)
return self._id_to_word[word_id]
def NumIds(self):
return self._count
def ExampleGen(data_path, num_epochs=None):
"""Generates tf.Examples from path of data files.
Binary data format: <length><blob>. <length> represents the byte size
of <blob>. <blob> is serialized tf.Example proto. The tf.Example contains
the tokenized article text and summary.
Args:
data_path: path to tf.Example data files.
num_epochs: Number of times to go through the data. None means infinite.
Yields:
Deserialized tf.Example.
If there are multiple files specified, they accessed in a random order.
"""
epoch = 0
while True:
if num_epochs is not None and epoch >= num_epochs:
break
filelist = glob.glob(data_path)
assert filelist, 'Empty filelist.'
random.shuffle(filelist)
for f in filelist:
reader = open(f, 'rb')
while True:
len_bytes = reader.read(8)
if not len_bytes: break
str_len = struct.unpack('q', len_bytes)[0]
example_str = struct.unpack('%ds' % str_len, reader.read(str_len))[0]
yield example_pb2.Example.FromString(example_str)
epoch += 1
def Pad(ids, pad_id, length):
"""Pad or trim list to len length.
Args:
ids: list of ints to pad
pad_id: what to pad with
length: length to pad or trim to
Returns:
ids trimmed or padded with pad_id
"""
assert pad_id is not None
assert length is not None
if len(ids) < length:
a = [pad_id] * (length - len(ids))
return ids + a
else:
return ids[:length]
def GetWordIds(text, vocab, pad_len=None, pad_id=None):
"""Get ids corresponding to words in text.
Assumes tokens separated by space.
Args:
text: a string
vocab: TextVocabularyFile object
pad_len: int, length to pad to
pad_id: int, word id for pad symbol
Returns:
A list of ints representing word ids.
"""
ids = []
for w in text.split():
i = vocab.WordToId(w)
if i >= 0:
ids.append(i)
else:
ids.append(vocab.WordToId(UNKNOWN_TOKEN))
if pad_len is not None:
return Pad(ids, pad_id, pad_len)
return ids
def Ids2Words(ids_list, vocab):
"""Get words from ids.
Args:
ids_list: list of int32
vocab: TextVocabulary object
Returns:
List of words corresponding to ids.
"""
assert isinstance(ids_list, list), '%s is not a list' % ids_list
return [vocab.IdToWord(i) for i in ids_list]
def SnippetGen(text, start_tok, end_tok, inclusive=True):
"""Generates consecutive snippets between start and end tokens.
Args:
text: a string
start_tok: a string denoting the start of snippets
end_tok: a string denoting the end of snippets
inclusive: Whether include the tokens in the returned snippets.
Yields:
String snippets
"""
cur = 0
while True:
try:
start_p = text.index(start_tok, cur)
end_p = text.index(end_tok, start_p + 1)
cur = end_p + len(end_tok)
if inclusive:
yield text[start_p:cur]
else:
yield text[start_p+len(start_tok):end_p]
except ValueError as e:
raise StopIteration('no more snippets in text: %s' % e)
def GetExFeatureText(ex, key):
return ex.features.feature[key].bytes_list.value[0]
def ToSentences(paragraph, include_token=True):
"""Takes tokens of a paragraph and returns list of sentences.
Args:
paragraph: string, text of paragraph
include_token: Whether include the sentence separation tokens result.
Returns:
List of sentence strings.
"""
s_gen = SnippetGen(paragraph, SENTENCE_START, SENTENCE_END, include_token)
return [s for s in s_gen]
|
yongshengwang/hue | refs/heads/master | desktop/core/ext-py/boto-2.38.0/boto/ec2/keypair.py | 150 | # Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# 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 to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Represents an EC2 Keypair
"""
import os
from boto.ec2.ec2object import EC2Object
from boto.exception import BotoClientError
class KeyPair(EC2Object):
def __init__(self, connection=None):
super(KeyPair, self).__init__(connection)
self.name = None
self.fingerprint = None
self.material = None
def __repr__(self):
return 'KeyPair:%s' % self.name
def endElement(self, name, value, connection):
if name == 'keyName':
self.name = value
elif name == 'keyFingerprint':
self.fingerprint = value
elif name == 'keyMaterial':
self.material = value
else:
setattr(self, name, value)
def delete(self, dry_run=False):
"""
Delete the KeyPair.
:rtype: bool
:return: True if successful, otherwise False.
"""
return self.connection.delete_key_pair(self.name, dry_run=dry_run)
def save(self, directory_path):
"""
Save the material (the unencrypted PEM encoded RSA private key)
of a newly created KeyPair to a local file.
:type directory_path: string
:param directory_path: The fully qualified path to the directory
in which the keypair will be saved. The
keypair file will be named using the name
of the keypair as the base name and .pem
for the file extension. If a file of that
name already exists in the directory, an
exception will be raised and the old file
will not be overwritten.
:rtype: bool
:return: True if successful.
"""
if self.material:
directory_path = os.path.expanduser(directory_path)
file_path = os.path.join(directory_path, '%s.pem' % self.name)
if os.path.exists(file_path):
raise BotoClientError('%s already exists, it will not be overwritten' % file_path)
fp = open(file_path, 'wb')
fp.write(self.material)
fp.close()
os.chmod(file_path, 0o600)
return True
else:
raise BotoClientError('KeyPair contains no material')
def copy_to_region(self, region, dry_run=False):
"""
Create a new key pair of the same new in another region.
Note that the new key pair will use a different ssh
cert than the this key pair. After doing the copy,
you will need to save the material associated with the
new key pair (use the save method) to a local file.
:type region: :class:`boto.ec2.regioninfo.RegionInfo`
:param region: The region to which this security group will be copied.
:rtype: :class:`boto.ec2.keypair.KeyPair`
:return: The new key pair
"""
if region.name == self.region:
raise BotoClientError('Unable to copy to the same Region')
conn_params = self.connection.get_params()
rconn = region.connect(**conn_params)
kp = rconn.create_key_pair(self.name, dry_run=dry_run)
return kp
|
nishigori/boto | refs/heads/develop | boto/swf/__init__.py | 145 | # Copyright (c) 2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# 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 to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from boto.ec2.regioninfo import RegionInfo
from boto.regioninfo import get_regions, load_regions
import boto.swf.layer1
REGION_ENDPOINTS = load_regions().get('swf', {})
def regions(**kw_params):
"""
Get all available regions for the Amazon Simple Workflow service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
return get_regions('swf', connection_cls=boto.swf.layer1.Layer1)
def connect_to_region(region_name, **kw_params):
for region in regions():
if region.name == region_name:
return region.connect(**kw_params)
return None
|
gaojinhua/cocos2d-x-samples | refs/heads/v3 | samples/MoonWarriors/frameworks/runtime-src/proj.android/build_native.py | 43 | #!/usr/bin/python
'''
build_native.py
This script will copy resources to assets and build native code with NDK.
'''
import sys
import os, os.path
import shutil
from optparse import OptionParser
def get_num_of_cpu():
''' The build process can be accelerated by running multiple concurrent job processes using the -j-option.
'''
try:
platform = sys.platform
if platform == 'win32':
if 'NUMBER_OF_PROCESSORS' in os.environ:
return int(os.environ['NUMBER_OF_PROCESSORS'])
else:
return 1
else:
from numpy.distutils import cpuinfo
return cpuinfo.cpu._getNCPUs()
except Exception:
print "Can't know cpuinfo, use default 1 cpu"
return 1
def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building
'''
try:
NDK_ROOT = os.environ['NDK_ROOT']
except Exception:
print "NDK_ROOT not defined. Please define NDK_ROOT in your environment"
sys.exit(1)
return NDK_ROOT
def select_toolchain_version(ndk_root):
ret_version = "4.8"
version_file_path = os.path.join(ndk_root, "RELEASE.TXT")
try:
versionFile = open(version_file_path)
lines = versionFile.readlines()
versionFile.close()
version_num = None
version_char = None
pattern = r'^[a-zA-Z]+(\d+)(\w)'
for line in lines:
str_line = line.lstrip()
match = re.match(pattern, str_line)
if match:
version_num = int(match.group(1))
version_char = match.group(2)
break
if version_num is None:
print("Parse NDK version from file %s failed." % version_file_path)
else:
version_char = version_char.lower()
if version_num > 10 or (version_num == 10 and cmp(version_char, 'c') >= 0):
ret_version = "4.9"
except:
print("Parse NDK version from file %s failed." % version_file_path)
print("NDK_TOOLCHAIN_VERSION: %s" % ret_version)
if ret_version == "4.8":
print(
"Your application may crash when using c++ 11 regular expression with NDK_TOOLCHAIN_VERSION %s" % ret_version)
return ret_version
def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,build_mode):
ndk_path = os.path.join(ndk_root, "ndk-build")
ndk_toolchain_version = select_toolchain_version(ndk_root)
# windows should use ";" to seperate module paths
platform = sys.platform
if platform == 'win32':
ndk_module_path = 'NDK_MODULE_PATH=%s/..;%s;%s/external;%s/cocos NDK_TOOLCHAIN_VERSION=%s' % (cocos_root, cocos_root, cocos_root, cocos_root, ndk_toolchain_version)
else:
ndk_module_path = 'NDK_MODULE_PATH=%s/..:%s:%s/external:%s/cocos NDK_TOOLCHAIN_VERSION=%s' % (cocos_root, cocos_root, cocos_root, cocos_root, ndk_toolchain_version)
num_of_cpu = get_num_of_cpu()
if ndk_build_param == None:
command = '%s -j%d -C %s NDK_DEBUG=%d %s' % (ndk_path, num_of_cpu, app_android_root, build_mode=='debug', ndk_module_path)
else:
command = '%s -j%d -C %s NDK_DEBUG=%d %s %s' % (ndk_path, num_of_cpu, app_android_root, build_mode=='debug', ndk_build_param, ndk_module_path)
print command
if os.system(command) != 0:
raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!")
def copy_files(src, dst):
for item in os.listdir(src):
path = os.path.join(src, item)
# Android can not package the file that ends with ".gz"
if not item.startswith('.') and not item.endswith('.gz') and os.path.isfile(path):
shutil.copy(path, dst)
if os.path.isdir(path):
new_dst = os.path.join(dst, item)
os.mkdir(new_dst)
copy_files(path, new_dst)
def copy_resources(app_android_root):
# remove app_android_root/assets if it exists
assets_dir = os.path.join(app_android_root, "assets")
if os.path.isdir(assets_dir):
shutil.rmtree(assets_dir)
# copy resources
os.mkdir(assets_dir)
assets_res_dir = assets_dir + "/res";
assets_scripts_dir = assets_dir + "/src";
assets_jsb_dir = assets_dir + "/script";
os.mkdir(assets_res_dir);
os.mkdir(assets_scripts_dir);
os.mkdir(assets_jsb_dir);
shutil.copy(os.path.join(app_android_root, "../../../main.js"), assets_dir)
shutil.copy(os.path.join(app_android_root, "../../../project.json"), assets_dir)
resources_dir = os.path.join(app_android_root, "../../../res")
copy_files(resources_dir, assets_res_dir)
resources_dir = os.path.join(app_android_root, "../../../src")
copy_files(resources_dir, assets_scripts_dir)
resources_dir = os.path.join(app_android_root, "../../../frameworks/js-bindings/bindings/script")
copy_files(resources_dir, assets_jsb_dir)
def build(targets,ndk_build_param,build_mode):
ndk_root = check_environment_variables()
sdk_root = None
project_root = os.path.dirname(os.path.realpath(__file__))
cocos_root = os.path.join(project_root, "..", "..", "..", "frameworks/js-bindings/cocos2d-x")
print cocos_root
if build_mode is None:
build_mode = 'debug'
elif build_mode != 'release':
build_mode = 'debug'
copy_resources(project_root)
do_build(cocos_root, ndk_root, project_root,ndk_build_param,sdk_root,build_mode)
# -------------- main --------------
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-n", "--ndk", dest="ndk_build_param",
help='Parameter for ndk-build')
parser.add_option("-b", "--build", dest="build_mode",
help='The build mode for NDK project, debug or release')
(opts, args) = parser.parse_args()
try:
build(args, opts.ndk_build_param,opts.build_mode)
except Exception as e:
print e
sys.exit(1)
|
projectcalico/calico-neutron | refs/heads/calico-readme | neutron/tests/unit/cisco/l3/test_l3_router_appliance_plugin.py | 3 | # Copyright 2014 Cisco Systems, 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from oslo.config import cfg
from oslo.utils import timeutils
from webob import exc
import neutron
from neutron.api.v2 import attributes
from neutron import context as n_context
from neutron.db import agents_db
from neutron.db import common_db_mixin
from neutron.extensions import providernet as pnet
from neutron import manager
from neutron.plugins.cisco.common import cisco_constants as c_constants
from neutron.plugins.cisco.db.l3 import device_handling_db
from neutron.plugins.cisco.db.l3 import l3_router_appliance_db
from neutron.plugins.cisco.l3.rpc import devices_cfgagent_rpc_cb
from neutron.plugins.cisco.l3.rpc import l3_router_cfgagent_rpc_cb
from neutron.plugins.cisco.l3 import service_vm_lib
from neutron.plugins.common import constants as service_constants
from neutron.tests.unit.cisco.l3 import device_handling_test_support
from neutron.tests.unit import test_db_plugin
from neutron.tests.unit import test_extension_extraroute as test_ext_extraroute
from neutron.tests.unit import test_l3_plugin
from neutron.tests.unit import testlib_plugin
CORE_PLUGIN_KLASS = ('neutron.tests.unit.cisco.l3.'
'test_l3_router_appliance_plugin.TestNoL3NatPlugin')
L3_PLUGIN_KLASS = (
"neutron.tests.unit.cisco.l3.test_l3_router_appliance_plugin."
"TestApplianceL3RouterServicePlugin")
extensions_path = neutron.plugins.__path__[0] + '/cisco/extensions'
class L3RouterApplianceTestExtensionManager(
test_ext_extraroute.ExtraRouteTestExtensionManager):
def get_actions(self):
return []
def get_request_extensions(self):
return []
def get_extended_resources(self, version):
return pnet.get_extended_resources(version)
class TestNoL3NatPlugin(test_l3_plugin.TestNoL3NatPlugin,
agents_db.AgentDbMixin):
# There is no need to expose agent REST API
supported_extension_aliases = ["external-net", "provider"]
NET_TYPE = 'vlan'
def __init__(self):
self.tags = {}
self.tag = 1
super(TestNoL3NatPlugin, self).__init__()
def _make_network_dict(self, network, fields=None,
process_extensions=True):
res = {'id': network['id'],
'name': network['name'],
'tenant_id': network['tenant_id'],
'admin_state_up': network['admin_state_up'],
'status': network['status'],
'shared': network['shared'],
'subnets': [subnet['id']
for subnet in network['subnets']]}
try:
tag = self.tags[network['id']]
except KeyError:
self.tag += 1
tag = self.tag
self.tags[network['id']] = tag
res.update({pnet.PHYSICAL_NETWORK: 'phy',
pnet.NETWORK_TYPE: self.NET_TYPE,
pnet.SEGMENTATION_ID: tag})
# Call auxiliary extend functions, if any
if process_extensions:
self._apply_dict_extend_functions(
attributes.NETWORKS, res, network)
return self._fields(res, fields)
def get_network_profiles(self, context, filters=None, fields=None):
return [{'id': "1234"}]
def get_policy_profiles(self, context, filters=None, fields=None):
return [{'id': "4321"}]
# A set routes capable L3 routing service plugin class supporting appliances
class TestApplianceL3RouterServicePlugin(
agents_db.AgentDbMixin, common_db_mixin.CommonDbMixin,
device_handling_db.DeviceHandlingMixin,
l3_router_appliance_db.L3RouterApplianceDBMixin):
supported_extension_aliases = ["router", "extraroute"]
def __init__(self):
self._setup_backlog_handling()
self._svc_vm_mgr = service_vm_lib.ServiceVMManager()
super(TestApplianceL3RouterServicePlugin, self).__init__()
def get_plugin_type(self):
return service_constants.L3_ROUTER_NAT
def get_plugin_description(self):
return "L3 Routing Service Plugin for testing"
class L3RouterApplianceTestCaseBase(
test_db_plugin.NeutronDbPluginV2TestCase,
testlib_plugin.NotificationSetupHelper,
device_handling_test_support.DeviceHandlingTestSupportMixin):
def setUp(self, core_plugin=None, l3_plugin=None, ext_mgr=None):
# Save the global RESOURCE_ATTRIBUTE_MAP
self.saved_attr_map = {}
for resource, attrs in attributes.RESOURCE_ATTRIBUTE_MAP.iteritems():
self.saved_attr_map[resource] = attrs.copy()
if not core_plugin:
core_plugin = CORE_PLUGIN_KLASS
if l3_plugin is None:
l3_plugin = L3_PLUGIN_KLASS
service_plugins = {'l3_plugin_name': l3_plugin}
cfg.CONF.set_override('api_extensions_path', extensions_path)
# for these tests we need to enable overlapping ips
cfg.CONF.set_default('allow_overlapping_ips', True)
cfg.CONF.set_default('max_routes', 3)
if ext_mgr is None:
ext_mgr = L3RouterApplianceTestExtensionManager()
super(L3RouterApplianceTestCaseBase, self).setUp(
plugin=core_plugin, service_plugins=service_plugins,
ext_mgr=ext_mgr)
self.core_plugin = manager.NeutronManager.get_plugin()
self.plugin = manager.NeutronManager.get_service_plugins().get(
service_constants.L3_ROUTER_NAT)
self.setup_notification_driver()
cfg.CONF.set_override('allow_sorting', True)
test_opts = [
cfg.StrOpt('auth_uri', default='http://localhost:35357/v2.0/'),
cfg.StrOpt('identity_uri', default='http://localhost:5000'),
cfg.StrOpt('admin_user', default='neutron'),
cfg.StrOpt('admin_password', default='secrete')]
cfg.CONF.register_opts(test_opts, 'keystone_authtoken')
self._mock_l3_admin_tenant()
self._create_mgmt_nw_for_tests(self.fmt)
self._mock_svc_vm_create_delete(self.plugin)
self._mock_io_file_ops()
def restore_attribute_map(self):
# Restore the original RESOURCE_ATTRIBUTE_MAP
attributes.RESOURCE_ATTRIBUTE_MAP = self.saved_attr_map
def tearDown(self):
self._remove_mgmt_nw_for_tests()
(neutron.tests.unit.cisco.l3.test_l3_router_appliance_plugin.
TestApplianceL3RouterServicePlugin._mgmt_nw_uuid) = None
(neutron.tests.unit.cisco.l3.test_l3_router_appliance_plugin.
TestApplianceL3RouterServicePlugin._refresh_router_backlog) = True
(neutron.tests.unit.cisco.l3.test_l3_router_appliance_plugin.
TestApplianceL3RouterServicePlugin._nova_running) = False
plugin = manager.NeutronManager.get_service_plugins()[
service_constants.L3_ROUTER_NAT]
plugin._heartbeat.stop()
self.restore_attribute_map()
super(L3RouterApplianceTestCaseBase, self).tearDown()
class L3RouterApplianceVMTestCase(
L3RouterApplianceTestCaseBase, test_l3_plugin.L3NatTestCaseBase,
test_ext_extraroute.ExtraRouteDBTestCaseBase):
def setUp(self, core_plugin=None, l3_plugin=None, dm_plugin=None,
ext_mgr=None):
super(L3RouterApplianceVMTestCase, self).setUp(
core_plugin=core_plugin, l3_plugin=l3_plugin, ext_mgr=ext_mgr)
def test_floatingip_with_assoc_fails(self):
self._test_floatingip_with_assoc_fails(
'neutron.db.l3_db.L3_NAT_dbonly_mixin._check_and_get_fip_assoc')
class CfgAgentRouterApplianceVMTestCase(L3RouterApplianceTestCaseBase,
test_l3_plugin.L3AgentDbTestCaseBase):
def setUp(self, core_plugin=None, l3_plugin=None, ext_mgr=None):
super(CfgAgentRouterApplianceVMTestCase, self).setUp(
core_plugin=core_plugin, l3_plugin=l3_plugin, ext_mgr=ext_mgr)
# Rewire function name so we can use existing l3 agent tests
# to test the cfg agent rpc.
self.plugin.get_sync_data = self.plugin.get_sync_data_ext
def _test_notify_op_agent(self, target_func, *args):
l3_rpc_agent_api_str = (
'neutron.plugins.cisco.l3.rpc.l3_router_rpc_joint_agent_api'
'.L3RouterJointAgentNotifyAPI')
plugin = manager.NeutronManager.get_service_plugins()[
service_constants.L3_ROUTER_NAT]
oldNotify = plugin.l3_cfg_rpc_notifier
try:
with mock.patch(l3_rpc_agent_api_str) as notifyApi:
plugin.l3_cfg_rpc_notifier = notifyApi
kargs = [item for item in args]
kargs.append(notifyApi)
target_func(*kargs)
except Exception:
plugin.l3_cfg_rpc_notifier = oldNotify
raise
else:
plugin.l3_cfg_rpc_notifier = oldNotify
DB_PLUGIN_KLASS = ('neutron.tests.unit.cisco.l3.ovs_neutron_plugin.'
'OVSNeutronPluginV2')
HOST = 'my_cfgagent_host'
FIRST_CFG_AGENT = {
'binary': 'neutron-cisco-cfg-agent',
'host': HOST,
'topic': c_constants.CFG_AGENT,
'configurations': {},
'agent_type': c_constants.AGENT_TYPE_CFG,
'start_flag': True
}
class RouterSchedulingTestCase(L3RouterApplianceTestCaseBase,
test_l3_plugin.L3NatTestCaseMixin):
def setUp(self):
super(RouterSchedulingTestCase, self).setUp()
self.adminContext = n_context.get_admin_context()
def _register_cfg_agent(self):
callback = agents_db.AgentExtRpcCallback()
callback.report_state(self.adminContext,
agent_state={'agent_state': FIRST_CFG_AGENT},
time=timeutils.strtime())
agent_db = self.core_plugin.get_agents_db(self.adminContext,
filters={'host': [HOST]})
self.agent_id1 = agent_db[0].id
def _update_router_name(self, router_id, new_name='new_name'):
return self._update('routers', router_id,
{'router': {'name': new_name}},
expected_code=exc.HTTPOk.code)
def test_router_scheduled_to_device_with_no_cfg_agent(self):
with self.router() as router:
r_id = router['router']['id']
self._update_router_name(r_id)
routers = self.plugin.get_sync_data_ext(self.adminContext,
[r_id])
self.assertEqual(1, len(routers))
hosting_device = routers[0]['hosting_device']
self.assertIsNotNone(hosting_device)
self.assertIsNone(hosting_device['cfg_agent_id'])
def test_router_not_scheduled_to_device_without_nova_services(self):
self._nclient_services_mock.list = self._novaclient_services_list(
False)
with self.router() as router:
r_id = router['router']['id']
self._update_router_name(r_id)
routers = self.plugin.get_sync_data_ext(self.adminContext,
[r_id])
self.assertEqual(1, len(routers))
hosting_device = routers[0]['hosting_device']
self.assertIsNone(hosting_device)
def test_router_scheduled_to_device_and_cfg_agent(self):
self._register_cfg_agent()
cfg_rpc = l3_router_cfgagent_rpc_cb.L3RouterCfgRpcCallbackMixin()
cfg_rpc._core_plugin = self.core_plugin
cfg_rpc._l3plugin = self.plugin
with self.router() as router:
r_id = router['router']['id']
self._update_router_name(r_id)
routers = cfg_rpc.cfg_sync_routers(
self.adminContext, host=HOST)
self.assertEqual(1, len(routers))
hosting_device = routers[0]['hosting_device']
self.assertIsNotNone(hosting_device)
self.assertIsNotNone(hosting_device['cfg_agent_id'])
def test_dead_device_is_removed(self):
cfg_dh_rpc = devices_cfgagent_rpc_cb.DeviceCfgRpcCallbackMixin()
cfg_dh_rpc._l3plugin = self.plugin
with mock.patch(
'neutron.plugins.cisco.l3.rpc.l3_router_rpc_joint_agent_api.'
'L3RouterJointAgentNotifyAPI.hosting_devices_removed') as (
mock_notify):
with self.router() as router:
r_id = router['router']['id']
routers_1 = self.plugin.get_sync_data_ext(self.adminContext,
[r_id])
self.assertEqual(1, len(routers_1))
hosting_device_1 = routers_1[0]['hosting_device']
self.assertIsNotNone(hosting_device_1)
cfg_dh_rpc.report_non_responding_hosting_devices(
self.adminContext,
host=None,
hosting_device_ids=[hosting_device_1['id']])
self.assertEqual(1, mock_notify.call_count)
mock_notify.assert_called_with(
mock.ANY,
{hosting_device_1['id']: {'routers': [r_id]}},
False,
mock.ANY)
def test_cfg_agent_registration_triggers_autoscheduling(self):
with self.router() as router:
r_id = router['router']['id']
routers_1 = self.plugin.get_sync_data_ext(self.adminContext,
[r_id])
self.assertEqual(1, len(routers_1))
hosting_device_1 = routers_1[0]['hosting_device']
self.assertIsNotNone(hosting_device_1)
self.assertIsNone(hosting_device_1['cfg_agent_id'])
cfg_dh_rpc = devices_cfgagent_rpc_cb.DeviceCfgRpcCallbackMixin()
cfg_dh_rpc._l3plugin = self.plugin
self._register_cfg_agent()
res = cfg_dh_rpc.register_for_duty(self.adminContext, host=HOST)
self.assertTrue(res)
routers_2 = self.plugin.get_sync_data_ext(self.adminContext,
[r_id])
self.assertEqual(1, len(routers_2))
hosting_device_2 = routers_2[0]['hosting_device']
self.assertIsNotNone(hosting_device_2)
self.assertIsNotNone(hosting_device_2['cfg_agent_id'])
|
StephenOrJames/aviation | refs/heads/master | aviation_weather/components/temperature.py | 2 | import re
from aviation_weather.components import Component
from aviation_weather.exceptions import TemperatureDecodeError
class Temperature(Component):
"""The Temperature class represents a combined group of temperature and dew point.
Attributes:
temperature (int): The temperature in whole degrees Celcius.
dew_point (int): The dew point in whole degrees Celcius.
"""
def __init__(self, raw: str):
"""Parse `raw` to create a new Temperature object.
Args:
raw (str): The temperature and dew point to be parsed.
Raises:
TemperatureDecodeError: If `raw` could not be parsed.
"""
m = re.search(r"\b(?P<temperature>M?\d{1,2})/(?P<dew_point>M?\d{1,2})?\b", raw)
if not m:
raise TemperatureDecodeError("Temperature(%r) could not be parsed" % raw)
temperature = m.group("temperature")
dew_point = m.group("dew_point")
if temperature.startswith("M"):
self.temperature = -int(temperature[1:])
else:
self.temperature = int(temperature)
if dew_point.startswith("M"):
self.dew_point = -int(dew_point[1:])
else:
self.dew_point = int(dew_point)
@property
def raw(self):
raw = ""
if self.temperature < 0:
raw += "M%02d/" % -self.temperature
else:
raw += "%02d/" % self.temperature
if self.dew_point is not None:
if self.dew_point < 0:
raw += "M%02d" % -self.dew_point
else:
raw += "%02d" % self.dew_point
return raw
|
buguelos/odoo | refs/heads/master | openerp/addons/test_impex/tests/test_import.py | 154 | # -*- coding: utf-8 -*-
import openerp.modules.registry
import openerp
from openerp.tests import common
from openerp.tools.misc import mute_logger
def ok(n):
""" Successful import of ``n`` records
:param int n: number of records which should have been imported
"""
return n, 0, 0, 0
def error(row, message, record=None, **kwargs):
""" Failed import of the record ``record`` at line ``row``, with the error
message ``message``
:param str message:
:param dict record:
"""
return (
-1, dict(record or {}, **kwargs),
"Line %d : %s" % (row, message),
'')
def values(seq, field='value'):
return [item[field] for item in seq]
class ImporterCase(common.TransactionCase):
model_name = False
def __init__(self, *args, **kwargs):
super(ImporterCase, self).__init__(*args, **kwargs)
self.model = None
def setUp(self):
super(ImporterCase, self).setUp()
self.model = self.registry(self.model_name)
def import_(self, fields, rows, context=None):
return self.model.import_data(
self.cr, openerp.SUPERUSER_ID, fields, rows, context=context)
def read(self, fields=('value',), domain=(), context=None):
return self.model.read(
self.cr, openerp.SUPERUSER_ID,
self.model.search(self.cr, openerp.SUPERUSER_ID, domain, context=context),
fields=fields, context=context)
def browse(self, domain=(), context=None):
return self.model.browse(
self.cr, openerp.SUPERUSER_ID,
self.model.search(self.cr, openerp.SUPERUSER_ID, domain, context=context),
context=context)
def xid(self, record):
ModelData = self.registry('ir.model.data')
ids = ModelData.search(
self.cr, openerp.SUPERUSER_ID,
[('model', '=', record._name), ('res_id', '=', record.id)])
if ids:
d = ModelData.read(
self.cr, openerp.SUPERUSER_ID, ids, ['name', 'module'])[0]
if d['module']:
return '%s.%s' % (d['module'], d['name'])
return d['name']
name = record.name_get()[0][1]
# fix dotted name_get results, otherwise xid lookups blow up
name = name.replace('.', '-')
ModelData.create(self.cr, openerp.SUPERUSER_ID, {
'name': name,
'model': record._name,
'res_id': record.id,
'module': '__test__'
})
return '__test__.' + name
class test_ids_stuff(ImporterCase):
model_name = 'export.integer'
def test_create_with_id(self):
self.assertEqual(
self.import_(['.id', 'value'], [['42', '36']]),
error(1, u"Unknown database identifier '42'"))
def test_create_with_xid(self):
self.assertEqual(
self.import_(['id', 'value'], [['somexmlid', '42']]),
ok(1))
self.assertEqual(
'somexmlid',
self.xid(self.browse()[0]))
def test_update_with_id(self):
id = self.model.create(self.cr, openerp.SUPERUSER_ID, {'value': 36})
self.assertEqual(
36,
self.model.browse(self.cr, openerp.SUPERUSER_ID, id).value)
self.assertEqual(
self.import_(['.id', 'value'], [[str(id), '42']]),
ok(1))
self.assertEqual(
[42], # updated value to imported
values(self.read()))
def test_update_with_xid(self):
self.import_(['id', 'value'], [['somexmlid', '36']])
self.assertEqual([36], values(self.read()))
self.import_(['id', 'value'], [['somexmlid', '1234567']])
self.assertEqual([1234567], values(self.read()))
class test_boolean_field(ImporterCase):
model_name = 'export.boolean'
def test_empty(self):
self.assertEqual(
self.import_(['value'], []),
ok(0))
def test_exported(self):
self.assertEqual(
self.import_(['value'], [
['False'],
['True'],
]),
ok(2))
records = self.read()
self.assertEqual([
False,
True,
], values(records))
def test_falses(self):
self.assertEqual(
self.import_(['value'], [
[u'0'],
[u'no'],
[u'false'],
[u'FALSE'],
[u''],
]),
ok(5))
self.assertEqual([
False,
False,
False,
False,
False,
],
values(self.read()))
def test_trues(self):
self.assertEqual(
self.import_(['value'], [
['off'],
['None'],
['nil'],
['()'],
['f'],
['#f'],
# Problem: OpenOffice (and probably excel) output localized booleans
['VRAI'],
[u'OFF'],
]),
ok(8))
self.assertEqual(
[True] * 8,
values(self.read()))
class test_integer_field(ImporterCase):
model_name = 'export.integer'
def test_none(self):
self.assertEqual(
self.import_(['value'], []),
ok(0))
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual(
[False],
values(self.read()))
def test_zero(self):
self.assertEqual(
self.import_(['value'], [['0']]),
ok(1))
self.assertEqual(
self.import_(['value'], [['-0']]),
ok(1))
self.assertEqual([False, False], values(self.read()))
def test_positives(self):
self.assertEqual(
self.import_(['value'], [
['1'],
['42'],
[str(2**31-1)],
['12345678']
]),
ok(4))
self.assertEqual([
1, 42, 2**31-1, 12345678
], values(self.read()))
def test_negatives(self):
self.assertEqual(
self.import_(['value'], [
['-1'],
['-42'],
[str(-(2**31 - 1))],
[str(-(2**31))],
['-12345678']
]),
ok(5))
self.assertEqual([
-1, -42, -(2**31 - 1), -(2**31), -12345678
], values(self.read()))
@mute_logger('openerp.sql_db')
def test_out_of_range(self):
self.assertEqual(
self.import_(['value'], [[str(2**31)]]),
error(1, "integer out of range\n"))
# auto-rollbacks if error is in process_liness, but not during
# ir.model.data write. Can differentiate because former ends lines
# error lines with "!"
self.cr.rollback()
self.assertEqual(
self.import_(['value'], [[str(-2**32)]]),
error(1, "integer out of range\n"))
def test_nonsense(self):
self.assertEqual(
self.import_(['value'], [['zorglub']]),
error(1, u"'zorglub' does not seem to be an integer for field 'unknown'"))
class test_float_field(ImporterCase):
model_name = 'export.float'
def test_none(self):
self.assertEqual(
self.import_(['value'], []),
ok(0))
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual(
[False],
values(self.read()))
def test_zero(self):
self.assertEqual(
self.import_(['value'], [['0']]),
ok(1))
self.assertEqual(
self.import_(['value'], [['-0']]),
ok(1))
self.assertEqual([False, False], values(self.read()))
def test_positives(self):
self.assertEqual(
self.import_(['value'], [
['1'],
['42'],
[str(2**31-1)],
['12345678'],
[str(2**33)],
['0.000001'],
]),
ok(6))
self.assertEqual([
1, 42, 2**31-1, 12345678, 2.0**33, .000001
], values(self.read()))
def test_negatives(self):
self.assertEqual(
self.import_(['value'], [
['-1'],
['-42'],
[str(-2**31 + 1)],
[str(-2**31)],
['-12345678'],
[str(-2**33)],
['-0.000001'],
]),
ok(7))
self.assertEqual([
-1, -42, -(2**31 - 1), -(2**31), -12345678, -2.0**33, -.000001
], values(self.read()))
def test_nonsense(self):
self.assertEqual(
self.import_(['value'], [['foobar']]),
error(1, u"'foobar' does not seem to be a number for field 'unknown'"))
class test_string_field(ImporterCase):
model_name = 'export.string.bounded'
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual([False], values(self.read()))
def test_imported(self):
self.assertEqual(
self.import_(['value'], [
[u'foobar'],
[u'foobarbaz'],
[u'Með suð í eyrum við spilum endalaust'],
[u"People 'get' types. They use them all the time. Telling "
u"someone he can't pound a nail with a banana doesn't much "
u"surprise him."]
]),
ok(4))
self.assertEqual([
u"foobar",
u"foobarbaz",
u"Með suð í eyrum ",
u"People 'get' typ",
], values(self.read()))
class test_unbound_string_field(ImporterCase):
model_name = 'export.string'
def test_imported(self):
self.assertEqual(
self.import_(['value'], [
[u'í dag viðrar vel til loftárása'],
# ackbar.jpg
[u"If they ask you about fun, you tell them – fun is a filthy"
u" parasite"]
]),
ok(2))
self.assertEqual([
u"í dag viðrar vel til loftárása",
u"If they ask you about fun, you tell them – fun is a filthy parasite"
], values(self.read()))
class test_text(ImporterCase):
model_name = 'export.text'
def test_empty(self):
self.assertEqual(
self.import_(['value'], [['']]),
ok(1))
self.assertEqual([False], values(self.read()))
def test_imported(self):
s = (u"Breiðskífa er notað um útgefna hljómplötu sem inniheldur "
u"stúdíóupptökur frá einum flytjanda. Breiðskífur eru oftast "
u"milli 25-80 mínútur og er lengd þeirra oft miðuð við 33⅓ "
u"snúninga 12 tommu vínylplötur (sem geta verið allt að 30 mín "
u"hvor hlið).\n\nBreiðskífur eru stundum tvöfaldar og eru þær þá"
u" gefnar út á tveimur geisladiskum eða tveimur vínylplötum.")
self.assertEqual(
self.import_(['value'], [[s]]),
ok(1))
self.assertEqual([s], values(self.read()))
class test_selection(ImporterCase):
model_name = 'export.selection'
translations_fr = [
("Qux", "toto"),
("Bar", "titi"),
("Foo", "tete"),
]
def test_imported(self):
self.assertEqual(
self.import_(['value'], [
['Qux'],
['Bar'],
['Foo'],
['2'],
]),
ok(4))
self.assertEqual([3, 2, 1, 2], values(self.read()))
def test_imported_translated(self):
self.registry('res.lang').create(self.cr, openerp.SUPERUSER_ID, {
'name': u'Français',
'code': 'fr_FR',
'translatable': True,
'date_format': '%d.%m.%Y',
'decimal_point': ',',
'thousands_sep': ' ',
})
Translations = self.registry('ir.translation')
for source, value in self.translations_fr:
Translations.create(self.cr, openerp.SUPERUSER_ID, {
'name': 'export.selection,value',
'lang': 'fr_FR',
'type': 'selection',
'src': source,
'value': value
})
self.assertEqual(
self.import_(['value'], [
['toto'],
['tete'],
['titi'],
], context={'lang': 'fr_FR'}),
ok(3))
self.assertEqual([3, 1, 2], values(self.read()))
self.assertEqual(
self.import_(['value'], [['Foo']], context={'lang': 'fr_FR'}),
ok(1))
def test_invalid(self):
self.assertEqual(
self.import_(['value'], [['Baz']]),
error(1, u"Value 'Baz' not found in selection field 'unknown'"))
self.cr.rollback()
self.assertEqual(
self.import_(['value'], [[42]]),
error(1, u"Value '42' not found in selection field 'unknown'"))
class test_selection_function(ImporterCase):
model_name = 'export.selection.function'
translations_fr = [
("Corge", "toto"),
("Grault", "titi"),
("Wheee", "tete"),
("Moog", "tutu"),
]
def test_imported(self):
""" import uses fields_get, so translates import label (may or may not
be good news) *and* serializes the selection function to reverse it:
import does not actually know that the selection field uses a function
"""
# NOTE: conflict between a value and a label => ?
self.assertEqual(
self.import_(['value'], [
['3'],
["Grault"],
]),
ok(2))
self.assertEqual(
[3, 1],
values(self.read()))
def test_translated(self):
""" Expects output of selection function returns translated labels
"""
self.registry('res.lang').create(self.cr, openerp.SUPERUSER_ID, {
'name': u'Français',
'code': 'fr_FR',
'translatable': True,
'date_format': '%d.%m.%Y',
'decimal_point': ',',
'thousands_sep': ' ',
})
Translations = self.registry('ir.translation')
for source, value in self.translations_fr:
Translations.create(self.cr, openerp.SUPERUSER_ID, {
'name': 'export.selection,value',
'lang': 'fr_FR',
'type': 'selection',
'src': source,
'value': value
})
self.assertEqual(
self.import_(['value'], [
['toto'],
['tete'],
], context={'lang': 'fr_FR'}),
ok(2))
self.assertEqual(
self.import_(['value'], [['Wheee']], context={'lang': 'fr_FR'}),
ok(1))
class test_m2o(ImporterCase):
model_name = 'export.many2one'
def test_by_name(self):
# create integer objects
integer_id1 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
integer_id2 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 36})
# get its name
name1 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id1]))[integer_id1]
name2 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id2]))[integer_id2]
self.assertEqual(
self.import_(['value'], [
# import by name_get
[name1],
[name1],
[name2],
]),
ok(3))
# correct ids assigned to corresponding records
self.assertEqual([
(integer_id1, name1),
(integer_id1, name1),
(integer_id2, name2),],
values(self.read()))
def test_by_xid(self):
ExportInteger = self.registry('export.integer')
integer_id = ExportInteger.create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
xid = self.xid(ExportInteger.browse(
self.cr, openerp.SUPERUSER_ID, [integer_id])[0])
self.assertEqual(
self.import_(['value/id'], [[xid]]),
ok(1))
b = self.browse()
self.assertEqual(42, b[0].value.value)
def test_by_id(self):
integer_id = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
self.assertEqual(
self.import_(['value/.id'], [[integer_id]]),
ok(1))
b = self.browse()
self.assertEqual(42, b[0].value.value)
def test_by_names(self):
integer_id1 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
integer_id2 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
name1 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id1]))[integer_id1]
name2 = dict(self.registry('export.integer').name_get(
self.cr, openerp.SUPERUSER_ID,[integer_id2]))[integer_id2]
# names should be the same
self.assertEqual(name1, name2)
self.assertEqual(
self.import_(['value'], [[name2]]),
ok(1))
self.assertEqual([
(integer_id1, name1)
], values(self.read()))
def test_fail_by_implicit_id(self):
""" Can't implicitly import records by id
"""
# create integer objects
integer_id1 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 42})
integer_id2 = self.registry('export.integer').create(
self.cr, openerp.SUPERUSER_ID, {'value': 36})
self.assertEqual(
self.import_(['value'], [
# import by id, without specifying it
[integer_id1],
[integer_id2],
[integer_id1],
]),
error(1, u"No matching record found for name '%s' in field 'unknown'" % integer_id1))
def test_sub_field(self):
""" Does not implicitly create the record, does not warn that you can't
import m2o subfields (at all)...
"""
self.assertEqual(
self.import_(['value/value'], [['42']]),
error(1, u"Can not create Many-To-One records indirectly, import the field separately"))
def test_fail_noids(self):
self.assertEqual(
self.import_(['value'], [['nameisnoexist:3']]),
error(1, u"No matching record found for name 'nameisnoexist:3' in field 'unknown'"))
self.cr.rollback()
self.assertEqual(
self.import_(['value/id'], [['noxidhere']]),
error(1, u"No matching record found for external id 'noxidhere' in field 'unknown'"))
self.cr.rollback()
self.assertEqual(
self.import_(['value/.id'], [[66]]),
error(1, u"No matching record found for database id '66' in field 'unknown'"))
class test_m2m(ImporterCase):
model_name = 'export.many2many'
# apparently, one and only thing which works is a
# csv_internal_sep-separated list of ids, xids, or names (depending if
# m2m/.id, m2m/id or m2m[/anythingelse]
def test_ids(self):
id1 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
id5 = self.registry('export.many2many.other').create(
self.cr, openerp.SUPERUSER_ID, {'value': 99, 'str': 'record4'})
self.assertEqual(
self.import_(['value/.id'], [
['%d,%d' % (id1, id2)],
['%d,%d,%d' % (id1, id3, id4)],
['%d,%d,%d' % (id1, id2, id3)],
['%d' % id5]
]),
ok(4))
ids = lambda records: [record.id for record in records]
b = self.browse()
self.assertEqual(ids(b[0].value), [id1, id2])
self.assertEqual(values(b[0].value), [3, 44])
self.assertEqual(ids(b[2].value), [id1, id2, id3])
self.assertEqual(values(b[2].value), [3, 44, 84])
def test_noids(self):
self.assertEqual(
self.import_(['value/.id'], [['42']]),
error(1, u"No matching record found for database id '42' in field 'unknown'"))
def test_xids(self):
M2O_o = self.registry('export.many2many.other')
id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
records = M2O_o.browse(self.cr, openerp.SUPERUSER_ID, [id1, id2, id3, id4])
self.assertEqual(
self.import_(['value/id'], [
['%s,%s' % (self.xid(records[0]), self.xid(records[1]))],
['%s' % self.xid(records[3])],
['%s,%s' % (self.xid(records[2]), self.xid(records[1]))],
]),
ok(3))
b = self.browse()
self.assertEqual(values(b[0].value), [3, 44])
self.assertEqual(values(b[2].value), [44, 84])
def test_noxids(self):
self.assertEqual(
self.import_(['value/id'], [['noxidforthat']]),
error(1, u"No matching record found for external id 'noxidforthat' in field 'unknown'"))
def test_names(self):
M2O_o = self.registry('export.many2many.other')
id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
records = M2O_o.browse(self.cr, openerp.SUPERUSER_ID, [id1, id2, id3, id4])
name = lambda record: record.name_get()[0][1]
self.assertEqual(
self.import_(['value'], [
['%s,%s' % (name(records[1]), name(records[2]))],
['%s,%s,%s' % (name(records[0]), name(records[1]), name(records[2]))],
['%s,%s' % (name(records[0]), name(records[3]))],
]),
ok(3))
b = self.browse()
self.assertEqual(values(b[1].value), [3, 44, 84])
self.assertEqual(values(b[2].value), [3, 9])
def test_nonames(self):
self.assertEqual(
self.import_(['value'], [['wherethem2mhavenonames']]),
error(1, u"No matching record found for name 'wherethem2mhavenonames' in field 'unknown'"))
def test_import_to_existing(self):
M2O_o = self.registry('export.many2many.other')
id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'})
id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'})
id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'})
id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'})
xid = 'myxid'
self.assertEqual(
self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id1, id2)]]),
ok(1))
self.assertEqual(
self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id3, id4)]]),
ok(1))
b = self.browse()
self.assertEqual(len(b), 1)
# TODO: replacement of existing m2m values is correct?
self.assertEqual(values(b[0].value), [84, 9])
class test_o2m(ImporterCase):
model_name = 'export.one2many'
def test_name_get(self):
s = u'Java is a DSL for taking large XML files and converting them to' \
u' stack traces'
self.assertEqual(
self.import_(
['const', 'value'],
[['5', s]]),
error(1, u"No matching record found for name '%s' in field 'unknown'" % s))
def test_single(self):
self.assertEqual(
self.import_(['const', 'value/value'], [
['5', '63']
]),
ok(1))
(b,) = self.browse()
self.assertEqual(b.const, 5)
self.assertEqual(values(b.value), [63])
def test_multicore(self):
self.assertEqual(
self.import_(['const', 'value/value'], [
['5', '63'],
['6', '64'],
]),
ok(2))
b1, b2 = self.browse()
self.assertEqual(b1.const, 5)
self.assertEqual(values(b1.value), [63])
self.assertEqual(b2.const, 6)
self.assertEqual(values(b2.value), [64])
def test_multisub(self):
self.assertEqual(
self.import_(['const', 'value/value'], [
['5', '63'],
['', '64'],
['', '65'],
['', '66'],
]),
ok(4))
(b,) = self.browse()
self.assertEqual(values(b.value), [63, 64, 65, 66])
def test_multi_subfields(self):
self.assertEqual(
self.import_(['value/str', 'const', 'value/value'], [
['this', '5', '63'],
['is', '', '64'],
['the', '', '65'],
['rhythm', '', '66'],
]),
ok(4))
(b,) = self.browse()
self.assertEqual(values(b.value), [63, 64, 65, 66])
self.assertEqual(
values(b.value, 'str'),
'this is the rhythm'.split())
def test_link_inline(self):
id1 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Bf', 'value': 109
})
id2 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Me', 'value': 262
})
try:
self.import_(['const', 'value/.id'], [
['42', '%d,%d' % (id1, id2)]
])
except ValueError, e:
# should be Exception(Database ID doesn't exist: export.one2many.child : $id1,$id2)
self.assertIs(type(e), ValueError)
self.assertEqual(
e.args[0],
"invalid literal for int() with base 10: '%d,%d'" % (id1, id2))
def test_link(self):
id1 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Bf', 'value': 109
})
id2 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Me', 'value': 262
})
self.assertEqual(
self.import_(['const', 'value/.id'], [
['42', str(id1)],
['', str(id2)],
]),
ok(2))
[b] = self.browse()
self.assertEqual(b.const, 42)
# automatically forces link between core record and o2ms
self.assertEqual(values(b.value), [109, 262])
self.assertEqual(values(b.value, field='parent_id'), [b, b])
def test_link_2(self):
O2M_c = self.registry('export.one2many.child')
id1 = O2M_c.create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Bf', 'value': 109
})
id2 = O2M_c.create(self.cr, openerp.SUPERUSER_ID, {
'str': 'Me', 'value': 262
})
self.assertEqual(
self.import_(['const', 'value/.id', 'value/value'], [
['42', str(id1), '1'],
['', str(id2), '2'],
]),
ok(2))
[b] = self.browse()
self.assertEqual(b.const, 42)
self.assertEqual(values(b.value), [1, 2])
self.assertEqual(values(b.value, field='parent_id'), [b, b])
class test_o2m_multiple(ImporterCase):
model_name = 'export.one2many.multiple'
def test_multi_mixed(self):
self.assertEqual(
self.import_(['const', 'child1/value', 'child2/value'], [
['5', '11', '21'],
['', '12', '22'],
['', '13', '23'],
['', '14', ''],
]),
ok(4))
[b] = self.browse()
self.assertEqual(values(b.child1), [11, 12, 13, 14])
self.assertEqual(values(b.child2), [21, 22, 23])
def test_multi(self):
self.assertEqual(
self.import_(['const', 'child1/value', 'child2/value'], [
['5', '11', '21'],
['', '12', ''],
['', '13', ''],
['', '14', ''],
['', '', '22'],
['', '', '23'],
]),
ok(6))
[b] = self.browse()
self.assertEqual(values(b.child1), [11, 12, 13, 14])
self.assertEqual(values(b.child2), [21, 22, 23])
def test_multi_fullsplit(self):
self.assertEqual(
self.import_(['const', 'child1/value', 'child2/value'], [
['5', '11', ''],
['', '12', ''],
['', '13', ''],
['', '14', ''],
['', '', '21'],
['', '', '22'],
['', '', '23'],
]),
ok(7))
[b] = self.browse()
self.assertEqual(b.const, 5)
self.assertEqual(values(b.child1), [11, 12, 13, 14])
self.assertEqual(values(b.child2), [21, 22, 23])
# function, related, reference: written to db as-is...
# => function uses @type for value coercion/conversion
|
2014cdag5/2014cdag5 | refs/heads/master | wsgi/static/Brython2.1.0-20140419-113919/Lib/unittest/test/dummy.py | 1061 | # Empty module for testing the loading of modules
|
oz123/python-nvd3 | refs/heads/develop | nvd3/NVD3Chart.py | 5 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Python-nvd3 is a Python wrapper for NVD3 graph library.
NVD3 is an attempt to build re-usable charts and chart components
for d3.js without taking away the power that d3.js gives you.
Project location : https://github.com/areski/python-nvd3
"""
from __future__ import unicode_literals
from optparse import OptionParser
from jinja2 import Environment, PackageLoader
from slugify import slugify
try:
import simplejson as json
except ImportError:
import json
CONTENT_FILENAME = "./content.html"
PAGE_FILENAME = "./page.html"
pl = PackageLoader('nvd3', 'templates')
jinja2_env = Environment(lstrip_blocks=True, trim_blocks=True, loader=pl)
template_content = jinja2_env.get_template(CONTENT_FILENAME)
template_page = jinja2_env.get_template(PAGE_FILENAME)
def stab(tab=1):
"""
create space tabulation
"""
return ' ' * 4 * tab
class NVD3Chart(object):
"""
NVD3Chart Base class.
"""
#: chart count
count = 0
#: directory holding the assets (bower_components)
assets_directory = './bower_components/'
# this attribute is overriden by children of this
# class
CHART_FILENAME = None
template_environment = Environment(lstrip_blocks=True, trim_blocks=True,
loader=pl)
def __init__(self, **kwargs):
"""
This is the base class for all the charts. The following keywords are
accepted:
:keyword: **display_container** - default: ``True``
:keyword: **jquery_on_ready** - default: ``False``
:keyword: **charttooltip_dateformat** - default: ``'%d %b %Y'``
:keyword: **name** - default: the class name
``model`` - set the model (e.g. ``pieChart``, `
``LineWithFocusChart``, ``MultiBarChart``).
:keyword: **color_category** - default - ``None``
:keyword: **color_list** - default - ``None``
used by pieChart (e.g. ``['red', 'blue', 'orange']``)
:keyword: **margin_bottom** - default - ``20``
:keyword: **margin_left** - default - ``60``
:keyword: **margin_right** - default - ``60``
:keyword: **margin_top** - default - ``30``
:keyword: **height** - default - ``''``
:keyword: **width** - default - ``''``
:keyword: **stacked** - default - ``False``
:keyword: **focus_enable** - default - ``False``
:keyword: **resize** - define - ``False``
:keyword: **show_legend** - default - ``True``
:keyword: **show_labels** - default - ``True``
:keyword: **tag_script_js** - default - ``True``
:keyword: **use_interactive_guideline** - default - ``False``
:keyword: **chart_attr** - default - ``None``
:keyword: **extras** - default - ``None``
Extra chart modifiers. Use this to modify different attributes of
the chart.
:keyword: **x_axis_date** - default - False
Signal that x axis is a date axis
:keyword: **date_format** - default - ``%x``
see https://github.com/mbostock/d3/wiki/Time-Formatting
:keyword: **x_axis_format** - default - ``''``.
:keyword: **y_axis_format** - default - ``''``.
:keyword: **style** - default - ``''``
Style modifiers for the DIV container.
:keyword: **color_category** - default - ``category10``
Acceptable values are nvd3 categories such as
``category10``, ``category20``, ``category20c``.
"""
# set the model
self.model = self.__class__.__name__ #: The chart model,
#: an Instance of Jinja2 template
self.template_page_nvd3 = template_page
self.template_content_nvd3 = template_content
self.series = []
self.axislist = {}
# accepted keywords
self.display_container = kwargs.get('display_container', True)
self.charttooltip_dateformat = kwargs.get('charttooltip_dateformat',
'%d %b %Y')
self._slugify_name(kwargs.get('name', self.model))
self.jquery_on_ready = kwargs.get('jquery_on_ready', False)
self.color_category = kwargs.get('color_category', None)
self.color_list = kwargs.get('color_list', None)
self.margin_bottom = kwargs.get('margin_bottom', 20)
self.margin_left = kwargs.get('margin_left', 60)
self.margin_right = kwargs.get('margin_right', 60)
self.margin_top = kwargs.get('margin_top', 30)
self.height = kwargs.get('height', '')
self.width = kwargs.get('width', '')
self.stacked = kwargs.get('stacked', False)
self.focus_enable = kwargs.get('focus_enable', False)
self.resize = kwargs.get('resize', False)
self.show_legend = kwargs.get('show_legend', True)
self.show_labels = kwargs.get('show_labels', True)
self.tag_script_js = kwargs.get('tag_script_js', True)
self.use_interactive_guideline = kwargs.get("use_interactive_guideline",
False)
self.chart_attr = kwargs.get("chart_attr", {})
self.extras = kwargs.get('extras', None)
self.style = kwargs.get('style', '')
self.date_format = kwargs.get('date_format', '%x')
self.x_axis_date = kwargs.get('x_axis_date', False)
#: x-axis contain date format or not
# possible duplicate of x_axis_date
self.date_flag = kwargs.get('date_flag', False)
self.x_axis_format = kwargs.get('x_axis_format', '')
# Load remote JS assets or use the local bower assets?
self.remote_js_assets = kwargs.get('remote_js_assets', True)
# None keywords attribute that should be modified by methods
# We should change all these to _attr
self.htmlcontent = '' #: written by buildhtml
self.htmlheader = ''
#: Place holder for the graph (the HTML div)
#: Written by ``buildcontainer``
self.container = u''
#: Header for javascript code
self.containerheader = u''
# CDN http://cdnjs.com/libraries/nvd3/ needs to make sure it's up to
# date
self.header_css = [
'<link href="%s" rel="stylesheet" />' % h for h in
(
'https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.min.css' if self.remote_js_assets else self.assets_directory + 'nvd3/src/nv.d3.css',
)
]
self.header_js = [
'<script src="%s"></script>' % h for h in
(
'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js' if self.remote_js_assets else self.assets_directory + 'd3/d3.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.min.js' if self.remote_js_assets else self.assets_directory + 'nvd3/nv.d3.min.js'
)
]
#: Javascript code as string
self.jschart = None
self.custom_tooltip_flag = False
self.tooltip_condition_string = ''
self.charttooltip = ''
self.serie_no = 1
def _slugify_name(self, name):
"""Slufigy name with underscore"""
self.name = slugify(name, separator='_')
def add_serie(self, y, x, name=None, extra=None, **kwargs):
"""
add serie - Series are list of data that will be plotted
y {1, 2, 3, 4, 5} / x {1, 2, 3, 4, 5}
**Attributes**:
* ``name`` - set Serie name
* ``x`` - x-axis data
* ``y`` - y-axis data
kwargs:
* ``shape`` - for scatterChart, you can set different shapes
(circle, triangle etc...)
* ``size`` - for scatterChart, you can set size of different shapes
* ``type`` - for multiChart, type should be bar
* ``bar`` - to display bars in Chart
* ``color_list`` - define list of colors which will be
used by pieChart
* ``color`` - set axis color
* ``disabled`` -
extra:
* ``tooltip`` - set tooltip flag
* ``date_format`` - set date_format for tooltip if x-axis is in
date format
"""
if not name:
name = "Serie %d" % (self.serie_no)
# For scatterChart shape & size fields are added in serie
if 'shape' in kwargs or 'size' in kwargs:
csize = kwargs.get('size', 1)
cshape = kwargs.get('shape', 'circle')
serie = [{
'x': x[i],
'y': j,
'shape': cshape,
'size': csize[i] if isinstance(csize, list) else csize
} for i, j in enumerate(y)]
else:
if self.model == 'pieChart':
serie = [{'label': x[i], 'value': y} for i, y in enumerate(y)]
else:
serie = [{'x': x[i], 'y': y} for i, y in enumerate(y)]
data_keyvalue = {'values': serie, 'key': name}
# multiChart
# Histogram type='bar' for the series
if 'type' in kwargs and kwargs['type']:
data_keyvalue['type'] = kwargs['type']
# Define on which Y axis the serie is related
# a chart can have 2 Y axis, left and right, by default only one Y Axis is used
if 'yaxis' in kwargs and kwargs['yaxis']:
data_keyvalue['yAxis'] = kwargs['yaxis']
else:
if self.model != 'pieChart':
data_keyvalue['yAxis'] = '1'
if 'bar' in kwargs and kwargs['bar']:
data_keyvalue['bar'] = 'true'
if 'disabled' in kwargs and kwargs['disabled']:
data_keyvalue['disabled'] = 'true'
if 'color' in kwargs and kwargs['color']:
data_keyvalue['color'] = kwargs['color']
if extra:
if self.model == 'pieChart':
if 'color_list' in extra and extra['color_list']:
self.color_list = extra['color_list']
if extra.get('date_format'):
self.charttooltip_dateformat = extra['date_format']
if extra.get('tooltip'):
self.custom_tooltip_flag = True
if self.model != 'pieChart':
_start = extra['tooltip']['y_start']
_end = extra['tooltip']['y_end']
_start = ("'" + str(_start) + "' + ") if _start else ''
_end = (" + '" + str(_end) + "'") if _end else ''
if self.model == 'linePlusBarChart':
if self.tooltip_condition_string:
self.tooltip_condition_string += stab(5)
self.tooltip_condition_string += stab(0) + "if(key.indexOf('" + name + "') > -1 ){\n" +\
stab(6) + "var y = " + _start + " String(graph.point.y) " + _end + ";\n" +\
stab(5) + "}\n"
elif self.model == 'cumulativeLineChart':
self.tooltip_condition_string += stab(0) + "if(key == '" + name + "'){\n" +\
stab(6) + "var y = " + _start + " String(e) " + _end + ";\n" +\
stab(5) + "}\n"
else:
self.tooltip_condition_string += stab(5) + "if(key == '" + name + "'){\n" +\
stab(6) + "var y = " + _start + " String(graph.point.y) " + _end + ";\n" +\
stab(5) + "}\n"
if self.model == 'pieChart':
_start = extra['tooltip']['y_start']
_end = extra['tooltip']['y_end']
_start = ("'" + str(_start) + "' + ") if _start else ''
_end = (" + '" + str(_end) + "'") if _end else ''
self.tooltip_condition_string += "var y = " + _start + " String(y) " + _end + ";\n"
# Increment series counter & append
self.serie_no += 1
self.series.append(data_keyvalue)
def add_chart_extras(self, extras):
"""
Use this method to add extra d3 properties to your chart.
For example, you want to change the text color of the graph::
chart = pieChart(name='pieChart', color_category='category20c', height=400, width=400)
xdata = ["Orange", "Banana", "Pear", "Kiwi", "Apple", "Strawberry", "Pineapple"]
ydata = [3, 4, 0, 1, 5, 7, 3]
extra_serie = {"tooltip": {"y_start": "", "y_end": " cal"}}
chart.add_serie(y=ydata, x=xdata, extra=extra_serie)
The above code will create graph with a black text, the following will change it::
text_white="d3.selectAll('#pieChart text').style('fill', 'white');"
chart.add_chart_extras(text_white)
The above extras will be appended to the java script generated.
Alternatively, you can use the following initialization::
chart = pieChart(name='pieChart',
color_category='category20c',
height=400, width=400,
extras=text_white)
"""
self.extras = extras
def set_graph_height(self, height):
"""Set Graph height"""
self.height = str(height)
def set_graph_width(self, width):
"""Set Graph width"""
self.width = str(width)
def set_containerheader(self, containerheader):
"""Set containerheader"""
self.containerheader = containerheader
def set_date_flag(self, date_flag=False):
"""Set date flag"""
self.date_flag = date_flag
def set_custom_tooltip_flag(self, custom_tooltip_flag):
"""Set custom_tooltip_flag & date_flag"""
self.custom_tooltip_flag = custom_tooltip_flag
def __str__(self):
"""return htmlcontent"""
self.buildhtml()
return self.htmlcontent
def buildcontent(self):
"""Build HTML content only, no header or body tags. To be useful this
will usually require the attribute `juqery_on_ready` to be set which
will wrap the js in $(function(){<regular_js>};)
"""
self.buildcontainer()
# if the subclass has a method buildjs this method will be
# called instead of the method defined here
# when this subclass method is entered it does call
# the method buildjschart defined here
self.buildjschart()
self.htmlcontent = self.template_content_nvd3.render(chart=self)
def buildhtml(self):
"""Build the HTML page
Create the htmlheader with css / js
Create html page
Add Js code for nvd3
"""
self.buildcontent()
self.content = self.htmlcontent
self.htmlcontent = self.template_page_nvd3.render(chart=self)
# this is used by django-nvd3
def buildhtmlheader(self):
"""generate HTML header content"""
self.htmlheader = ''
# If the JavaScript assets have already been injected, don't bother re-sourcing them.
global _js_initialized
if '_js_initialized' not in globals() or not _js_initialized:
for css in self.header_css:
self.htmlheader += css
for js in self.header_js:
self.htmlheader += js
def buildcontainer(self):
"""generate HTML div"""
if self.container:
return
# Create SVG div with style
if self.width:
if self.width[-1] != '%':
self.style += 'width:%spx;' % self.width
else:
self.style += 'width:%s;' % self.width
if self.height:
if self.height[-1] != '%':
self.style += 'height:%spx;' % self.height
else:
self.style += 'height:%s;' % self.height
if self.style:
self.style = 'style="%s"' % self.style
self.container = self.containerheader + \
'<div id="%s"><svg %s></svg></div>\n' % (self.name, self.style)
def buildjschart(self):
"""generate javascript code for the chart"""
self.jschart = ''
# add custom tooltip string in jschart
# default condition (if build_custom_tooltip is not called explicitly with date_flag=True)
if self.tooltip_condition_string == '':
self.tooltip_condition_string = 'var y = String(graph.point.y);\n'
# Include data
self.series_js = json.dumps(self.series)
def create_x_axis(self, name, label=None, format=None, date=False, custom_format=False):
"""Create X-axis"""
axis = {}
if custom_format and format:
axis['tickFormat'] = format
elif format:
if format == 'AM_PM':
axis['tickFormat'] = "function(d) { return get_am_pm(parseInt(d)); }"
else:
axis['tickFormat'] = "d3.format(',%s')" % format
if label:
axis['axisLabel'] = "'" + label + "'"
# date format : see https://github.com/mbostock/d3/wiki/Time-Formatting
if date:
self.dateformat = format
axis['tickFormat'] = ("function(d) { return d3.time.format('%s')"
"(new Date(parseInt(d))) }\n"
"" % self.dateformat)
# flag is the x Axis is a date
if name[0] == 'x':
self.x_axis_date = True
# Add new axis to list of axis
self.axislist[name] = axis
# Create x2Axis if focus_enable
if name == "xAxis" and self.focus_enable:
self.axislist['x2Axis'] = axis
def create_y_axis(self, name, label=None, format=None, custom_format=False):
"""
Create Y-axis
"""
axis = {}
if custom_format and format:
axis['tickFormat'] = format
elif format:
axis['tickFormat'] = "d3.format(',%s')" % format
if label:
axis['axisLabel'] = "'" + label + "'"
# Add new axis to list of axis
self.axislist[name] = axis
class TemplateMixin(object):
"""
A mixin that override buildcontent. Instead of building the complex
content template we exploit Jinja2 inheritance. Thus each chart class
renders it's own chart template which inherits from content.html
"""
def buildcontent(self):
"""Build HTML content only, no header or body tags. To be useful this
will usually require the attribute `juqery_on_ready` to be set which
will wrap the js in $(function(){<regular_js>};)
"""
self.buildcontainer()
# if the subclass has a method buildjs this method will be
# called instead of the method defined here
# when this subclass method is entered it does call
# the method buildjschart defined here
self.buildjschart()
self.htmlcontent = self.template_chart_nvd3.render(chart=self)
def _main():
"""
Parse options and process commands
"""
# Parse arguments
usage = "usage: nvd3.py [options]"
parser = OptionParser(usage=usage,
version=("python-nvd3 - Charts generator with "
"nvd3.js and d3.js"))
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print messages to stdout")
(options, args) = parser.parse_args()
if __name__ == '__main__':
_main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.